"use client"; import { useDevice } from "@/lib/context/DeviceContext"; import React, { useEffect, useState } from "react"; export default function PostsPage() { const [postText, setPostText] = useState(""); const [posts, setPosts] = useState([]); const [userReactions, setUserReactions] = useState<{ [index: number]: { liked: boolean; warned: boolean }; }>({}); const [imageFile, setImageFile] = useState(null); const { isAuthenticated, session } = useDevice(); useEffect(() => { if (isAuthenticated && session?.username) { fetch(`/api/user/${session.username}`).then((res) => res.json()); } }, [isAuthenticated, session?.username]); const handlePostSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!imageFile) { alert("Please select an image to upload."); return; } const formData = new FormData(); formData.append("image", imageFile); formData.append("text", postText); try { const response = await fetch("/api/post", { method: "POST", body: formData, }); const data = await response.json(); if (response.ok) { alert("Post uploaded successfully!"); setPosts([data.postData, ...posts]); setPostText(""); setImageFile(null); } else { alert(data.message || "Failed to upload post."); } } catch (error) { console.error("Error uploading post:", error); alert("An error occurred while uploading the post."); } }; const handleLike = (index: number) => { const updatedPosts = [...posts]; const reactions = { ...userReactions }; const alreadyLiked = reactions[index]?.liked; updatedPosts[index].likes += alreadyLiked ? -1 : 1; reactions[index] = { ...reactions[index], liked: !alreadyLiked, }; setPosts(updatedPosts); setUserReactions(reactions); }; const handleWarning = (index: number) => { const updatedPosts = [...posts]; const reactions = { ...userReactions }; const alreadyWarned = reactions[index]?.warned; updatedPosts[index].warnings += alreadyWarned ? -1 : 1; reactions[index] = { ...reactions[index], warned: !alreadyWarned, }; setPosts(updatedPosts); setUserReactions(reactions); }; return (

Posts