@channelhub/widget 0.0.0-stage โ†’ 0.1.4

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 +36 -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 +114 -0
  25. package/dist/index.d.ts +6 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +2376 -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 +1133 -0
  46. package/src/LiveChatWidget.tsx +441 -0
  47. package/src/api.ts +100 -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 +7 -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,1133 @@
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, Image, Inbox, Info, Loader2, MoreHorizontal, Paperclip, Play, Search, Send, SlidersHorizontal, Smile, X, Zap } 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
+
12
+ const EMOJI_CATEGORIES: { icon: string; emojis: string[] }[] = [
13
+ { icon: '๐Ÿ˜Š', emojis: ['๐Ÿ˜€','๐Ÿ˜','๐Ÿ˜‚','๐Ÿคฃ','๐Ÿ˜Š','๐Ÿ˜‡','๐Ÿ™‚','๐Ÿ˜‰','๐Ÿ˜','๐Ÿฅฐ','๐Ÿ˜˜','๐Ÿ˜‹','๐Ÿ˜Ž','๐Ÿคฉ','๐Ÿ˜','๐Ÿ˜’','๐Ÿ˜”','๐Ÿ˜ข','๐Ÿ˜ญ','๐Ÿ˜ค','๐Ÿ˜ ','๐Ÿคฏ','๐Ÿ˜ฑ','๐Ÿฅณ','๐Ÿ˜ด','๐Ÿค”','๐Ÿค—','๐Ÿซก','๐Ÿ˜ฎ','๐Ÿคง','๐Ÿฅบ','๐Ÿ˜ถ','๐Ÿซ ','๐Ÿคญ','๐Ÿคซ'] },
14
+ { icon: '๐Ÿ‘‹', emojis: ['๐Ÿ‘','๐Ÿ‘Ž','๐Ÿ‘','๐Ÿ™','๐Ÿค','โœŒ๏ธ','๐Ÿคž','๐Ÿซก','๐Ÿ’ช','๐Ÿคœ','๐Ÿ‘Š','โœŠ','๐Ÿ–','๐Ÿ‘Œ','๐ŸคŒ','๐Ÿค','โ˜๏ธ','๐Ÿ‘†','๐Ÿ‘‡','๐Ÿ‘‰','๐Ÿ‘ˆ','๐Ÿค™','๐Ÿ’…','๐Ÿซถ','โค๏ธ','๐Ÿงก','๐Ÿ’›','๐Ÿ’š','๐Ÿ’™','๐Ÿ’œ','๐Ÿ–ค','๐Ÿ’”','โฃ๏ธ','๐Ÿ’•','๐Ÿ’ฏ'] },
15
+ { icon: '๐Ÿฑ', emojis: ['๐Ÿถ','๐Ÿฑ','๐Ÿญ','๐Ÿน','๐Ÿฐ','๐ŸฆŠ','๐Ÿป','๐Ÿผ','๐Ÿจ','๐Ÿฏ','๐Ÿฆ','๐Ÿฎ','๐Ÿท','๐Ÿธ','๐Ÿต','๐Ÿ™ˆ','๐Ÿ”','๐Ÿง','๐Ÿฆ','๐Ÿฆ†','๐Ÿฆ…','๐Ÿฆ‰','๐Ÿฆ‹','๐Ÿ','๐Ÿ›','๐Ÿข','๐ŸฆŽ','๐Ÿฌ','๐Ÿฆˆ','๐Ÿณ','๐Ÿ™','๐Ÿฆ‘'] },
16
+ { icon: '๐Ÿ•', emojis: ['๐ŸŽ','๐ŸŠ','๐Ÿ‹','๐Ÿ‡','๐Ÿ“','๐Ÿ’','๐Ÿฅ','๐Ÿฅ‘','๐Ÿ”','๐Ÿ•','๐ŸŒฎ','๐Ÿœ','๐Ÿฃ','๐Ÿฆ','๐ŸŽ‚','๐Ÿฐ','๐Ÿง','โ˜•','๐Ÿง‹','๐Ÿฅค','๐Ÿบ','๐Ÿฅ‚','๐Ÿพ','๐Ÿงƒ','๐ŸงŠ'] },
17
+ { icon: 'โšฝ', emojis: ['โšฝ','๐Ÿ€','๐Ÿˆ','โšพ','๐ŸŽพ','๐Ÿ','๐Ÿ“','๐ŸŽฎ','๐ŸŽฒ','๐ŸŽฏ','๐ŸŽณ','๐Ÿ†','๐Ÿฅ‡','๐ŸŽ–','๐ŸŽ','๐ŸŽ‰','๐ŸŽŠ','๐ŸŽˆ','๐ŸŽญ','๐ŸŽจ','๐ŸŽฌ','๐ŸŽต','๐ŸŽธ','๐ŸŽน','๐ŸŽบ','๐Ÿช—','๐ŸŽป'] },
18
+ { icon: '๐ŸŒ', emojis: ['๐ŸŒ','๐ŸŒˆ','โญ','๐ŸŒ™','โ˜€๏ธ','โ›…','๐ŸŒŠ','๐Ÿ”ฅ','๐Ÿ’ง','๐ŸŒฟ','๐ŸŒธ','๐ŸŒบ','๐ŸŒป','๐Ÿ€','๐ŸŒด','๐Ÿ”','๐Ÿ–','๐Ÿ•','๐ŸŒƒ','๐Ÿ™','๐ŸŒ…','๐ŸŒ„','๐ŸŒ ','๐ŸŒŒ','๐ŸŒ‹','๐Ÿ'] },
19
+ ];
20
+
21
+ const ApiUrlCtx = createContext('');
22
+ const TokenCtx = createContext('');
23
+
24
+ function playNotificationSound() {
25
+ try {
26
+ const ctx = new AudioContext();
27
+ const osc = ctx.createOscillator();
28
+ const gain = ctx.createGain();
29
+ osc.connect(gain);
30
+ gain.connect(ctx.destination);
31
+ osc.type = 'sine';
32
+ osc.frequency.setValueAtTime(880, ctx.currentTime);
33
+ osc.frequency.exponentialRampToValueAtTime(660, ctx.currentTime + 0.12);
34
+ gain.gain.setValueAtTime(0.25, ctx.currentTime);
35
+ gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.35);
36
+ osc.start(ctx.currentTime);
37
+ osc.stop(ctx.currentTime + 0.35);
38
+ } catch {
39
+ // AudioContext blocked (no prior user interaction) โ€” silently skip
40
+ }
41
+ }
42
+
43
+ function connectionDisplayName(c?: Connection): string | undefined {
44
+ if (!c?.metadata) return undefined;
45
+ const m = c.metadata as Record<string, unknown>;
46
+ const v = m['pageName'] ?? m['displayName'] ?? m['username'] ?? m['name'];
47
+ return typeof v === 'string' && v ? v : undefined;
48
+ }
49
+
50
+ function providerLabel(p?: Provider): string {
51
+ if (p === 'facebook') return 'Facebook Messenger';
52
+ if (p === 'instagram') return 'Instagram';
53
+ if (p === 'telegram') return 'Telegram';
54
+ if (p === 'zalo') return 'Zalo OA';
55
+ return 'Channel';
56
+ }
57
+
58
+ function providerShortLabel(p?: Provider): string {
59
+ if (p === 'facebook') return 'Facebook';
60
+ if (p === 'instagram') return 'Instagram';
61
+ if (p === 'telegram') return 'Telegram';
62
+ if (p === 'zalo') return 'Zalo';
63
+ return String(p ?? '');
64
+ }
65
+
66
+ const mimeLabel = (mime?: string) => {
67
+ const map: Record<string, string> = {
68
+ 'application/pdf': 'PDF', 'video/mp4': 'Video MP4',
69
+ 'audio/mpeg': 'Audio MP3', 'audio/ogg': 'Audio OGG',
70
+ 'application/octet-stream': 'Tแป‡p ฤ‘รญnh kรจm',
71
+ };
72
+ if (!mime) return 'Tแป‡p ฤ‘รญnh kรจm';
73
+ return map[mime] ?? mime.split('/')[1]?.toUpperCase() ?? 'Tแป‡p';
74
+ };
75
+
76
+ function StatusIcon({ status }: { status?: Message['status'] }) {
77
+ if (status === 'read') return <CheckCheck size={11} strokeWidth={2} style={{ display: 'inline', verticalAlign: 'middle' }} />;
78
+ if (status === 'delivered') return <CheckCheck size={11} strokeWidth={2} style={{ display: 'inline', verticalAlign: 'middle', opacity: 0.5 }} />;
79
+ if (status === 'sent') return <Check size={11} strokeWidth={2} style={{ display: 'inline', verticalAlign: 'middle' }} />;
80
+ return null;
81
+ }
82
+
83
+ type ActiveFilters = { provider: Provider | 'all'; unreadOnly: boolean };
84
+
85
+ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(function ChannelHubInbox(
86
+ { apiUrl, token, theme, height, defaultConversationId, disableAttachments, disableNotificationSound, hideKeyboardHint, locale = 'vi', onNewMessage, onConversationSelect },
87
+ ref
88
+ ) {
89
+ const client = useRef(new ChannelHubClient(apiUrl, token));
90
+ const [items, setItems] = useState<Conversation[]>([]); const [connections, setConnections] = useState<Connection[]>([]); const [cursor, setCursor] = useState<string>();
91
+ const [selected, setSelected] = useState<Conversation>(); const selectedId = useRef<string | undefined>(undefined);
92
+ const [query, setQuery] = useState('');
93
+ const [activeFilters, setActiveFilters] = useState<ActiveFilters>({ provider: 'all', unreadOnly: false });
94
+ const [filterOpen, setFilterOpen] = useState(false);
95
+ const filterBtnRef = useRef<HTMLButtonElement>(null);
96
+ const filterPopoverRef = useRef<HTMLDivElement>(null);
97
+ const [popoverAnchor, setPopoverAnchor] = useState<{ top: number; left: number } | null>(null);
98
+ const [loading, setLoading] = useState(true); const [error, setError] = useState('');
99
+ const [infoOpen, setInfoOpen] = useState(false);
100
+ const primary = theme?.primaryColor ?? '#2563eb';
101
+ const connectionById = useMemo(() => new Map(connections.map(connection => [connection.id, connection])), [connections]);
102
+ const appendMessageRef = useRef<((msg: Message) => void) | null>(null);
103
+ const [msgRefreshKey, setMsgRefreshKey] = useState(0);
104
+ const availableProviders = useMemo(() => {
105
+ const ps = new Set(connections.map(cn => cn.provider));
106
+ return (['facebook', 'instagram', 'telegram', 'zalo'] as const).filter(p => ps.has(p));
107
+ }, [connections]);
108
+ const countByProvider = useMemo(() => {
109
+ const counts: Record<string, number> = {};
110
+ for (const conv of items) {
111
+ const p = connectionById.get(conv.connectionId)?.provider ?? 'unknown';
112
+ counts[p] = (counts[p] ?? 0) + 1;
113
+ }
114
+ return counts;
115
+ }, [items, connectionById]);
116
+ 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]);
117
+ 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]);
118
+ useEffect(() => { selectedId.current = selected?.id; }, [selected]);
119
+ useEffect(() => { if (selected?.unreadCount) void client.current.markRead(selected.id).then(() => load()).catch(() => undefined); }, [selected?.id]); // eslint-disable-line react-hooks/exhaustive-deps
120
+
121
+ useEffect(() => {
122
+ if (!filterOpen) return;
123
+ function handleOutside(e: MouseEvent) {
124
+ if (filterBtnRef.current?.contains(e.target as Node)) return;
125
+ if (filterPopoverRef.current?.contains(e.target as Node)) return;
126
+ setFilterOpen(false);
127
+ }
128
+ document.addEventListener('mousedown', handleOutside);
129
+ return () => document.removeEventListener('mousedown', handleOutside);
130
+ }, [filterOpen]);
131
+
132
+ const visible = useMemo(() => {
133
+ const needle = query.toLowerCase().trim();
134
+ return items.filter(x => {
135
+ const label = `${x.contactName ?? ''} ${x.subject ?? ''} ${x.providerConversationKey}`.toLowerCase();
136
+ const provider = connectionById.get(x.connectionId)?.provider ?? 'unknown';
137
+ const matchProvider = activeFilters.provider === 'all' || provider === activeFilters.provider;
138
+ const matchUnread = !activeFilters.unreadOnly || (x.unreadCount ?? 0) > 0;
139
+ return matchProvider && matchUnread && (!needle || label.includes(needle));
140
+ });
141
+ }, [items, connectionById, activeFilters, query]);
142
+
143
+ const hasActiveFilters = activeFilters.provider !== 'all' || activeFilters.unreadOnly;
144
+
145
+ const t: WidgetTranslations = locale === 'en' ? {
146
+ today: 'TODAY', loadOlder: 'โ†‘ Load older messages', loading: 'Loading messagesโ€ฆ', noMessages: 'No messages in this conversation.',
147
+ searchPlaceholder: 'Search conversationsโ€ฆ', unreadOnly: 'Unread only', sendPlaceholder: 'Write a messageโ€ฆ', send: 'Send', all: 'All',
148
+ } : {
149
+ 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.',
150
+ 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แบฃ',
151
+ };
152
+
153
+ useImperativeHandle(ref, () => ({
154
+ openConversation: (id: string) => { const conv = items.find(c => c.id === id); if (conv) setSelected(conv); },
155
+ refresh: () => void load(),
156
+ }), [items, load]);
157
+
158
+ const frame: React.CSSProperties = {
159
+ ...css.frame,
160
+ height: height ?? 620,
161
+ ...(height ? { maxHeight: 'none' } : {}),
162
+ fontFamily: theme?.fontFamily ?? 'Inter, ui-sans-serif, system-ui, sans-serif',
163
+ borderRadius: theme?.borderRadius ?? '16px',
164
+ gridTemplateColumns: infoOpen
165
+ ? 'minmax(260px, 300px) minmax(0, 1fr) 260px'
166
+ : 'minmax(260px, 300px) minmax(0, 1fr)',
167
+ transition: 'grid-template-columns 220ms ease',
168
+ };
169
+ if (loading) return <div style={{ ...css.state, borderRadius: theme?.borderRadius ?? '16px' }}><Spinner /> ฤang tแบฃi hแป™p thฦฐโ€ฆ</div>;
170
+ 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>;
171
+ return (
172
+ <ApiUrlCtx.Provider value={apiUrl}>
173
+ <TokenCtx.Provider value={token}>
174
+ <div style={frame} onFocusCapture={() => { const y = window.scrollY; requestAnimationFrame(() => { if (window.scrollY !== y) window.scrollTo({ top: y, behavior: 'instant' }); }); }}>
175
+ <aside style={css.sidebar}>
176
+ <div style={css.brand}>
177
+ <div style={{ ...css.brandMark, background: primary, overflow: 'hidden', padding: 0 }}>
178
+ {theme?.branding?.logoUrl
179
+ ? <img src={theme.branding.logoUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
180
+ : (theme?.branding?.mark ?? 'C')}
181
+ </div>
182
+ <div>
183
+ <strong>{theme?.branding?.name ?? 'Hแป™p thฦฐ'}</strong>
184
+ {!theme?.branding?.name && <span style={css.eyebrow}>CHANNELHUB</span>}
185
+ </div>
186
+ <Button aria-label="Tรนy chแปn" style={css.iconButton}><MoreHorizontal size={16} strokeWidth={2} /></Button>
187
+ </div>
188
+ <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>
189
+
190
+ {/* Active filter chips */}
191
+ {hasActiveFilters && (
192
+ <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', padding: '0 14px 8px' }}>
193
+ {activeFilters.provider !== 'all' && (
194
+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: '#eef2ff', color: primary, borderRadius: 6, fontSize: 11, padding: '2px 8px', fontWeight: 500 }}>
195
+ <ProviderMark provider={activeFilters.provider} />
196
+ {providerShortLabel(activeFilters.provider)}
197
+ <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>
198
+ </span>
199
+ )}
200
+ {activeFilters.unreadOnly && (
201
+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: '#eef2ff', color: primary, borderRadius: 6, fontSize: 11, padding: '2px 8px', fontWeight: 500 }}>
202
+ {t.unreadOnly}
203
+ <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>
204
+ </span>
205
+ )}
206
+ <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>
207
+ </div>
208
+ )}
209
+
210
+ <div style={css.listHeader}>
211
+ <span>{visible.length} hแป™i thoแบกi</span>
212
+ <button
213
+ ref={filterBtnRef}
214
+ style={{ ...css.iconButton, background: hasActiveFilters ? `${primary}14` : 'transparent', color: hasActiveFilters ? primary : c.muted }}
215
+ aria-label="Bแป™ lแปc"
216
+ onClick={() => {
217
+ if (!filterOpen) {
218
+ const rect = filterBtnRef.current?.getBoundingClientRect();
219
+ if (rect) setPopoverAnchor({ top: rect.bottom + 6, left: rect.left });
220
+ }
221
+ setFilterOpen(o => !o);
222
+ }}
223
+ >
224
+ <SlidersHorizontal size={15} strokeWidth={2} />
225
+ </button>
226
+ </div>
227
+
228
+ {/* Portal popover โ€” rendered into document.body, escapes overflow:hidden entirely */}
229
+ {filterOpen && popoverAnchor && createPortal(
230
+ <div
231
+ ref={filterPopoverRef}
232
+ 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 }}
233
+ >
234
+ <div style={{ fontSize: 10, fontWeight: 700, color: c.muted, letterSpacing: 1, textTransform: 'uppercase' as const, marginBottom: 8 }}>Kรชnh</div>
235
+ {(['all', ...availableProviders] as const).map(p => (
236
+ <label key={p} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 6px', cursor: 'pointer', borderRadius: 6, background: activeFilters.provider === p ? `${primary}0f` : 'transparent' }}>
237
+ <input type="radio" name="provider-filter" checked={activeFilters.provider === p} onChange={() => setActiveFilters(f => ({ ...f, provider: p }))} style={{ accentColor: primary }} />
238
+ {p === 'all'
239
+ ? <span style={{ color: c.ink }}>{t.all} ({items.length})</span>
240
+ : <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>}
241
+ </label>
242
+ ))}
243
+ <div style={{ borderTop: `1px solid ${c.line}`, margin: '8px 0 6px' }} />
244
+ <label style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 6px', cursor: 'pointer', borderRadius: 6, background: activeFilters.unreadOnly ? `${primary}0f` : 'transparent' }}>
245
+ <input type="checkbox" checked={activeFilters.unreadOnly} onChange={e => setActiveFilters(f => ({ ...f, unreadOnly: e.target.checked }))} style={{ accentColor: primary }} />
246
+ <span style={{ color: c.ink }}>{t.unreadOnly}</span>
247
+ </label>
248
+ </div>,
249
+ document.body
250
+ )}
251
+
252
+ <ScrollArea style={css.conversationList}>
253
+ {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); }} />)}
254
+ {!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>}
255
+ {cursor && <button style={css.loadMore} onClick={() => void load(cursor)}>Xem thรชm hแป™i thoแบกi</button>}
256
+ </ScrollArea>
257
+ </aside>
258
+ <main style={css.main}>
259
+ {selected ? (
260
+ <MessagePanel
261
+ key={selected.id}
262
+ conversation={selected}
263
+ provider={connectionById.get(selected.connectionId)?.provider}
264
+ connection={connectionById.get(selected.connectionId)}
265
+ client={client.current}
266
+ primary={primary}
267
+ error={error}
268
+ onRegisterAppend={(fn) => { appendMessageRef.current = fn; }}
269
+ refreshKey={msgRefreshKey}
270
+ infoOpen={infoOpen}
271
+ onToggleInfo={() => setInfoOpen(o => !o)}
272
+ t={t}
273
+ disableAttachments={disableAttachments}
274
+ hideKeyboardHint={hideKeyboardHint}
275
+ />
276
+ ) : <EmptyConversation />}
277
+ </main>
278
+ {infoOpen && selected && (
279
+ <ContactInfoPanel
280
+ conversation={selected}
281
+ connection={connectionById.get(selected.connectionId)}
282
+ primary={primary}
283
+ onClose={() => setInfoOpen(false)}
284
+ client={client.current}
285
+ />
286
+ )}
287
+ </div>
288
+ </TokenCtx.Provider>
289
+ </ApiUrlCtx.Provider>
290
+ );
291
+ });
292
+
293
+ function ConversationRow({ conversation, provider, selected, primary, onSelect }: { conversation: Conversation; provider?: Provider; selected: boolean; primary: string; onSelect: () => void }) {
294
+ const [hovered, setHovered] = useState(false);
295
+ const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
296
+ const unread = conversation.unreadCount ?? 0;
297
+ const rawText = conversation.lastMessageText ?? '';
298
+ const prefix = conversation.lastMessageDirection === 'outbound' ? 'Bแบกn: ' : '';
299
+ const truncated = rawText.length > 60 ? rawText.slice(0, 60) + 'โ€ฆ' : rawText;
300
+ const preview = rawText ? prefix + truncated : '';
301
+
302
+ let rowBg = 'transparent';
303
+ if (selected) rowBg = '#eef2ff';
304
+ else if (hovered) rowBg = '#f7f9fc';
305
+ else if (unread > 0) rowBg = '#f0f4ff';
306
+
307
+ const rowStyle: React.CSSProperties = {
308
+ ...css.row,
309
+ background: rowBg,
310
+ ...(selected ? { boxShadow: `inset 3px 0 0 ${primary}` } : unread > 0 && !hovered ? { boxShadow: `inset 3px 0 0 ${primary}` } : {}),
311
+ };
312
+
313
+ return (
314
+ <button
315
+ onClick={onSelect}
316
+ style={rowStyle}
317
+ onMouseEnter={() => setHovered(true)}
318
+ onMouseLeave={() => setHovered(false)}
319
+ >
320
+ <ContactAvatar name={name} color={primary} image={conversation.contactPictureUrl} provider={provider} />
321
+ <span style={css.rowBody}>
322
+ <span style={css.rowTop}>
323
+ <strong style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: unread > 0 ? 700 : 500 }}>{name}</strong>
324
+ <span style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
325
+ <time style={{ color: c.muted, fontSize: 11, whiteSpace: 'nowrap' }}>{formatTime(conversation.lastMessageAt)}</time>
326
+ {unread > 0 && (
327
+ <span aria-label={`${unread} tin nhแบฏn chฦฐa ฤ‘แปc`} style={css.unreadBadge}>
328
+ {unread > 99 ? '99+' : unread}
329
+ </span>
330
+ )}
331
+ </span>
332
+ </span>
333
+ <span style={{ ...css.rowBottom, color: unread > 0 && !selected ? '#4a5568' : c.muted }}>
334
+ <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>
335
+ {preview || <span style={{ opacity: 0.5 }}>Chฦฐa cรณ tin nhแบฏn</span>}
336
+ </span>
337
+ </span>
338
+ </span>
339
+ </button>
340
+ );
341
+ }
342
+
343
+ type PendingAttachment = { file: File; uploading: boolean; url?: string; mimeType?: string; attachmentType?: string; objectUrl?: string };
344
+
345
+ 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 }) {
346
+ 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;
347
+ const fileImageRef = useRef<HTMLInputElement>(null);
348
+ const fileDocRef = useRef<HTMLInputElement>(null);
349
+ const [pendingAttachment, setPendingAttachment] = useState<PendingAttachment | null>(null);
350
+ const [boldActive, setBoldActive] = useState(false);
351
+ const [italicActive, setItalicActive] = useState(false);
352
+ const [emojiOpen, setEmojiOpen] = useState(false);
353
+ const [emojiCategory, setEmojiCategory] = useState(0);
354
+ const emojiPickerRef = useRef<HTMLDivElement>(null);
355
+ const emojiBtnRef = useRef<HTMLButtonElement>(null);
356
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
357
+ const [templateOpen, setTemplateOpen] = useState(false);
358
+ const [templateSearch, setTemplateSearch] = useState('');
359
+ const [templates, setTemplates] = useState<{ id: string; title: string; content: string; shortcut: string | null }[]>([]);
360
+ const templatePickerRef = useRef<HTMLDivElement>(null);
361
+ const templateBtnRef = useRef<HTMLButtonElement>(null);
362
+
363
+ useEffect(() => {
364
+ return () => { if (pendingAttachment?.objectUrl) URL.revokeObjectURL(pendingAttachment.objectUrl); };
365
+ }, [pendingAttachment?.objectUrl]);
366
+
367
+ useEffect(() => {
368
+ if (!emojiOpen) return;
369
+ function handleOutside(e: MouseEvent) {
370
+ if (emojiBtnRef.current?.contains(e.target as Node)) return;
371
+ if (emojiPickerRef.current?.contains(e.target as Node)) return;
372
+ setEmojiOpen(false);
373
+ }
374
+ document.addEventListener('mousedown', handleOutside);
375
+ return () => document.removeEventListener('mousedown', handleOutside);
376
+ }, [emojiOpen]);
377
+
378
+ useEffect(() => {
379
+ void client.listCannedResponses().then(setTemplates).catch(() => undefined);
380
+ }, [client]);
381
+
382
+ useEffect(() => {
383
+ if (!templateOpen) return;
384
+ function handleOutside(e: MouseEvent) {
385
+ if (templateBtnRef.current?.contains(e.target as Node)) return;
386
+ if (templatePickerRef.current?.contains(e.target as Node)) return;
387
+ setTemplateOpen(false);
388
+ }
389
+ document.addEventListener('mousedown', handleOutside);
390
+ return () => document.removeEventListener('mousedown', handleOutside);
391
+ }, [templateOpen]);
392
+
393
+
394
+ const shouldScrollToBottom = useRef(true);
395
+
396
+ const load = useCallback(async (next?: string, silent?: boolean) => {
397
+ if (!silent) shouldScrollToBottom.current = !next;
398
+ try {
399
+ const page = await client.listMessages(conversation.id, next);
400
+ setMessages(old => next ? [...page.items, ...old] : page.items);
401
+ setCursor(page.nextCursor);
402
+ } catch (e) { setSendError(e instanceof Error ? e.message : 'Khรดng tแบฃi ฤ‘ฦฐแปฃc tin nhแบฏn'); }
403
+ finally { if (!silent) setLoading(false); }
404
+ }, [client, conversation.id]);
405
+
406
+ useEffect(() => { setLoading(true); void load(); }, [load]);
407
+
408
+ useEffect(() => {
409
+ if (!refreshKey) return;
410
+ void load(undefined, true);
411
+ }, [refreshKey]); // eslint-disable-line react-hooks/exhaustive-deps
412
+
413
+ useEffect(() => {
414
+ if (!shouldScrollToBottom.current) return;
415
+ requestAnimationFrame(() => { const el = messageAreaRef.current; if (el) el.scrollTop = el.scrollHeight; });
416
+ }, [messages]);
417
+
418
+ useEffect(() => {
419
+ onRegisterAppend?.((msg: Message) => {
420
+ shouldScrollToBottom.current = true;
421
+ setMessages(prev => { if (prev.some(m => m.id === msg.id)) return prev; return [...prev, msg]; });
422
+ });
423
+ return () => { onRegisterAppend?.(null); };
424
+ }, [onRegisterAppend]);
425
+
426
+ async function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
427
+ const file = e.target.files?.[0];
428
+ if (!file) return;
429
+ e.target.value = '';
430
+ const objectUrl = URL.createObjectURL(file);
431
+ setPendingAttachment({ file, uploading: true, objectUrl });
432
+ try {
433
+ const result = await client.uploadAttachment(file);
434
+ setPendingAttachment({ file, uploading: false, url: result.url, mimeType: result.mimeType, attachmentType: result.attachmentType, objectUrl });
435
+ } catch {
436
+ URL.revokeObjectURL(objectUrl);
437
+ setPendingAttachment(null);
438
+ setSendError('Khรดng tแบฃi lรชn ฤ‘ฦฐแปฃc tแป‡p ฤ‘รญnh kรจm');
439
+ }
440
+ }
441
+
442
+ async function send(event: FormEvent) {
443
+ event.preventDefault();
444
+ const value = text.trim();
445
+ const attachments: MessageAttachment[] = pendingAttachment?.url
446
+ ? [{ url: pendingAttachment.url, mimeType: pendingAttachment.mimeType ?? 'application/octet-stream', type: pendingAttachment.attachmentType as MessageAttachment['type'] }]
447
+ : [];
448
+ if (!value && !attachments.length || sending) return;
449
+ setSending(true); setSendError('');
450
+ try {
451
+ await client.sendMessage(conversation.id, value || undefined, attachments.length ? attachments : undefined);
452
+ if (pendingAttachment?.objectUrl) URL.revokeObjectURL(pendingAttachment.objectUrl);
453
+ setText(''); setPendingAttachment(null); await load();
454
+ } catch (e) { setSendError(e instanceof Error ? e.message : 'Khรดng gแปญi ฤ‘ฦฐแปฃc tin nhแบฏn'); } finally { setSending(false); }
455
+ }
456
+
457
+ function insertEmoji(emoji: string) {
458
+ const ta = textareaRef.current;
459
+ if (!ta) { setText(t => t + emoji); setEmojiOpen(false); return; }
460
+ const start = ta.selectionStart ?? text.length;
461
+ const end = ta.selectionEnd ?? text.length;
462
+ const newText = text.slice(0, start) + emoji + text.slice(end);
463
+ setText(newText);
464
+ setEmojiOpen(false);
465
+ requestAnimationFrame(() => {
466
+ ta.focus();
467
+ ta.selectionStart = ta.selectionEnd = start + emoji.length;
468
+ });
469
+ }
470
+
471
+ function insertTemplate(content: string) {
472
+ setText(content);
473
+ setTemplateOpen(false);
474
+ setTemplateSearch('');
475
+ requestAnimationFrame(() => {
476
+ const ta = textareaRef.current;
477
+ if (!ta) return;
478
+ ta.focus();
479
+ ta.selectionStart = ta.selectionEnd = content.length;
480
+ });
481
+ }
482
+
483
+ const canSend = !sending && (text.trim().length > 0 || (pendingAttachment?.url != null && !pendingAttachment.uploading));
484
+
485
+ return (
486
+ <section style={css.chat}>
487
+ <header style={css.chatHeader}>
488
+ <ContactAvatar name={name} color={primary} image={conversation.contactPictureUrl} provider={provider} />
489
+ <div style={css.contact}>
490
+ <strong style={css.contactName}>{name}</strong>
491
+ <span style={css.contactMeta}>{connectionDisplayName(connection) ?? providerLabel(provider)}</span>
492
+ </div>
493
+ <div style={css.headerActions}>
494
+ <button style={css.iconButton} aria-label="Thรชm tรนy chแปn">
495
+ <MoreHorizontal size={16} strokeWidth={2} />
496
+ </button>
497
+ <button
498
+ style={{
499
+ ...css.iconButton,
500
+ background: infoOpen ? `${primary}14` : 'transparent',
501
+ color: infoOpen ? primary : c.muted,
502
+ }}
503
+ aria-label="Thรดng tin liรชn hแป‡"
504
+ onClick={onToggleInfo}
505
+ >
506
+ <Info size={16} strokeWidth={2} />
507
+ </button>
508
+ </div>
509
+ </header>
510
+ <ScrollArea ref={messageAreaRef} style={css.messageArea}>
511
+ <div style={css.day}>{t.today}</div>
512
+ {cursor && <button onClick={() => void load(cursor)} style={css.historyButton}>{t.loadOlder}</button>}
513
+ {loading && <div style={css.messageHint}><Spinner /> {t.loading}</div>}
514
+ {!loading && !messages.length && <div style={css.messageHint}>{t.noMessages}</div>}
515
+ {messages.map(m => <MessageBubble key={m.id} message={m} primary={primary} />)}
516
+ </ScrollArea>
517
+ {/* Quick reply chips */}
518
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', padding: '6px 14px 2px', borderTop: `1px solid ${c.line}` }}>
519
+ {['Cแบฃm ฦกn bแบกn ฤ‘รฃ liรชn hแป‡ ๐Ÿ™', 'Mรฌnh sแบฝ kiแปƒm tra ngay', 'Vui lรฒng chแป 1-2 phรบt'].map(chip => (
520
+ <button
521
+ key={chip}
522
+ type="button"
523
+ onClick={() => setText(chip)}
524
+ style={{
525
+ fontSize: 11, padding: '3px 10px', borderRadius: 999,
526
+ background: `${primary}0f`, color: primary,
527
+ border: `1px solid ${primary}33`,
528
+ cursor: 'pointer', whiteSpace: 'nowrap' as const,
529
+ }}
530
+ >
531
+ {chip}
532
+ </button>
533
+ ))}
534
+ </div>
535
+ <form onSubmit={send} style={{ flex: '0 0 auto', padding: '8px 14px 12px', borderTop: `1px solid ${c.line}`, background: c.white, position: 'relative' }}>
536
+ {/* Emoji picker popover โ€” absolute positioned above composer */}
537
+ {emojiOpen && (
538
+ <div
539
+ ref={emojiPickerRef}
540
+ style={{
541
+ position: 'absolute',
542
+ bottom: 'calc(100% + 6px)',
543
+ left: 0,
544
+ zIndex: 100,
545
+ background: c.white,
546
+ border: `1px solid ${c.line}`,
547
+ borderRadius: 12,
548
+ boxShadow: '0 8px 24px rgba(23,32,51,.14)',
549
+ width: 280,
550
+ overflow: 'hidden',
551
+ fontFamily: 'inherit',
552
+ }}
553
+ >
554
+ {/* Category tabs */}
555
+ <div style={{ display: 'flex', borderBottom: `1px solid ${c.line}`, background: '#f9fafb' }}>
556
+ {EMOJI_CATEGORIES.map((cat, i) => (
557
+ <button
558
+ key={i}
559
+ type="button"
560
+ onClick={() => setEmojiCategory(i)}
561
+ style={{
562
+ flex: 1, border: 0, background: 'transparent', padding: '7px 2px',
563
+ fontSize: 16, cursor: 'pointer', lineHeight: 1,
564
+ borderBottom: emojiCategory === i ? `2px solid ${primary}` : '2px solid transparent',
565
+ opacity: emojiCategory === i ? 1 : 0.5,
566
+ transition: 'opacity 100ms ease',
567
+ }}
568
+ >
569
+ {cat.icon}
570
+ </button>
571
+ ))}
572
+ </div>
573
+ {/* Emoji grid */}
574
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 2, padding: 8, maxHeight: 180, overflowY: 'auto' }}>
575
+ {EMOJI_CATEGORIES[emojiCategory]?.emojis.map((emoji, i) => (
576
+ <button
577
+ key={i}
578
+ type="button"
579
+ onClick={() => insertEmoji(emoji)}
580
+ style={{
581
+ border: 0, background: 'transparent', padding: '5px 2px',
582
+ fontSize: 18, cursor: 'pointer', borderRadius: 6, lineHeight: 1,
583
+ transition: 'background 80ms ease',
584
+ }}
585
+ onMouseEnter={e => { (e.target as HTMLElement).style.background = '#f3f4f6'; }}
586
+ onMouseLeave={e => { (e.target as HTMLElement).style.background = 'transparent'; }}
587
+ >
588
+ {emoji}
589
+ </button>
590
+ ))}
591
+ </div>
592
+ </div>
593
+ )}
594
+ {templateOpen && (
595
+ <div
596
+ ref={templatePickerRef}
597
+ style={{
598
+ position: 'absolute',
599
+ bottom: 'calc(100% + 6px)',
600
+ left: 0,
601
+ zIndex: 100,
602
+ background: c.white,
603
+ border: `1px solid ${c.line}`,
604
+ borderRadius: 12,
605
+ boxShadow: '0 8px 24px rgba(23,32,51,.14)',
606
+ width: 300,
607
+ overflow: 'hidden',
608
+ fontFamily: 'inherit',
609
+ }}
610
+ >
611
+ <div style={{ padding: '8px 10px', borderBottom: `1px solid ${c.line}` }}>
612
+ <input
613
+ autoFocus
614
+ type="text"
615
+ placeholder="Tรฌm templateโ€ฆ"
616
+ value={templateSearch}
617
+ onChange={e => setTemplateSearch(e.target.value)}
618
+ style={{ width: '100%', boxSizing: 'border-box' as const, border: `1px solid ${c.line}`, borderRadius: 7, padding: '5px 8px', fontSize: 12, outline: 'none', fontFamily: 'inherit', color: c.ink }}
619
+ />
620
+ </div>
621
+ <div style={{ maxHeight: 220, overflowY: 'auto' }}>
622
+ {(() => {
623
+ const q = templateSearch.trim().toLowerCase();
624
+ const filtered = q ? templates.filter(t => t.title.toLowerCase().includes(q) || t.content.toLowerCase().includes(q) || (t.shortcut ?? '').toLowerCase().includes(q)) : templates;
625
+ if (!filtered.length) return (
626
+ <div style={{ padding: '24px 16px', textAlign: 'center' as const, color: c.muted, fontSize: 12 }}>
627
+ {templates.length === 0 ? 'Chฦฐa cรณ template nร o' : 'Khรดng tรฌm thแบฅy'}
628
+ </div>
629
+ );
630
+ return filtered.map(tpl => (
631
+ <button
632
+ key={tpl.id}
633
+ type="button"
634
+ onClick={() => insertTemplate(tpl.content)}
635
+ style={{ display: 'block', width: '100%', textAlign: 'left' as const, border: 0, borderBottom: `1px solid ${c.line}`, background: 'transparent', padding: '9px 12px', cursor: 'pointer', fontFamily: 'inherit' }}
636
+ onMouseEnter={e => { (e.currentTarget as HTMLElement).style.background = '#f7f9fc'; }}
637
+ onMouseLeave={e => { (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
638
+ >
639
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
640
+ <span style={{ fontSize: 12, fontWeight: 600, color: c.ink }}>{tpl.title}</span>
641
+ {tpl.shortcut && <span style={{ fontSize: 10, color: primary, background: `${primary}18`, borderRadius: 4, padding: '1px 5px' }}>{tpl.shortcut}</span>}
642
+ </div>
643
+ <div style={{ fontSize: 11, color: c.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const }}>{tpl.content}</div>
644
+ </button>
645
+ ));
646
+ })()}
647
+ </div>
648
+ </div>
649
+ )}
650
+ <div style={{ border: `1.5px solid ${c.line}`, borderRadius: 12, background: c.white, overflow: 'hidden' }}>
651
+
652
+ {/* Attachment preview */}
653
+ {pendingAttachment && (
654
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderBottom: `1px solid ${c.line}`, fontSize: 12 }}>
655
+ {pendingAttachment.uploading
656
+ ? <><Spinner /><span style={{ color: c.muted }}>ฤang tแบฃi lรชnโ€ฆ</span></>
657
+ : pendingAttachment.attachmentType === 'image' && pendingAttachment.objectUrl
658
+ ? <img src={pendingAttachment.objectUrl} alt="" style={{ height: 48, width: 48, objectFit: 'cover', borderRadius: 6 }} />
659
+ : <span style={{ color: c.muted }}>๐Ÿ“Ž {pendingAttachment.file.name} ({Math.round(pendingAttachment.file.size / 1024)} KB)</span>
660
+ }
661
+ {!pendingAttachment.uploading && (
662
+ <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>
663
+ )}
664
+ </div>
665
+ )}
666
+
667
+ {/* Toolbar */}
668
+ <div style={{ display: 'flex', alignItems: 'center', gap: 2, padding: '4px 8px', borderBottom: `1px solid #f3f4f6` }}>
669
+ {/* Emoji */}
670
+ <button
671
+ ref={emojiBtnRef}
672
+ type="button"
673
+ title="Chรจn emoji"
674
+ onClick={() => setEmojiOpen(o => !o)}
675
+ style={{ ...css.toolbarBtn, background: emojiOpen ? `${primary}18` : 'transparent', color: emojiOpen ? primary : '#9ca3af' }}
676
+ >
677
+ <Smile size={13} strokeWidth={2} />
678
+ </button>
679
+ {/* Image/Video button */}
680
+ {!disableAttachments && (
681
+ <button type="button" title="Gแปญi แบฃnh / video" aria-label="Gแปญi แบฃnh hoแบทc video" style={css.toolbarBtn} onClick={() => fileImageRef.current?.click()}>
682
+ <Image size={13} strokeWidth={2} />
683
+ </button>
684
+ )}
685
+ {/* File button */}
686
+ {!disableAttachments && (
687
+ <button type="button" title="Gแปญi tแป‡p ฤ‘รญnh kรจm" aria-label="Gแปญi tแป‡p ฤ‘รญnh kรจm" style={css.toolbarBtn} onClick={() => fileDocRef.current?.click()}>
688
+ <Paperclip size={13} strokeWidth={2} />
689
+ </button>
690
+ )}
691
+ {!disableAttachments && (
692
+ <>
693
+ <input ref={fileImageRef} type="file" style={{ display: 'none' }} onChange={handleFileSelect} accept="image/*,video/mp4" />
694
+ <input ref={fileDocRef} type="file" style={{ display: 'none' }} onChange={handleFileSelect} accept=".pdf,audio/mpeg,audio/ogg,application/octet-stream,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
695
+ </>
696
+ )}
697
+ {/* Template */}
698
+ <button
699
+ ref={templateBtnRef}
700
+ type="button"
701
+ title="Template nhanh"
702
+ onClick={() => { setTemplateOpen(o => !o); setTemplateSearch(''); }}
703
+ style={{ ...css.toolbarBtn, background: templateOpen ? `${primary}18` : 'transparent', color: templateOpen ? primary : '#9ca3af' }}
704
+ >
705
+ <Zap size={13} strokeWidth={2} />
706
+ </button>
707
+ {/* Separator */}
708
+ <span style={{ width: 1, height: 14, background: '#e5e7eb', margin: '0 2px' }} />
709
+ {/* Bold */}
710
+ <button type="button" title="In ฤ‘แบญm" onClick={() => setBoldActive(b => !b)}
711
+ style={{ ...css.toolbarBtn, fontWeight: 700, fontSize: 12, background: boldActive ? `${primary}18` : 'transparent', color: boldActive ? primary : '#9ca3af', border: boldActive ? `1px solid ${primary}33` : '1px solid transparent' }}>
712
+ B
713
+ </button>
714
+ {/* Italic */}
715
+ <button type="button" title="Nghiรชng" onClick={() => setItalicActive(i => !i)}
716
+ style={{ ...css.toolbarBtn, fontStyle: 'italic', fontSize: 12, background: italicActive ? `${primary}18` : 'transparent', color: italicActive ? primary : '#9ca3af', border: italicActive ? `1px solid ${primary}33` : '1px solid transparent' }}>
717
+ I
718
+ </button>
719
+ </div>
720
+
721
+ {/* Textarea */}
722
+ <Textarea
723
+ ref={textareaRef}
724
+ aria-label="Soแบกn tin nhแบฏn"
725
+ rows={2}
726
+ value={text}
727
+ onChange={e => setText(e.target.value)}
728
+ onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(e); } }}
729
+ placeholder={t.sendPlaceholder}
730
+ style={{
731
+ display: 'block', width: '100%', minWidth: 0, boxSizing: 'border-box' as const,
732
+ minHeight: 52, maxHeight: 120, resize: 'none' as const,
733
+ border: 0, outline: 0,
734
+ background: 'transparent',
735
+ color: c.ink,
736
+ padding: '8px 12px 4px',
737
+ font: 'inherit', fontSize: 13, lineHeight: 1.45,
738
+ fontStyle: italicActive ? 'italic' : 'normal',
739
+ fontWeight: boldActive ? 700 : 400,
740
+ }}
741
+ />
742
+
743
+ {/* Bottom bar */}
744
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 8px 6px 12px' }}>
745
+ <span style={{
746
+ fontSize: 11,
747
+ color: text.length > 1000 ? '#ef4444' : text.length > 900 ? '#f59e0b' : '#9ca3af',
748
+ fontWeight: text.length > 1000 ? 600 : 400,
749
+ }}>
750
+ {text.length}/1000
751
+ </span>
752
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
753
+ {!hideKeyboardHint && <span style={{ fontSize: 10, color: '#9ca3af' }}>โ†ต Gแปญi ยท โ‡งโ†ต Xuแป‘ng dรฒng</span>}
754
+ <button
755
+ disabled={!canSend}
756
+ aria-label="Gแปญi tin nhแบฏn"
757
+ style={{
758
+ display: 'flex', alignItems: 'center', gap: 5,
759
+ padding: '5px 12px', border: 0, borderRadius: 999,
760
+ fontSize: 12, fontWeight: 600,
761
+ background: !canSend ? '#e5e7eb' : `linear-gradient(135deg,${primary},#0ea5e9)`,
762
+ color: !canSend ? '#9ca3af' : '#fff',
763
+ cursor: !canSend ? 'not-allowed' : 'pointer',
764
+ boxShadow: canSend ? '0 2px 8px rgba(37,99,235,0.25)' : 'none',
765
+ transition: 'all 150ms ease',
766
+ }}
767
+ >
768
+ {sending ? <Loader2 size={12} style={{ animation: 'channelhub-spin .7s linear infinite' }} /> : <Send size={12} strokeWidth={2} />}
769
+ {t.send}
770
+ </button>
771
+ </div>
772
+ </div>
773
+ </div>
774
+ </form>
775
+ {(sendError || error) && <div role="alert" style={css.error}>{sendError || error}</div>}
776
+ </section>
777
+ );
778
+ }
779
+
780
+ function MessageBubble({ message, primary }: { message: Message; primary: string }) {
781
+ const apiUrl = useContext(ApiUrlCtx);
782
+ const token = useContext(TokenCtx);
783
+ const resolveUrl = (url: string): string =>
784
+ url.startsWith('/v1/media/proxy') ? `${apiUrl}${url}&tok=${encodeURIComponent(token)}` : url;
785
+
786
+ const outbound = message.direction === 'outbound';
787
+ const images = message.attachments?.filter(a => a.type === 'image') ?? [];
788
+ const stickers = message.attachments?.filter(a => a.type === 'sticker') ?? [];
789
+ const videos = message.attachments?.filter(a => a.type === 'video') ?? [];
790
+ const audios = message.attachments?.filter(a => a.type === 'audio') ?? [];
791
+ const files = message.attachments?.filter(a => a.type === 'file') ?? [];
792
+ const [lightbox, setLightbox] = useState<{ url: string; kind: 'image' | 'video' } | null>(null);
793
+ const align = outbound ? 'flex-end' : 'flex-start';
794
+
795
+ const timeEl = (
796
+ <time style={{ display: 'block', marginTop: 4, fontSize: 10, opacity: 0.65, textAlign: 'right', letterSpacing: 0.2, userSelect: 'none' as const }}>
797
+ {formatTime(message.occurredAt, true)}{outbound && <> <StatusIcon status={message.status} /></>}
798
+ </time>
799
+ );
800
+
801
+ const overlayTime = (
802
+ <div style={{ position: 'absolute', bottom: 6, right: 8 }}>
803
+ <time style={{ fontSize: 10, color: '#fff', textShadow: '0 1px 3px rgba(0,0,0,.5)', letterSpacing: 0.2, userSelect: 'none' as const }}>
804
+ {formatTime(message.occurredAt, true)}{outbound && <> <StatusIcon status={message.status} /></>}
805
+ </time>
806
+ </div>
807
+ );
808
+
809
+ const bubbleStyle = outbound
810
+ ? { ...css.bubbleOut, background: primary, color: '#fff', border: '1px solid transparent' }
811
+ : css.bubbleIn;
812
+
813
+ const mediaOnly = !message.text && audios.length === 0 && files.length === 0;
814
+
815
+ return (
816
+ <div style={{ ...css.messageLine, justifyContent: align, flexDirection: 'column', alignItems: align }}>
817
+ {/* Stickers โ€” small, no lightbox */}
818
+ {stickers.map((a, i) => (
819
+ <div key={`s${i}`} style={{ position: 'relative', marginBottom: 2 }}>
820
+ <img src={resolveUrl(a.url)} alt="sticker" style={{ display: 'block', maxWidth: 128, maxHeight: 128, objectFit: 'contain' }} />
821
+ {mediaOnly && images.length === 0 && videos.length === 0 && i === stickers.length - 1 && overlayTime}
822
+ </div>
823
+ ))}
824
+ {/* Images โ€” outside bubble */}
825
+ {images.map((a, i) => (
826
+ <div key={i} style={{ position: 'relative', marginBottom: 2, cursor: 'zoom-in' }} onClick={() => setLightbox({ url: resolveUrl(a.url), kind: 'image' })}>
827
+ <img src={resolveUrl(a.url)} alt="" style={{ display: 'block', maxWidth: 260, maxHeight: 260, borderRadius: 12, objectFit: 'cover' }} />
828
+ {mediaOnly && i === images.length - 1 && videos.length === 0 && overlayTime}
829
+ </div>
830
+ ))}
831
+ {/* Videos โ€” outside bubble, thumbnail with play overlay */}
832
+ {videos.map((a, i) => (
833
+ <div key={i} style={{ position: 'relative', marginBottom: 2, cursor: 'pointer' }} onClick={() => setLightbox({ url: resolveUrl(a.url), kind: 'video' })}>
834
+ <video src={resolveUrl(a.url)} style={{ display: 'block', maxWidth: 260, maxHeight: 200, borderRadius: 12, objectFit: 'cover' }} />
835
+ <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 12, background: 'rgba(0,0,0,.25)' }}>
836
+ <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'rgba(255,255,255,.9)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
837
+ <Play size={16} fill="#172033" color="#172033" style={{ marginLeft: 2 }} />
838
+ </div>
839
+ </div>
840
+ {mediaOnly && i === videos.length - 1 && overlayTime}
841
+ </div>
842
+ ))}
843
+ {/* Audio / file / text inside bubble */}
844
+ {(audios.length > 0 || files.length > 0 || message.text || (!images.length && !videos.length && !stickers.length && !message.text)) && (
845
+ <div style={bubbleStyle}>
846
+ {audios.map((a, i) => <audio key={i} src={resolveUrl(a.url)} controls style={{ display: 'block', width: '100%', marginBottom: 4 }} />)}
847
+ {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>)}
848
+ {message.text && <p style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{message.text}</p>}
849
+ {!audios.length && !files.length && !message.text && <p style={{ margin: 0, opacity: 0.5 }}>[attachment]</p>}
850
+ {timeEl}
851
+ </div>
852
+ )}
853
+ {/* Lightbox */}
854
+ {lightbox && createPortal(
855
+ <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' }}>
856
+ {lightbox.kind === 'image'
857
+ ? <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()} />
858
+ : <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()} />
859
+ }
860
+ <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' }}>
861
+ <X size={18} />
862
+ </button>
863
+ </div>,
864
+ document.body
865
+ )}
866
+ </div>
867
+ );
868
+ }
869
+
870
+ function ContactInfoPanel({
871
+ conversation,
872
+ connection,
873
+ primary,
874
+ onClose,
875
+ client,
876
+ }: {
877
+ conversation: Conversation;
878
+ connection?: Connection;
879
+ primary: string;
880
+ onClose: () => void;
881
+ client: ChannelHubClient;
882
+ }) {
883
+ const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
884
+ const provider = connection?.provider;
885
+ const [expanded, setExpanded] = useState<Record<string, boolean>>({ channel: true, stats: false, extra: false });
886
+ const toggle = (key: string) => setExpanded(e => ({ ...e, [key]: !e[key] }));
887
+ const [noteText, setNoteText] = useState('');
888
+ const [noteSaving, setNoteSaving] = useState(false);
889
+ const [noteSaved, setNoteSaved] = useState(false);
890
+ const [noteError, setNoteError] = useState('');
891
+
892
+ useEffect(() => {
893
+ setNoteText('');
894
+ setNoteSaved(false);
895
+ setNoteError('');
896
+ client.getNote(conversation.id)
897
+ .then(note => { if (note) setNoteText(note.content); })
898
+ .catch(() => undefined);
899
+ }, [conversation.id, client]);
900
+
901
+ async function saveNote() {
902
+ if (!noteText.trim() || noteSaving) return;
903
+ setNoteSaving(true);
904
+ setNoteError('');
905
+ try {
906
+ await client.upsertNote(conversation.id, noteText.trim());
907
+ setNoteSaved(true);
908
+ setTimeout(() => setNoteSaved(false), 2000);
909
+ } catch {
910
+ setNoteError('Lฦฐu thแบฅt bแบกi');
911
+ } finally {
912
+ setNoteSaving(false);
913
+ }
914
+ }
915
+
916
+ return (
917
+ <aside style={css.infoPanel}>
918
+ <div style={css.infoPanelHeader}>
919
+ <span style={{ fontWeight: 600, fontSize: 13, color: c.ink }}>Thรดng tin liรชn hแป‡</span>
920
+ <button style={css.iconButton} onClick={onClose} aria-label="ฤรณng">
921
+ <X size={16} strokeWidth={2} />
922
+ </button>
923
+ </div>
924
+
925
+ <div style={{ overflowY: 'auto', flex: 1 }}>
926
+ <div style={css.infoPanelIdentity}>
927
+ <span style={{ ...css.avatarWrap, width: 48, height: 48 }}>
928
+ <UiAvatar
929
+ src={conversation.contactPictureUrl}
930
+ fallback={initials(name)}
931
+ style={{ ...css.avatar, width: 48, height: 48, fontSize: 16 }}
932
+ />
933
+ <span style={{ ...css.providerBadge, width: 20, height: 20 }}>
934
+ <ProviderMark provider={provider} />
935
+ </span>
936
+ </span>
937
+ <strong style={{ marginTop: 10, fontSize: 15, color: c.ink, textAlign: 'center' }}>{name}</strong>
938
+ <span style={{ fontSize: 11, color: c.muted, fontFamily: 'monospace', textAlign: 'center' }}>
939
+ {conversation.providerConversationKey}
940
+ </span>
941
+ </div>
942
+
943
+ <InfoSection label="KรŠNH" sectionKey="channel" expanded={expanded['channel']} onToggle={() => toggle('channel')}>
944
+ <InfoRow label="Nแปn tแบฃng">
945
+ <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
946
+ <ProviderMark provider={provider} />
947
+ <span>{providerLabel(provider)}</span>
948
+ </span>
949
+ </InfoRow>
950
+ <InfoRow label="ID hแป™i thoแบกi">
951
+ <span style={{ fontFamily: 'monospace', fontSize: 11 }}>
952
+ {conversation.id.slice(0, 8)}โ€ฆ
953
+ </span>
954
+ <CopyButton value={conversation.id} />
955
+ </InfoRow>
956
+ </InfoSection>
957
+
958
+ <InfoSection label="THแปNG KรŠ" sectionKey="stats" expanded={expanded['stats']} onToggle={() => toggle('stats')}>
959
+ <InfoRow label="Tin nhแบฏn" value={String(conversation.messageCount ?? 0)} />
960
+ {(conversation.unreadCount ?? 0) > 0 && (
961
+ <InfoRow label="Chฦฐa ฤ‘แปc" value={String(conversation.unreadCount)} valueColor="#ef4444" />
962
+ )}
963
+ <InfoRow
964
+ label="Gแบงn nhแบฅt"
965
+ value={conversation.lastMessageAt
966
+ ? new Date(conversation.lastMessageAt).toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit', year: 'numeric' })
967
+ : 'โ€”'}
968
+ />
969
+ <InfoRow label="Lแบงn ฤ‘แบงu" value="โ€”" />
970
+ </InfoSection>
971
+
972
+ <InfoSection label="THร”NG TIN Bแป” SUNG" sectionKey="extra" expanded={expanded['extra']} onToggle={() => toggle('extra')}>
973
+ <InfoRow label="ฤiแป‡n thoแบกi" value="โ€” chฦฐa cรณ" valueMuted />
974
+ <InfoRow label="Email" value="โ€” chฦฐa cรณ" valueMuted />
975
+ <InfoRow label="Nhรฃn" value="โ€” chฦฐa cรณ" valueMuted />
976
+ </InfoSection>
977
+
978
+ <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
979
+ <button style={{ ...css.ghostButton, color: primary, borderColor: `${primary}33` }}>Xem lแป‹ch sแปญ</button>
980
+ <div style={{ border: '1.5px solid #fde68a', borderRadius: 10, background: '#fffbeb', overflow: 'hidden' }}>
981
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 10px', borderBottom: '1px solid #fde68a', fontSize: 11, fontWeight: 600, color: '#92400e' }}>
982
+ ๐Ÿ”’ Ghi chรบ nแป™i bแป™
983
+ </div>
984
+ <textarea
985
+ value={noteText}
986
+ onChange={e => setNoteText(e.target.value)}
987
+ placeholder="Nhแบญp ghi chรบ..."
988
+ rows={3}
989
+ style={{ display: 'block', width: '100%', boxSizing: 'border-box' as const, border: 0, outline: 0, background: 'transparent', resize: 'none' as const, padding: '8px 10px', font: 'inherit', fontSize: 12, color: c.ink, lineHeight: 1.5 }}
990
+ />
991
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 10px 6px' }}>
992
+ {noteSaved
993
+ ? <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: '#16a34a' }}><Check size={11} strokeWidth={2.5} /> ฤรฃ lฦฐu</span>
994
+ : noteError
995
+ ? <span style={{ fontSize: 11, color: '#ef4444' }}>{noteError}</span>
996
+ : <span />
997
+ }
998
+ <button type="button" onClick={() => { void saveNote(); }} disabled={!noteText.trim() || noteSaving}
999
+ style={{ padding: '4px 12px', border: 0, borderRadius: 7, fontSize: 12, fontWeight: 600, background: noteText.trim() && !noteSaving ? 'linear-gradient(135deg,#f59e0b,#fbbf24)' : '#e5e7eb', color: noteText.trim() && !noteSaving ? '#fff' : '#9ca3af', cursor: noteText.trim() && !noteSaving ? 'pointer' : 'not-allowed' }}>
1000
+ {noteSaving ? 'ฤang lฦฐuโ€ฆ' : 'Lฦฐu ghi chรบ'}
1001
+ </button>
1002
+ </div>
1003
+ </div>
1004
+ </div>
1005
+ </div>
1006
+ </aside>
1007
+ );
1008
+ }
1009
+
1010
+ function InfoSection({ label, children, sectionKey, expanded, onToggle }: { label: string; children: React.ReactNode; sectionKey?: string; expanded?: boolean; onToggle?: () => void }) {
1011
+ const isCollapsible = !!onToggle;
1012
+ const isExpanded = expanded ?? true;
1013
+ return (
1014
+ <div style={{ borderTop: `1px solid ${c.line}` }}>
1015
+ <div
1016
+ 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' }}
1017
+ onClick={onToggle}
1018
+ >
1019
+ <span>{label}</span>
1020
+ {isCollapsible && (isExpanded
1021
+ ? <ChevronDown size={12} strokeWidth={2} />
1022
+ : <ChevronRight size={12} strokeWidth={2} />)}
1023
+ </div>
1024
+ {isExpanded && children}
1025
+ </div>
1026
+ );
1027
+ }
1028
+
1029
+ function InfoRow({ label, value, children, valueColor, valueMuted }: {
1030
+ label: string; value?: string; children?: React.ReactNode; valueColor?: string; valueMuted?: boolean;
1031
+ }) {
1032
+ return (
1033
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '3px 16px', fontSize: 12, gap: 8 }}>
1034
+ <span style={{ color: c.muted, flexShrink: 0 }}>{label}</span>
1035
+ <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 }}>
1036
+ {children ?? value}
1037
+ </span>
1038
+ </div>
1039
+ );
1040
+ }
1041
+
1042
+ function CopyButton({ value }: { value: string }) {
1043
+ const [copied, setCopied] = useState(false);
1044
+ return (
1045
+ <button
1046
+ style={{ border: 0, background: 'none', cursor: 'pointer', color: c.muted, padding: 2, lineHeight: 1 }}
1047
+ title="Sao chรฉp"
1048
+ onClick={() => { void navigator.clipboard.writeText(value).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }); }}
1049
+ aria-label="Sao chรฉp ID"
1050
+ >
1051
+ {copied ? 'โœ“' : 'โŽ˜'}
1052
+ </button>
1053
+ );
1054
+ }
1055
+
1056
+ 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>; }
1057
+ 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>; }
1058
+ 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 }} />; }
1059
+ function Spinner() { return <Loader2 size={14} style={css.spinner} aria-hidden="true" />; }
1060
+ function initials(name: string) { return name.split(/\s+/).filter(Boolean).slice(-2).map(x => x[0]).join('').toUpperCase() || '?'; }
1061
+
1062
+ const providerLogoSlug: Partial<Record<string, string>> = { livechat: 'web' };
1063
+
1064
+ function ProviderMark({ provider }: { provider?: Provider }) {
1065
+ const apiUrl = useContext(ApiUrlCtx);
1066
+ const size = 14;
1067
+ if (!provider) return null;
1068
+ const slug = providerLogoSlug[provider] ?? provider;
1069
+ return <img src={`${apiUrl}/static/logos/${slug}.avif`} alt={provider} width={size} height={size} style={{ borderRadius: '50%', objectFit: 'cover', display: 'block' }} />;
1070
+ }
1071
+ function formatTime(value?: string | Date, _full = false) {
1072
+ if (!value) return '';
1073
+ const d = new Date(value as string);
1074
+ if (d.toDateString() === new Date().toDateString()) {
1075
+ return d.toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
1076
+ }
1077
+ return d.toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit' });
1078
+ }
1079
+
1080
+ const css: Record<string, React.CSSProperties> = {
1081
+ 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)' },
1082
+ sidebar: { display: 'flex', flexDirection: 'column', minWidth: 0, minHeight: 0, borderRight: `1px solid ${c.line}`, background: c.white },
1083
+ brand: { display: 'flex', alignItems: 'center', gap: 10, padding: '20px 18px 16px' },
1084
+ brandMark: { display: 'grid', placeItems: 'center', width: 32, height: 32, borderRadius: 10, color: '#fff', fontWeight: 800 },
1085
+ eyebrow: { display: 'block', marginTop: 2, fontSize: 9, letterSpacing: 1.3, color: c.muted },
1086
+ iconButton: { display: 'inline-grid', placeItems: 'center', width: 32, height: 32, marginLeft: 'auto', border: 0, borderRadius: 8, background: 'transparent', color: c.muted, cursor: 'pointer' },
1087
+ searchInput: { width: '100%', minWidth: 0, border: 0, outline: 0, background: 'transparent', color: c.ink, font: 'inherit', fontSize: 12 },
1088
+ 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 },
1089
+ clear: { border: 0, background: 'none', color: c.muted, cursor: 'pointer', fontSize: 18 },
1090
+ 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' },
1091
+ conversationList: { overflowY: 'auto', flex: 1, minHeight: 0 },
1092
+ 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' },
1093
+ avatarWrap: { position: 'relative', flex: '0 0 auto', width: 38, height: 38 },
1094
+ avatar: { flex: '0 0 auto', width: 38, height: 38, display: 'grid', placeItems: 'center', borderRadius: '50%', objectFit: 'cover', fontSize: 12, fontWeight: 800 },
1095
+ 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' },
1096
+ rowBody: { minWidth: 0, flex: 1 },
1097
+ rowTop: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, fontSize: 13 },
1098
+ rowBottom: { display: 'flex', marginTop: 4, fontSize: 11, minWidth: 0, overflow: 'hidden', lineHeight: 1.4 },
1099
+ channel: { color: '#9aa5b5' },
1100
+ unreadBadge: { display: 'inline-grid', placeItems: 'center', minWidth: 18, height: 18, borderRadius: 999, background: '#ef4444', color: '#fff', fontSize: 10, fontWeight: 800, padding: '0 5px' },
1101
+ loadMore: { width: '100%', border: 0, background: 'transparent', color: '#4c72ca', padding: 14, cursor: 'pointer', fontSize: 12 },
1102
+ emptySmall: { display: 'grid', justifyItems: 'center', gap: 7, padding: '56px 24px', color: c.muted, fontSize: 12, textAlign: 'center' },
1103
+ emptyIcon: { display: 'grid', placeItems: 'center', width: 40, height: 40, borderRadius: 12, background: c.surface },
1104
+ main: { minWidth: 0, minHeight: 0, overflow: 'hidden', background: c.surface },
1105
+ chat: { display: 'flex', flexDirection: 'column', height: '100%', minWidth: 0, minHeight: 0 },
1106
+ 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 },
1107
+ contact: { display: 'grid', gap: 3, minWidth: 0, flex: 1 },
1108
+ contactName: { fontSize: 14, fontWeight: 600, color: c.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
1109
+ contactMeta: { display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: c.muted },
1110
+ headerActions: { display: 'flex', gap: 2, marginLeft: 'auto' },
1111
+ messageArea: { flex: 1, minHeight: 0, overflowY: 'auto', overscrollBehavior: 'contain', padding: '20px clamp(16px,5vw,56px)', background: 'linear-gradient(180deg,#f9fbfe 0%,#f4f7fb 100%)' },
1112
+ day: { margin: '0 auto 18px', color: '#a1acbb', fontSize: 10, letterSpacing: 1.2, fontWeight: 700, textAlign: 'center' },
1113
+ 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 },
1114
+ messageHint: { display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, padding: 40, color: c.muted, fontSize: 12 },
1115
+ messageLine: { display: 'flex', marginBottom: 10 },
1116
+ 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 },
1117
+ 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 },
1118
+ composer: { flex: '0 0 auto', display: 'flex', alignItems: 'flex-end', gap: 10, padding: '10px 14px 12px', borderTop: `1px solid ${c.line}`, background: c.white },
1119
+ 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 },
1120
+ composerBox: { flex: 1, minWidth: 0, border: `1px solid ${c.line}`, borderRadius: 10, background: c.surface, overflow: 'hidden' },
1121
+ send: { display: 'grid', placeItems: 'center', width: 38, height: 38, border: 0, borderRadius: '50%', color: '#fff', flexShrink: 0 },
1122
+ error: { padding: '8px 18px', background: '#fff2f0', color: '#b42318', fontSize: 12 },
1123
+ empty: { display: 'grid', placeItems: 'center', alignContent: 'center', height: '100%', padding: 30, textAlign: 'center', color: c.muted },
1124
+ emptyHero: { display: 'grid', placeItems: 'center', width: 64, height: 64, marginBottom: 16, borderRadius: 20, background: '#eaf0ff', color: '#5277d7' },
1125
+ state: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, minHeight: 180, border: `1px solid ${c.line}`, background: c.white, color: c.muted, fontSize: 13 },
1126
+ retry: { border: 0, borderRadius: 7, padding: '7px 10px', background: '#eff4ff', color: '#315dbb', cursor: 'pointer' },
1127
+ spinner: { display: 'inline-block', width: 14, height: 14, border: '2px solid #dbe3f3', borderTopColor: '#5277d7', borderRadius: '50%', animation: 'channelhub-spin .7s linear infinite' },
1128
+ toolbarBtn: { display: 'inline-grid', placeItems: 'center', width: 26, height: 26, border: '1px solid transparent', borderRadius: 6, background: 'transparent', color: '#9ca3af', cursor: 'pointer', padding: 0, lineHeight: 1 } as React.CSSProperties,
1129
+ infoPanel: { display: 'flex', flexDirection: 'column', borderLeft: `1px solid ${c.line}`, background: c.white, minHeight: 0, overflow: 'hidden' },
1130
+ infoPanelHeader: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 16px 12px', borderBottom: `1px solid ${c.line}`, flex: '0 0 auto' },
1131
+ infoPanelIdentity: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '20px 16px 16px', gap: 4 },
1132
+ ghostButton: { width: '100%', padding: '8px 12px', border: `1px solid ${c.line}`, borderRadius: 8, background: 'transparent', fontSize: 12, cursor: 'pointer', textAlign: 'center' as const },
1133
+ };