"use client"; import { useRouter } from "next/navigation"; import { useState } from "react"; interface CommentFormProps { slug: string; parentId?: string | null; replyToName?: string | null; initialContent?: string; onSubmitted?: () => void; } export default function CommentForm({ slug, parentId = null, replyToName = null, initialContent = "", onSubmitted, }: CommentFormProps) { const router = useRouter(); const [isPending, setIsPending] = useState(false); const [authorName, setAuthorName] = useState(""); const [content, setContent] = useState(initialContent); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"; const onSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(null); setSuccess(null); if (!authorName.trim() || !content.trim()) { setError("Please enter your name and comment."); return; } try { setIsPending(true); const res = await fetch(`${apiUrl}/api/blog/${slug}/comments`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", }, body: JSON.stringify({ authorName: authorName.trim(), content: content.trim(), ...(parentId ? { parentId } : {}), }), }); const data = await res.json(); if (!res.ok || !data?.success) { throw new Error(data?.message || "Failed to submit comment"); } setAuthorName(""); setContent(""); setSuccess("Comment submitted."); // Re-fetch server data (blog detail is no-store) to show new comment immediately router.refresh(); onSubmitted?.(); } catch (err) { setError(err instanceof Error ? err.message : "Failed to submit comment"); } finally { setIsPending(false); } }; return (

{parentId ? (replyToName ? `Reply to @${replyToName}` : "Reply") : "Leave A Comment"}

{error &&

{error}

} {success &&

{success}

}
Your Name setAuthorName(e.target.value)} disabled={isPending} />
); }