File size: 9,246 Bytes
5463318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Mail, Lock, Loader2, ArrowRight, Check, ShieldCheck } from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';
import { AuthInput } from './AuthInput';
import { useToast } from '../ui/Toast';
import { useAuthToggle } from './AuthToggleContext';
import { supabase } from '../../../src/utils/supabaseClient';

export const LoginForm = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [isSuccess, setIsSuccess] = useState(false);
    const [errors, setErrors] = useState({});
    const [rememberMe, setRememberMe] = useState(false);

    const navigate = useNavigate();
    const { addToast } = useToast();
    const { toggleMode } = useAuthToggle();

    // AI-driven greeting based on time
    const hour = new Date().getHours();
    const greeting = hour < 12 ? 'Good Morning' : hour < 18 ? 'Good Afternoon' : 'Good Evening';
    const subGreeting = hour < 12 ? "Ready to shape minds today?" : hour < 18 ? "Let's build smarter assessments." : "Ready to build tomorrow's exam?";

    const validateEmail = (email) => {
        return /\S+@\S+\.\S+/.test(email);
    };

    const handleEmailBlur = () => {
        if (email && !validateEmail(email)) {
            setErrors(prev => ({ ...prev, email: 'Please enter a valid email address' }));
        } else {
            setErrors(prev => { const { email, ...rest } = prev; return rest; });
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setErrors({});

        let currentErrors = {};
        if (!email) currentErrors.email = 'Email is required';
        if (!password) currentErrors.password = 'Password is required';

        if (Object.keys(currentErrors).length > 0) {
            setErrors(currentErrors);
            return;
        }

        setIsLoading(true);

        try {
            const { data, error } = await supabase.auth.signInWithPassword({
                email,
                password,
            });

            if (error) throw error;

            setIsSuccess(true);
            setTimeout(() => {
                navigate('/app');
                addToast({
                    title: 'Welcome Back!',
                    description: 'Successfully logged into ExamCraft.AI',
                    variant: 'success'
                });
            }, 600);
        } catch (error) {
            addToast({
                title: 'Login Failed',
                description: error.message || 'Invalid credentials. Please try again.',
                variant: 'destructive',
            });
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className="w-full h-full flex flex-col justify-center">
            <motion.div
                initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }}
                className="mb-8"
            >
                <h2 className="text-3xl font-extrabold mb-2 text-slate-900 dark:text-white tracking-tight flex items-center gap-2">
                    {greeting}, Educator                     <motion.span
                        animate={{ rotate: [0, 14, -8, 14, -4, 10, 0, 0] }}
                        transition={{ duration: 2.5, repeat: Infinity, ease: "easeInOut", repeatDelay: 5 }}
                        className="text-2xl inline-block origin-bottom-right"
                    >
                        👋
                    </motion.span>
                </h2>
                <p className="text-slate-500 dark:text-slate-400 text-sm font-medium">{subGreeting}</p>
            </motion.div>

            <form onSubmit={handleSubmit} className="w-full space-y-5">
                <AuthInput
                    label="Email Address"
                    type="email"
                    value={email}
                    onChange={(e) => {
                        setEmail(e.target.value);
                        if (errors.email) setErrors(prev => { const { email, ...rest } = prev; return rest; });
                    }}
                    onBlur={handleEmailBlur}
                    error={errors.email}
                    isValid={email.length > 0 && !errors.email && validateEmail(email)}
                    icon={Mail}
                    placeholder="name@institution.edu"
                />

                <AuthInput
                    label="Password"
                    type="password"
                    value={password}
                    onChange={(e) => {
                        setPassword(e.target.value);
                        if (errors.password) setErrors(prev => { const { password, ...rest } = prev; return rest; });
                    }}
                    error={errors.password}
                    isValid={password.length > 0 && !errors.password}
                    icon={Lock}
                    placeholder="••••••••"
                />

                <div className="flex items-center justify-between mt-2">
                    <label className="flex items-center gap-2 cursor-pointer group">
                        <div className="relative flex items-center justify-center">
                            <input
                                type="checkbox"
                                checked={rememberMe}
                                onChange={() => setRememberMe(!rememberMe)}
                                className="peer sr-only"
                            />
                            <div className="w-4 h-4 rounded border border-slate-300 dark:border-white/20 peer-checked:bg-[#4F7CFF] peer-checked:border-[#4F7CFF] transition-colors flex items-center justify-center group-hover:border-[#4F7CFF]">
                                <Check size={12} className="text-white opacity-0 peer-checked:opacity-100 transition-opacity" strokeWidth={3} />
                            </div>
                        </div>
                        <span className="text-xs text-slate-500 dark:text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-200 transition-colors">
                            Remember me
                        </span>
                    </label>

                    <Link to="/forgot-password" className="text-xs font-semibold text-[#4F7CFF] hover:text-[#8B5CF6] transition-colors">
                        Forgot password?
                    </Link>
                </div>

                <div className="pt-2">
                    <motion.button
                        type="submit"
                        disabled={isLoading || isSuccess}
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                        className="group relative w-full rounded-xl bg-gradient-to-r from-[#8B5CF6] to-[#4F7CFF] text-white font-bold py-3.5 hover:shadow-[0_0_20px_rgba(79,124,255,0.4)] transition-all duration-300 disabled:opacity-80 flex items-center justify-center overflow-hidden"
                    >
                        <AnimatePresence mode="wait">
                            {isLoading ? (
                                <motion.div key="loading" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
                                    <Loader2 className="w-5 h-5 animate-spin" />
                                </motion.div>
                            ) : isSuccess ? (
                                <motion.div key="success" initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ type: 'spring', stiffness: 300, damping: 20 }}>
                                    <Check className="w-6 h-6 text-white drop-shadow-md" strokeWidth={3} />
                                </motion.div>
                            ) : (
                                <motion.span key="text" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
                                    Sign In to Dashboard
                                </motion.span>
                            )}
                        </AnimatePresence>
                        <div className="absolute inset-0 -translate-x-full bg-gradient-to-r from-transparent via-white/20 to-transparent group-hover:animate-[shimmer_1.5s_infinite] pointer-events-none" />
                    </motion.button>
                </div>
            </form>


            <div className="mt-8 flex items-center justify-center gap-2 text-xs text-slate-500 font-medium">
                <ShieldCheck size={14} className="text-emerald-500" />
                <span>End-to-end encrypted · Privacy-first platform</span>
            </div>

            {/* Switch to Signup */}
            <div className="mt-6 text-center">
                <p className="text-sm text-slate-500">
                    Don't have an account?{' '}
                    <button onClick={toggleMode} type="button" className="font-semibold text-[#4F7CFF] hover:underline">
                        Sign up here
                    </button>
                </p>
            </div>
        </div>
    );
};