"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { toast } from "sonner"; import { useTranslations } from "next-intl"; import { Send } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { cn } from "@/lib/utils"; type Message = { id: string; content: string; senderId: string; createdAt: string; }; export function MessageThread({ conversationId, currentUserId, }: { conversationId: string; currentUserId: string; }) { const t = useTranslations("messages"); const [messages, setMessages] = useState([]); const [loading, setLoading] = useState(true); const [content, setContent] = useState(""); const [sending, setSending] = useState(false); const bottomRef = useRef(null); const load = useCallback(async () => { const res = await fetch(`/api/v1/conversations/${conversationId}/messages`); if (res.ok) { const data = (await res.json()) as { messages: Message[] }; setMessages(data.messages); } setLoading(false); }, [conversationId]); useEffect(() => { void load(); const interval = setInterval(() => { void load(); }, 5000); return () => clearInterval(interval); }, [load]); useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages.length]); async function send() { if (!content.trim()) return; setSending(true); try { const res = await fetch(`/api/v1/conversations/${conversationId}/messages`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content: content.trim() }), }); if (!res.ok) { const err = await res.json().catch(() => ({})) as { error?: string }; toast.error(err.error ?? t("sendFailed")); return; } setContent(""); await load(); } finally { setSending(false); } } return (
{loading ? (

{t("loading")}

) : messages.length === 0 ? (

{t("noMessagesYet")}

) : ( messages.map((m) => { const isOwn = m.senderId === currentUserId; return (
{m.content}
); }) )}