"use client"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { KycDrawer } from "@/app/components/kyc/KycDrawer"; import { Button } from "@/app/components/ui/button"; import { ErrorState } from "@/app/components/ui/states"; import { Textarea } from "@/app/components/ui/textarea"; import { ImageAttachments, useAttachments } from "@/app/components/messages/ImageAttachments"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { formatDateTime } from "@/app/lib/format"; import { MAX_BODY, adminMessageImageUrl, getAdminConversation, listAdminMessages, markAdminRead, messageErrorText, sendAdminMessage, type ConversationView, type MessageView, } from "@/app/lib/services/adminMessages"; const POLL_MS = 15_000; /** Merge by uuid (a poll and an in-flight send can both return the same message), oldest first. */ export function mergeMessages(cur: MessageView[], incoming: MessageView[]): MessageView[] { const byId = new Map(cur.map((m) => [m.uuid, m])); for (const m of incoming) byId.set(m.uuid, m); return [...byId.values()].sort((a, b) => a.seq - b.seq); // seq, not createdAt: whole seconds, ties are common } const oldestFirst = (items: MessageView[]) => [...items].reverse(); // the API returns newest first export function MessageThreadDrawer({ uuid, onClose, onChanged, initialDraft }: { uuid: string; onClose: () => void; onChanged: () => void; initialDraft?: string }) { const t = useT(); const [head, setHead] = useState(null); const [messages, setMessages] = useState([]); const [hasMore, setHasMore] = useState(false); const [error, setError] = useState(null); const [body, setBody] = useState(initialDraft ?? ""); const [sending, setSending] = useState(false); const [sendError, setSendError] = useState(null); const [loadingOlder, setLoadingOlder] = useState(false); const [olderError, setOlderError] = useState(null); const attachments = useAttachments(); // `onChanged` is a fresh closure each parent render; a ref keeps the effects below from re-running. const onChangedRef = useRef(onChanged); useEffect(() => { onChangedRef.current = onChanged; }, [onChanged]); const known = useRef(new Set()); useEffect(() => { known.current = new Set(messages.map((m) => m.uuid)); }, [messages]); const markRead = useCallback(() => { markAdminRead(uuid) .then(() => onChangedRef.current()) .catch(() => { /* the unread dot just stays until the next open */ }); }, [uuid]); useEffect(() => { let cancelled = false; Promise.all([getAdminConversation(uuid), listAdminMessages(uuid)]) .then(([h, page]) => { if (cancelled) return; setHead(h); setMessages((cur) => mergeMessages(cur, oldestFirst(page.items))); setHasMore(page.hasMore); markRead(); }) .catch(() => { if (!cancelled) setError(t("MsgThreadFailed")); }); return () => { cancelled = true; }; }, [uuid, markRead]); // Poll only while the tab is visible; merge by uuid; clear unread when a member message arrives. useEffect(() => { const id = setInterval(() => { if (document.visibilityState !== "visible") return; listAdminMessages(uuid) .then((page) => { const fresh = page.items.filter((m) => !known.current.has(m.uuid)); if (fresh.length === 0) return; setMessages((cur) => mergeMessages(cur, oldestFirst(page.items))); if (fresh.some((m) => m.senderType === "M")) markRead(); }) .catch(() => { /* transient: the next tick retries */ }); }, POLL_MS); return () => clearInterval(id); }, [uuid, markRead]); const loadOlder = () => { const oldest = messages[0]; if (!oldest || loadingOlder) return; setLoadingOlder(true); setOlderError(null); listAdminMessages(uuid, oldest.uuid) .then((page) => { setMessages((cur) => mergeMessages(cur, oldestFirst(page.items))); setHasMore(page.hasMore); }) // Inline and retryable: a failed older page must not replace the thread or the reply box. .catch(() => setOlderError(t("MsgThreadFailed"))) .finally(() => setLoadingOlder(false)); }; // Scroll only the message pane: keep the reader's place when older messages load above, and follow new // messages only when they are mine (admin) or the reader is already near the bottom. const pane = useRef(null); const nearBottom = useRef(true); const lastHeight = useRef(0); const oldestUuid = messages[0]?.uuid; const newest = messages[messages.length - 1]; useLayoutEffect(() => { const el = pane.current; if (el && lastHeight.current) el.scrollTop += el.scrollHeight - lastHeight.current; }, [oldestUuid]); useLayoutEffect(() => { const el = pane.current; if (el && (nearBottom.current || newest?.senderType === "A")) el.scrollTop = el.scrollHeight; }, [newest?.uuid]); // eslint-disable-line react-hooks/exhaustive-deps -- only a new newest message scrolls useLayoutEffect(() => { if (pane.current) lastHeight.current = pane.current.scrollHeight; }); const canSend = !sending && !attachments.busy && body.length <= MAX_BODY && (body.trim() !== "" || attachments.refs.length > 0); const send = async () => { setSending(true); setSendError(null); const refs = attachments.refs; // snapshot: only these went out try { const m = await sendAdminMessage(uuid, body.trim(), refs); setMessages((cur) => mergeMessages(cur, [m])); setBody(""); attachments.removeSent(refs); onChangedRef.current(); } catch (e) { setSendError(messageErrorText(e, t)); } finally { setSending(false); } }; const composer = (