import React, { useState } from 'react'; import { Eye, EyeOff } from 'lucide-react'; import logo from '../assets/logo.png'; export default function Auth({ onLoginSuccess, isArabic }) { const [isLogin, setIsLogin] = useState(true); const [isForgot, setIsForgot] = useState(false); const [email, setEmail] = useState(''); const [name, setName] = useState(''); const [password, setPassword] = useState(''); const [token, setToken] = useState(''); const [error, setError] = useState(''); const [message, setMessage] = useState(''); const [loading, setLoading] = useState(false); const [requestSent, setRequestSent] = useState(false); const [showPassword, setShowPassword] = useState(false); const API_URL = "/api/auth"; const handleSubmit = async (e) => { e.preventDefault(); setError(''); setMessage(''); setLoading(true); try { if (isForgot) { // Forgot password flow const res = await fetch(`${API_URL}/forgot-password`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }), }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || 'Error generating reset link.'); setRequestSent(true); setMessage(isArabic ? 'إن كان البريد مسجلاً فقد أُرسل رمز الاستعادة. أدخله بالأسفل مع كلمة المرور الجديدة.' : 'If the email is registered, a reset token was sent. Enter it below with your new password.'); } else if (isLogin) { // Login flow const res = await fetch(`${API_URL}/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || 'Login failed.'); localStorage.setItem('qto_token', data.token); localStorage.setItem('qto_user', JSON.stringify(data.user)); onLoginSuccess(data.token, data.user); } else { // Register flow const res = await fetch(`${API_URL}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password, name }), }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || 'Registration failed.'); setMessage(isArabic ? 'تم التسجيل بنجاح! يمكنك الآن تسجيل الدخول.' : 'Registration successful! You can now log in.'); setIsLogin(true); } } catch (err) { setError(err.message); } finally { setLoading(false); } }; const handleResetPassword = async (e) => { e.preventDefault(); setError(''); setMessage(''); setLoading(true); try { const res = await fetch(`${API_URL}/reset-password`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token, password }), }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || 'Reset failed.'); setMessage(isArabic ? 'تم تحديث كلمة المرور بنجاح.' : 'Password updated successfully.'); setIsForgot(false); setIsLogin(true); } catch (err) { setError(err.message); } finally { setLoading(false); } }; return (