"use client"; import { useEffect, useRef, useState } from "react"; import Link from "next/link"; import { ArrowLeft, Check, CheckCheck, Clock, FileText, MapPin } from "lucide-react"; import { Button } from "@/app/components/ui/button"; import { ErrorState } from "@/app/components/ui/states"; import { ApiError } from "@/app/lib/clientApi"; import { usePolling } from "@/app/lib/hooks/usePolling"; import { assignConversation, getThread, listAssignees, markRead, mediaUrl, sendText, type WhatsAppConversation, type WhatsAppMessage, } from "@/app/lib/services/whatsapp"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { cn } from "@/app/lib/utils"; import { contactLabel, shortTime } from "./ConversationList"; import { TemplatePicker } from "./TemplatePicker"; const HOUR = 3600_000; /** * Older pages, then the latest page, then messages sent here that no poll has returned yet; each uuid once. * The server's copy wins over the one kept from the send, so delivery ticks move on. */ function merge(older: WhatsAppMessage[], latest: WhatsAppMessage[], local: WhatsAppMessage[]) { const byUuid = new Map(); for (const m of [...older, ...latest]) byUuid.set(m.uuid, m); for (const m of local) if (!byUuid.has(m.uuid)) byUuid.set(m.uuid, m); return [...byUuid.values()]; } type Props = { uuid: string; companyId: number | undefined; admin: boolean; onBack: () => void }; /** One chat: header, bubbles and composer. Keyed by uuid in the page, so a new chat starts clean. */ export function Thread({ uuid, companyId, admin, onBack }: Props) { const t = useT(); const [conv, setConv] = useState(null); const [latest, setLatest] = useState([]); const [older, setOlder] = useState([]); const [local, setLocal] = useState([]); const [hasOlder, setHasOlder] = useState(false); const [failed, setFailed] = useState(false); const [notice, setNotice] = useState(null); const [text, setText] = useState(""); const [sending, setSending] = useState(false); const [picker, setPicker] = useState(false); // When the last poll returned: the window countdown reads it instead of the clock during render. const [polledAt, setPolledAt] = useState(0); const loadedOlder = useRef(false); const bottom = useRef(null); const load = () => getThread(uuid, undefined, companyId).then( (r) => { setConv(r.conversation); setPolledAt(Date.now()); setLatest(r.messages); setFailed(false); if (!loadedOlder.current) setHasOlder(r.hasOlder); if (r.conversation.unreadCount > 0) { markRead(uuid, companyId).then(() => window.dispatchEvent(new Event("whatsapp-unread-changed")), () => {}); } }, () => setFailed(true), ); // ponytail: polling every 10 s while open; server-sent events if replies must feel instant. usePolling(load, 10_000); const messages = merge(older, latest, local); const lastUuid = messages[messages.length - 1]?.uuid; useEffect(() => { bottom.current?.scrollIntoView?.({ block: "end" }); }, [lastUuid]); const loadOlder = () => { const first = messages[0]; if (!first) return; getThread(uuid, first.uuid, companyId).then((r) => { loadedOlder.current = true; setOlder((o) => [...r.messages, ...o]); setHasOlder(r.hasOlder); }, () => setNotice(t("WaThreadFailed"))); }; const send = (body: string, clear: boolean) => { setSending(true); setNotice(null); sendText(uuid, body, companyId) .then((m) => { setLocal((l) => [...l, m]); if (clear) setText(""); }) .catch((err: unknown) => { const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined; if (code === "WINDOW_CLOSED") { setNotice(t("WaWindowClosedNow")); load(); } else setNotice(t("WaSendFailed")); }) .finally(() => setSending(false)); }; if (failed && !conv) return ; if (!conv) return
; const hoursLeft = conv.lastInboundAt ? Math.ceil((Date.parse(conv.lastInboundAt) + 24 * HOUR - polledAt) / HOUR) : 0; return (

{contactLabel(conv)}

{conv.contactName && +{conv.contactWaId}} {conv.leadUuid && ( <> {conv.contactName && " ยท "} {conv.leadName || t("WaLead")} )}

{admin ? ( ) : ( {t("WaOwnerIs", { name: conv.ownerName ?? t("WaUnassigned") })} )} {conv.windowOpen ? t("WaWindowOpen", { h: Math.max(hoursLeft, 1) }) : t("WaWindowClosed")}
{hasOlder && (
)}
    {messages.map((m) => ( send(m.body!, false) : undefined} /> ))}
{notice &&

{notice}

} {conv.windowOpen ? (
{ e.preventDefault(); if (text.trim()) send(text.trim(), true); }} >