@channelhub/widget 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/ChannelHubChannels.d.ts +15 -0
  2. package/dist/ChannelHubChannels.d.ts.map +1 -0
  3. package/dist/ChannelHubInbox.d.ts +3 -0
  4. package/dist/ChannelHubInbox.d.ts.map +1 -0
  5. package/dist/LiveChatWidget.d.ts +12 -0
  6. package/dist/LiveChatWidget.d.ts.map +1 -0
  7. package/dist/api.d.ts +20 -0
  8. package/dist/api.d.ts.map +1 -0
  9. package/dist/channels/ProviderLogo.d.ts +8 -0
  10. package/dist/channels/ProviderLogo.d.ts.map +1 -0
  11. package/dist/components/ui/avatar.d.ts +8 -0
  12. package/dist/components/ui/avatar.d.ts.map +1 -0
  13. package/dist/components/ui/button.d.ts +5 -0
  14. package/dist/components/ui/button.d.ts.map +1 -0
  15. package/dist/components/ui/index.d.ts +6 -0
  16. package/dist/components/ui/index.d.ts.map +1 -0
  17. package/dist/components/ui/input.d.ts +3 -0
  18. package/dist/components/ui/input.d.ts.map +1 -0
  19. package/dist/components/ui/scroll-area.d.ts +6 -0
  20. package/dist/components/ui/scroll-area.d.ts.map +1 -0
  21. package/dist/components/ui/textarea.d.ts +3 -0
  22. package/dist/components/ui/textarea.d.ts.map +1 -0
  23. package/dist/facebook_icon.avif +0 -0
  24. package/dist/index.cjs +99 -0
  25. package/dist/index.d.ts +6 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +1975 -0
  28. package/dist/instagram_icon.avif +0 -0
  29. package/dist/livechat-standalone.d.ts +23 -0
  30. package/dist/livechat-standalone.d.ts.map +1 -0
  31. package/dist/standalone.d.ts +22 -0
  32. package/dist/standalone.d.ts.map +1 -0
  33. package/dist/telegram_icon.avif +0 -0
  34. package/dist/types.d.ts +66 -0
  35. package/dist/types.d.ts.map +1 -0
  36. package/dist/web.avif +0 -0
  37. package/dist/zalo_icon.avif +0 -0
  38. package/package.json +45 -3
  39. package/public/facebook_icon.avif +0 -0
  40. package/public/instagram_icon.avif +0 -0
  41. package/public/telegram_icon.avif +0 -0
  42. package/public/web.avif +0 -0
  43. package/public/zalo_icon.avif +0 -0
  44. package/src/ChannelHubChannels.tsx +941 -0
  45. package/src/ChannelHubInbox.tsx +769 -0
  46. package/src/LiveChatWidget.tsx +380 -0
  47. package/src/api.ts +84 -0
  48. package/src/assets/facebook_icon.avif +0 -0
  49. package/src/assets/instagram_icon.avif +0 -0
  50. package/src/assets/telegram_icon.avif +0 -0
  51. package/src/assets/web.avif +0 -0
  52. package/src/assets/zalo_icon.avif +0 -0
  53. package/src/assets.d.ts +4 -0
  54. package/src/channels/ProviderLogo.tsx +59 -0
  55. package/src/components/ui/avatar.tsx +2 -0
  56. package/src/components/ui/button.tsx +4 -0
  57. package/src/components/ui/index.ts +5 -0
  58. package/src/components/ui/input.tsx +2 -0
  59. package/src/components/ui/scroll-area.tsx +5 -0
  60. package/src/components/ui/textarea.tsx +2 -0
  61. package/src/index.ts +8 -0
  62. package/src/livechat-standalone.tsx +75 -0
  63. package/src/standalone.tsx +68 -0
  64. package/src/types.ts +65 -0
  65. package/tsconfig.json +14 -0
  66. package/vite.config.ts +76 -0
  67. package/README.md +0 -3
