import { useEffect, useRef, useState } from 'react' interface Comment { id: string displayName: string text: string createdAt: string } interface Props { studySlug: string sectionId: string isEnrolled: boolean } function formatDate(iso: string) { try { return new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) } catch { return '' } } export function StudySectionComments({ studySlug, sectionId, isEnrolled }: Props) { const [comments, setComments] = useState([]) const [loading, setLoading] = useState(true) const [text, setText] = useState('') const [submitting, setSubmitting] = useState(false) const [error, setError] = useState(null) const [success, setSuccess] = useState(false) const [deletingId, setDeletingId] = useState(null) const textRef = useRef(null) useEffect(() => { setLoading(true) fetch(`/api/study-comments/${studySlug}/${sectionId}`) .then(r => r.json()) .then(data => setComments(Array.isArray(data.comments) ? data.comments : [])) .catch(() => setComments([])) .finally(() => setLoading(false)) }, [studySlug, sectionId]) async function handleSubmit(e: React.FormEvent) { e.preventDefault() if (!text.trim()) return setSubmitting(true) setError(null) setSuccess(false) try { const res = await fetch(`/api/study-comments/${studySlug}/${sectionId}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: text.trim() }), }) const data = await res.json() if (!res.ok) { setError(data.message ?? 'Failed to post comment.') return } setComments(prev => [...prev, data.comment]) setText('') setSuccess(true) setTimeout(() => setSuccess(false), 3000) } catch { setError('Network error. Please try again.') } finally { setSubmitting(false) } } async function handleDelete(commentId: string) { setDeletingId(commentId) try { const res = await fetch(`/api/study-comments/${commentId}`, { method: 'DELETE' }) if (!res.ok) { setError('Could not delete that comment.') return } setComments(prev => prev.filter(c => c.id !== commentId)) } catch { setError('Network error. Please try again.') } finally { setDeletingId(null) } } return (

Share Your Thoughts

{loading ? (

Loading comments…

) : comments.length === 0 ? (

No comments yet. Be the first to share a thought!

) : (
    {comments.map(comment => (
  • {comment.displayName} {formatDate(comment.createdAt)}

    {comment.text}

  • ))}
)} {isEnrolled ? (