"use client" import Altcha from "@/components/core/altcha"; import { Nav } from "@/components/core/nav"; import { TbUserPlus } from "react-icons/tb"; import { useState } from "react"; import { useForm, SubmitHandler } from "react-hook-form"; import { useRouter } from "next/navigation"; import { authClient } from "@/util/auth-client"; interface SignupForm { email: string; password: string; confirmPassword: string; name?: string; } export default function Signup() { const router = useRouter(); const [altchaState, setAltchaState] = useState<{ status: "success" | "error" | "expired" | "waiting", token: string }>({ status: "waiting", token: "" }); const [isLoading, setIsLoading] = useState(false); const [apiError, setApiError] = useState(""); const { register, handleSubmit, formState: { errors }, watch, } = useForm(); const password = watch("password"); const onSubmit: SubmitHandler = async (data) => { if (altchaState.status !== "success") { setApiError("Please complete the captcha"); return; } setIsLoading(true); setApiError(""); try { const response = await fetch("/api/signup", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ...data, token: altchaState.token, }), }); const result = await response.json(); if (!response.ok) { setApiError(result.error || "Failed to create account"); return; } try { await authClient.signIn.email({ email: data.email, password: data.password, }); router.push("/"); } catch (signInError) { console.error("Auto-login failed:", signInError); router.push("/login?message=Account created successfully. Please sign in."); } } catch (error) { console.error("Signup error:", error); setApiError("An unexpected error occurred. Please try again."); } finally { setIsLoading(false); } }; const handleAltchaStateChange = (e: Event | CustomEvent) => { if ('detail' in e && e.detail?.payload) { setAltchaState({ status: "success", token: e.detail.payload }); } else { setAltchaState({ status: "error", token: "" }); } }; return (
); }