"use client"; // Mark as a Client Component import { useState } from "react"; import { signIn } from "next-auth/react"; import { useRouter } from "next/navigation"; import Link from "next/link"; export default function Register() { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const handleRegister = async (e) => { e.preventDefault(); // Basic validation if (!username || !password) { setError("Username and password are required"); return; } setIsLoading(true); setError(""); try { // First register the user const response = await fetch("/api/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), }); const result = await response.json(); if (!response.ok) { setError(result.error || "Failed to register"); setIsLoading(false); return; } // Then try to sign in const signInResult = await signIn("credentials", { redirect: false, username, password, callbackUrl: "/team-selection", }); if (signInResult?.error) { setError(`Login failed: ${signInResult.error}`); setIsLoading(false); } else { // Successful login router.push(signInResult?.url || "/team-selection"); } } catch (err) { console.error("Registration/login error:", err); setError("An unexpected error occurred. Please try again."); setIsLoading(false); } }; return (
Register
setUsername(e.target.value)} required className="auth-input" />
setPassword(e.target.value)} required className="auth-input" />
{error &&
{error}
}
); }