"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(); setIsLoading(true); setError(""); try { const response = await fetch("/api/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), }); if (!response.ok) { const result = await response.json(); setError(result.error || "Failed to register"); setIsLoading(false); return; } const result = await response.json(); if (result.error) { setError(result.error); setIsLoading(false); } else { // Automatically log in the user after successful registration const signInResult = await signIn("credentials", { redirect: false, username, password, }); if (signInResult?.error) { setError("Registration successful, but failed to log in"); setIsLoading(false); } else { router.push("/team-selection"); } } } catch (err) { if (err instanceof SyntaxError) { setError("Unexpected response from server"); } else { setError("An unexpected error occurred"); } console.error(err); setIsLoading(false); } }; return (