@@ -0,0 +1,769 @@
1
+ import { FormEvent, createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
2
+ import { createPortal } from 'react-dom';
3
+ import { AlertCircle, Check, CheckCheck, ChevronDown, ChevronRight, Inbox, Info, Loader2, MoreHorizontal, Paperclip, Play, Search, Send, SlidersHorizontal, X } from 'lucide-react';
4
+ import { ChannelHubClient } from './api.js';
5
+ import type { ChannelHubInboxHandle, Connection, Conversation, Message, MessageAttachment, Page, Provider, WidgetProps } from './types.js';
6
+
7
+ type WidgetTranslations = { today: string; loadOlder: string; loading: string; noMessages: string; searchPlaceholder: string; unreadOnly: string; sendPlaceholder: string; send: string; all: string };
8
+ import { Avatar as UiAvatar, Button, Input, ScrollArea, Textarea } from './components/ui/index.js';
9
+
10
+ const c = { ink: '#172033', muted: '#718096', line: '#e7ebf2', surface: '#f7f9fc', white: '#fff' };
11
+ const ApiUrlCtx = createContext('');
12
+ const TokenCtx = createContext('');
13
+
14
+ function playNotificationSound() {
15
+ try {
16
+ const ctx = new AudioContext();
17
+ const osc = ctx.createOscillator();
18
+ const gain = ctx.createGain();
19
+ osc.connect(gain);
20
+ gain.connect(ctx.destination);
21
+ osc.type = 'sine';
22
+ osc.frequency.setValueAtTime(880, ctx.currentTime);
23
+ osc.frequency.exponentialRampToValueAtTime(660, ctx.currentTime + 0.12);
24
+ gain.gain.setValueAtTime(0.25, ctx.currentTime);
25
+ gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.35);
26
+ osc.start(ctx.currentTime);
27
+ osc.stop(ctx.currentTime + 0.35);
28
+ } catch {
29
+ // AudioContext blocked (no prior user interaction) — silently skip
30
+ }
31
+ }
32
+
33
+ function connectionDisplayName(c?: Connection): string | undefined {
34
+ if (!c?.metadata) return undefined;
35
+ const m = c.metadata as Record<string, unknown>;
36
+ const v = m['pageName'] ?? m['displayName'] ?? m['username'] ?? m['name'];
37
+ return typeof v === 'string' && v ? v : undefined;
38
+ }
39
+
40
+ function providerLabel(p?: Provider): string {
41
+ if (p === 'facebook') return 'Facebook Messenger';
42
+ if (p === 'instagram') return 'Instagram';
43
+ if (p === 'telegram') return 'Telegram';
44
+ if (p === 'zalo') return 'Zalo OA';
45
+ return 'Channel';
46
+ }
47
+
48
+ function providerShortLabel(p?: Provider): string {
49
+ if (p === 'facebook') return 'Facebook';
50
+ if (p === 'instagram') return 'Instagram';
51
+ if (p === 'telegram') return 'Telegram';
52
+ if (p === 'zalo') return 'Zalo';
53
+ return String(p ?? '');
54
+ }
55
+
56
+ const mimeLabel = (mime?: string) => {
57
+ const map: Record<string, string> = {
58
+ 'application/pdf': 'PDF', 'video/mp4': 'Video MP4',
59
+ 'audio/mpeg': 'Audio MP3', 'audio/ogg': 'Audio OGG',
60
+ 'application/octet-stream': 'Tệp đính kèm',
61
+ };
62
+ if (!mime) return 'Tệp đính kèm';
63
+ return map[mime] ?? mime.split('/')[1]?.toUpperCase() ?? 'Tệp';
64
+ };
65
+
66
+ function StatusIcon({ status }: { status?: Message['status'] }) {
67
+ if (status === 'read') return <CheckCheck size={11} strokeWidth={2} style={{ display: 'inline', verticalAlign: 'middle' }} />;
68
+ if (status === 'delivered') return <CheckCheck size={11} strokeWidth={2} style={{ display: 'inline', verticalAlign: 'middle', opacity: 0.5 }} />;
69
+ if (status === 'sent') return <Check size={11} strokeWidth={2} style={{ display: 'inline', verticalAlign: 'middle' }} />;
70
+ return null;
71
+ }
72
+
73
+ type ActiveFilters = { provider: Provider | 'all'; unreadOnly: boolean };
74
+
75
+ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(function ChannelHubInbox(
76
+ { apiUrl, token, theme, height, defaultConversationId, disableAttachments, disableNotificationSound, hideKeyboardHint, locale = 'vi', onNewMessage, onConversationSelect },
77
+ ref
78
+ ) {
79
+ const client = useRef(new ChannelHubClient(apiUrl, token));
80
+ const [items, setItems] = useState<Conversation[]>([]); const [connections, setConnections] = useState<Connection[]>([]); const [cursor, setCursor] = useState<string>();
81
+ const [selected, setSelected] = useState<Conversation>(); const selectedId = useRef<string | undefined>(undefined);
82
+ const [query, setQuery] = useState('');
83
+ const [activeFilters, setActiveFilters] = useState<ActiveFilters>({ provider: 'all', unreadOnly: false });
84
+ const [filterOpen, setFilterOpen] = useState(false);
85
+ const filterBtnRef = useRef<HTMLButtonElement>(null);
86
+ const filterPopoverRef = useRef<HTMLDivElement>(null);
87
+ const [popoverAnchor, setPopoverAnchor] = useState<{ top: number; left: number } | null>(null);
88
+ const [loading, setLoading] = useState(true); const [error, setError] = useState('');
89
+ const [infoOpen, setInfoOpen] = useState(false);
90
+ const primary = theme?.primaryColor ?? '#2563eb';
91
+ const connectionById = useMemo(() => new Map(connections.map(connection => [connection.id, connection])), [connections]);
92
+ const appendMessageRef = useRef<((msg: Message) => void) | null>(null);
93
+ const [msgRefreshKey, setMsgRefreshKey] = useState(0);
94
+ const availableProviders = useMemo(() => {
95
+ const ps = new Set(connections.map(cn => cn.provider));
96
+ return (['facebook', 'instagram', 'telegram', 'zalo'] as const).filter(p => ps.has(p));
97
+ }, [connections]);
98
+ const countByProvider = useMemo(() => {
99
+ const counts: Record<string, number> = {};
100
+ for (const conv of items) {
101
+ const p = connectionById.get(conv.connectionId)?.provider ?? 'unknown';
102
+ counts[p] = (counts[p] ?? 0) + 1;
103
+ }
104
+ return counts;
105
+ }, [items, connectionById]);
106
+ const load = useCallback(async (next?: string) => { try { const page: Page<Conversation> = await client.current.listConversations(next); setItems(old => next ? [...old, ...page.items] : page.items); setCursor(page.nextCursor); if (!next && page.items.length) setSelected(old => old ?? (defaultConversationId ? (page.items.find(c => c.id === defaultConversationId) ?? page.items[0]) : page.items[0])); setError(''); } catch (e) { setError(e instanceof Error ? e.message : 'Không tải được hội thoại'); } finally { setLoading(false); } }, [defaultConversationId]);
107
+ useEffect(() => { void client.current.listConnections().then(setConnections).catch(() => undefined); void load(); const stop = client.current.connectSSE((type, data) => { if (type === 'message.new' || type === 'conversation.updated') { void load(); if (type === 'message.new') { const evtData = typeof data === 'object' && data ? data as Record<string, unknown> : {}; const evtConvId = evtData['conversationId'] ? String(evtData['conversationId']) : ''; const evtMsgId = evtData['messageId'] ? String(evtData['messageId']) : ''; const evtDirection = evtData['direction'] ? String(evtData['direction']) : ''; if (evtDirection === 'inbound' && !disableNotificationSound) playNotificationSound(); if (evtConvId && evtConvId === selectedId.current && evtMsgId && appendMessageRef.current) { const appendFn = appendMessageRef.current; void client.current.getMessage(evtMsgId).then(msg => { appendFn(msg); }).catch(() => undefined); } onNewMessage?.(evtConvId || selectedId.current || ''); } } else if (type === 'message.status_updated') { setMsgRefreshKey(k => k + 1); } }); return stop; }, [load, onNewMessage]);
108
+ useEffect(() => { selectedId.current = selected?.id; }, [selected]);
109
+ useEffect(() => { if (selected?.unreadCount) void client.current.markRead(selected.id).then(() => load()).catch(() => undefined); }, [selected?.id]); // eslint-disable-line react-hooks/exhaustive-deps
110
+
111
+ useEffect(() => {
112
+ if (!filterOpen) return;
113
+ function handleOutside(e: MouseEvent) {
114
+ if (filterBtnRef.current?.contains(e.target as Node)) return;
115
+ if (filterPopoverRef.current?.contains(e.target as Node)) return;
116
+ setFilterOpen(false);
117
+ }
118
+ document.addEventListener('mousedown', handleOutside);
119
+ return () => document.removeEventListener('mousedown', handleOutside);
120
+ }, [filterOpen]);
121
+
122
+ const visible = useMemo(() => {
123
+ const needle = query.toLowerCase().trim();
124
+ return items.filter(x => {
125
+ const label = `${x.contactName ?? ''} ${x.subject ?? ''} ${x.providerConversationKey}`.toLowerCase();
126
+ const provider = connectionById.get(x.connectionId)?.provider ?? 'unknown';
127
+ const matchProvider = activeFilters.provider === 'all' || provider === activeFilters.provider;
128
+ const matchUnread = !activeFilters.unreadOnly || (x.unreadCount ?? 0) > 0;
129
+ return matchProvider && matchUnread && (!needle || label.includes(needle));
130
+ });
131
+ }, [items, connectionById, activeFilters, query]);
132
+
133
+ const hasActiveFilters = activeFilters.provider !== 'all' || activeFilters.unreadOnly;
134
+
135
+ const t: WidgetTranslations = locale === 'en' ? {
136
+ today: 'TODAY', loadOlder: '↑ Load older messages', loading: 'Loading messages…', noMessages: 'No messages in this conversation.',
137
+ searchPlaceholder: 'Search conversations…', unreadOnly: 'Unread only', sendPlaceholder: 'Write a message…', send: 'Send', all: 'All',
138
+ } : {
139
+ today: 'HÔM NAY', loadOlder: '↑ Tải tin cũ hơn', loading: 'Đang tải tin nhắn…', noMessages: 'Chưa có tin nhắn trong hội thoại này.',
140
+ searchPlaceholder: 'Tìm kiếm hội thoại…', unreadOnly: 'Chưa đọc', sendPlaceholder: 'Viết tin nhắn…', send: 'Gửi', all: 'Tất cả',
141
+ };
142
+
143
+ useImperativeHandle(ref, () => ({
144
+ openConversation: (id: string) => { const conv = items.find(c => c.id === id); if (conv) setSelected(conv); },
145
+ refresh: () => void load(),
146
+ }), [items, load]);
147
+
148
+ const frame: React.CSSProperties = {
149
+ ...css.frame,
150
+ height: height ?? 620,
151
+ ...(height ? { maxHeight: 'none' } : {}),
152
+ fontFamily: theme?.fontFamily ?? 'Inter, ui-sans-serif, system-ui, sans-serif',
153
+ borderRadius: theme?.borderRadius ?? '16px',
154
+ gridTemplateColumns: infoOpen
155
+ ? 'minmax(260px, 300px) minmax(0, 1fr) 260px'
156
+ : 'minmax(260px, 300px) minmax(0, 1fr)',
157
+ transition: 'grid-template-columns 220ms ease',
158
+ };
159
+ if (loading) return <div style={{ ...css.state, borderRadius: theme?.borderRadius ?? '16px' }}><Spinner /> Đang tải hộp thư…</div>;
160
+ if (error && !items.length) return <div style={{ ...css.state, color: '#b42318', borderRadius: theme?.borderRadius ?? '16px' }}><AlertCircle size={16} strokeWidth={2} /> {error}<button style={css.retry} onClick={() => { setLoading(true); void load(); }}>Thử lại</button></div>;
161
+ return (
162
+ <ApiUrlCtx.Provider value={apiUrl}>
163
+ <TokenCtx.Provider value={token}>
164
+ <div style={frame} onFocusCapture={() => { const y = window.scrollY; requestAnimationFrame(() => { if (window.scrollY !== y) window.scrollTo({ top: y, behavior: 'instant' }); }); }}>
165
+ <aside style={css.sidebar}>
166
+ <div style={css.brand}>
167
+ <div style={{ ...css.brandMark, background: primary, overflow: 'hidden', padding: 0 }}>
168
+ {theme?.branding?.logoUrl
169
+ ? <img src={theme.branding.logoUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
170
+ : (theme?.branding?.mark ?? 'C')}
171
+ </div>
172
+ <div>
173
+ <strong>{theme?.branding?.name ?? 'Hộp thư'}</strong>
174
+ {!theme?.branding?.name && <span style={css.eyebrow}>CHANNELHUB</span>}
175
+ </div>
176
+ <Button aria-label="Tùy chọn" style={css.iconButton}><MoreHorizontal size={16} strokeWidth={2} /></Button>
177
+ </div>
178
+ <div style={css.search}><Search size={16} strokeWidth={2} /><Input aria-label={t.searchPlaceholder} value={query} onChange={e => setQuery(e.target.value)} placeholder={t.searchPlaceholder} />{query && <button style={css.clear} onClick={() => setQuery('')} aria-label="Xóa tìm kiếm">×</button>}</div>
179
+
180
+ {/* Active filter chips */}
181
+ {hasActiveFilters && (
182
+ <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', padding: '0 14px 8px' }}>
183
+ {activeFilters.provider !== 'all' && (
184
+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: '#eef2ff', color: primary, borderRadius: 6, fontSize: 11, padding: '2px 8px', fontWeight: 500 }}>
185
+ <ProviderMark provider={activeFilters.provider} />
186
+ {providerShortLabel(activeFilters.provider)}
187
+ <button style={{ border: 0, background: 'none', cursor: 'pointer', color: primary, padding: 0, lineHeight: 1, display: 'flex' }} onClick={() => setActiveFilters(f => ({ ...f, provider: 'all' }))} aria-label="Xóa filter kênh"><X size={10} /></button>
188
+ </span>
189
+ )}
190
+ {activeFilters.unreadOnly && (
191
+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: '#eef2ff', color: primary, borderRadius: 6, fontSize: 11, padding: '2px 8px', fontWeight: 500 }}>
192
+ {t.unreadOnly}
193
+ <button style={{ border: 0, background: 'none', cursor: 'pointer', color: primary, padding: 0, lineHeight: 1, display: 'flex' }} onClick={() => setActiveFilters(f => ({ ...f, unreadOnly: false }))} aria-label="Xóa filter chưa đọc"><X size={10} /></button>
194
+ </span>
195
+ )}
196
+ <button style={{ border: 0, background: 'none', cursor: 'pointer', color: c.muted, fontSize: 11, padding: '2px 4px' }} onClick={() => setActiveFilters({ provider: 'all', unreadOnly: false })}>Xóa tất cả</button>
197
+ </div>
198
+ )}
199
+
200
+ <div style={css.listHeader}>
201
+ <span>{visible.length} hội thoại</span>
202
+ <button
203
+ ref={filterBtnRef}
204
+ style={{ ...css.iconButton, background: hasActiveFilters ? `${primary}14` : 'transparent', color: hasActiveFilters ? primary : c.muted }}
205
+ aria-label="Bộ lọc"
206
+ onClick={() => {
207
+ if (!filterOpen) {
208
+ const rect = filterBtnRef.current?.getBoundingClientRect();
209
+ if (rect) setPopoverAnchor({ top: rect.bottom + 6, left: rect.left });
210
+ }
211
+ setFilterOpen(o => !o);
212
+ }}
213
+ >
214
+ <SlidersHorizontal size={15} strokeWidth={2} />
215
+ </button>
216
+ </div>
217
+
218
+ {/* Portal popover — rendered into document.body, escapes overflow:hidden entirely */}
219
+ {filterOpen && popoverAnchor && createPortal(
220
+ <div
221
+ ref={filterPopoverRef}
222
+ style={{ position: 'fixed', top: popoverAnchor.top, left: popoverAnchor.left, zIndex: 9999, background: c.white, border: `1px solid ${c.line}`, borderRadius: 10, padding: '12px 14px', boxShadow: '0 8px 24px rgba(23,32,51,.14)', minWidth: 210, fontFamily: theme?.fontFamily ?? 'Inter, ui-sans-serif, system-ui, sans-serif', fontSize: 13 }}
223
+ >
224
+ <div style={{ fontSize: 10, fontWeight: 700, color: c.muted, letterSpacing: 1, textTransform: 'uppercase' as const, marginBottom: 8 }}>Kênh</div>
225
+ {(['all', ...availableProviders] as const).map(p => (
226
+ <label key={p} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 6px', cursor: 'pointer', borderRadius: 6, background: activeFilters.provider === p ? `${primary}0f` : 'transparent' }}>
227
+ <input type="radio" name="provider-filter" checked={activeFilters.provider === p} onChange={() => setActiveFilters(f => ({ ...f, provider: p }))} style={{ accentColor: primary }} />
228
+ {p === 'all'
229
+ ? <span style={{ color: c.ink }}>{t.all} ({items.length})</span>
230
+ : <span style={{ display: 'flex', alignItems: 'center', gap: 5, color: c.ink }}><ProviderMark provider={p} />{providerShortLabel(p)} <span style={{ color: c.muted }}>({countByProvider[p] ?? 0})</span></span>}
231
+ </label>
232
+ ))}
233
+ <div style={{ borderTop: `1px solid ${c.line}`, margin: '8px 0 6px' }} />
234
+ <label style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 6px', cursor: 'pointer', borderRadius: 6, background: activeFilters.unreadOnly ? `${primary}0f` : 'transparent' }}>
235
+ <input type="checkbox" checked={activeFilters.unreadOnly} onChange={e => setActiveFilters(f => ({ ...f, unreadOnly: e.target.checked }))} style={{ accentColor: primary }} />
236
+ <span style={{ color: c.ink }}>{t.unreadOnly}</span>
237
+ </label>
238
+ </div>,
239
+ document.body
240
+ )}
241
+
242
+ <ScrollArea style={css.conversationList}>
243
+ {visible.map(x => <ConversationRow key={x.id} conversation={x} provider={connectionById.get(x.connectionId)?.provider} selected={selected?.id === x.id} primary={primary} onSelect={() => { setSelected(x); onConversationSelect?.(x.id); void client.current.markRead(x.id).then(() => load()).catch(() => undefined); }} />)}
244
+ {!visible.length && <div style={css.emptySmall}><div style={css.emptyIcon}><Search size={16} strokeWidth={2} /></div><strong>Không tìm thấy</strong><span>Thử từ khóa hoặc bộ lọc khác.</span></div>}
245
+ {cursor && <button style={css.loadMore} onClick={() => void load(cursor)}>Xem thêm hội thoại</button>}
246
+ </ScrollArea>
247
+ </aside>
248
+ <main style={css.main}>
249
+ {selected ? (
250
+ <MessagePanel
251
+ key={selected.id}
252
+ conversation={selected}
253
+ provider={connectionById.get(selected.connectionId)?.provider}
254
+ connection={connectionById.get(selected.connectionId)}
255
+ client={client.current}
256
+ primary={primary}
257
+ error={error}
258
+ onRegisterAppend={(fn) => { appendMessageRef.current = fn; }}
259
+ refreshKey={msgRefreshKey}
260
+ infoOpen={infoOpen}
261
+ onToggleInfo={() => setInfoOpen(o => !o)}
262
+ t={t}
263
+ disableAttachments={disableAttachments}
264
+ hideKeyboardHint={hideKeyboardHint}
265
+ />
266
+ ) : <EmptyConversation />}
267
+ </main>
268
+ {infoOpen && selected && (
269
+ <ContactInfoPanel
270
+ conversation={selected}
271
+ connection={connectionById.get(selected.connectionId)}
272
+ primary={primary}
273
+ onClose={() => setInfoOpen(false)}
274
+ />
275
+ )}
276
+ </div>
277
+ </TokenCtx.Provider>
278
+ </ApiUrlCtx.Provider>
279
+ );
280
+ });
281
+
282
+ function ConversationRow({ conversation, provider, selected, primary, onSelect }: { conversation: Conversation; provider?: Provider; selected: boolean; primary: string; onSelect: () => void }) {
283
+ const [hovered, setHovered] = useState(false);
284
+ const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
285
+ const unread = conversation.unreadCount ?? 0;
286
+ const rawText = conversation.lastMessageText ?? '';
287
+ const prefix = conversation.lastMessageDirection === 'outbound' ? 'Bạn: ' : '';
288
+ const truncated = rawText.length > 60 ? rawText.slice(0, 60) + '…' : rawText;
289
+ const preview = rawText ? prefix + truncated : '';
290
+
291
+ let rowBg = 'transparent';
292
+ if (selected) rowBg = '#eef2ff';
293
+ else if (hovered) rowBg = '#f7f9fc';
294
+ else if (unread > 0) rowBg = '#f0f4ff';
295
+
296
+ const rowStyle: React.CSSProperties = {
297
+ ...css.row,
298
+ background: rowBg,
299
+ ...(selected ? { boxShadow: `inset 3px 0 0 ${primary}` } : unread > 0 && !hovered ? { boxShadow: `inset 3px 0 0 ${primary}` } : {}),
300
+ };
301
+
302
+ return (
303
+ <button
304
+ onClick={onSelect}
305
+ style={rowStyle}
306
+ onMouseEnter={() => setHovered(true)}
307
+ onMouseLeave={() => setHovered(false)}
308
+ >
309
+ <ContactAvatar name={name} color={primary} image={conversation.contactPictureUrl} provider={provider} />
310
+ <span style={css.rowBody}>
311
+ <span style={css.rowTop}>
312
+ <strong style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: unread > 0 ? 700 : 500 }}>{name}</strong>
313
+ <span style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
314
+ <time style={{ color: c.muted, fontSize: 11, whiteSpace: 'nowrap' }}>{formatTime(conversation.lastMessageAt)}</time>
315
+ {unread > 0 && (
316
+ <span aria-label={`${unread} tin nhắn chưa đọc`} style={css.unreadBadge}>
317
+ {unread > 99 ? '99+' : unread}
318
+ </span>
319
+ )}
320
+ </span>
321
+ </span>
322
+ <span style={{ ...css.rowBottom, color: unread > 0 && !selected ? '#4a5568' : c.muted }}>
323
+ <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>
324
+ {preview || <span style={{ opacity: 0.5 }}>Chưa có tin nhắn</span>}
325
+ </span>
326
+ </span>
327
+ </span>
328
+ </button>
329
+ );
330
+ }
331
+
332
+ type PendingAttachment = { file: File; uploading: boolean; url?: string; mimeType?: string; attachmentType?: string; objectUrl?: string };
333
+
334
+ function MessagePanel({ conversation, provider, connection, client, primary, error, onRegisterAppend, refreshKey, infoOpen, onToggleInfo, t, disableAttachments, hideKeyboardHint }: { conversation: Conversation; provider?: Provider; connection?: Connection; client: ChannelHubClient; primary: string; error: string; onRegisterAppend?: (fn: ((msg: Message) => void) | null) => void; refreshKey?: number; infoOpen: boolean; onToggleInfo: () => void; t: WidgetTranslations; disableAttachments?: boolean; hideKeyboardHint?: boolean }) {
335
+ const [messages, setMessages] = useState<Message[]>([]); const [cursor, setCursor] = useState<string>(); const [text, setText] = useState(''); const [loading, setLoading] = useState(true); const [sending, setSending] = useState(false); const [sendError, setSendError] = useState(''); const messageAreaRef = useRef<HTMLDivElement>(null); const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
336
+ const fileRef = useRef<HTMLInputElement>(null);
337
+ const [pendingAttachment, setPendingAttachment] = useState<PendingAttachment | null>(null);
338
+
339
+ useEffect(() => {
340
+ return () => { if (pendingAttachment?.objectUrl) URL.revokeObjectURL(pendingAttachment.objectUrl); };
341
+ }, [pendingAttachment?.objectUrl]);
342
+
343
+ const shouldScrollToBottom = useRef(true);
344
+
345
+ const load = useCallback(async (next?: string, silent?: boolean) => {
346
+ if (!silent) shouldScrollToBottom.current = !next;
347
+ try {
348
+ const page = await client.listMessages(conversation.id, next);
349
+ setMessages(old => next ? [...page.items, ...old] : page.items);
350
+ setCursor(page.nextCursor);
351
+ } catch (e) { setSendError(e instanceof Error ? e.message : 'Không tải được tin nhắn'); }
352
+ finally { if (!silent) setLoading(false); }
353
+ }, [client, conversation.id]);
354
+
355
+ useEffect(() => { setLoading(true); void load(); }, [load]);
356
+
357
+ useEffect(() => {
358
+ if (!refreshKey) return;
359
+ void load(undefined, true);
360
+ }, [refreshKey]); // eslint-disable-line react-hooks/exhaustive-deps
361
+
362
+ useEffect(() => {
363
+ if (!shouldScrollToBottom.current) return;
364
+ requestAnimationFrame(() => { const el = messageAreaRef.current; if (el) el.scrollTop = el.scrollHeight; });
365
+ }, [messages]);
366
+
367
+ useEffect(() => {
368
+ onRegisterAppend?.((msg: Message) => {
369
+ shouldScrollToBottom.current = true;
370
+ setMessages(prev => { if (prev.some(m => m.id === msg.id)) return prev; return [...prev, msg]; });
371
+ });
372
+ return () => { onRegisterAppend?.(null); };
373
+ }, [onRegisterAppend]);
374
+
375
+ async function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
376
+ const file = e.target.files?.[0];
377
+ if (!file) return;
378
+ e.target.value = '';
379
+ const objectUrl = URL.createObjectURL(file);
380
+ setPendingAttachment({ file, uploading: true, objectUrl });
381
+ try {
382
+ const result = await client.uploadAttachment(file);
383
+ setPendingAttachment({ file, uploading: false, url: result.url, mimeType: result.mimeType, attachmentType: result.attachmentType, objectUrl });
384
+ } catch {
385
+ URL.revokeObjectURL(objectUrl);
386
+ setPendingAttachment(null);
387
+ setSendError('Không tải lên được tệp đính kèm');
388
+ }
389
+ }
390
+
391
+ async function send(event: FormEvent) {
392
+ event.preventDefault();
393
+ const value = text.trim();
394
+ const attachments: MessageAttachment[] = pendingAttachment?.url
395
+ ? [{ url: pendingAttachment.url, mimeType: pendingAttachment.mimeType ?? 'application/octet-stream', type: pendingAttachment.attachmentType as MessageAttachment['type'] }]
396
+ : [];
397
+ if (!value && !attachments.length || sending) return;
398
+ setSending(true); setSendError('');
399
+ try {
400
+ await client.sendMessage(conversation.id, value || undefined, attachments.length ? attachments : undefined);
401
+ if (pendingAttachment?.objectUrl) URL.revokeObjectURL(pendingAttachment.objectUrl);
402
+ setText(''); setPendingAttachment(null); await load();
403
+ } catch (e) { setSendError(e instanceof Error ? e.message : 'Không gửi được tin nhắn'); } finally { setSending(false); }
404
+ }
405
+
406
+ const canSend = !sending && (text.trim().length > 0 || (pendingAttachment?.url != null && !pendingAttachment.uploading));
407
+
408
+ return (
409
+ <section style={css.chat}>
410
+ <header style={css.chatHeader}>
411
+ <ContactAvatar name={name} color={primary} image={conversation.contactPictureUrl} provider={provider} />
412
+ <div style={css.contact}>
413
+ <strong style={css.contactName}>{name}</strong>
414
+ <span style={css.contactMeta}>{connectionDisplayName(connection) ?? providerLabel(provider)}</span>
415
+ </div>
416
+ <div style={css.headerActions}>
417
+ <button style={css.iconButton} aria-label="Thêm tùy chọn">
418
+ <MoreHorizontal size={16} strokeWidth={2} />
419
+ </button>
420
+ <button
421
+ style={{
422
+ ...css.iconButton,
423
+ background: infoOpen ? `${primary}14` : 'transparent',
424
+ color: infoOpen ? primary : c.muted,
425
+ }}
426
+ aria-label="Thông tin liên hệ"
427
+ onClick={onToggleInfo}
428
+ >
429
+ <Info size={16} strokeWidth={2} />
430
+ </button>
431
+ </div>
432
+ </header>
433
+ <ScrollArea ref={messageAreaRef} style={css.messageArea}>
434
+ <div style={css.day}>{t.today}</div>
435
+ {cursor && <button onClick={() => void load(cursor)} style={css.historyButton}>{t.loadOlder}</button>}
436
+ {loading && <div style={css.messageHint}><Spinner /> {t.loading}</div>}
437
+ {!loading && !messages.length && <div style={css.messageHint}>{t.noMessages}</div>}
438
+ {messages.map(m => <MessageBubble key={m.id} message={m} primary={primary} />)}
439
+ </ScrollArea>
440
+ <form onSubmit={send} style={css.composer}>
441
+ <div style={css.composerBox}>
442
+ {pendingAttachment && (
443
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderBottom: `1px solid ${c.line}`, fontSize: 12 }}>
444
+ {pendingAttachment.uploading
445
+ ? <><Spinner /><span style={{ color: c.muted }}>Đang tải lên…</span></>
446
+ : pendingAttachment.attachmentType === 'image' && pendingAttachment.objectUrl
447
+ ? <img src={pendingAttachment.objectUrl} alt="" style={{ height: 48, width: 48, objectFit: 'cover', borderRadius: 6 }} />
448
+ : <span style={{ color: c.muted }}>📎 {pendingAttachment.file.name} ({Math.round(pendingAttachment.file.size / 1024)} KB)</span>
449
+ }
450
+ {!pendingAttachment.uploading && (
451
+ <button type="button" onClick={() => { if (pendingAttachment?.objectUrl) URL.revokeObjectURL(pendingAttachment.objectUrl); setPendingAttachment(null); }} style={{ marginLeft: 'auto', border: 0, background: 'none', color: c.muted, cursor: 'pointer', fontSize: 16 }} aria-label="Xóa tệp đính kèm">✕</button>
452
+ )}
453
+ </div>
454
+ )}
455
+ <Textarea aria-label="Soạn tin nhắn" rows={1} value={text} onChange={e => setText(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(e); } }} placeholder={t.sendPlaceholder} style={css.textarea} />
456
+ <div style={css.composerTools}>
457
+ {!hideKeyboardHint && <span>↵ Gửi · ⇧↵ Xuống dòng</span>}
458
+ {!disableAttachments && <button type="button" style={css.iconButton} aria-label="Đính kèm tệp" onClick={() => fileRef.current?.click()}><Paperclip size={16} strokeWidth={2} /></button>}
459
+ {!disableAttachments && <input ref={fileRef} type="file" style={{ display: 'none' }} onChange={handleFileSelect} accept="image/jpeg,image/png,image/gif,image/webp,application/pdf,video/mp4,audio/mpeg,audio/ogg" />}
460
+ </div>
461
+ </div>
462
+ <button disabled={!canSend} aria-label="Gửi tin nhắn" style={{ ...css.send, background: primary, opacity: !canSend ? .5 : 1, cursor: !canSend ? 'not-allowed' : 'pointer' }}><Send size={16} strokeWidth={2} /></button>
463
+ </form>
464
+ {(sendError || error) && <div role="alert" style={css.error}>{sendError || error}</div>}
465
+ </section>
466
+ );
467
+ }
468
+
469
+ function MessageBubble({ message, primary }: { message: Message; primary: string }) {
470
+ const apiUrl = useContext(ApiUrlCtx);
471
+ const token = useContext(TokenCtx);
472
+ const resolveUrl = (url: string): string =>
473
+ url.startsWith('/v1/media/proxy') ? `${apiUrl}${url}&tok=${encodeURIComponent(token)}` : url;
474
+
475
+ const outbound = message.direction === 'outbound';
476
+ const images = message.attachments?.filter(a => a.type === 'image') ?? [];
477
+ const stickers = message.attachments?.filter(a => a.type === 'sticker') ?? [];
478
+ const videos = message.attachments?.filter(a => a.type === 'video') ?? [];
479
+ const audios = message.attachments?.filter(a => a.type === 'audio') ?? [];
480
+ const files = message.attachments?.filter(a => a.type === 'file') ?? [];
481
+ const [lightbox, setLightbox] = useState<{ url: string; kind: 'image' | 'video' } | null>(null);
482
+ const align = outbound ? 'flex-end' : 'flex-start';
483
+
484
+ const timeEl = (
485
+ <time style={{ display: 'block', marginTop: 4, fontSize: 10, opacity: 0.65, textAlign: 'right', letterSpacing: 0.2, userSelect: 'none' as const }}>
486
+ {formatTime(message.occurredAt, true)}{outbound && <> <StatusIcon status={message.status} /></>}
487
+ </time>
488
+ );
489
+
490
+ const overlayTime = (
491
+ <div style={{ position: 'absolute', bottom: 6, right: 8 }}>
492
+ <time style={{ fontSize: 10, color: '#fff', textShadow: '0 1px 3px rgba(0,0,0,.5)', letterSpacing: 0.2, userSelect: 'none' as const }}>
493
+ {formatTime(message.occurredAt, true)}{outbound && <> <StatusIcon status={message.status} /></>}
494
+ </time>
495
+ </div>
496
+ );
497
+
498
+ const bubbleStyle = outbound
499
+ ? { ...css.bubbleOut, background: primary, color: '#fff', border: '1px solid transparent' }
500
+ : css.bubbleIn;
501
+
502
+ const mediaOnly = !message.text && audios.length === 0 && files.length === 0;
503
+
504
+ return (
505
+ <div style={{ ...css.messageLine, justifyContent: align, flexDirection: 'column', alignItems: align }}>
506
+ {/* Stickers — small, no lightbox */}
507
+ {stickers.map((a, i) => (
508
+ <div key={`s${i}`} style={{ position: 'relative', marginBottom: 2 }}>
509
+ <img src={resolveUrl(a.url)} alt="sticker" style={{ display: 'block', maxWidth: 128, maxHeight: 128, objectFit: 'contain' }} />
510
+ {mediaOnly && images.length === 0 && videos.length === 0 && i === stickers.length - 1 && overlayTime}
511
+ </div>
512
+ ))}
513
+ {/* Images — outside bubble */}
514
+ {images.map((a, i) => (
515
+ <div key={i} style={{ position: 'relative', marginBottom: 2, cursor: 'zoom-in' }} onClick={() => setLightbox({ url: resolveUrl(a.url), kind: 'image' })}>
516
+ <img src={resolveUrl(a.url)} alt="" style={{ display: 'block', maxWidth: 260, maxHeight: 260, borderRadius: 12, objectFit: 'cover' }} />
517
+ {mediaOnly && i === images.length - 1 && videos.length === 0 && overlayTime}
518
+ </div>
519
+ ))}
520
+ {/* Videos — outside bubble, thumbnail with play overlay */}
521
+ {videos.map((a, i) => (
522
+ <div key={i} style={{ position: 'relative', marginBottom: 2, cursor: 'pointer' }} onClick={() => setLightbox({ url: resolveUrl(a.url), kind: 'video' })}>
523
+ <video src={resolveUrl(a.url)} style={{ display: 'block', maxWidth: 260, maxHeight: 200, borderRadius: 12, objectFit: 'cover' }} />
524
+ <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 12, background: 'rgba(0,0,0,.25)' }}>
525
+ <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'rgba(255,255,255,.9)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
526
+ <Play size={16} fill="#172033" color="#172033" style={{ marginLeft: 2 }} />
527
+ </div>
528
+ </div>
529
+ {mediaOnly && i === videos.length - 1 && overlayTime}
530
+ </div>
531
+ ))}
532
+ {/* Audio / file / text inside bubble */}
533
+ {(audios.length > 0 || files.length > 0 || message.text || (!images.length && !videos.length && !stickers.length && !message.text)) && (
534
+ <div style={bubbleStyle}>
535
+ {audios.map((a, i) => <audio key={i} src={resolveUrl(a.url)} controls style={{ display: 'block', width: '100%', marginBottom: 4 }} />)}
536
+ {files.map((a, i) => <a key={i} href={resolveUrl(a.url)} target="_blank" rel="noreferrer" style={{ display: 'block', fontSize: 12, color: outbound ? '#fff' : '#2563eb', textDecoration: 'underline', marginBottom: 4 }}>📎 {mimeLabel(a.mimeType)}</a>)}
537
+ {message.text && <p style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{message.text}</p>}
538
+ {!audios.length && !files.length && !message.text && <p style={{ margin: 0, opacity: 0.5 }}>[attachment]</p>}
539
+ {timeEl}
540
+ </div>
541
+ )}
542
+ {/* Lightbox */}
543
+ {lightbox && createPortal(
544
+ <div onClick={() => setLightbox(null)} style={{ position: 'fixed', inset: 0, zIndex: 10000, background: 'rgba(0,0,0,.88)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'zoom-out' }}>
545
+ {lightbox.kind === 'image'
546
+ ? <img src={lightbox.url} alt="" style={{ maxWidth: '90vw', maxHeight: '90vh', borderRadius: 8, objectFit: 'contain', boxShadow: '0 8px 40px rgba(0,0,0,.5)' }} onClick={e => e.stopPropagation()} />
547
+ : <video src={lightbox.url} controls autoPlay style={{ maxWidth: '90vw', maxHeight: '90vh', borderRadius: 8, boxShadow: '0 8px 40px rgba(0,0,0,.5)' }} onClick={e => e.stopPropagation()} />
548
+ }
549
+ <button onClick={() => setLightbox(null)} style={{ position: 'absolute', top: 16, right: 16, background: 'rgba(255,255,255,.15)', border: 'none', borderRadius: '50%', width: 36, height: 36, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
550
+ <X size={18} />
551
+ </button>
552
+ </div>,
553
+ document.body
554
+ )}
555
+ </div>
556
+ );
557
+ }
558
+
559
+ function ContactInfoPanel({
560
+ conversation,
561
+ connection,
562
+ primary,
563
+ onClose,
564
+ }: {
565
+ conversation: Conversation;
566
+ connection?: Connection;
567
+ primary: string;
568
+ onClose: () => void;
569
+ }) {
570
+ const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
571
+ const provider = connection?.provider;
572
+ const [expanded, setExpanded] = useState<Record<string, boolean>>({ channel: true, stats: false, extra: false });
573
+ const toggle = (key: string) => setExpanded(e => ({ ...e, [key]: !e[key] }));
574
+
575
+ return (
576
+ <aside style={css.infoPanel}>
577
+ <div style={css.infoPanelHeader}>
578
+ <span style={{ fontWeight: 600, fontSize: 13, color: c.ink }}>Thông tin liên hệ</span>
579
+ <button style={css.iconButton} onClick={onClose} aria-label="Đóng">
580
+ <X size={16} strokeWidth={2} />
581
+ </button>
582
+ </div>
583
+
584
+ <div style={{ overflowY: 'auto', flex: 1 }}>
585
+ <div style={css.infoPanelIdentity}>
586
+ <span style={{ ...css.avatarWrap, width: 48, height: 48 }}>
587
+ <UiAvatar
588
+ src={conversation.contactPictureUrl}
589
+ fallback={initials(name)}
590
+ style={{ ...css.avatar, width: 48, height: 48, fontSize: 16 }}
591
+ />
592
+ <span style={{ ...css.providerBadge, width: 20, height: 20 }}>
593
+ <ProviderMark provider={provider} />
594
+ </span>
595
+ </span>
596
+ <strong style={{ marginTop: 10, fontSize: 15, color: c.ink, textAlign: 'center' }}>{name}</strong>
597
+ <span style={{ fontSize: 11, color: c.muted, fontFamily: 'monospace', textAlign: 'center' }}>
598
+ {conversation.providerConversationKey}
599
+ </span>
600
+ </div>
601
+
602
+ <InfoSection label="KÊNH" sectionKey="channel" expanded={expanded['channel']} onToggle={() => toggle('channel')}>
603
+ <InfoRow label="Nền tảng">
604
+ <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
605
+ <ProviderMark provider={provider} />
606
+ <span>{providerLabel(provider)}</span>
607
+ </span>
608
+ </InfoRow>
609
+ <InfoRow label="ID hội thoại">
610
+ <span style={{ fontFamily: 'monospace', fontSize: 11 }}>
611
+ {conversation.id.slice(0, 8)}…
612
+ </span>
613
+ <CopyButton value={conversation.id} />
614
+ </InfoRow>
615
+ </InfoSection>
616
+
617
+ <InfoSection label="THỐNG KÊ" sectionKey="stats" expanded={expanded['stats']} onToggle={() => toggle('stats')}>
618
+ <InfoRow label="Tin nhắn" value={String(conversation.messageCount ?? 0)} />
619
+ {(conversation.unreadCount ?? 0) > 0 && (
620
+ <InfoRow label="Chưa đọc" value={String(conversation.unreadCount)} valueColor="#ef4444" />
621
+ )}
622
+ <InfoRow
623
+ label="Gần nhất"
624
+ value={conversation.lastMessageAt
625
+ ? new Date(conversation.lastMessageAt).toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit', year: 'numeric' })
626
+ : '—'}
627
+ />
628
+ <InfoRow label="Lần đầu" value="—" />
629
+ </InfoSection>
630
+
631
+ <InfoSection label="THÔNG TIN BỔ SUNG" sectionKey="extra" expanded={expanded['extra']} onToggle={() => toggle('extra')}>
632
+ <InfoRow label="Điện thoại" value="— chưa có" valueMuted />
633
+ <InfoRow label="Email" value="— chưa có" valueMuted />
634
+ <InfoRow label="Nhãn" value="— chưa có" valueMuted />
635
+ </InfoSection>
636
+
637
+ <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
638
+ <button style={{ ...css.ghostButton, color: primary, borderColor: `${primary}33` }}>Xem lịch sử</button>
639
+ <button style={{ ...css.ghostButton, color: primary, borderColor: `${primary}33` }}>Thêm ghi chú</button>
640
+ </div>
641
+ </div>
642
+ </aside>
643
+ );
644
+ }
645
+
646
+ function InfoSection({ label, children, sectionKey, expanded, onToggle }: { label: string; children: React.ReactNode; sectionKey?: string; expanded?: boolean; onToggle?: () => void }) {
647
+ const isCollapsible = !!onToggle;
648
+ const isExpanded = expanded ?? true;
649
+ return (
650
+ <div style={{ borderTop: `1px solid ${c.line}` }}>
651
+ <div
652
+ style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 16px 6px', fontSize: 10, fontWeight: 700, letterSpacing: 1, color: c.muted, textTransform: 'uppercase' as const, cursor: isCollapsible ? 'pointer' : 'default' }}
653
+ onClick={onToggle}
654
+ >
655
+ <span>{label}</span>
656
+ {isCollapsible && (isExpanded
657
+ ? <ChevronDown size={12} strokeWidth={2} />
658
+ : <ChevronRight size={12} strokeWidth={2} />)}
659
+ </div>
660
+ {isExpanded && children}
661
+ </div>
662
+ );
663
+ }
664
+
665
+ function InfoRow({ label, value, children, valueColor, valueMuted }: {
666
+ label: string; value?: string; children?: React.ReactNode; valueColor?: string; valueMuted?: boolean;
667
+ }) {
668
+ return (
669
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '3px 16px', fontSize: 12, gap: 8 }}>
670
+ <span style={{ color: c.muted, flexShrink: 0 }}>{label}</span>
671
+ <span style={{ color: valueColor ?? (valueMuted ? c.muted : c.ink), textAlign: 'right', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 4 }}>
672
+ {children ?? value}
673
+ </span>
674
+ </div>
675
+ );
676
+ }
677
+
678
+ function CopyButton({ value }: { value: string }) {
679
+ const [copied, setCopied] = useState(false);
680
+ return (
681
+ <button
682
+ style={{ border: 0, background: 'none', cursor: 'pointer', color: c.muted, padding: 2, lineHeight: 1 }}
683
+ title="Sao chép"
684
+ onClick={() => { void navigator.clipboard.writeText(value).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }); }}
685
+ aria-label="Sao chép ID"
686
+ >
687
+ {copied ? '✓' : '⎘'}
688
+ </button>
689
+ );
690
+ }
691
+
692
+ function EmptyConversation() { return <div style={css.empty}><div style={css.emptyHero}><Inbox size={16} strokeWidth={2} /></div><h2>Chọn một hội thoại</h2><p>Chọn hội thoại bên trái để xem và trả lời tin nhắn.</p></div>; }
693
+ function ContactAvatar({ name, color, image, provider }: { name: string; color: string; image?: string; provider?: Provider }) { return <span style={css.avatarWrap}><Avatar name={name} color={color} image={image} />{provider && <span style={css.providerBadge}><ProviderMark provider={provider} /></span>}</span>; }
694
+ function Avatar({ name, color, image }: { name: string; color: string; image?: string }) { return <UiAvatar src={image} fallback={initials(name)} style={{ ...css.avatar, background: `${color}18`, color }} />; }
695
+ function Spinner() { return <Loader2 size={14} style={css.spinner} aria-hidden="true" />; }
696
+ function initials(name: string) { return name.split(/\s+/).filter(Boolean).slice(-2).map(x => x[0]).join('').toUpperCase() || '?'; }
697
+
698
+ const providerLogoSlug: Partial<Record<string, string>> = { livechat: 'web' };
699
+
700
+ function ProviderMark({ provider }: { provider?: Provider }) {
701
+ const apiUrl = useContext(ApiUrlCtx);
702
+ const size = 14;
703
+ if (!provider) return null;
704
+ const slug = providerLogoSlug[provider] ?? provider;
705
+ return <img src={`${apiUrl}/static/logos/${slug}.avif`} alt={provider} width={size} height={size} style={{ borderRadius: '50%', objectFit: 'cover', display: 'block' }} />;
706
+ }
707
+ function formatTime(value?: string | Date, _full = false) {
708
+ if (!value) return '';
709
+ const d = new Date(value as string);
710
+ if (d.toDateString() === new Date().toDateString()) {
711
+ return d.toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
712
+ }
713
+ return d.toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit' });
714
+ }
715
+
716
+ const css: Record<string, React.CSSProperties> = {
717
+ frame: { display: 'grid', gridTemplateRows: 'minmax(0, 1fr)', height: 620, maxHeight: 'calc(100dvh - 220px)', minHeight: 0, overflow: 'hidden', border: `1px solid ${c.line}`, background: c.white, color: c.ink, boxShadow: '0 18px 50px rgba(31,45,72,.10)' },
718
+ sidebar: { display: 'flex', flexDirection: 'column', minWidth: 0, minHeight: 0, borderRight: `1px solid ${c.line}`, background: c.white },
719
+ brand: { display: 'flex', alignItems: 'center', gap: 10, padding: '20px 18px 16px' },
720
+ brandMark: { display: 'grid', placeItems: 'center', width: 32, height: 32, borderRadius: 10, color: '#fff', fontWeight: 800 },
721
+ eyebrow: { display: 'block', marginTop: 2, fontSize: 9, letterSpacing: 1.3, color: c.muted },
722
+ iconButton: { display: 'inline-grid', placeItems: 'center', width: 32, height: 32, marginLeft: 'auto', border: 0, borderRadius: 8, background: 'transparent', color: c.muted, cursor: 'pointer' },
723
+ searchInput: { width: '100%', minWidth: 0, border: 0, outline: 0, background: 'transparent', color: c.ink, font: 'inherit', fontSize: 12 },
724
+ search: { display: 'flex', alignItems: 'center', gap: 8, margin: '0 14px 12px', padding: '9px 10px', border: `1px solid ${c.line}`, borderRadius: 9, color: c.muted, background: c.surface },
725
+ clear: { border: 0, background: 'none', color: c.muted, cursor: 'pointer', fontSize: 18 },
726
+ listHeader: { display: 'flex', alignItems: 'center', padding: '10px 18px', borderTop: `1px solid ${c.line}`, borderBottom: `1px solid ${c.line}`, color: c.muted, fontSize: 11, fontWeight: 700, letterSpacing: .4, textTransform: 'uppercase' },
727
+ conversationList: { overflowY: 'auto', flex: 1, minHeight: 0 },
728
+ row: { display: 'flex', width: '100%', gap: 11, padding: '10px 14px', border: 0, borderBottom: `1px solid ${c.line}`, background: 'transparent', textAlign: 'left', cursor: 'pointer', transition: 'background 120ms ease' },
729
+ avatarWrap: { position: 'relative', flex: '0 0 auto', width: 38, height: 38 },
730
+ avatar: { flex: '0 0 auto', width: 38, height: 38, display: 'grid', placeItems: 'center', borderRadius: '50%', objectFit: 'cover', fontSize: 12, fontWeight: 800 },
731
+ providerBadge: { position: 'absolute', left: -3, bottom: -3, display: 'grid', placeItems: 'center', width: 17, height: 17, border: '2px solid #fff', borderRadius: '50%', background: '#fff', color: '#64748b' },
732
+ rowBody: { minWidth: 0, flex: 1 },
733
+ rowTop: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, fontSize: 13 },
734
+ rowBottom: { display: 'flex', marginTop: 4, fontSize: 11, minWidth: 0, overflow: 'hidden', lineHeight: 1.4 },
735
+ channel: { color: '#9aa5b5' },
736
+ unreadBadge: { display: 'inline-grid', placeItems: 'center', minWidth: 18, height: 18, borderRadius: 999, background: '#ef4444', color: '#fff', fontSize: 10, fontWeight: 800, padding: '0 5px' },
737
+ loadMore: { width: '100%', border: 0, background: 'transparent', color: '#4c72ca', padding: 14, cursor: 'pointer', fontSize: 12 },
738
+ emptySmall: { display: 'grid', justifyItems: 'center', gap: 7, padding: '56px 24px', color: c.muted, fontSize: 12, textAlign: 'center' },
739
+ emptyIcon: { display: 'grid', placeItems: 'center', width: 40, height: 40, borderRadius: 12, background: c.surface },
740
+ main: { minWidth: 0, minHeight: 0, overflow: 'hidden', background: c.surface },
741
+ chat: { display: 'flex', flexDirection: 'column', height: '100%', minWidth: 0, minHeight: 0 },
742
+ chatHeader: { flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: 10, padding: '0 16px 0 18px', height: 56, borderBottom: `1px solid ${c.line}`, background: c.white },
743
+ contact: { display: 'grid', gap: 3, minWidth: 0, flex: 1 },
744
+ contactName: { fontSize: 14, fontWeight: 600, color: c.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
745
+ contactMeta: { display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: c.muted },
746
+ headerActions: { display: 'flex', gap: 2, marginLeft: 'auto' },
747
+ messageArea: { flex: 1, minHeight: 0, overflowY: 'auto', overscrollBehavior: 'contain', padding: '20px clamp(16px,5vw,56px)', background: 'linear-gradient(180deg,#f9fbfe 0%,#f4f7fb 100%)' },
748
+ day: { margin: '0 auto 18px', color: '#a1acbb', fontSize: 10, letterSpacing: 1.2, fontWeight: 700, textAlign: 'center' },
749
+ historyButton: { display: 'block', margin: '0 auto 18px', border: `1px solid ${c.line}`, borderRadius: 20, padding: '6px 12px', background: c.white, color: c.muted, cursor: 'pointer', fontSize: 11 },
750
+ messageHint: { display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, padding: 40, color: c.muted, fontSize: 12 },
751
+ messageLine: { display: 'flex', marginBottom: 10 },
752
+ bubbleOut: { maxWidth: 'min(70%,480px)', padding: '9px 13px', borderRadius: '14px 14px 3px 14px', boxShadow: '0 2px 5px rgba(30,43,65,.03)', fontSize: 14, lineHeight: 1.55 },
753
+ bubbleIn: { maxWidth: 'min(70%,480px)', padding: '9px 13px', borderRadius: '14px 14px 14px 3px', border: `1px solid ${c.line}`, background: c.surface, boxShadow: '0 2px 5px rgba(30,43,65,.03)', fontSize: 14, lineHeight: 1.55 },
754
+ composer: { flex: '0 0 auto', display: 'flex', alignItems: 'flex-end', gap: 10, padding: '10px 14px 12px', borderTop: `1px solid ${c.line}`, background: c.white },
755
+ textarea: { display: 'block', width: '100%', minWidth: 0, boxSizing: 'border-box', minHeight: 44, maxHeight: 120, resize: 'vertical', border: 0, outline: 0, background: 'transparent', color: c.ink, padding: '10px 12px 4px', font: 'inherit', fontSize: 13, lineHeight: 1.45 },
756
+ composerBox: { flex: 1, minWidth: 0, border: `1px solid ${c.line}`, borderRadius: 10, background: c.surface, overflow: 'hidden' },
757
+ send: { display: 'grid', placeItems: 'center', width: 38, height: 38, border: 0, borderRadius: '50%', color: '#fff', flexShrink: 0 },
758
+ error: { padding: '8px 18px', background: '#fff2f0', color: '#b42318', fontSize: 12 },
759
+ empty: { display: 'grid', placeItems: 'center', alignContent: 'center', height: '100%', padding: 30, textAlign: 'center', color: c.muted },
760
+ emptyHero: { display: 'grid', placeItems: 'center', width: 64, height: 64, marginBottom: 16, borderRadius: 20, background: '#eaf0ff', color: '#5277d7' },
761
+ state: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, minHeight: 180, border: `1px solid ${c.line}`, background: c.white, color: c.muted, fontSize: 13 },
762
+ retry: { border: 0, borderRadius: 7, padding: '7px 10px', background: '#eff4ff', color: '#315dbb', cursor: 'pointer' },
763
+ spinner: { display: 'inline-block', width: 14, height: 14, border: '2px solid #dbe3f3', borderTopColor: '#5277d7', borderRadius: '50%', animation: 'channelhub-spin .7s linear infinite' },
764
+ composerTools: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 8px 4px 12px', color: '#a0aabd', fontSize: 12 },
765
+ infoPanel: { display: 'flex', flexDirection: 'column', borderLeft: `1px solid ${c.line}`, background: c.white, minHeight: 0, overflow: 'hidden' },
766
+ infoPanelHeader: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 16px 12px', borderBottom: `1px solid ${c.line}`, flex: '0 0 auto' },
767
+ infoPanelIdentity: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '20px 16px 16px', gap: 4 },
768
+ ghostButton: { width: '100%', padding: '8px 12px', border: `1px solid ${c.line}`, borderRadius: 8, background: 'transparent', fontSize: 12, cursor: 'pointer', textAlign: 'center' as const },
769
+ };