'use client' import { useState, useCallback } from 'react' import { useAuthStore } from '@/store/authStore' import Link from 'next/link' import api from '@/services/api' import { linkifyText } from '@/utils/linkify' import { WhoCanReplyNotice } from '@/components/WhoCanReply' import { normalizeReplyPermission, type ReplyPermission } from '@/services/postService' interface Comment { id: string content: string createdAt: string likesCount: number isPinned?: boolean parentId?: string user?: { id: string username: string avatar?: string } replies?: Comment[] _count?: { likes: number replies: number } } interface CommentThreadProps { postId: string comments: Comment[] onCommentAdded?: (comment: Comment) => void onCommentDeleted?: (commentId: string) => void /** Threadgate — who may reply. Defaults to everyone when unset. */ replyPermission?: ReplyPermission } export default function CommentThread({ postId, comments, onCommentAdded, onCommentDeleted, replyPermission, }: CommentThreadProps) { const { user, isAuthenticated } = useAuthStore() const effectiveReplyPermission = normalizeReplyPermission(replyPermission) const repliesDisabled = effectiveReplyPermission === 'nobody' const [replyingTo, setReplyingTo] = useState(null) const [replyContent, setReplyContent] = useState('') const [submitting, setSubmitting] = useState(false) const [expandedReplies, setExpandedReplies] = useState>(new Set()) const [likedComments, setLikedComments] = useState>(new Set()) const handleLike = useCallback(async (commentId: string) => { if (!isAuthenticated) return try { await api.post(`/posts/${postId}/comments/${commentId}/like`) setLikedComments(prev => { const newSet = new Set(prev) if (newSet.has(commentId)) { newSet.delete(commentId) } else { newSet.add(commentId) } return newSet }) } catch (error) { console.error('Like comment error:', error) } }, [isAuthenticated, postId]) const handleReply = async (parentId: string) => { if (!replyContent.trim() || submitting) return setSubmitting(true) try { const { data } = await api.post(`/posts/${postId}/comments/${parentId}/reply`, { content: replyContent, }) setReplyContent('') setReplyingTo(null) if (onCommentAdded) { onCommentAdded(data) } // Expand replies to show the new one setExpandedReplies(prev => new Set(prev).add(parentId)) } catch (error) { console.error('Reply error:', error) } finally { setSubmitting(false) } } const handleDelete = async (commentId: string) => { if (!confirm('Delete this comment?')) return try { await api.delete(`/posts/${postId}/comments/${commentId}`) if (onCommentDeleted) { onCommentDeleted(commentId) } } catch (error) { console.error('Delete comment error:', error) } } const toggleReplies = (commentId: string) => { setExpandedReplies(prev => { const newSet = new Set(prev) if (newSet.has(commentId)) { newSet.delete(commentId) } else { newSet.add(commentId) } return newSet }) } const formatTime = (dateString: string) => { const date = new Date(dateString) const now = new Date() const diffMs = now.getTime() - date.getTime() const diffMins = Math.floor(diffMs / (1000 * 60)) const diffHours = Math.floor(diffMs / (1000 * 60 * 60)) const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)) if (diffMins < 1) return 'now' if (diffMins < 60) return `${diffMins}m` if (diffHours < 24) return `${diffHours}h` if (diffDays < 7) return `${diffDays}d` return date.toLocaleDateString() } const renderComment = (comment: Comment, depth = 0) => { const isLiked = likedComments.has(comment.id) const hasReplies = (comment._count?.replies || comment.replies?.length || 0) > 0 const isExpanded = expandedReplies.has(comment.id) const isOwner = user?.id === comment.user?.id return (
0 ? 'ml-8 border-l-2 border-border pl-4' : ''}`} >
{comment.user?.avatar ? ( {comment.user.username} ) : (
{comment.user?.username?.[0]?.toUpperCase() || '?'}
)}
{comment.user?.username || 'Unknown'} {comment.isPinned && ( Pinned )} {formatTime(comment.createdAt)}

{linkifyText(comment.content)}

{isAuthenticated && depth < 3 && !repliesDisabled && ( )} {hasReplies && ( )} {isOwner && ( )}
{/* Reply input */} {replyingTo === comment.id && (
setReplyContent(e.target.value)} placeholder={`Reply to @${comment.user?.username}...`} className="flex-1 px-3 py-2 bg-muted rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary" onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() handleReply(comment.id) } }} autoFocus />
)}
{/* Render replies */} {isExpanded && comment.replies && comment.replies.length > 0 && (
{comment.replies.map(reply => renderComment(reply, depth + 1))}
)}
) } // Sort comments: pinned first, then by date const sortedComments = [...comments].sort((a, b) => { if (a.isPinned && !b.isPinned) return -1 if (!a.isPinned && b.isPinned) return 1 return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime() }) // Filter to only root comments (no parentId) const rootComments = sortedComments.filter(c => !c.parentId) return (
{effectiveReplyPermission !== 'everyone' && (
)}
{rootComments.map(comment => renderComment(comment))}
) }