import {useAuth} from "../contexts/AuthContext.jsx"; import {useRef, useState} from "react"; export default function Comment({ comment, index, videoId, refetchVideo, doShowCommands=true }) { let {user, isAuthenticated} = useAuth(); let commentRef = useRef(); let [editMode, setEditMode] = useState(false); let editClass = "glassmorphism rounded-md p-4 mb-3 text-white focus:outline-none"; const handleEdit = () => { setEditMode(true); const commentElement = commentRef.current; commentElement.contentEditable = true; } const handleDelete = async (id) => { try { const token = localStorage.getItem('token'); const response = await fetch(`/api/comments/${id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } }); if (response.ok) { // Refresh the video data to update the comments list refetchVideo(); } } catch (error) { console.error('Error deleting comment:', error); } } const handleEditSubmit = async (id, content) => { if (!content.trim()) { alert("Comment cannot be empty"); return; } try { // Retrieve the token from localStorage const token = localStorage.getItem('token'); if (!token) { navigation('/login'); return; } const response = await fetch(`/api/comments/${comment.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ content: content, video: videoId }) }); if (!response.ok) { throw new Error('Failed to post comment'); } setEditMode(false); } catch (error) { console.error('Error posting comment:', error); } } return (
{comment.username} {comment.username} {new Date(comment.created_at).toLocaleDateString()}

{comment.content}

{ doShowCommands && (
{ isAuthenticated && user.username === comment.username && editMode === false ? ( ) : null } { isAuthenticated && user.username === comment.username && editMode === false ? ( ) : null } { isAuthenticated && user.username === comment.username && editMode ? ( ) : null } { isAuthenticated && user.username === comment.username && editMode ? ( ) : null }
) }
) }