"use client"; import { useState } from "react"; import { signIn } from "next-auth/react"; type Mode = "login" | "register"; export function AuthModal({ onClose, onSuccess }: { onClose: () => void; onSuccess: () => void }) { const [mode, setMode] = useState("login"); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); setLoading(true); try { if (mode === "register") { const res = await fetch("/api/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, email, password }), }); const data = await res.json() as { error?: string }; if (!res.ok) { setError(data.error ?? "Erreur"); return; } } const result = await signIn("credentials", { email, password, redirect: false, }); if (result?.error) { setError("Email ou mot de passe incorrect"); return; } onSuccess(); } finally { setLoading(false); } } return (
e.stopPropagation()}>
{mode === "register" && ( setName(e.target.value)} required maxLength={30} /> )} setEmail(e.target.value)} required /> setPassword(e.target.value)} required minLength={6} /> {error &&
{error}
}
); }