"use client"; import axios from "axios"; import { FormEvent, MouseEvent, useEffect, useRef, useState } from "react"; interface AuthModalProps { isOpen: boolean; // bool for if the modal should be visible onClose: () => void; //A function that will be executed to close the modal } export default function AuthModal({ isOpen, onClose }: AuthModalProps) { const [isLogin, setIsLogin] = useState(true); const modalRef = useRef(null); const [isFailed, setIsFailed] = useState(false); const [failMessage, setFailMessage] = useState(false); useEffect(() => { if (isOpen) setIsLogin(true); // runs when isOpen changes, if it is true, the login is shown }, [isOpen]); if (!isOpen) return null; // if is open is false, the model isnt shown const handleOverlayClick = (e: MouseEvent) => { if (modalRef.current && !modalRef.current.contains(e.target as Node)) { onClose(); } }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); // stops page from refreshing setIsFailed(false); const formData = new FormData(e.currentTarget); const email = formData.get("email") as string; const password = formData.get("password") as string; const name = isLogin ? undefined : (formData.get("name") as string); try { const res = await axios.post(`/api/${isLogin ? "login" : "signup"}`, { headers: { "Content-Type": "application/json" }, body: isLogin ? { email, password } : { name: name!, email, password }, }); if (res.status) { onClose(); } else if (res.status >= 400 && res.status < 500) { console.log("4xx error:", res.data); setFailMessage(res.data.message); setIsFailed(true); } else { console.error("Error:", await res.data.message); } } catch (error) { console.error("Request failed:", error instanceof Error ? error.message : String(error)); } }; return (

{isLogin ? "Login" : "Sign Up"}

{/* Form */}
{!isLogin && (
)}
{isFailed && (
)}

{isLogin ? "Need an account?" : "Already have an account?"}{" "}

); }