"use client"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useState, useRef, useEffect } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { PlayerAvatar } from "@/components/PlayerAvatar"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; type ChatMessage = { time: string; type: "chat" | "join" | "leave" | "death" | "server"; player: string; message: string; }; export function ChatBridge() { const queryClient = useQueryClient(); const chatRef = useRef(null); const [message, setMessage] = useState(""); const autoScrollRef = useRef(true); const { data: messages = [] } = useQuery({ queryKey: ["chat"], queryFn: () => fetch("/api/chat?lines=50").then((r) => r.json()), refetchInterval: 5000, staleTime: 2000, }); const send = useMutation({ mutationFn: async (msg: string) => { const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: msg }), }); if (!res.ok) throw new Error("Failed to send"); return res.json(); }, onSuccess: () => { setMessage(""); autoScrollRef.current = true; setTimeout(() => queryClient.invalidateQueries({ queryKey: ["chat"] }), 500); }, }); useEffect(() => { if (chatRef.current && autoScrollRef.current) { chatRef.current.scrollTop = chatRef.current.scrollHeight; } }, [messages]); const handleScroll = () => { if (!chatRef.current) return; const { scrollTop, scrollHeight, clientHeight } = chatRef.current; autoScrollRef.current = scrollHeight - scrollTop - clientHeight < 60; }; const handleSend = () => { const msg = message.trim(); if (!msg) return; send.mutate(msg); }; const typeColors: Record = { chat: "text-foreground", join: "text-emerald-300", leave: "text-amber-300", death: "text-red-300", server: "text-blue-300", }; const MAX_NAME = 16; const truncateName = (n: string) => n.length > MAX_NAME ? `${n.slice(0, MAX_NAME - 1)}…` : n; return ( Chat Bridge Live in-game chat — auto-refreshes every 3 seconds {/* Chat window */}
{messages.length === 0 ? (

No chat messages yet

) : ( messages.map((msg, i) => { const hasPlayer = msg.type !== "server"; const shortName = truncateName(msg.player); return (
{msg.time} {hasPlayer ? ( ) : (
S
)} {msg.type === "chat" ? ( <>{shortName} {msg.message} ) : msg.type === "join" ? ( <>{shortName} joined the game ) : msg.type === "leave" ? ( <>{shortName} left the game ) : msg.type === "death" ? ( <>{shortName} {msg.message} ) : ( <>[Server] {msg.message} )}
); }) )}
{/* Send message */}
setMessage(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") handleSend(); }} maxLength={256} className="flex-1" />
); }