@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,941 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { ProviderLogo } from './channels/ProviderLogo.js';
3
+
4
+ export interface ChannelConnection {
5
+ id: string;
6
+ provider: string;
7
+ type: string;
8
+ externalAccountId: string;
9
+ status: string;
10
+ metadata: Record<string, unknown>;
11
+ }
12
+
13
+ export interface ChannelHubChannelsProps {
14
+ apiUrl: string;
15
+ token: string;
16
+ onConnectionChange?: (connections: ChannelConnection[]) => void;
17
+ }
18
+
19
+ type OAuthProvider = 'facebook' | 'zalo' | 'instagram';
20
+
21
+ type SelectPage = { id: string; name: string };
22
+
23
+ type View =
24
+ | { name: 'list' }
25
+ | { name: 'add' }
26
+ | { name: 'connect-telegram' }
27
+ | { name: 'connect-livechat' }
28
+ | { name: 'livechat-result'; connectionId: string; embedScript: string; identitySecret: string; allowedDomains: string[] }
29
+ | { name: 'oauth-waiting'; provider: OAuthProvider; popup: Window | null }
30
+ | { name: 'oauth-select'; provider: OAuthProvider; sessionId: string; pages: SelectPage[]; popup: Window | null };
31
+
32
+ const PROVIDER_LABEL: Record<string, string> = {
33
+ facebook: 'Facebook',
34
+ zalo: 'Zalo OA',
35
+ instagram: 'Instagram',
36
+ telegram: 'Telegram',
37
+ livechat: 'Live Chat',
38
+ whatsapp: 'WhatsApp',
39
+ };
40
+
41
+ const PROVIDER_BG: Record<string, string> = {
42
+ facebook: '#dbeafe',
43
+ zalo: '#e0f2fe',
44
+ instagram: '#fce7f3',
45
+ telegram: '#cffafe',
46
+ livechat: '#ede9fe',
47
+ whatsapp: '#dcfce7',
48
+ };
49
+
50
+ function displayName(conn: ChannelConnection): string {
51
+ const m = conn.metadata;
52
+ return String(m['displayName'] ?? m['pageName'] ?? m['username'] ?? m['name'] ?? conn.externalAccountId);
53
+ }
54
+
55
+ function metaLine(conn: ChannelConnection): string {
56
+ const label = PROVIDER_LABEL[conn.provider] ?? conn.provider;
57
+ const name = String(conn.metadata['username'] ?? conn.metadata['pageName'] ?? '');
58
+ return name ? `${label} · ${name}` : label;
59
+ }
60
+
61
+ // ── Shared style tokens ────────────────────────────────────────────────────────
62
+
63
+ const s = {
64
+ root: {
65
+ background: '#fff',
66
+ borderRadius: 16,
67
+ boxShadow: '0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06)',
68
+ overflow: 'hidden' as const,
69
+ minWidth: 320,
70
+ width: '100%',
71
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif",
72
+ fontSize: 14,
73
+ color: '#0f172a',
74
+ },
75
+ header: {
76
+ padding: '20px 24px 0',
77
+ display: 'flex' as const,
78
+ alignItems: 'center' as const,
79
+ justifyContent: 'space-between' as const,
80
+ },
81
+ headerLeft: { display: 'flex' as const, alignItems: 'center' as const, gap: 10 },
82
+ title: { fontSize: 16, fontWeight: 700, color: '#0f172a', lineHeight: 1.3 },
83
+ subtitle: { fontSize: 12, color: '#94a3b8', marginTop: 1 },
84
+ divider: { height: 1, background: '#f1f5f9', margin: '16px 0 0' },
85
+ body: { padding: '16px 24px 24px' },
86
+ backBtn: {
87
+ width: 32, height: 32, borderRadius: 8,
88
+ border: '1px solid #e2e8f0', background: '#fff',
89
+ display: 'flex' as const, alignItems: 'center' as const, justifyContent: 'center' as const,
90
+ cursor: 'pointer', color: '#475569', flexShrink: 0,
91
+ },
92
+ addBtn: {
93
+ display: 'flex' as const, alignItems: 'center' as const, gap: 6,
94
+ padding: '8px 14px', borderRadius: 8, border: 'none',
95
+ background: '#2563eb', color: '#fff', fontSize: 13, fontWeight: 600,
96
+ cursor: 'pointer', whiteSpace: 'nowrap' as const, flexShrink: 0,
97
+ },
98
+ errorBanner: {
99
+ margin: '12px 24px 0',
100
+ padding: '10px 14px',
101
+ borderRadius: 10,
102
+ background: '#fef2f2',
103
+ border: '1px solid #fecaca',
104
+ color: '#dc2626',
105
+ fontSize: 13,
106
+ },
107
+ channelItem: {
108
+ display: 'flex' as const, alignItems: 'center' as const, gap: 12,
109
+ padding: '12px 14px', borderRadius: 12,
110
+ border: '1px solid #f1f5f9', background: '#fafafa',
111
+ marginBottom: 8,
112
+ },
113
+ channelInfo: { flex: 1, minWidth: 0 },
114
+ channelName: { fontSize: 14, fontWeight: 600, color: '#0f172a', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const },
115
+ channelMeta: { fontSize: 12, color: '#94a3b8', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const },
116
+ channelActions: { display: 'flex' as const, alignItems: 'center' as const, gap: 8, flexShrink: 0 },
117
+ badgeActive: { fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 999, background: '#d1fae5', color: '#059669' },
118
+ badgeInactive: { fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 999, background: '#f1f5f9', color: '#94a3b8' },
119
+ disconnectBtn: {
120
+ fontSize: 12, fontWeight: 500, padding: '5px 10px', borderRadius: 7,
121
+ border: '1px solid #e2e8f0', background: '#fff', color: '#64748b', cursor: 'pointer',
122
+ },
123
+ providerGrid: { display: 'grid' as const, gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))', gap: 10 },
124
+ providerCard: {
125
+ display: 'flex' as const, flexDirection: 'column' as const, alignItems: 'center' as const,
126
+ gap: 8, padding: '16px 12px 14px', borderRadius: 12,
127
+ borderWidth: '1.5px', borderStyle: 'solid' as const, borderColor: '#f1f5f9',
128
+ background: '#fafafa',
129
+ cursor: 'pointer', textAlign: 'center' as const,
130
+ boxShadow: 'none', transform: 'none',
131
+ },
132
+ providerName: { fontSize: 13, fontWeight: 600, color: '#0f172a', lineHeight: 1.2 },
133
+ providerDesc: { fontSize: 11, color: '#94a3b8', lineHeight: 1.4 },
134
+ connectHeader: {
135
+ display: 'flex' as const, alignItems: 'center' as const, gap: 12,
136
+ padding: '20px 24px 16px', borderBottom: '1px solid #f1f5f9',
137
+ },
138
+ connectTitle: { fontSize: 15, fontWeight: 700, color: '#0f172a' },
139
+ connectDesc: { fontSize: 12, color: '#94a3b8', marginTop: 2, lineHeight: 1.5 },
140
+ form: { padding: '20px 24px 24px', display: 'flex' as const, flexDirection: 'column' as const, gap: 16 },
141
+ field: { display: 'flex' as const, flexDirection: 'column' as const, gap: 6 },
142
+ label: { fontSize: 13, fontWeight: 600, color: '#374151' },
143
+ labelHint: { fontSize: 11, fontWeight: 400, color: '#94a3b8', marginLeft: 4 },
144
+ input: {
145
+ padding: '9px 12px', borderRadius: 8, border: '1.5px solid #e2e8f0',
146
+ fontSize: 13, color: '#0f172a', background: '#fff', outline: 'none',
147
+ fontFamily: 'inherit', width: '100%', boxSizing: 'border-box' as const,
148
+ },
149
+ inputHint: { fontSize: 11, color: '#94a3b8', lineHeight: 1.5 },
150
+ infoBox: {
151
+ display: 'flex' as const, gap: 8, padding: '10px 12px', borderRadius: 8,
152
+ background: '#eff6ff', border: '1px solid #bfdbfe', color: '#1e40af',
153
+ fontSize: 13, lineHeight: 1.5,
154
+ },
155
+ formActions: { display: 'flex' as const, gap: 8, flexWrap: 'wrap' as const },
156
+ btnPrimary: {
157
+ flex: 1, minWidth: 120, padding: '10px 16px', borderRadius: 9,
158
+ border: 'none', background: '#2563eb', color: '#fff',
159
+ fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
160
+ },
161
+ btnSecondary: {
162
+ padding: '10px 16px', borderRadius: 9,
163
+ border: '1.5px solid #e2e8f0', background: '#fff', color: '#64748b',
164
+ fontSize: 14, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
165
+ },
166
+ resultBanner: {
167
+ display: 'flex' as const, alignItems: 'flex-start' as const, gap: 10,
168
+ padding: '12px 14px', borderRadius: 10, background: '#f0fdf4', border: '1px solid #bbf7d0',
169
+ fontSize: 13, color: '#166534', lineHeight: 1.5,
170
+ },
171
+ codeLabel: { fontSize: 11, fontWeight: 600, color: '#64748b', textTransform: 'uppercase' as const, letterSpacing: '.05em', marginBottom: 6 },
172
+ codeBlock: { background: '#0f172a', borderRadius: 10, padding: '14px 16px', position: 'relative' as const, overflowX: 'auto' as const },
173
+ codePre: {
174
+ fontFamily: "'JetBrains Mono', 'Fira Code', 'Courier New', monospace",
175
+ fontSize: 11.5, lineHeight: 1.6, color: '#e2e8f0',
176
+ whiteSpace: 'pre-wrap' as const, wordBreak: 'break-all' as const, margin: 0,
177
+ },
178
+ copyBtn: {
179
+ position: 'absolute' as const, top: 10, right: 10,
180
+ display: 'flex' as const, alignItems: 'center' as const, gap: 4,
181
+ padding: '4px 10px', borderRadius: 6, border: '1px solid #334155',
182
+ background: '#1e293b', color: '#94a3b8', fontSize: 11, fontWeight: 500,
183
+ cursor: 'pointer', fontFamily: 'inherit',
184
+ },
185
+ secretRow: {
186
+ display: 'flex' as const, alignItems: 'center' as const, gap: 8,
187
+ padding: '10px 12px', borderRadius: 8, background: '#fefce8', border: '1px solid #fef08a',
188
+ },
189
+ secretLabel: { fontSize: 12, fontWeight: 600, color: '#854d0e', whiteSpace: 'nowrap' as const },
190
+ secretValue: {
191
+ fontFamily: "'JetBrains Mono', monospace", fontSize: 12, color: '#0f172a',
192
+ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const,
193
+ },
194
+ oauthWaiting: {
195
+ display: 'flex' as const, flexDirection: 'column' as const, alignItems: 'center' as const,
196
+ justifyContent: 'center' as const, padding: '40px 24px 48px', gap: 16, textAlign: 'center' as const,
197
+ },
198
+ oauthTitle: { fontSize: 16, fontWeight: 700, color: '#0f172a' },
199
+ oauthDesc: { fontSize: 13, color: '#64748b', lineHeight: 1.6, maxWidth: 300 },
200
+ oauthCancel: {
201
+ marginTop: 8, padding: '10px 20px', borderRadius: 9,
202
+ border: '1.5px solid #e2e8f0', background: '#fff', color: '#64748b',
203
+ fontSize: 14, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
204
+ },
205
+ empty: {
206
+ display: 'flex' as const, flexDirection: 'column' as const, alignItems: 'center' as const,
207
+ padding: '40px 24px 48px', gap: 12, textAlign: 'center' as const,
208
+ },
209
+ emptyTitle: { fontSize: 15, fontWeight: 700, color: '#0f172a' },
210
+ emptyDesc: { fontSize: 13, color: '#94a3b8', lineHeight: 1.6, maxWidth: 280 },
211
+ emptyCta: {
212
+ marginTop: 4, display: 'flex' as const, alignItems: 'center' as const, gap: 6,
213
+ padding: '10px 20px', borderRadius: 9, border: 'none',
214
+ background: '#2563eb', color: '#fff', fontSize: 14, fontWeight: 600,
215
+ cursor: 'pointer', fontFamily: 'inherit',
216
+ },
217
+ };
218
+
219
+ // ── Icons ─────────────────────────────────────────────────────────────────────
220
+
221
+ function IconPlus() {
222
+ return (
223
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
224
+ <path d="M7 1v12M1 7h12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
225
+ </svg>
226
+ );
227
+ }
228
+
229
+ function IconBack() {
230
+ return (
231
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
232
+ <path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
233
+ </svg>
234
+ );
235
+ }
236
+
237
+ function IconCopy() {
238
+ return (
239
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
240
+ <rect x="4" y="4" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1.3" />
241
+ <path d="M2.5 8H2a1 1 0 01-1-1V2a1 1 0 011-1h5a1 1 0 011 1v.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
242
+ </svg>
243
+ );
244
+ }
245
+
246
+ function IconCheck() {
247
+ return (
248
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
249
+ <path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
250
+ </svg>
251
+ );
252
+ }
253
+
254
+ function IconKey() {
255
+ return (
256
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0 }}>
257
+ <circle cx="5" cy="6" r="3.5" stroke="#ca8a04" strokeWidth="1.4" />
258
+ <path d="M8 7.5l4.5 4.5M10.5 10l1.5 1.5" stroke="#ca8a04" strokeWidth="1.4" strokeLinecap="round" />
259
+ </svg>
260
+ );
261
+ }
262
+
263
+ function IconInfo() {
264
+ return (
265
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0, marginTop: 1 }}>
266
+ <circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.5" />
267
+ <path d="M7 6v5M7 4.5v.01" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
268
+ </svg>
269
+ );
270
+ }
271
+
272
+ // ── Spinner ring (CSS keyframes via style tag injected once) ──────────────────
273
+
274
+ let spinnerInjected = false;
275
+ function ensureSpinnerStyle() {
276
+ if (spinnerInjected || typeof document === 'undefined') return;
277
+ spinnerInjected = true;
278
+ const el = document.createElement('style');
279
+ el.textContent = `@keyframes ch-spin{to{transform:rotate(360deg)}}`;
280
+ document.head.appendChild(el);
281
+ }
282
+
283
+ // ── Main component ────────────────────────────────────────────────────────────
284
+
285
+ export function ChannelHubChannels({ apiUrl, token, onConnectionChange }: ChannelHubChannelsProps) {
286
+ const base = apiUrl.replace(/\/$/, '');
287
+ const [connections, setConnections] = useState<ChannelConnection[]>([]);
288
+ const [loading, setLoading] = useState(true);
289
+ const [view, setView] = useState<View>({ name: 'list' });
290
+ const [error, setError] = useState<string | null>(null);
291
+ const [submitting, setSubmitting] = useState(false);
292
+
293
+ // Form state — telegram
294
+ const [tgToken, setTgToken] = useState('');
295
+ const [tgName, setTgName] = useState('');
296
+
297
+ // Form state — livechat
298
+ const [lcName, setLcName] = useState('');
299
+ const [lcDomains, setLcDomains] = useState('');
300
+
301
+ // Copy button state
302
+ const [copiedScript, setCopiedScript] = useState(false);
303
+ const [copiedSecret, setCopiedSecret] = useState(false);
304
+
305
+ // OAuth popup message listener ref
306
+ const oauthHandlerRef = useRef<((e: MessageEvent) => void) | null>(null);
307
+
308
+ ensureSpinnerStyle();
309
+
310
+ const loadConnections = useCallback(async () => {
311
+ try {
312
+ const res = await fetch(`${base}/v1/connections`, {
313
+ headers: { authorization: `Bearer ${token}` },
314
+ });
315
+ if (!res.ok) throw new Error('Không tải được kênh');
316
+ const data = await res.json() as ChannelConnection[];
317
+ setConnections(data);
318
+ onConnectionChange?.(data);
319
+ } catch (e) {
320
+ setError(e instanceof Error ? e.message : 'Lỗi tải dữ liệu');
321
+ } finally {
322
+ setLoading(false);
323
+ }
324
+ }, [base, token, onConnectionChange]);
325
+
326
+ useEffect(() => { void loadConnections(); }, [loadConnections]);
327
+
328
+ // Auto-dismiss error after 5 s
329
+ useEffect(() => {
330
+ if (!error) return;
331
+ const t = setTimeout(() => setError(null), 5000);
332
+ return () => clearTimeout(t);
333
+ }, [error]);
334
+
335
+ // Cleanup OAuth listener on unmount
336
+ useEffect(() => {
337
+ return () => {
338
+ if (oauthHandlerRef.current) {
339
+ window.removeEventListener('message', oauthHandlerRef.current);
340
+ }
341
+ };
342
+ }, []);
343
+
344
+ async function disconnect(id: string, name: string) {
345
+ if (!confirm(`Bạn chắc chắn muốn ngắt kết nối "${name}"?\n\nHành động này không thể hoàn tác.`)) return;
346
+ try {
347
+ const res = await fetch(`${base}/v1/connections/${id}`, {
348
+ method: 'DELETE',
349
+ headers: { authorization: `Bearer ${token}` },
350
+ });
351
+ if (!res.ok) throw new Error('Không thể ngắt kết nối');
352
+ await loadConnections();
353
+ } catch (e) {
354
+ setError(e instanceof Error ? e.message : 'Lỗi ngắt kết nối');
355
+ }
356
+ }
357
+
358
+ async function connectTelegram() {
359
+ if (!tgToken.trim()) { setError('Vui lòng nhập Bot Token'); return; }
360
+ if (!/^\d+:[A-Za-z0-9_-]+$/.test(tgToken.trim())) { setError('Token không đúng định dạng'); return; }
361
+ setSubmitting(true);
362
+ setError(null);
363
+ try {
364
+ const res = await fetch(`${base}/v1/connect/telegram/start`, {
365
+ method: 'POST',
366
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
367
+ body: JSON.stringify({ botToken: tgToken.trim(), displayName: tgName.trim() || undefined }),
368
+ });
369
+ const body = await res.json() as { connectionId?: string; message?: string };
370
+ if (!res.ok || !body.connectionId) throw new Error(body.message ?? 'Không thể kết nối Telegram');
371
+ setTgToken(''); setTgName('');
372
+ await loadConnections();
373
+ setView({ name: 'list' });
374
+ } catch (e) {
375
+ setError(e instanceof Error ? e.message : 'Lỗi kết nối');
376
+ } finally {
377
+ setSubmitting(false);
378
+ }
379
+ }
380
+
381
+ async function connectLivechat() {
382
+ if (!lcName.trim()) { setError('Vui lòng nhập tên widget'); return; }
383
+ setSubmitting(true);
384
+ setError(null);
385
+ try {
386
+ const allowedDomains = lcDomains.split(/[\n,]+/).map(d => d.trim()).filter(Boolean);
387
+ const res = await fetch(`${base}/v1/connect/livechat/start`, {
388
+ method: 'POST',
389
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
390
+ body: JSON.stringify({ displayName: lcName.trim(), allowedDomains: allowedDomains.length ? allowedDomains : undefined }),
391
+ });
392
+ const body = await res.json() as { connectionId?: string; embedScript?: string; identitySecret?: string; allowedDomains?: string[]; message?: string };
393
+ if (!res.ok || !body.connectionId || !body.embedScript) throw new Error(body.message ?? 'Không thể tạo widget');
394
+ setLcName(''); setLcDomains('');
395
+ await loadConnections();
396
+ setView({
397
+ name: 'livechat-result',
398
+ connectionId: body.connectionId,
399
+ embedScript: body.embedScript,
400
+ identitySecret: body.identitySecret ?? '',
401
+ allowedDomains: body.allowedDomains ?? [],
402
+ });
403
+ } catch (e) {
404
+ setError(e instanceof Error ? e.message : 'Lỗi tạo widget');
405
+ } finally {
406
+ setSubmitting(false);
407
+ }
408
+ }
409
+
410
+ async function startOAuth(provider: OAuthProvider) {
411
+ setError(null);
412
+ try {
413
+ const callbackUrl = `${base}/static/oauth-popup.html`;
414
+ const res = await fetch(`${base}/v1/connect/${provider}/start`, {
415
+ method: 'POST',
416
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
417
+ body: JSON.stringify({ callbackUrl }),
418
+ });
419
+ const body = await res.json() as { authorizationUrl?: string; message?: string };
420
+ if (!res.ok || !body.authorizationUrl) throw new Error(body.message ?? 'Không thể bắt đầu kết nối');
421
+
422
+ const popup = window.open(body.authorizationUrl, 'channelhub-oauth', 'width=600,height=700,scrollbars=yes,resizable=yes');
423
+ setView({ name: 'oauth-waiting', provider, popup });
424
+
425
+ if (oauthHandlerRef.current) window.removeEventListener('message', oauthHandlerRef.current);
426
+ const handler = (event: MessageEvent) => {
427
+ if (!event.data) return;
428
+ if (event.data.type === 'channelhub:oauth-select') {
429
+ // Page/account selection required — show inline selector, keep popup open
430
+ setView({
431
+ name: 'oauth-select',
432
+ provider: event.data.provider as OAuthProvider,
433
+ sessionId: String(event.data.sessionId ?? ''),
434
+ pages: (event.data.pages as SelectPage[]) ?? [],
435
+ popup,
436
+ });
437
+ return; // keep listener alive until selection done
438
+ }
439
+ if (event.data.type !== 'channelhub:oauth') return;
440
+ window.removeEventListener('message', handler);
441
+ oauthHandlerRef.current = null;
442
+ if (event.data.status === 'active') {
443
+ void loadConnections();
444
+ setView({ name: 'list' });
445
+ } else {
446
+ setError('Kết nối thất bại: ' + String(event.data.error ?? 'Không xác định'));
447
+ setView({ name: 'list' });
448
+ }
449
+ };
450
+ oauthHandlerRef.current = handler;
451
+ window.addEventListener('message', handler);
452
+ } catch (e) {
453
+ setError(e instanceof Error ? e.message : 'Lỗi kết nối');
454
+ setView({ name: 'list' });
455
+ }
456
+ }
457
+
458
+ function copy(text: string, type: 'script' | 'secret') {
459
+ void navigator.clipboard.writeText(text).then(() => {
460
+ if (type === 'script') { setCopiedScript(true); setTimeout(() => setCopiedScript(false), 2000); }
461
+ else { setCopiedSecret(true); setTimeout(() => setCopiedSecret(false), 2000); }
462
+ });
463
+ }
464
+
465
+ function cancelOAuth() {
466
+ const popup = (view.name === 'oauth-waiting' || view.name === 'oauth-select') ? view.popup : null;
467
+ if (popup) { try { popup.close(); } catch { /* cross-origin */ } }
468
+ if (oauthHandlerRef.current) {
469
+ window.removeEventListener('message', oauthHandlerRef.current);
470
+ oauthHandlerRef.current = null;
471
+ }
472
+ setView({ name: 'add' });
473
+ }
474
+
475
+ async function selectAccount(pageId: string) {
476
+ if (view.name !== 'oauth-select') return;
477
+ const { provider, sessionId, popup } = view;
478
+ setSubmitting(true);
479
+ setError(null);
480
+ const endpointMap: Record<string, string> = {
481
+ facebook: `${base}/v1/connect/facebook/select-page`,
482
+ instagram: `${base}/v1/connect/instagram/select-account`,
483
+ zalo: `${base}/v1/connect/zalo/select-oa`,
484
+ };
485
+ const bodyKeyMap: Record<string, string> = {
486
+ facebook: 'pageId',
487
+ instagram: 'accountId',
488
+ zalo: 'oaId',
489
+ };
490
+ try {
491
+ const res = await fetch(endpointMap[provider] ?? `${base}/v1/connect/${provider}/select-page`, {
492
+ method: 'POST',
493
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
494
+ body: JSON.stringify({ sessionId, [bodyKeyMap[provider] ?? 'pageId']: pageId }),
495
+ });
496
+ const body = await res.json() as { connectionId?: string; message?: string };
497
+ if (!res.ok || !body.connectionId) throw new Error(body.message ?? 'Không thể kết nối');
498
+ // Signal popup to close
499
+ if (popup) { try { popup.postMessage({ type: 'channelhub:close-popup' }, '*'); } catch { /* ignore */ } }
500
+ if (oauthHandlerRef.current) {
501
+ window.removeEventListener('message', oauthHandlerRef.current);
502
+ oauthHandlerRef.current = null;
503
+ }
504
+ await loadConnections();
505
+ setView({ name: 'list' });
506
+ } catch (e) {
507
+ setError(e instanceof Error ? e.message : 'Lỗi kết nối');
508
+ } finally {
509
+ setSubmitting(false);
510
+ }
511
+ }
512
+
513
+ // ── Render ──────────────────────────────────────────────────────────────────
514
+
515
+ return (
516
+ <div style={s.root}>
517
+ {/* Error banner */}
518
+ {error && <div style={s.errorBanner}>{error}</div>}
519
+
520
+ {/* LIST VIEW */}
521
+ {view.name === 'list' && (
522
+ <>
523
+ <div style={s.header}>
524
+ <div style={s.headerLeft}>
525
+ <div>
526
+ <div style={s.title}>Kênh kết nối</div>
527
+ <div style={s.subtitle}>
528
+ {loading ? 'Đang tải…' : `${connections.filter(c => c.status === 'active').length} kênh đang hoạt động`}
529
+ </div>
530
+ </div>
531
+ </div>
532
+ <button style={s.addBtn} onClick={() => setView({ name: 'add' })}>
533
+ <IconPlus />
534
+ <span>Thêm kênh</span>
535
+ </button>
536
+ </div>
537
+ <div style={s.divider} />
538
+ <div style={s.body}>
539
+ {!loading && connections.length === 0 ? (
540
+ <div style={s.empty}>
541
+ <div style={{ width: 64, height: 64, borderRadius: 16, background: '#f1f5f9', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
542
+ <ProviderLogo provider="livechat" apiUrl={base} size={40} />
543
+ </div>
544
+ <div style={s.emptyTitle}>Chưa có kênh nào được kết nối</div>
545
+ <div style={s.emptyDesc}>Kết nối Facebook, Zalo OA, Telegram hoặc Live Chat để bắt đầu nhận tin nhắn từ khách hàng.</div>
546
+ <button style={s.emptyCta} onClick={() => setView({ name: 'add' })}>
547
+ <IconPlus />
548
+ Kết nối kênh đầu tiên
549
+ </button>
550
+ </div>
551
+ ) : (
552
+ <div>
553
+ {connections.map(conn => (
554
+ <ChannelItem
555
+ key={conn.id}
556
+ conn={conn}
557
+ apiUrl={base}
558
+ onDisconnect={() => void disconnect(conn.id, displayName(conn))}
559
+ />
560
+ ))}
561
+ </div>
562
+ )}
563
+ </div>
564
+ </>
565
+ )}
566
+
567
+ {/* ADD PANEL */}
568
+ {view.name === 'add' && (
569
+ <>
570
+ <div style={s.header}>
571
+ <div style={s.headerLeft}>
572
+ <button style={s.backBtn} onClick={() => setView({ name: 'list' })}><IconBack /></button>
573
+ <div>
574
+ <div style={s.title}>Thêm kênh mới</div>
575
+ <div style={s.subtitle}>Chọn nền tảng bạn muốn kết nối</div>
576
+ </div>
577
+ </div>
578
+ </div>
579
+ <div style={s.divider} />
580
+ <div style={s.body}>
581
+ <div style={s.providerGrid}>
582
+ {PROVIDERS.map(p => (
583
+ <ProviderCard
584
+ key={p.id}
585
+ provider={p}
586
+ apiUrl={base}
587
+ onClick={() => {
588
+ if (p.type === 'oauth') void startOAuth(p.id as OAuthProvider);
589
+ else if (p.id === 'telegram') setView({ name: 'connect-telegram' });
590
+ else setView({ name: 'connect-livechat' });
591
+ }}
592
+ />
593
+ ))}
594
+ </div>
595
+ </div>
596
+ </>
597
+ )}
598
+
599
+ {/* TELEGRAM FORM */}
600
+ {view.name === 'connect-telegram' && (
601
+ <>
602
+ <div style={s.connectHeader}>
603
+ <button style={s.backBtn} onClick={() => setView({ name: 'add' })}><IconBack /></button>
604
+ <ProviderLogo provider="telegram" apiUrl={base} size={44} />
605
+ <div>
606
+ <div style={s.connectTitle}>Kết nối Telegram Bot</div>
607
+ <div style={s.connectDesc}>Nhập Bot Token để bắt đầu nhận tin nhắn</div>
608
+ </div>
609
+ </div>
610
+ <div style={s.form}>
611
+ <div style={s.infoBox}>
612
+ <IconInfo />
613
+ <div>
614
+ Tạo bot mới bằng cách nhắn tin cho <strong>@BotFather</strong> trên Telegram, dùng lệnh <strong>/newbot</strong> rồi sao chép token được cấp.
615
+ </div>
616
+ </div>
617
+ <div style={s.field}>
618
+ <label style={s.label}>Bot Token <span style={s.labelHint}>bắt buộc</span></label>
619
+ <input
620
+ style={s.input}
621
+ type="text"
622
+ value={tgToken}
623
+ onChange={e => setTgToken(e.target.value)}
624
+ placeholder="1234567890:AAExxxxxxxxxxxxxxxxxxxxxxxx"
625
+ autoComplete="off"
626
+ spellCheck={false}
627
+ />
628
+ <div style={s.inputHint}>Định dạng: <code>số:ký_tự</code>, ví dụ: <code>1234567890:AAExxxxxxxx</code></div>
629
+ </div>
630
+ <div style={s.field}>
631
+ <label style={s.label}>Tên hiển thị <span style={s.labelHint}>tùy chọn</span></label>
632
+ <input
633
+ style={s.input}
634
+ type="text"
635
+ value={tgName}
636
+ onChange={e => setTgName(e.target.value)}
637
+ placeholder="VD: Bot hỗ trợ cửa hàng"
638
+ />
639
+ </div>
640
+ <div style={s.formActions}>
641
+ <button style={s.btnSecondary} onClick={() => setView({ name: 'add' })}>Hủy</button>
642
+ <button style={s.btnPrimary} disabled={submitting} onClick={() => void connectTelegram()}>
643
+ {submitting ? 'Đang kết nối…' : 'Kết nối Telegram'}
644
+ </button>
645
+ </div>
646
+ </div>
647
+ </>
648
+ )}
649
+
650
+ {/* LIVECHAT FORM */}
651
+ {view.name === 'connect-livechat' && (
652
+ <>
653
+ <div style={s.connectHeader}>
654
+ <button style={s.backBtn} onClick={() => setView({ name: 'add' })}><IconBack /></button>
655
+ <ProviderLogo provider="livechat" apiUrl={base} size={44} />
656
+ <div>
657
+ <div style={s.connectTitle}>Tạo Live Chat Widget</div>
658
+ <div style={s.connectDesc}>Nhúng vào website để nhận tin nhắn từ khách hàng</div>
659
+ </div>
660
+ </div>
661
+ <div style={s.form}>
662
+ <div style={s.field}>
663
+ <label style={s.label}>Tên widget <span style={s.labelHint}>bắt buộc</span></label>
664
+ <input
665
+ style={s.input}
666
+ type="text"
667
+ value={lcName}
668
+ onChange={e => setLcName(e.target.value)}
669
+ placeholder="VD: Hỗ trợ website hanashop.vn"
670
+ />
671
+ </div>
672
+ <div style={s.field}>
673
+ <label style={s.label}>Tên miền được phép <span style={s.labelHint}>tùy chọn</span></label>
674
+ <textarea
675
+ style={{ ...s.input, resize: 'vertical', minHeight: 80, lineHeight: 1.5 }}
676
+ value={lcDomains}
677
+ onChange={e => setLcDomains(e.target.value)}
678
+ placeholder={'https://myshop.com\nhttps://www.myshop.com'}
679
+ spellCheck={false}
680
+ />
681
+ <div style={s.inputHint}>Mỗi domain một dòng. Để trống để cho phép tất cả.</div>
682
+ </div>
683
+ <div style={s.formActions}>
684
+ <button style={s.btnSecondary} onClick={() => setView({ name: 'add' })}>Hủy</button>
685
+ <button style={s.btnPrimary} disabled={submitting} onClick={() => void connectLivechat()}>
686
+ {submitting ? 'Đang tạo…' : 'Tạo widget'}
687
+ </button>
688
+ </div>
689
+ </div>
690
+ </>
691
+ )}
692
+
693
+ {/* LIVECHAT RESULT */}
694
+ {view.name === 'livechat-result' && (
695
+ <>
696
+ <div style={s.connectHeader}>
697
+ <button style={s.backBtn} onClick={() => setView({ name: 'list' })}><IconBack /></button>
698
+ <ProviderLogo provider="livechat" apiUrl={base} size={44} />
699
+ <div>
700
+ <div style={s.connectTitle}>Widget đã được tạo!</div>
701
+ <div style={s.connectDesc}>Sao chép mã nhúng và dán vào website của bạn</div>
702
+ </div>
703
+ </div>
704
+ <div style={s.form}>
705
+ <div style={s.resultBanner}>
706
+ <span style={{ fontSize: 16, flexShrink: 0 }}>✅</span>
707
+ <div>
708
+ <strong>Tạo thành công!</strong> Dán đoạn script dưới đây vào thẻ <code style={{ background: '#dcfce7', padding: '1px 4px', borderRadius: 4 }}>&lt;/body&gt;</code> của website.
709
+ </div>
710
+ </div>
711
+ <div>
712
+ <div style={s.codeLabel}>Mã nhúng</div>
713
+ <div style={s.codeBlock}>
714
+ <pre style={s.codePre}>{view.embedScript}</pre>
715
+ <button style={{ ...s.copyBtn, ...(copiedScript ? { background: '#166534', borderColor: '#166534', color: '#bbf7d0' } : {}) }} onClick={() => copy(view.embedScript, 'script')}>
716
+ {copiedScript ? <><IconCheck /> Đã sao chép</> : <><IconCopy /> Sao chép</>}
717
+ </button>
718
+ </div>
719
+ </div>
720
+ {view.identitySecret && (
721
+ <div>
722
+ <div style={s.codeLabel}>Identity Secret <span style={{ ...s.labelHint, color: '#dc2626', fontWeight: 600 }}>Lưu ngay — chỉ hiển thị một lần</span></div>
723
+ <div style={s.secretRow}>
724
+ <IconKey />
725
+ <span style={s.secretLabel}>Secret:</span>
726
+ <span style={s.secretValue}>{view.identitySecret}</span>
727
+ <button
728
+ onClick={() => copy(view.identitySecret, 'secret')}
729
+ style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: copiedSecret ? '#059669' : '#ca8a04', padding: 2, display: 'flex', alignItems: 'center' }}
730
+ >
731
+ {copiedSecret ? <IconCheck /> : <IconCopy />}
732
+ </button>
733
+ </div>
734
+ <div style={{ ...s.inputHint, marginTop: 6 }}>Dùng secret này để xác thực danh tính người dùng (HMAC). Giữ bí mật — không chia sẻ nơi công khai.</div>
735
+ </div>
736
+ )}
737
+ <div style={s.formActions}>
738
+ <button style={s.btnSecondary} onClick={() => setView({ name: 'list' })}>Về danh sách</button>
739
+ <button style={s.btnPrimary} onClick={() => setView({ name: 'add' })}>Thêm kênh khác</button>
740
+ </div>
741
+ </div>
742
+ </>
743
+ )}
744
+
745
+ {/* OAUTH WAITING */}
746
+ {view.name === 'oauth-waiting' && (
747
+ <>
748
+ <div style={s.header}>
749
+ <div style={s.headerLeft}>
750
+ <button style={s.backBtn} onClick={cancelOAuth}><IconBack /></button>
751
+ <div>
752
+ <div style={s.title}>Đang xác thực {PROVIDER_LABEL[view.provider]}</div>
753
+ <div style={s.subtitle}>Vui lòng hoàn thành trong cửa sổ bật lên</div>
754
+ </div>
755
+ </div>
756
+ </div>
757
+ <div style={s.oauthWaiting}>
758
+ <div style={{ position: 'relative', width: 72, height: 72 }}>
759
+ <div style={{ width: 72, height: 72, borderRadius: 20, background: PROVIDER_BG[view.provider] ?? '#f1f5f9', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
760
+ <ProviderLogo provider={view.provider} apiUrl={base} size={48} />
761
+ </div>
762
+ {/* SVG spinner — guaranteed circular, no browser quirks */}
763
+ <svg
764
+ width={92} height={92} viewBox="0 0 92 92" fill="none"
765
+ style={{ position: 'absolute', top: -10, left: -10, animation: 'ch-spin 1.2s linear infinite' }}
766
+ >
767
+ <circle cx="46" cy="46" r="42" stroke="#e2e8f0" strokeWidth="3.5" />
768
+ <circle cx="46" cy="46" r="42" stroke="#2563eb" strokeWidth="3.5"
769
+ strokeLinecap="round" strokeDasharray="66 198" />
770
+ </svg>
771
+ </div>
772
+ <div style={s.oauthTitle}>Đang chờ xác thực với {PROVIDER_LABEL[view.provider]}</div>
773
+ <div style={s.oauthDesc}>
774
+ Một cửa sổ đăng nhập đã được mở. Vui lòng đăng nhập và cấp quyền truy cập để hoàn tất kết nối.
775
+ </div>
776
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start', width: '100%', maxWidth: 280 }}>
777
+ <OAuthStep done label={`Đã mở cửa sổ ${PROVIDER_LABEL[view.provider]}`} />
778
+ <OAuthStep active label="Đang chờ bạn đăng nhập & cấp quyền" />
779
+ <OAuthStep label="Lưu kết nối & quay về" />
780
+ </div>
781
+ <button style={s.oauthCancel} onClick={cancelOAuth}>Hủy và quay lại</button>
782
+ </div>
783
+ </>
784
+ )}
785
+
786
+ {/* ACCOUNT SELECTION VIEW (Facebook/Instagram page_selection_required) */}
787
+ {view.name === 'oauth-select' && (
788
+ <>
789
+ <div style={s.connectHeader}>
790
+ <button style={s.backBtn} onClick={cancelOAuth}><IconBack /></button>
791
+ <ProviderLogo provider={view.provider} apiUrl={base} size={44} />
792
+ <div>
793
+ <div style={s.connectTitle}>Chọn {view.provider === 'instagram' ? 'tài khoản' : 'trang'}</div>
794
+ <div style={s.connectDesc}>Chọn {PROVIDER_LABEL[view.provider]} bạn muốn kết nối với ChannelHub</div>
795
+ </div>
796
+ </div>
797
+ <div style={s.body}>
798
+ {view.pages.length === 0 ? (
799
+ <div style={{ textAlign: 'center', color: '#94a3b8', fontSize: 13, padding: '24px 0' }}>
800
+ Không tìm thấy trang/tài khoản nào. Hãy thử lại.
801
+ </div>
802
+ ) : (
803
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
804
+ {view.pages.map(page => (
805
+ <button
806
+ key={page.id}
807
+ disabled={submitting}
808
+ onClick={() => void selectAccount(page.id)}
809
+ style={{
810
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
811
+ padding: '12px 16px', borderRadius: 12,
812
+ border: '1.5px solid #e2e8f0', background: '#fff',
813
+ cursor: submitting ? 'not-allowed' : 'pointer',
814
+ opacity: submitting ? 0.6 : 1,
815
+ textAlign: 'left', fontFamily: 'inherit', transition: 'border-color .15s, background .15s',
816
+ }}
817
+ >
818
+ <div>
819
+ <div style={{ fontSize: 14, fontWeight: 600, color: '#0f172a' }}>{page.name}</div>
820
+ <div style={{ fontSize: 11, color: '#94a3b8', fontFamily: 'monospace', marginTop: 2 }}>{page.id}</div>
821
+ </div>
822
+ <span style={{ fontSize: 13, color: '#2563eb', fontWeight: 500 }}>
823
+ {submitting ? 'Đang kết nối…' : 'Chọn →'}
824
+ </span>
825
+ </button>
826
+ ))}
827
+ </div>
828
+ )}
829
+ </div>
830
+ </>
831
+ )}
832
+ </div>
833
+ );
834
+ }
835
+
836
+ // ── Helpers ───────────────────────────────────────────────────────────────────
837
+
838
+ function resolveAvatarUrl(conn: ChannelConnection): string | null {
839
+ const m = conn.metadata;
840
+ if (typeof m['pictureUrl'] === 'string') return m['pictureUrl'];
841
+ if (conn.provider === 'facebook') {
842
+ return `https://graph.facebook.com/${conn.externalAccountId}/picture?type=square`;
843
+ }
844
+ if (conn.provider === 'instagram') {
845
+ const pageId = typeof m['pageId'] === 'string' ? m['pageId'] : null;
846
+ if (pageId) return `https://graph.facebook.com/${pageId}/picture?type=square`;
847
+ }
848
+ return null;
849
+ }
850
+
851
+ // ── Sub-components ────────────────────────────────────────────────────────────
852
+
853
+ function ChannelAvatar({ conn, apiUrl, size = 40 }: { conn: ChannelConnection; apiUrl: string; size?: number }) {
854
+ const [imgError, setImgError] = useState(false);
855
+ const avatarUrl = resolveAvatarUrl(conn);
856
+ const radius = Math.round(size * 0.28);
857
+
858
+ if (avatarUrl && !imgError) {
859
+ return (
860
+ <img
861
+ src={avatarUrl}
862
+ alt={displayName(conn)}
863
+ referrerPolicy="no-referrer"
864
+ onError={() => setImgError(true)}
865
+ style={{ width: size, height: size, borderRadius: radius, objectFit: 'cover', flexShrink: 0, display: 'block' }}
866
+ />
867
+ );
868
+ }
869
+ return <ProviderLogo provider={conn.provider} apiUrl={apiUrl} size={size} />;
870
+ }
871
+
872
+ function ChannelItem({ conn, apiUrl, onDisconnect }: { conn: ChannelConnection; apiUrl: string; onDisconnect: () => void }) {
873
+ const [hover, setHover] = useState(false);
874
+ return (
875
+ <div style={s.channelItem}>
876
+ <ChannelAvatar conn={conn} apiUrl={apiUrl} size={40} />
877
+ <div style={s.channelInfo}>
878
+ <div style={s.channelName}>{displayName(conn)}</div>
879
+ <div style={s.channelMeta}>{metaLine(conn)}</div>
880
+ </div>
881
+ <div style={s.channelActions}>
882
+ <span style={conn.status === 'active' ? s.badgeActive : s.badgeInactive}>
883
+ {conn.status === 'active' ? 'Hoạt động' : conn.status}
884
+ </span>
885
+ <button
886
+ style={{
887
+ ...s.disconnectBtn,
888
+ ...(hover ? { background: '#fef2f2', borderColor: '#fca5a5', color: '#dc2626' } : {}),
889
+ }}
890
+ onMouseEnter={() => setHover(true)}
891
+ onMouseLeave={() => setHover(false)}
892
+ onClick={onDisconnect}
893
+ >
894
+ Ngắt kết nối
895
+ </button>
896
+ </div>
897
+ </div>
898
+ );
899
+ }
900
+
901
+ const PROVIDERS: Array<{ id: string; name: string; desc: string; type: 'oauth' | 'token' | 'livechat' }> = [
902
+ { id: 'facebook', name: 'Facebook', desc: 'Fanpage & Messenger', type: 'oauth' },
903
+ { id: 'zalo', name: 'Zalo OA', desc: 'Official Account', type: 'oauth' },
904
+ { id: 'instagram', name: 'Instagram', desc: 'DM & Comments', type: 'oauth' },
905
+ { id: 'telegram', name: 'Telegram', desc: 'Bot token', type: 'token' },
906
+ { id: 'livechat', name: 'Live Chat', desc: 'Website widget', type: 'livechat' },
907
+ ];
908
+
909
+ function ProviderCard({ provider, apiUrl, onClick }: { provider: typeof PROVIDERS[number]; apiUrl: string; onClick: () => void }) {
910
+ const [hover, setHover] = useState(false);
911
+ return (
912
+ <div
913
+ style={{
914
+ ...s.providerCard,
915
+ ...(hover ? { background: '#fff', borderColor: '#e2e8f0', boxShadow: '0 2px 8px rgba(0,0,0,.07)', transform: 'translateY(-1px)' } : {}),
916
+ }}
917
+ onClick={onClick}
918
+ onMouseEnter={() => setHover(true)}
919
+ onMouseLeave={() => setHover(false)}
920
+ >
921
+ <ProviderLogo provider={provider.id} apiUrl={apiUrl} size={44} />
922
+ <div>
923
+ <div style={s.providerName}>{provider.name}</div>
924
+ <div style={s.providerDesc}>{provider.desc}</div>
925
+ </div>
926
+ </div>
927
+ );
928
+ }
929
+
930
+ function OAuthStep({ done, active, label }: { done?: boolean; active?: boolean; label: string }) {
931
+ const dotColor = done ? '#059669' : active ? '#2563eb' : '#cbd5e1';
932
+ return (
933
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: done ? '#059669' : active ? '#0f172a' : '#94a3b8' }}>
934
+ <div style={{
935
+ width: 10, height: 10, borderRadius: '50%', background: dotColor, flexShrink: 0,
936
+ ...(active ? { boxShadow: '0 0 0 3px rgba(37,99,235,.2)' } : {}),
937
+ }} />
938
+ {label}
939
+ </div>
940
+ );
941
+ }