'use client' import { useState, useEffect, useCallback } from 'react' import { useSocket, useCommentTyping } from '@/hooks/useSocket' import { useAuthStore } from '@/store/authStore' import Link from 'next/link' import api from '@/services/api' import TypingIndicator from './TypingIndicator' import MentionInput from './MentionInput' interface Comment { id: string content: string createdAt: string likesCount: number user?: { id: string username: string avatar?: string } } interface RealTimeCommentsProps { postId: string initialComments?: Comment[] onCommentCountChange?: (count: number) => void } export default function RealTimeComments({ postId, initialComments = [], onCommentCountChange, }: RealTimeCommentsProps) { const { user, isAuthenticated } = useAuthStore() const { subscribeToPost, unsubscribeFromPost, onNewComment, onCommentUpdate, onCommentRemoved, onCommentLikeUpdate, isConnected, } = useSocket() const { typingUsers, handleTyping, stopTyping } = useCommentTyping(postId) const [comments, setComments] = useState(initialComments) const [newComment, setNewComment] = useState('') const [submitting, setSubmitting] = useState(false) const [likedComments, setLikedComments] = useState>(new Set()) // Subscribe to post when component mounts useEffect(() => { if (isConnected) { subscribeToPost(postId) return () => unsubscribeFromPost(postId) } }, [postId, isConnected, subscribeToPost, unsubscribeFromPost]) // Listen for real-time events useEffect(() => { const unsubNewComment = onNewComment((data) => { if (data.postId !== postId) return setComments((prev) => { // Avoid duplicates if (prev.some((c) => c.id === data.comment.id)) return prev const newList = [data.comment, ...prev] onCommentCountChange?.(newList.length) return newList }) }) const unsubUpdate = onCommentUpdate((data) => { if (data.postId !== postId) return setComments((prev) => prev.map((c) => c.id === data.commentId ? { ...c, content: data.content } : c ) ) }) const unsubRemoved = onCommentRemoved((data) => { if (data.postId !== postId) return setComments((prev) => { const newList = prev.filter((c) => c.id !== data.commentId) onCommentCountChange?.(newList.length) return newList }) }) const unsubLike = onCommentLikeUpdate((data) => { if (data.postId !== postId) return setComments((prev) => prev.map((c) => c.id === data.commentId ? { ...c, likesCount: data.newCount } : c ) ) if (data.userId === user?.id) { setLikedComments((prev) => { const newSet = new Set(prev) if (data.liked) { newSet.add(data.commentId) } else { newSet.delete(data.commentId) } return newSet }) } }) return () => { unsubNewComment() unsubUpdate() unsubRemoved() unsubLike() } }, [postId, user?.id, onNewComment, onCommentUpdate, onCommentRemoved, onCommentLikeUpdate, onCommentCountChange]) const handleSubmit = async (e?: React.FormEvent) => { e?.preventDefault() if (!newComment.trim() || submitting) return setSubmitting(true) stopTyping() try { const { data } = await api.post(`/posts/${postId}/comments`, { content: newComment, }) // Optimistically add the comment (real-time will also broadcast it) setComments((prev) => [data, ...prev]) onCommentCountChange?.(comments.length + 1) setNewComment('') } catch (error) { console.error('Failed to submit comment:', error) } finally { setSubmitting(false) } } const handleLike = async (commentId: string) => { if (!isAuthenticated) return // Optimistic update const isLiked = likedComments.has(commentId) setLikedComments((prev) => { const newSet = new Set(prev) if (isLiked) { newSet.delete(commentId) } else { newSet.add(commentId) } return newSet }) setComments((prev) => prev.map((c) => c.id === commentId ? { ...c, likesCount: c.likesCount + (isLiked ? -1 : 1) } : c ) ) try { await api.post(`/posts/${postId}/comments/${commentId}/like`) } catch (error) { // Rollback on error setLikedComments((prev) => { const newSet = new Set(prev) if (isLiked) { newSet.add(commentId) } else { newSet.delete(commentId) } return newSet }) setComments((prev) => prev.map((c) => c.id === commentId ? { ...c, likesCount: c.likesCount + (isLiked ? 1 : -1) } : c ) ) } } const handleDelete = async (commentId: string) => { if (!confirm('Delete this comment?')) return try { await api.delete(`/posts/${postId}/comments/${commentId}`) setComments((prev) => prev.filter((c) => c.id !== commentId)) onCommentCountChange?.(comments.length - 1) } catch (error) { console.error('Failed to delete comment:', error) } } 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() } return (
{/* Comment Input */} {isAuthenticated && (
{ setNewComment(value) handleTyping() }} placeholder="Write a comment..." maxLength={500} rows={2} onSubmit={handleSubmit} />
{typingUsers.length > 0 && ( )}
)} {/* Connection Status */} {!isConnected && isAuthenticated && (
Connecting for real-time updates...
)} {/* Comments List */}
{comments.map((comment) => { const isLiked = likedComments.has(comment.id) const isOwner = user?.id === comment.user?.id return (
{comment.user?.avatar ? ( {comment.user.username} ) : (
{comment.user?.username?.[0]?.toUpperCase() || '?'}
)}
{comment.user?.username || 'Unknown'} {formatTime(comment.createdAt)}

{comment.content}

{isOwner && ( )}
) })}
{comments.length === 0 && (

No comments yet. Be the first to comment!

)}
) }