"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; export default function AuthForm() { const [mode, setMode] = useState<"login" | "register">("login"); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const router = useRouter(); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(""); setLoading(true); try { const endpoint = mode === "login" ? "/api/auth/login" : "/api/auth/register"; const body = mode === "login" ? { email, password } : { email, password, name }; const response = await fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || "Authentication failed"); } // Store token for authenticated requests if (data.data?.token) { localStorage.setItem("token", data.data.token); } router.push("/"); } catch (err: any) { setError(err.message); } finally { setLoading(false); } }; return (
{mode === "login" ? "Sign in to continue" : "Join and start earning"}