"use client"; import { useActionState, useRef, useEffect, useState, useCallback, useMemo, } from "react"; import Image from "next/image"; import { createClient } from "@/utils/supabase/client"; import type { Message } from "@/types/chat"; import { sendMessageAction, decryptMessageAction, type SendMessageState, } from "./actions"; import type { MemberInfo } from "./member-map"; const initialState: SendMessageState = null; // Prefix for temporary optimistic IDs const OPTIMISTIC_PREFIX = "optimistic-"; export function Chat({ roomId, initialMessages, currentUserId, memberMap, }: { roomId: string; initialMessages: Message[]; currentUserId: string; memberMap: Map; }) { const boundAction = sendMessageAction.bind(null, roomId); const [state, action, pending] = useActionState(boundAction, initialState); const formRef = useRef(null); const bottomRef = useRef(null); const optimisticCounter = useRef(0); const [localMessages, setLocalMessages] = useState([]); // Merge server messages (prop) with local messages (optimistic + realtime) // Server messages that match local optimistic ones by user+value are replaced // by the local version (which may have a real ID from realtime confirmation) const messages = useMemo(() => { const serverIds = new Set(initialMessages.map((m) => m.id)); const optimisticConfirmed = new Set(); for (const local of localMessages) { if (!local.id.startsWith(OPTIMISTIC_PREFIX) && !serverIds.has(local.id)) { const match = initialMessages.find( (s) => s.user_id === local.user_id && s.value === local.value, ); if (match) optimisticConfirmed.add(match.id); } } const serverFiltered = initialMessages.filter( (m) => !optimisticConfirmed.has(m.id), ); const localFiltered = localMessages.filter((m) => { if (serverIds.has(m.id)) return false; if (m.id.startsWith(OPTIMISTIC_PREFIX)) { const serverValues = new Set( initialMessages .filter((s) => s.user_id === m.user_id) .map((s) => s.value), ); if (serverValues.has(m.value)) return false; } return true; }); const merged = [...serverFiltered, ...localFiltered]; merged.sort( (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime(), ); return merged; }, [initialMessages, localMessages]); const scrollToBottom = useCallback(() => { bottomRef.current?.scrollIntoView({ behavior: "smooth" }); }, []); const messageCount = messages.length; useEffect(() => { scrollToBottom(); }, [messageCount, scrollToBottom]); // Clear input after successful send useEffect(() => { if (state !== null && !("error" in state) && !pending) { formRef.current?.reset(); } }, [state, pending]); const handleAction = useCallback( (formData: FormData) => { const value = formData.get("message"); if (typeof value === "string" && value.trim()) { const tempId = `${OPTIMISTIC_PREFIX}${++optimisticCounter.current}`; const optimisticMsg: Message = { id: tempId, value: value.trim(), created_at: new Date().toISOString(), user_id: currentUserId, room_id: roomId, user: { name: memberMap.get(currentUserId)?.name ?? "You", avatar_url: memberMap.get(currentUserId)?.avatar_url ?? null, }, }; setLocalMessages((prev) => [optimisticMsg, ...prev]); } action(formData); }, [action, currentUserId, roomId, memberMap], ); useEffect(() => { const supabase = createClient(); const channel = supabase .channel(`room-messages:${roomId}`) .on( "postgres_changes", { event: "INSERT", schema: "public", table: "messages", filter: `room_id=eq.${roomId}`, }, (payload: { new: Record }) => { const realId = payload.new.id; const realUserId = payload.new.user_id; if (realUserId === currentUserId) { // Own message confirmed by server — swap optimistic ID → real ID setLocalMessages((prev) => { if (prev.some((m) => m.id === realId)) return prev; const optimisticIdx = prev.findIndex( (m) => m.id.startsWith(OPTIMISTIC_PREFIX) && m.user_id === currentUserId, ); if (optimisticIdx !== -1) { const updated = [...prev]; updated[optimisticIdx] = { ...updated[optimisticIdx], id: realId, created_at: payload.new.created_at, }; return updated; } return prev; }); } else { // Other user's message — decrypt via server action void decryptMessageAction( roomId, payload.new.value, payload.new.iv ?? "", payload.new.auth_tag ?? "", ).then((result) => { if ("plaintext" in result) { const msg: Message = { id: realId, value: result.plaintext, created_at: payload.new.created_at, user_id: realUserId, room_id: payload.new.room_id, user: { name: memberMap.get(realUserId)?.name ?? "Unknown", avatar_url: memberMap.get(realUserId)?.avatar_url ?? null, }, }; setLocalMessages((prev) => { if (prev.some((m) => m.id === realId)) return prev; return [msg, ...prev]; }); } }); } }, ) .subscribe(); return () => { void supabase.removeChannel(channel); }; }, [roomId, memberMap, currentUserId]); const displayMessages = [...messages].reverse(); return (
{/* Messages area */}
{displayMessages.length === 0 ? (

No messages yet. Start the conversation!

) : (
{displayMessages.map((msg) => { const isOwn = msg.user_id === currentUserId; const isPending = msg.id.startsWith(OPTIMISTIC_PREFIX); return (
{!isOwn && (
{msg.user?.name ?? "Unknown"}
)}

{msg.value}

{isPending ? "Sending..." : formatTime(msg.created_at)}

); })}
)}
{/* Send bar */}
{state && "error" in state && (

{state.error}

)}
); } function formatTime(isoString: string): string { const date = new Date(isoString); return date.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", }); } function Avatar({ name, avatarUrl, size = "md", }: { name: string; avatarUrl: string | null; size?: "sm" | "md"; }) { const sizeClass = size === "sm" ? "size-5" : "size-8"; const textSize = size === "sm" ? "text-[10px]" : "text-xs"; if (avatarUrl) { return ( ); } return (
{name.charAt(0).toUpperCase()}
); }