@channelhub/widget 0.1.12 → 0.1.14

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.
@@ -0,0 +1,1846 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import {
3
+ Bot,
4
+ Check,
5
+ Clock,
6
+ Edit3,
7
+ Inbox,
8
+ KeyRound,
9
+ Loader2,
10
+ MessageSquarePlus,
11
+ Plus,
12
+ Radio,
13
+ Save,
14
+ ShieldCheck,
15
+ Sliders,
16
+ Sparkles,
17
+ Trash2,
18
+ Webhook,
19
+ X,
20
+ Zap,
21
+ } from 'lucide-react';
22
+ import { ChannelHubClient, DEFAULT_TENANT_SETTINGS } from './api.js';
23
+ import { ChannelHubChannels } from './ChannelHubChannels.js';
24
+ import type {
25
+ CannedResponse,
26
+ ChannelHubAiMode,
27
+ ChannelHubAiProvider,
28
+ ChannelHubAiTone,
29
+ ChannelHubSettingsProps,
30
+ ChannelHubSettingsTab,
31
+ ChannelHubTenantSettings,
32
+ } from './types.js';
33
+
34
+ const c = {
35
+ ink: '#172033',
36
+ muted: '#718096',
37
+ line: '#e7ebf2',
38
+ surface: '#f7f9fc',
39
+ white: '#ffffff',
40
+ };
41
+
42
+ const DEFAULT_STARTER_TEMPLATES: { title: string; content: string; shortcut?: string }[] = [
43
+ {
44
+ title: 'Chào khách hàng',
45
+ shortcut: '/chao',
46
+ content: 'Dạ chào Anh/Chị ạ! Em có thể hỗ trợ tư vấn sản phẩm hoặc kiểm tra đơn hàng gì cho mình hôm nay ạ?',
47
+ },
48
+ {
49
+ title: 'Báo phí giao hàng',
50
+ shortcut: '/ship',
51
+ content: 'Dạ phí giao hàng tiêu chuẩn bên em là 25.000đ toàn quốc, miễn phí ship cho đơn hàng từ 300.000đ trở lên ạ.',
52
+ },
53
+ {
54
+ title: 'Xin thông tin đặt hàng',
55
+ shortcut: '/don',
56
+ content: 'Dạ để em lên đơn nhanh cho mình, Anh/Chị cho em xin: Họ tên + Số điện thoại + Địa chỉ nhận hàng nhé ạ!',
57
+ },
58
+ {
59
+ title: 'Cảm ơn khách hàng',
60
+ shortcut: '/camon',
61
+ content: 'Dạ em cảm ơn Anh/Chị đã tin tưởng ủng hộ cửa hàng! Nếu cần hỗ trợ thêm bất kỳ thông tin gì, Anh/Chị cứ nhắn cho em nhé ạ 🙏',
62
+ },
63
+ ];
64
+
65
+ function ToggleSwitch({
66
+ checked,
67
+ onChange,
68
+ primary,
69
+ label,
70
+ description,
71
+ }: {
72
+ checked: boolean;
73
+ onChange: (next: boolean) => void;
74
+ primary: string;
75
+ label: string;
76
+ description?: string;
77
+ }) {
78
+ return (
79
+ <div
80
+ style={{
81
+ display: 'flex',
82
+ alignItems: 'flex-start',
83
+ justifyContent: 'space-between',
84
+ gap: 14,
85
+ padding: '12px 14px',
86
+ borderRadius: 10,
87
+ border: `1px solid ${c.line}`,
88
+ background: c.white,
89
+ }}
90
+ >
91
+ <div style={{ minWidth: 0, flex: 1 }}>
92
+ <div style={{ fontSize: 13, fontWeight: 600, color: c.ink, lineHeight: 1.35 }}>{label}</div>
93
+ {description && (
94
+ <div style={{ fontSize: 11.5, color: c.muted, marginTop: 3, lineHeight: 1.45 }}>{description}</div>
95
+ )}
96
+ </div>
97
+ <button
98
+ type="button"
99
+ role="switch"
100
+ aria-checked={checked}
101
+ aria-label={label}
102
+ onClick={() => onChange(!checked)}
103
+ style={{
104
+ position: 'relative',
105
+ width: 40,
106
+ height: 22,
107
+ borderRadius: 999,
108
+ border: 0,
109
+ padding: 0,
110
+ flexShrink: 0,
111
+ cursor: 'pointer',
112
+ background: checked ? primary : '#cbd5e1',
113
+ transition: 'background 150ms ease',
114
+ }}
115
+ >
116
+ <span
117
+ style={{
118
+ position: 'absolute',
119
+ top: 2,
120
+ left: checked ? 20 : 2,
121
+ width: 18,
122
+ height: 18,
123
+ borderRadius: '50%',
124
+ background: '#fff',
125
+ boxShadow: '0 1px 3px rgba(15,23,42,.2)',
126
+ transition: 'left 150ms ease',
127
+ }}
128
+ />
129
+ </button>
130
+ </div>
131
+ );
132
+ }
133
+
134
+ const DEFAULT_SETTINGS_TABS: ChannelHubSettingsTab[] = ['ai', 'templates', 'inbox'];
135
+
136
+ export function ChannelHubSettings({
137
+ apiUrl,
138
+ token,
139
+ theme,
140
+ initialTab = 'ai',
141
+ tabs,
142
+ hideTechnicalAiConfig,
143
+ customParameters,
144
+ starterTemplates,
145
+ onSettingsChange,
146
+ onClose,
147
+ }: ChannelHubSettingsProps) {
148
+ const client = useRef(new ChannelHubClient(apiUrl, token));
149
+ const primary = theme?.primaryColor ?? '#2563eb';
150
+ const fontFamily = theme?.fontFamily ?? 'Inter, ui-sans-serif, system-ui, sans-serif';
151
+
152
+ useEffect(() => {
153
+ client.current = new ChannelHubClient(apiUrl, token);
154
+ }, [apiUrl, token]);
155
+
156
+ const tabsKey = tabs && tabs.length > 0 ? tabs.join(',') : '';
157
+ const availableTabs: ChannelHubSettingsTab[] = useMemo(
158
+ () => (tabs && tabs.length > 0 ? tabs : DEFAULT_SETTINGS_TABS),
159
+ // eslint-disable-next-line react-hooks/exhaustive-deps
160
+ [tabsKey],
161
+ );
162
+ const [activeTab, setActiveTab] = useState<ChannelHubSettingsTab>(() =>
163
+ availableTabs.includes(initialTab) ? initialTab : availableTabs[0]!,
164
+ );
165
+
166
+ useEffect(() => {
167
+ if (availableTabs.includes(initialTab)) {
168
+ setActiveTab(initialTab);
169
+ }
170
+ }, [initialTab]);
171
+
172
+ const [settings, setSettings] = useState<ChannelHubTenantSettings>(DEFAULT_TENANT_SETTINGS);
173
+ const [loading, setLoading] = useState(true);
174
+ const [saving, setSaving] = useState(false);
175
+ const [saveSuccess, setSaveSuccess] = useState(false);
176
+ const [error, setError] = useState('');
177
+
178
+ // Canned responses state
179
+ const [templates, setTemplates] = useState<CannedResponse[]>([]);
180
+ const [templatesLoading, setTemplatesLoading] = useState(true);
181
+ const [seedingStarter, setSeedingStarter] = useState(false);
182
+ const [editingTplId, setEditingTplId] = useState<string | 'new' | null>(null);
183
+ const [tplTitle, setTplTitle] = useState('');
184
+ const [tplShortcut, setTplShortcut] = useState('');
185
+ const [tplContent, setTplContent] = useState('');
186
+ const [tplSaving, setTplSaving] = useState(false);
187
+
188
+ // Quick reply chip input
189
+ const [newQuickReply, setNewQuickReply] = useState('');
190
+
191
+ // Webhook test state
192
+ const [webhookTestMsg, setWebhookTestMsg] = useState('Shop ơi mẫu này còn hàng không, giá bao nhiêu ạ?');
193
+ const [webhookTesting, setWebhookTesting] = useState(false);
194
+ const [webhookTestResult, setWebhookTestResult] = useState<{
195
+ ok: boolean;
196
+ status: number;
197
+ latencyMs: number;
198
+ response: Record<string, unknown>;
199
+ } | null>(null);
200
+
201
+ // Responsive container observation
202
+ const rootRef = useRef<HTMLDivElement>(null);
203
+ const [isCompact, setIsCompact] = useState<boolean>(() =>
204
+ typeof window !== 'undefined' ? window.innerWidth < 680 : false,
205
+ );
206
+
207
+ useEffect(() => {
208
+ const el = rootRef.current;
209
+ if (!el || typeof ResizeObserver === 'undefined') return;
210
+ const ro = new ResizeObserver(entries => {
211
+ for (const entry of entries) {
212
+ if (entry.contentRect.width > 0) {
213
+ setIsCompact(entry.contentRect.width < 640);
214
+ }
215
+ }
216
+ });
217
+ ro.observe(el);
218
+ return () => ro.disconnect();
219
+ }, []);
220
+
221
+ const loadAll = useCallback(async () => {
222
+ setLoading(true);
223
+ try {
224
+ const s = await client.current.getSettings();
225
+ // Merge customParameter defaults if not yet set
226
+ if (customParameters?.length) {
227
+ const nextParams = { ...s.ai.parameters };
228
+ for (const p of customParameters) {
229
+ if (nextParams[p.key] === undefined && p.defaultValue !== undefined) {
230
+ nextParams[p.key] = p.defaultValue;
231
+ }
232
+ }
233
+ s.ai.parameters = nextParams;
234
+ }
235
+ setSettings(s);
236
+ } catch (e) {
237
+ setError(e instanceof Error ? e.message : 'Không tải được cài đặt');
238
+ } finally {
239
+ setLoading(false);
240
+ }
241
+ }, [customParameters]);
242
+
243
+ const loadTemplates = useCallback(async () => {
244
+ setTemplatesLoading(true);
245
+ try {
246
+ const list = await client.current.listCannedResponses();
247
+ setTemplates(list);
248
+ } catch {
249
+ // Keep current list on failure
250
+ } finally {
251
+ setTemplatesLoading(false);
252
+ }
253
+ }, []);
254
+
255
+ useEffect(() => {
256
+ void loadAll();
257
+ void loadTemplates();
258
+ }, [loadAll, loadTemplates]);
259
+
260
+ async function handleSaveSettings(nextSettings?: ChannelHubTenantSettings) {
261
+ const target = nextSettings ?? settings;
262
+ setSaving(true);
263
+ setError('');
264
+ setSaveSuccess(false);
265
+ try {
266
+ const updated = await client.current.updateSettings({
267
+ ai: target.ai,
268
+ inbox: target.inbox,
269
+ });
270
+ setSettings(updated);
271
+ onSettingsChange?.(updated);
272
+ setSaveSuccess(true);
273
+ setTimeout(() => setSaveSuccess(false), 2200);
274
+ } catch (e) {
275
+ setError(e instanceof Error ? e.message : 'Lưu cài đặt thất bại');
276
+ } finally {
277
+ setSaving(false);
278
+ }
279
+ }
280
+
281
+ function updateAi<K extends keyof ChannelHubTenantSettings['ai']>(
282
+ key: K,
283
+ value: ChannelHubTenantSettings['ai'][K],
284
+ ) {
285
+ setSettings(prev => ({
286
+ ...prev,
287
+ ai: {
288
+ ...prev.ai,
289
+ [key]: value,
290
+ },
291
+ }));
292
+ }
293
+
294
+ function updateInbox<K extends keyof ChannelHubTenantSettings['inbox']>(
295
+ key: K,
296
+ value: ChannelHubTenantSettings['inbox'][K],
297
+ ) {
298
+ setSettings(prev => ({
299
+ ...prev,
300
+ inbox: {
301
+ ...prev.inbox,
302
+ [key]: value,
303
+ },
304
+ }));
305
+ }
306
+
307
+ function updateCustomParam(key: string, value: string | boolean) {
308
+ setSettings(prev => ({
309
+ ...prev,
310
+ ai: {
311
+ ...prev.ai,
312
+ parameters: {
313
+ ...prev.ai.parameters,
314
+ [key]: value,
315
+ },
316
+ },
317
+ }));
318
+ }
319
+
320
+ function startNewTemplate() {
321
+ setEditingTplId('new');
322
+ setTplTitle('');
323
+ setTplShortcut('');
324
+ setTplContent('');
325
+ }
326
+
327
+ function startEditTemplate(tpl: CannedResponse) {
328
+ setEditingTplId(tpl.id);
329
+ setTplTitle(tpl.title);
330
+ setTplShortcut(tpl.shortcut ?? '');
331
+ setTplContent(tpl.content);
332
+ }
333
+
334
+ async function saveTemplateForm() {
335
+ if (!tplTitle.trim() || !tplContent.trim() || tplSaving) return;
336
+ setTplSaving(true);
337
+ setError('');
338
+ const formattedShortcut = tplShortcut.trim()
339
+ ? tplShortcut.trim().startsWith('/')
340
+ ? tplShortcut.trim()
341
+ : `/${tplShortcut.trim()}`
342
+ : undefined;
343
+ try {
344
+ if (editingTplId === 'new') {
345
+ const created = await client.current.createCannedResponse({
346
+ title: tplTitle.trim(),
347
+ content: tplContent.trim(),
348
+ ...(formattedShortcut ? { shortcut: formattedShortcut } : {}),
349
+ });
350
+ setTemplates(prev => [...prev, created]);
351
+ } else if (editingTplId) {
352
+ const updated = await client.current.updateCannedResponse(editingTplId, {
353
+ title: tplTitle.trim(),
354
+ content: tplContent.trim(),
355
+ shortcut: formattedShortcut ?? null,
356
+ });
357
+ setTemplates(prev => prev.map(t => (t.id === updated.id ? updated : t)));
358
+ }
359
+ setEditingTplId(null);
360
+ } catch (e) {
361
+ setError(e instanceof Error ? e.message : 'Không lưu được mẫu câu');
362
+ } finally {
363
+ setTplSaving(false);
364
+ }
365
+ }
366
+
367
+ async function handleDeleteTemplate(id: string) {
368
+ try {
369
+ await client.current.deleteCannedResponse(id);
370
+ setTemplates(prev => prev.filter(t => t.id !== id));
371
+ if (editingTplId === id) setEditingTplId(null);
372
+ } catch (e) {
373
+ setError(e instanceof Error ? e.message : 'Không xóa được mẫu câu');
374
+ }
375
+ }
376
+
377
+ async function handleSeedStarterTemplates() {
378
+ if (seedingStarter) return;
379
+ setSeedingStarter(true);
380
+ setError('');
381
+ const listToSeed = starterTemplates?.length ? starterTemplates : DEFAULT_STARTER_TEMPLATES;
382
+ try {
383
+ const createdList: CannedResponse[] = [];
384
+ for (const item of listToSeed) {
385
+ const created = await client.current.createCannedResponse({
386
+ title: item.title,
387
+ content: item.content,
388
+ ...(item.shortcut ? { shortcut: item.shortcut } : {}),
389
+ });
390
+ createdList.push(created);
391
+ }
392
+ setTemplates(prev => [...prev, ...createdList]);
393
+ } catch (e) {
394
+ setError(e instanceof Error ? e.message : 'Không nạp được bộ mẫu câu gợi ý');
395
+ } finally {
396
+ setSeedingStarter(false);
397
+ }
398
+ }
399
+
400
+ function handleAddQuickReply() {
401
+ const val = newQuickReply.trim();
402
+ if (!val) return;
403
+ if (settings.inbox.quickReplies.includes(val)) {
404
+ setNewQuickReply('');
405
+ return;
406
+ }
407
+ const nextList = [...settings.inbox.quickReplies, val];
408
+ const nextSettings: ChannelHubTenantSettings = {
409
+ ...settings,
410
+ inbox: { ...settings.inbox, quickReplies: nextList },
411
+ };
412
+ setSettings(nextSettings);
413
+ setNewQuickReply('');
414
+ }
415
+
416
+ function handleRemoveQuickReply(chip: string) {
417
+ const nextList = settings.inbox.quickReplies.filter(x => x !== chip);
418
+ setSettings(prev => ({
419
+ ...prev,
420
+ inbox: { ...prev.inbox, quickReplies: nextList },
421
+ }));
422
+ }
423
+
424
+ const shouldHideTechnicalAi =
425
+ hideTechnicalAiConfig !== undefined ? hideTechnicalAiConfig : Boolean(settings.isPlatformManaged);
426
+
427
+ const tabMeta: Record<ChannelHubSettingsTab, { label: string; icon: React.ReactNode }> = {
428
+ ai: { label: 'Trợ lý AI', icon: <Sparkles size={15} /> },
429
+ templates: { label: 'Mẫu câu trả lời nhanh', icon: <Zap size={15} /> },
430
+ inbox: { label: 'Hộp thư & Tự động hóa', icon: <Inbox size={15} /> },
431
+ channels: { label: 'Kênh kết nối', icon: <Radio size={15} /> },
432
+ };
433
+
434
+ return (
435
+ <div
436
+ ref={rootRef}
437
+ style={{
438
+ display: 'flex',
439
+ flexDirection: 'column',
440
+ width: '100%',
441
+ height: '100%',
442
+ maxHeight: '100%',
443
+ background: c.white,
444
+ color: c.ink,
445
+ fontFamily,
446
+ borderRadius: theme?.borderRadius ?? '16px',
447
+ border: `1px solid ${c.line}`,
448
+ overflow: 'hidden',
449
+ boxSizing: 'border-box',
450
+ }}
451
+ >
452
+ {/* Header */}
453
+ <div
454
+ style={{
455
+ display: 'flex',
456
+ alignItems: 'center',
457
+ justifyContent: 'space-between',
458
+ gap: 12,
459
+ padding: isCompact ? '14px 16px' : '16px 22px',
460
+ borderBottom: `1px solid ${c.line}`,
461
+ background: c.white,
462
+ flexShrink: 0,
463
+ }}
464
+ >
465
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
466
+ <div
467
+ style={{
468
+ width: 34,
469
+ height: 34,
470
+ borderRadius: 10,
471
+ background: `${primary}14`,
472
+ color: primary,
473
+ display: 'grid',
474
+ placeItems: 'center',
475
+ flexShrink: 0,
476
+ }}
477
+ >
478
+ <Sliders size={17} />
479
+ </div>
480
+ <div style={{ minWidth: 0 }}>
481
+ <div style={{ fontSize: 15, fontWeight: 700, color: c.ink }}>Cài đặt Hộp thư & Trợ lý AI</div>
482
+ <div style={{ fontSize: 11.5, color: c.muted }}>
483
+ Thiết lập tự động trả lời, mẫu câu gợi ý và quy trình phối hợp nhân viên
484
+ </div>
485
+ </div>
486
+ </div>
487
+ {onClose && (
488
+ <button
489
+ type="button"
490
+ onClick={onClose}
491
+ aria-label="Đóng cài đặt"
492
+ style={{
493
+ width: 32,
494
+ height: 32,
495
+ borderRadius: 8,
496
+ border: 0,
497
+ background: 'transparent',
498
+ color: c.muted,
499
+ display: 'inline-grid',
500
+ placeItems: 'center',
501
+ cursor: 'pointer',
502
+ flexShrink: 0,
503
+ }}
504
+ >
505
+ <X size={18} />
506
+ </button>
507
+ )}
508
+ </div>
509
+
510
+ {/* Navigation Tabs */}
511
+ <div
512
+ role="tablist"
513
+ aria-label="Danh mục cài đặt"
514
+ style={{
515
+ display: 'flex',
516
+ gap: 4,
517
+ padding: isCompact ? '8px 12px' : '10px 22px',
518
+ borderBottom: `1px solid ${c.line}`,
519
+ background: c.surface,
520
+ overflowX: 'auto',
521
+ WebkitOverflowScrolling: 'touch',
522
+ scrollbarWidth: 'none',
523
+ flexShrink: 0,
524
+ }}
525
+ >
526
+ {availableTabs.map(tabKey => {
527
+ const active = activeTab === tabKey;
528
+ const info = tabMeta[tabKey];
529
+ return (
530
+ <button
531
+ key={tabKey}
532
+ type="button"
533
+ role="tab"
534
+ aria-selected={active}
535
+ onClick={() => setActiveTab(tabKey)}
536
+ style={{
537
+ display: 'inline-flex',
538
+ alignItems: 'center',
539
+ gap: 7,
540
+ padding: '7px 13px',
541
+ borderRadius: 8,
542
+ border: active ? `1px solid ${primary}33` : '1px solid transparent',
543
+ background: active ? c.white : 'transparent',
544
+ color: active ? primary : c.muted,
545
+ fontSize: 12.5,
546
+ fontWeight: active ? 700 : 600,
547
+ cursor: 'pointer',
548
+ whiteSpace: 'nowrap',
549
+ flexShrink: 0,
550
+ boxShadow: active ? '0 1px 3px rgba(23,32,51,.06)' : 'none',
551
+ transition: 'all 120ms ease',
552
+ }}
553
+ >
554
+ {info.icon}
555
+ <span>{info.label}</span>
556
+ </button>
557
+ );
558
+ })}
559
+ </div>
560
+
561
+ {/* Body Content */}
562
+ <div
563
+ style={{
564
+ flex: 1,
565
+ minHeight: 0,
566
+ overflowY: 'auto',
567
+ padding: isCompact ? 14 : 22,
568
+ background: c.surface,
569
+ }}
570
+ >
571
+ {loading ? (
572
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: 48, color: c.muted, fontSize: 13 }}>
573
+ <Loader2 size={16} style={{ animation: 'channelhub-spin .7s linear infinite' }} />
574
+ <span>Đang tải cài đặt…</span>
575
+ </div>
576
+ ) : (
577
+ <>
578
+ {/* ─── TAB 1: TRỢ LÝ AI ─────────────────────────────────────────────── */}
579
+ {activeTab === 'ai' && (
580
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 780, margin: '0 auto' }}>
581
+ {/* Mode selector cards */}
582
+ <div style={{ background: c.white, border: `1px solid ${c.line}`, borderRadius: 12, padding: isCompact ? 14 : 18 }}>
583
+ <div style={{ fontSize: 13.5, fontWeight: 700, color: c.ink, marginBottom: 4 }}>
584
+ Chế độ hoạt động của Trợ lý AI
585
+ </div>
586
+ <div style={{ fontSize: 12, color: c.muted, marginBottom: 14 }}>
587
+ Chọn mức độ tham gia của AI khi khách hàng nhắn tin đến các kênh của cửa hàng.
588
+ </div>
589
+
590
+ <div
591
+ style={{
592
+ display: 'grid',
593
+ gridTemplateColumns: isCompact ? '1fr' : 'repeat(3, 1fr)',
594
+ gap: 10,
595
+ }}
596
+ >
597
+ {([
598
+ {
599
+ mode: 'off' as ChannelHubAiMode,
600
+ title: 'Tắt AI',
601
+ badge: 'Thủ công',
602
+ desc: 'Nhân viên trực tiếp trả lời 100% tin nhắn như bình thường.',
603
+ icon: <X size={16} />,
604
+ },
605
+ {
606
+ mode: 'copilot' as ChannelHubAiMode,
607
+ title: 'AI Copilot',
608
+ badge: 'Gợi ý cho nhân viên',
609
+ desc: 'AI soạn sẵn câu trả lời gợi ý, nhân viên kiểm tra và bấm duyệt mới gửi.',
610
+ icon: <Sparkles size={16} />,
611
+ },
612
+ {
613
+ mode: 'autopilot' as ChannelHubAiMode,
614
+ title: 'AI Autopilot',
615
+ badge: 'Tự động trả lời',
616
+ desc: 'AI tự động phản hồi ngay cho các hội thoại chưa có nhân viên nhận phụ trách.',
617
+ icon: <Bot size={16} />,
618
+ },
619
+ ]).map(card => {
620
+ const selected = settings.ai.mode === card.mode;
621
+ return (
622
+ <button
623
+ key={card.mode}
624
+ type="button"
625
+ onClick={() => updateAi('mode', card.mode)}
626
+ style={{
627
+ textAlign: 'left',
628
+ padding: 14,
629
+ borderRadius: 11,
630
+ border: selected ? `2px solid ${primary}` : `1px solid ${c.line}`,
631
+ background: selected ? `${primary}08` : c.white,
632
+ cursor: 'pointer',
633
+ display: 'flex',
634
+ flexDirection: 'column',
635
+ gap: 8,
636
+ transition: 'all 120ms ease',
637
+ }}
638
+ >
639
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
640
+ <span
641
+ style={{
642
+ width: 30,
643
+ height: 30,
644
+ borderRadius: 8,
645
+ background: selected ? primary : c.surface,
646
+ color: selected ? '#fff' : c.muted,
647
+ display: 'inline-grid',
648
+ placeItems: 'center',
649
+ }}
650
+ >
651
+ {card.icon}
652
+ </span>
653
+ <span
654
+ style={{
655
+ fontSize: 10.5,
656
+ fontWeight: 700,
657
+ padding: '2px 8px',
658
+ borderRadius: 999,
659
+ background: selected ? `${primary}1a` : c.surface,
660
+ color: selected ? primary : c.muted,
661
+ }}
662
+ >
663
+ {card.badge}
664
+ </span>
665
+ </div>
666
+ <div style={{ fontSize: 13.5, fontWeight: 700, color: c.ink }}>{card.title}</div>
667
+ <div style={{ fontSize: 11.5, color: c.muted, lineHeight: 1.45 }}>{card.desc}</div>
668
+ </button>
669
+ );
670
+ })}
671
+ </div>
672
+ </div>
673
+
674
+ {/* Custom Business Parameters injected by Platform */}
675
+ {customParameters && customParameters.length > 0 && (
676
+ <div style={{ background: c.white, border: `1px solid ${c.line}`, borderRadius: 12, padding: isCompact ? 14 : 18 }}>
677
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
678
+ <ShieldCheck size={16} color={primary} />
679
+ <span style={{ fontSize: 13.5, fontWeight: 700, color: c.ink }}>
680
+ Thiết lập nghiệp vụ cửa hàng
681
+ </span>
682
+ </div>
683
+ <div style={{ fontSize: 12, color: c.muted, marginBottom: 14 }}>
684
+ Các tuỳ chỉnh dành riêng cho quy trình tư vấn và bán hàng của shop bạn.
685
+ </div>
686
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
687
+ {customParameters.map(param => {
688
+ const rawVal = settings.ai.parameters[param.key] ?? param.defaultValue;
689
+ if (param.type === 'toggle') {
690
+ return (
691
+ <ToggleSwitch
692
+ key={param.key}
693
+ label={param.label}
694
+ description={param.description}
695
+ checked={Boolean(rawVal)}
696
+ onChange={val => updateCustomParam(param.key, val)}
697
+ primary={primary}
698
+ />
699
+ );
700
+ }
701
+ if (param.type === 'select') {
702
+ return (
703
+ <div key={param.key} style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
704
+ <label style={{ fontSize: 12.5, fontWeight: 600, color: c.ink }}>{param.label}</label>
705
+ {param.description && (
706
+ <span style={{ fontSize: 11.5, color: c.muted }}>{param.description}</span>
707
+ )}
708
+ <select
709
+ value={String(rawVal ?? '')}
710
+ onChange={e => updateCustomParam(param.key, e.target.value)}
711
+ style={{
712
+ padding: '8px 10px',
713
+ borderRadius: 8,
714
+ border: `1px solid ${c.line}`,
715
+ background: c.white,
716
+ color: c.ink,
717
+ fontSize: isCompact ? 16 : 12.5,
718
+ fontFamily: 'inherit',
719
+ }}
720
+ >
721
+ {(param.options ?? []).map(opt => (
722
+ <option key={opt.value} value={opt.value}>
723
+ {opt.label}
724
+ </option>
725
+ ))}
726
+ </select>
727
+ </div>
728
+ );
729
+ }
730
+ if (param.type === 'textarea') {
731
+ return (
732
+ <div key={param.key} style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
733
+ <label style={{ fontSize: 12.5, fontWeight: 600, color: c.ink }}>{param.label}</label>
734
+ {param.description && (
735
+ <span style={{ fontSize: 11.5, color: c.muted }}>{param.description}</span>
736
+ )}
737
+ <textarea
738
+ rows={3}
739
+ value={String(rawVal ?? '')}
740
+ placeholder={param.placeholder}
741
+ onChange={e => updateCustomParam(param.key, e.target.value)}
742
+ style={{
743
+ padding: '8px 10px',
744
+ borderRadius: 8,
745
+ border: `1px solid ${c.line}`,
746
+ background: c.white,
747
+ color: c.ink,
748
+ fontSize: isCompact ? 16 : 12.5,
749
+ fontFamily: 'inherit',
750
+ resize: 'vertical',
751
+ }}
752
+ />
753
+ </div>
754
+ );
755
+ }
756
+ return (
757
+ <div key={param.key} style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
758
+ <label style={{ fontSize: 12.5, fontWeight: 600, color: c.ink }}>{param.label}</label>
759
+ {param.description && (
760
+ <span style={{ fontSize: 11.5, color: c.muted }}>{param.description}</span>
761
+ )}
762
+ <input
763
+ type="text"
764
+ value={String(rawVal ?? '')}
765
+ placeholder={param.placeholder}
766
+ onChange={e => updateCustomParam(param.key, e.target.value)}
767
+ style={{
768
+ padding: '8px 10px',
769
+ borderRadius: 8,
770
+ border: `1px solid ${c.line}`,
771
+ background: c.white,
772
+ color: c.ink,
773
+ fontSize: isCompact ? 16 : 12.5,
774
+ fontFamily: 'inherit',
775
+ }}
776
+ />
777
+ </div>
778
+ );
779
+ })}
780
+ </div>
781
+ </div>
782
+ )}
783
+
784
+ {/* Style & Human Handoff Rules */}
785
+ <div style={{ background: c.white, border: `1px solid ${c.line}`, borderRadius: 12, padding: isCompact ? 14 : 18 }}>
786
+ <div style={{ fontSize: 13.5, fontWeight: 700, color: c.ink, marginBottom: 4 }}>
787
+ Phong cách giao tiếp & Quy tắc chuyển giao cho nhân viên
788
+ </div>
789
+ <div style={{ fontSize: 12, color: c.muted, marginBottom: 14 }}>
790
+ Đảm bảo AI luôn nhường quyền ngay lập tức khi nhân viên vào cuộc hoặc khi khách hàng cần tư vấn sâu.
791
+ </div>
792
+
793
+ <div
794
+ style={{
795
+ display: 'grid',
796
+ gridTemplateColumns: isCompact ? '1fr' : 'repeat(2, 1fr)',
797
+ gap: 12,
798
+ marginBottom: 14,
799
+ }}
800
+ >
801
+ <div>
802
+ <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: c.ink, marginBottom: 5 }}>
803
+ Giọng điệu xưng hô
804
+ </label>
805
+ <select
806
+ value={settings.ai.tone}
807
+ onChange={e => updateAi('tone', e.target.value as ChannelHubAiTone)}
808
+ style={{
809
+ width: '100%',
810
+ padding: '8px 10px',
811
+ borderRadius: 8,
812
+ border: `1px solid ${c.line}`,
813
+ background: c.white,
814
+ color: c.ink,
815
+ fontSize: isCompact ? 16 : 12.5,
816
+ fontFamily: 'inherit',
817
+ }}
818
+ >
819
+ <option value="friendly">Thân thiện, nhiệt tình (Dạ / Em - Anh/Chị)</option>
820
+ <option value="professional">Lịch sự, chuyên nghiệp (Cửa hàng - Quý khách)</option>
821
+ <option value="concise">Ngắn gọn, đi thẳng vào trọng tâm</option>
822
+ </select>
823
+ </div>
824
+
825
+ <div>
826
+ <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: c.ink, marginBottom: 5 }}>
827
+ Thời gian chờ gom tin nhắn của khách (Debounce)
828
+ </label>
829
+ <select
830
+ value={settings.ai.debounceSeconds}
831
+ onChange={e => updateAi('debounceSeconds', Number(e.target.value))}
832
+ style={{
833
+ width: '100%',
834
+ padding: '8px 10px',
835
+ borderRadius: 8,
836
+ border: `1px solid ${c.line}`,
837
+ background: c.white,
838
+ color: c.ink,
839
+ fontSize: isCompact ? 16 : 12.5,
840
+ fontFamily: 'inherit',
841
+ }}
842
+ >
843
+ <option value={3}>3 giây (Phản hồi nhanh)</option>
844
+ <option value={5}>5 giây (Khuyên dùng - gom đủ các câu ngắn)</option>
845
+ <option value={8}>8 giây (Chờ khách gõ nhiều dòng)</option>
846
+ <option value={10}>10 giây</option>
847
+ </select>
848
+ </div>
849
+ </div>
850
+
851
+ {/* Schedule */}
852
+ <div
853
+ style={{
854
+ padding: 12,
855
+ borderRadius: 10,
856
+ border: `1px solid ${c.line}`,
857
+ background: c.surface,
858
+ marginBottom: 12,
859
+ }}
860
+ >
861
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10 }}>
862
+ <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
863
+ <Clock size={15} color={primary} />
864
+ <span style={{ fontSize: 12.5, fontWeight: 600, color: c.ink }}>Khung giờ AI hoạt động</span>
865
+ </div>
866
+ <div style={{ display: 'flex', gap: 6 }}>
867
+ {([
868
+ { key: 'always' as const, label: 'Luôn bật 24/7' },
869
+ { key: 'outside_hours' as const, label: 'Chỉ bật ngoài giờ làm việc' },
870
+ ]).map(opt => {
871
+ const active = settings.ai.schedule === opt.key;
872
+ return (
873
+ <button
874
+ key={opt.key}
875
+ type="button"
876
+ onClick={() => updateAi('schedule', opt.key)}
877
+ style={{
878
+ padding: '5px 10px',
879
+ borderRadius: 7,
880
+ border: active ? `1px solid ${primary}` : `1px solid ${c.line}`,
881
+ background: active ? `${primary}12` : c.white,
882
+ color: active ? primary : c.muted,
883
+ fontSize: 11.5,
884
+ fontWeight: active ? 700 : 500,
885
+ cursor: 'pointer',
886
+ }}
887
+ >
888
+ {opt.label}
889
+ </button>
890
+ );
891
+ })}
892
+ </div>
893
+ </div>
894
+ {settings.ai.schedule === 'outside_hours' && (
895
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10, fontSize: 12, color: c.muted, flexWrap: 'wrap' }}>
896
+ <span>Giờ làm việc của nhân viên: Từ</span>
897
+ <input
898
+ type="time"
899
+ value={settings.ai.businessHours.start}
900
+ onChange={e =>
901
+ updateAi('businessHours', { ...settings.ai.businessHours, start: e.target.value })
902
+ }
903
+ style={{ padding: '4px 8px', borderRadius: 6, border: `1px solid ${c.line}`, fontSize: 12 }}
904
+ />
905
+ <span>đến</span>
906
+ <input
907
+ type="time"
908
+ value={settings.ai.businessHours.end}
909
+ onChange={e =>
910
+ updateAi('businessHours', { ...settings.ai.businessHours, end: e.target.value })
911
+ }
912
+ style={{ padding: '4px 8px', borderRadius: 6, border: `1px solid ${c.line}`, fontSize: 12 }}
913
+ />
914
+ <span>(AI sẽ tự trả lời ngoài khung giờ này)</span>
915
+ </div>
916
+ )}
917
+ </div>
918
+
919
+ {/* Handoff Toggles */}
920
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
921
+ <ToggleSwitch
922
+ label="Tự động dừng AI khi có nhân viên nhận phụ trách"
923
+ description="Khi hội thoại đã được gán cho một nhân viên cụ thể, AI Autopilot sẽ ngừng trả lời tự động."
924
+ checked={settings.ai.autoPauseOnAgentAssign}
925
+ onChange={v => updateAi('autoPauseOnAgentAssign', v)}
926
+ primary={primary}
927
+ />
928
+ <ToggleSwitch
929
+ label="Tự động dừng AI ngay khi nhân viên nhắn tin vào hội thoại"
930
+ description="Tránh trường hợp nhân viên và AI cùng trả lời chồng chéo cho khách hàng."
931
+ checked={settings.ai.autoPauseOnAgentReply}
932
+ onChange={v => updateAi('autoPauseOnAgentReply', v)}
933
+ primary={primary}
934
+ />
935
+ <ToggleSwitch
936
+ label="Chuyển cho nhân viên khi khách để lại Số điện thoại"
937
+ description="Khi phát hiện số điện thoại trong tin nhắn, AI dừng lại và gắn cảnh báo để nhân viên chốt đơn."
938
+ checked={settings.ai.handoffOnPhone}
939
+ onChange={v => updateAi('handoffOnPhone', v)}
940
+ primary={primary}
941
+ />
942
+ <ToggleSwitch
943
+ label="Chuyển cho nhân viên khi khách khiếu nại hoặc yêu cầu gặp người thật"
944
+ description="Khi khách có dấu hiệu bức xúc hoặc yêu cầu gặp quản lý/nhân viên tư vấn."
945
+ checked={settings.ai.handoffOnComplaint}
946
+ onChange={v => updateAi('handoffOnComplaint', v)}
947
+ primary={primary}
948
+ />
949
+ </div>
950
+ </div>
951
+
952
+ {/* Standalone Store Knowledge & AI Engine Config (Hidden when platform-managed) */}
953
+ {!shouldHideTechnicalAi && (
954
+ <div style={{ background: c.white, border: `1px solid ${c.line}`, borderRadius: 12, padding: isCompact ? 14 : 18 }}>
955
+ <div style={{ fontSize: 13.5, fontWeight: 700, color: c.ink, marginBottom: 4 }}>
956
+ Kiến thức cửa hàng & Kết nối nguồn AI
957
+ </div>
958
+ <div style={{ fontSize: 12, color: c.muted, marginBottom: 14 }}>
959
+ Cung cấp thông tin sản phẩm, chính sách của shop và kết nối với mô hình AI hoặc Webhook của bạn.
960
+ </div>
961
+
962
+ <div style={{ marginBottom: 14 }}>
963
+ <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: c.ink, marginBottom: 5 }}>
964
+ Hướng dẫn & Kiến thức cửa hàng (System Prompt)
965
+ </label>
966
+ <textarea
967
+ rows={4}
968
+ value={settings.ai.systemPrompt ?? ''}
969
+ onChange={e => updateAi('systemPrompt', e.target.value)}
970
+ placeholder="Ví dụ: Bạn là trợ lý tư vấn của Shop Thời Trang ABC. Phí ship đồng giá 25k, miễn phí ship từ 300k. Đổi trả trong 7 ngày..."
971
+ style={{
972
+ width: '100%',
973
+ boxSizing: 'border-box',
974
+ padding: '9px 11px',
975
+ borderRadius: 8,
976
+ border: `1px solid ${c.line}`,
977
+ background: c.white,
978
+ color: c.ink,
979
+ fontSize: isCompact ? 16 : 12.5,
980
+ fontFamily: 'inherit',
981
+ lineHeight: 1.5,
982
+ resize: 'vertical',
983
+ }}
984
+ />
985
+ </div>
986
+
987
+ <div style={{ marginBottom: 12 }}>
988
+ <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: c.ink, marginBottom: 6 }}>
989
+ Nguồn xử lý AI (Provider)
990
+ </label>
991
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
992
+ {([
993
+ { id: 'openai' as ChannelHubAiProvider, label: 'OpenAI (GPT-4o)' },
994
+ { id: 'gemini' as ChannelHubAiProvider, label: 'Google Gemini' },
995
+ { id: 'anthropic' as ChannelHubAiProvider, label: 'Anthropic Claude' },
996
+ { id: 'webhook' as ChannelHubAiProvider, label: 'External Webhook (n8n / Dify)' },
997
+ ]).map(p => {
998
+ const active = settings.ai.provider === p.id;
999
+ return (
1000
+ <button
1001
+ key={p.id}
1002
+ type="button"
1003
+ onClick={() => updateAi('provider', p.id)}
1004
+ style={{
1005
+ padding: '6px 11px',
1006
+ borderRadius: 8,
1007
+ border: active ? `1px solid ${primary}` : `1px solid ${c.line}`,
1008
+ background: active ? `${primary}12` : c.surface,
1009
+ color: active ? primary : c.ink,
1010
+ fontSize: 12,
1011
+ fontWeight: active ? 700 : 500,
1012
+ cursor: 'pointer',
1013
+ }}
1014
+ >
1015
+ {p.label}
1016
+ </button>
1017
+ );
1018
+ })}
1019
+ </div>
1020
+ </div>
1021
+
1022
+ {settings.ai.provider === 'webhook' ? (
1023
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
1024
+ <div style={{ display: 'grid', gridTemplateColumns: isCompact ? '1fr' : '2fr 1fr', gap: 10 }}>
1025
+ <div>
1026
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 5 }}>
1027
+ <label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600, color: c.ink }}>
1028
+ <Webhook size={13} color={c.muted} /> Webhook Endpoint URL
1029
+ </label>
1030
+ <button
1031
+ type="button"
1032
+ onClick={() => {
1033
+ const origin = typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000';
1034
+ updateAi('webhookUrl', `${origin}/api/mock-ai-webhook`);
1035
+ }}
1036
+ style={{
1037
+ border: 0,
1038
+ background: 'none',
1039
+ color: primary,
1040
+ fontSize: 11,
1041
+ fontWeight: 600,
1042
+ cursor: 'pointer',
1043
+ padding: 0,
1044
+ textDecoration: 'underline',
1045
+ }}
1046
+ >
1047
+ Dùng URL Mock Local để test
1048
+ </button>
1049
+ </div>
1050
+ <input
1051
+ type="url"
1052
+ value={settings.ai.webhookUrl ?? ''}
1053
+ onChange={e => updateAi('webhookUrl', e.target.value)}
1054
+ placeholder="https://n8n.yourshop.com/webhook/channelhub-ai"
1055
+ style={{
1056
+ width: '100%',
1057
+ boxSizing: 'border-box',
1058
+ padding: '8px 10px',
1059
+ borderRadius: 8,
1060
+ border: `1px solid ${c.line}`,
1061
+ fontSize: isCompact ? 16 : 12.5,
1062
+ fontFamily: 'inherit',
1063
+ }}
1064
+ />
1065
+ </div>
1066
+ <div>
1067
+ <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: c.ink, marginBottom: 5 }}>
1068
+ Webhook Secret (Tùy chọn)
1069
+ </label>
1070
+ <input
1071
+ type="password"
1072
+ value={settings.ai.webhookSecret ?? ''}
1073
+ onChange={e => updateAi('webhookSecret', e.target.value)}
1074
+ placeholder="whsec_..."
1075
+ style={{
1076
+ width: '100%',
1077
+ boxSizing: 'border-box',
1078
+ padding: '8px 10px',
1079
+ borderRadius: 8,
1080
+ border: `1px solid ${c.line}`,
1081
+ fontSize: isCompact ? 16 : 12.5,
1082
+ fontFamily: 'inherit',
1083
+ }}
1084
+ />
1085
+ </div>
1086
+ </div>
1087
+
1088
+ {/* Interactive Webhook Test Console */}
1089
+ <div
1090
+ style={{
1091
+ borderRadius: 10,
1092
+ border: `1px solid ${c.line}`,
1093
+ background: c.surface,
1094
+ padding: 12,
1095
+ }}
1096
+ >
1097
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
1098
+ <span style={{ fontSize: 12, fontWeight: 700, color: c.ink }}>
1099
+ 🧪 Kiểm tra gọi Webhook & Phản hồi tự động
1100
+ </span>
1101
+ <span style={{ fontSize: 11, color: c.muted }}>
1102
+ Event: <code style={{ background: '#e2e8f0', padding: '1px 5px', borderRadius: 4 }}>ai.reply_requested</code>
1103
+ </span>
1104
+ </div>
1105
+ <div style={{ display: 'flex', gap: 8, flexDirection: isCompact ? 'column' : 'row' }}>
1106
+ <input
1107
+ type="text"
1108
+ value={webhookTestMsg}
1109
+ onChange={e => setWebhookTestMsg(e.target.value)}
1110
+ placeholder="Nhập tin nhắn giả lập của khách hàng..."
1111
+ style={{
1112
+ flex: 1,
1113
+ padding: '7px 10px',
1114
+ borderRadius: 8,
1115
+ border: `1px solid ${c.line}`,
1116
+ background: c.white,
1117
+ fontSize: isCompact ? 16 : 12,
1118
+ fontFamily: 'inherit',
1119
+ }}
1120
+ />
1121
+ <button
1122
+ type="button"
1123
+ disabled={webhookTesting || !settings.ai.webhookUrl?.trim()}
1124
+ onClick={async () => {
1125
+ const targetUrl = settings.ai.webhookUrl?.trim();
1126
+ if (!targetUrl) return;
1127
+ setWebhookTesting(true);
1128
+ setWebhookTestResult(null);
1129
+ const start = performance.now();
1130
+ const samplePayload = {
1131
+ event: 'ai.reply_requested',
1132
+ conversation: { id: 'conv_test_001', provider: 'facebook', assignedAgent: null },
1133
+ contact: { name: 'Khách hàng Test', providerUserId: 'psid_998877', externalId: 'CRM_01' },
1134
+ unansweredText: webhookTestMsg,
1135
+ recentMessages: [
1136
+ { direction: 'inbound', text: webhookTestMsg, occurredAt: new Date().toISOString() },
1137
+ ],
1138
+ aiConfig: {
1139
+ tone: settings.ai.tone,
1140
+ handoffOnPhone: settings.ai.handoffOnPhone,
1141
+ handoffOnComplaint: settings.ai.handoffOnComplaint,
1142
+ parameters: settings.ai.parameters,
1143
+ },
1144
+ };
1145
+ try {
1146
+ let res: Response;
1147
+ // Use local proxy if available to avoid CORS and compute HMAC signature
1148
+ if (typeof window !== 'undefined' && window.location.origin) {
1149
+ res = await fetch('/api/mock-ai-webhook', {
1150
+ method: 'POST',
1151
+ headers: { 'content-type': 'application/json' },
1152
+ body: JSON.stringify({
1153
+ ...samplePayload,
1154
+ _proxyWebhookUrl: targetUrl,
1155
+ _proxyWebhookSecret: settings.ai.webhookSecret ?? '',
1156
+ }),
1157
+ });
1158
+ } else {
1159
+ res = await fetch(targetUrl, {
1160
+ method: 'POST',
1161
+ headers: { 'content-type': 'application/json', 'x-channelhub-event': 'ai.reply_requested' },
1162
+ body: JSON.stringify(samplePayload),
1163
+ });
1164
+ }
1165
+ const latencyMs = Math.round(performance.now() - start);
1166
+ const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1167
+ setWebhookTestResult({
1168
+ ok: res.ok,
1169
+ status: res.status,
1170
+ latencyMs,
1171
+ response: data,
1172
+ });
1173
+ } catch (err) {
1174
+ setWebhookTestResult({
1175
+ ok: false,
1176
+ status: 0,
1177
+ latencyMs: Math.round(performance.now() - start),
1178
+ response: { error: err instanceof Error ? err.message : 'Lỗi kết nối Webhook' },
1179
+ });
1180
+ } finally {
1181
+ setWebhookTesting(false);
1182
+ }
1183
+ }}
1184
+ style={{
1185
+ padding: '7px 14px',
1186
+ borderRadius: 8,
1187
+ border: 0,
1188
+ background: !settings.ai.webhookUrl?.trim() ? '#cbd5e1' : primary,
1189
+ color: '#fff',
1190
+ fontSize: 12,
1191
+ fontWeight: 600,
1192
+ cursor: !settings.ai.webhookUrl?.trim() ? 'not-allowed' : 'pointer',
1193
+ whiteSpace: 'nowrap',
1194
+ }}
1195
+ >
1196
+ {webhookTesting ? 'Đang gọi Webhook…' : '🚀 Gửi test tới Webhook'}
1197
+ </button>
1198
+ </div>
1199
+
1200
+ {webhookTestResult && (
1201
+ <div
1202
+ style={{
1203
+ marginTop: 10,
1204
+ padding: '10px 12px',
1205
+ borderRadius: 8,
1206
+ background: webhookTestResult.ok ? '#f0fdf4' : '#fef2f2',
1207
+ border: `1px solid ${webhookTestResult.ok ? '#bbf7d0' : '#fecaca'}`,
1208
+ fontSize: 12,
1209
+ }}
1210
+ >
1211
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
1212
+ <strong style={{ color: webhookTestResult.ok ? '#15803d' : '#b91c1c' }}>
1213
+ {webhookTestResult.ok ? `✓ Webhook phản hồi thành công (HTTP ${webhookTestResult.status})` : `✕ Lỗi gọi Webhook (HTTP ${webhookTestResult.status})`}
1214
+ </strong>
1215
+ <span style={{ fontSize: 11, color: c.muted }}>{webhookTestResult.latencyMs} ms</span>
1216
+ </div>
1217
+ {Boolean(webhookTestResult.response['text'] ?? webhookTestResult.response['replyText']) && (
1218
+ <div style={{ marginBottom: 4, color: c.ink }}>
1219
+ <strong>Tin nhắn sẽ tự động rep khách:</strong>{' '}
1220
+ <span style={{ background: '#fff', padding: '2px 6px', borderRadius: 4, border: `1px solid ${c.line}` }}>
1221
+ {String(webhookTestResult.response['text'] ?? webhookTestResult.response['replyText'])}
1222
+ </span>
1223
+ </div>
1224
+ )}
1225
+ {Boolean(webhookTestResult.response['internalNote']) && (
1226
+ <div style={{ marginBottom: 4, color: c.muted, fontSize: 11.5 }}>
1227
+ <strong>Ghi chú nội bộ tự động lưu:</strong> {String(webhookTestResult.response['internalNote'])}
1228
+ </div>
1229
+ )}
1230
+ <pre
1231
+ style={{
1232
+ margin: '6px 0 0',
1233
+ padding: 8,
1234
+ borderRadius: 6,
1235
+ background: '#0f172a',
1236
+ color: '#e2e8f0',
1237
+ fontSize: 11,
1238
+ overflowX: 'auto',
1239
+ }}
1240
+ >
1241
+ {JSON.stringify(webhookTestResult.response, null, 2)}
1242
+ </pre>
1243
+ </div>
1244
+ )}
1245
+ </div>
1246
+ </div>
1247
+ ) : (
1248
+ <div style={{ display: 'grid', gridTemplateColumns: isCompact ? '1fr' : '2fr 1fr', gap: 10 }}>
1249
+ <div>
1250
+ <label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600, color: c.ink, marginBottom: 5 }}>
1251
+ <KeyRound size={13} color={c.muted} /> API Key ({settings.ai.provider.toUpperCase()})
1252
+ </label>
1253
+ <input
1254
+ type="password"
1255
+ value={settings.ai.apiKey ?? ''}
1256
+ onChange={e => updateAi('apiKey', e.target.value)}
1257
+ placeholder="sk-..."
1258
+ style={{
1259
+ width: '100%',
1260
+ boxSizing: 'border-box',
1261
+ padding: '8px 10px',
1262
+ borderRadius: 8,
1263
+ border: `1px solid ${c.line}`,
1264
+ fontSize: isCompact ? 16 : 12.5,
1265
+ fontFamily: 'inherit',
1266
+ }}
1267
+ />
1268
+ </div>
1269
+ <div>
1270
+ <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: c.ink, marginBottom: 5 }}>
1271
+ Model
1272
+ </label>
1273
+ <input
1274
+ type="text"
1275
+ value={settings.ai.model ?? ''}
1276
+ onChange={e => updateAi('model', e.target.value)}
1277
+ placeholder={
1278
+ settings.ai.provider === 'gemini'
1279
+ ? 'gemini-2.0-flash'
1280
+ : settings.ai.provider === 'anthropic'
1281
+ ? 'claude-3-5-haiku-latest'
1282
+ : 'gpt-4o-mini'
1283
+ }
1284
+ style={{
1285
+ width: '100%',
1286
+ boxSizing: 'border-box',
1287
+ padding: '8px 10px',
1288
+ borderRadius: 8,
1289
+ border: `1px solid ${c.line}`,
1290
+ fontSize: isCompact ? 16 : 12.5,
1291
+ fontFamily: 'inherit',
1292
+ }}
1293
+ />
1294
+ </div>
1295
+ </div>
1296
+ )}
1297
+ </div>
1298
+ )}
1299
+ </div>
1300
+ )}
1301
+
1302
+ {/* ─── TAB 2: MẪU CÂU TRẢ LỜI NHANH ────────────────────────────────── */}
1303
+ {activeTab === 'templates' && (
1304
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 780, margin: '0 auto' }}>
1305
+ {/* Canned Responses CRUD */}
1306
+ <div style={{ background: c.white, border: `1px solid ${c.line}`, borderRadius: 12, padding: isCompact ? 14 : 18 }}>
1307
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
1308
+ <div>
1309
+ <div style={{ fontSize: 13.5, fontWeight: 700, color: c.ink }}>
1310
+ Thư viện mẫu câu trả lời nhanh (⚡ Template)
1311
+ </div>
1312
+ <div style={{ fontSize: 12, color: c.muted, marginTop: 2 }}>
1313
+ Nhân viên bấm biểu tượng ⚡ trên khung chat để chèn nhanh các câu trả lời chuẩn của shop.
1314
+ </div>
1315
+ </div>
1316
+ <button
1317
+ type="button"
1318
+ onClick={startNewTemplate}
1319
+ style={{
1320
+ display: 'inline-flex',
1321
+ alignItems: 'center',
1322
+ gap: 6,
1323
+ padding: '7px 12px',
1324
+ borderRadius: 8,
1325
+ border: 0,
1326
+ background: primary,
1327
+ color: '#fff',
1328
+ fontSize: 12,
1329
+ fontWeight: 600,
1330
+ cursor: 'pointer',
1331
+ }}
1332
+ >
1333
+ <Plus size={14} /> Thêm mẫu câu
1334
+ </button>
1335
+ </div>
1336
+
1337
+ {/* Create / Edit Form */}
1338
+ {editingTplId && (
1339
+ <div
1340
+ style={{
1341
+ padding: 14,
1342
+ borderRadius: 10,
1343
+ border: `1px solid ${primary}40`,
1344
+ background: `${primary}06`,
1345
+ marginBottom: 14,
1346
+ display: 'flex',
1347
+ flexDirection: 'column',
1348
+ gap: 10,
1349
+ }}
1350
+ >
1351
+ <div style={{ fontSize: 12.5, fontWeight: 700, color: primary }}>
1352
+ {editingTplId === 'new' ? 'Tạo mẫu câu mới' : 'Chỉnh sửa mẫu câu'}
1353
+ </div>
1354
+ <div style={{ display: 'grid', gridTemplateColumns: isCompact ? '1fr' : '2fr 1fr', gap: 10 }}>
1355
+ <div>
1356
+ <label style={{ display: 'block', fontSize: 11.5, fontWeight: 600, color: c.ink, marginBottom: 4 }}>
1357
+ Tiêu đề mẫu câu *
1358
+ </label>
1359
+ <input
1360
+ type="text"
1361
+ value={tplTitle}
1362
+ onChange={e => setTplTitle(e.target.value)}
1363
+ placeholder="Ví dụ: Báo giá phí ship"
1364
+ style={{
1365
+ width: '100%',
1366
+ boxSizing: 'border-box',
1367
+ padding: '7px 10px',
1368
+ borderRadius: 7,
1369
+ border: `1px solid ${c.line}`,
1370
+ background: c.white,
1371
+ fontSize: isCompact ? 16 : 12.5,
1372
+ fontFamily: 'inherit',
1373
+ }}
1374
+ />
1375
+ </div>
1376
+ <div>
1377
+ <label style={{ display: 'block', fontSize: 11.5, fontWeight: 600, color: c.ink, marginBottom: 4 }}>
1378
+ Phím tắt (Tùy chọn)
1379
+ </label>
1380
+ <input
1381
+ type="text"
1382
+ value={tplShortcut}
1383
+ onChange={e => setTplShortcut(e.target.value)}
1384
+ placeholder="/ship"
1385
+ style={{
1386
+ width: '100%',
1387
+ boxSizing: 'border-box',
1388
+ padding: '7px 10px',
1389
+ borderRadius: 7,
1390
+ border: `1px solid ${c.line}`,
1391
+ background: c.white,
1392
+ fontSize: isCompact ? 16 : 12.5,
1393
+ fontFamily: 'inherit',
1394
+ }}
1395
+ />
1396
+ </div>
1397
+ </div>
1398
+ <div>
1399
+ <label style={{ display: 'block', fontSize: 11.5, fontWeight: 600, color: c.ink, marginBottom: 4 }}>
1400
+ Nội dung tin nhắn *
1401
+ </label>
1402
+ <textarea
1403
+ rows={3}
1404
+ value={tplContent}
1405
+ onChange={e => setTplContent(e.target.value)}
1406
+ placeholder="Nhập nội dung tin nhắn mẫu..."
1407
+ style={{
1408
+ width: '100%',
1409
+ boxSizing: 'border-box',
1410
+ padding: '8px 10px',
1411
+ borderRadius: 7,
1412
+ border: `1px solid ${c.line}`,
1413
+ background: c.white,
1414
+ fontSize: isCompact ? 16 : 12.5,
1415
+ fontFamily: 'inherit',
1416
+ resize: 'vertical',
1417
+ }}
1418
+ />
1419
+ </div>
1420
+ <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
1421
+ <button
1422
+ type="button"
1423
+ onClick={() => setEditingTplId(null)}
1424
+ style={{
1425
+ padding: '6px 12px',
1426
+ borderRadius: 7,
1427
+ border: `1px solid ${c.line}`,
1428
+ background: c.white,
1429
+ color: c.muted,
1430
+ fontSize: 12,
1431
+ fontWeight: 600,
1432
+ cursor: 'pointer',
1433
+ }}
1434
+ >
1435
+ Hủy
1436
+ </button>
1437
+ <button
1438
+ type="button"
1439
+ onClick={() => void saveTemplateForm()}
1440
+ disabled={!tplTitle.trim() || !tplContent.trim() || tplSaving}
1441
+ style={{
1442
+ padding: '6px 14px',
1443
+ borderRadius: 7,
1444
+ border: 0,
1445
+ background: !tplTitle.trim() || !tplContent.trim() || tplSaving ? '#cbd5e1' : primary,
1446
+ color: '#fff',
1447
+ fontSize: 12,
1448
+ fontWeight: 600,
1449
+ cursor: !tplTitle.trim() || !tplContent.trim() || tplSaving ? 'not-allowed' : 'pointer',
1450
+ }}
1451
+ >
1452
+ {tplSaving ? 'Đang lưu…' : 'Lưu mẫu câu'}
1453
+ </button>
1454
+ </div>
1455
+ </div>
1456
+ )}
1457
+
1458
+ {/* Template List */}
1459
+ {templatesLoading ? (
1460
+ <div style={{ padding: 24, textAlign: 'center', color: c.muted, fontSize: 12.5 }}>
1461
+ Đang tải danh sách mẫu câu…
1462
+ </div>
1463
+ ) : templates.length === 0 ? (
1464
+ <div
1465
+ style={{
1466
+ padding: '28px 16px',
1467
+ textAlign: 'center',
1468
+ borderRadius: 10,
1469
+ border: `1px dashed ${c.line}`,
1470
+ background: c.surface,
1471
+ }}
1472
+ >
1473
+ <div style={{ fontSize: 13, fontWeight: 600, color: c.ink, marginBottom: 4 }}>
1474
+ Chưa có mẫu câu trả lời nhanh nào
1475
+ </div>
1476
+ <div style={{ fontSize: 12, color: c.muted, marginBottom: 14 }}>
1477
+ Bạn có thể tạo mới hoặc nạp ngay bộ mẫu câu bán hàng phổ biến bên dưới.
1478
+ </div>
1479
+ <button
1480
+ type="button"
1481
+ onClick={() => void handleSeedStarterTemplates()}
1482
+ disabled={seedingStarter}
1483
+ style={{
1484
+ display: 'inline-flex',
1485
+ alignItems: 'center',
1486
+ gap: 6,
1487
+ padding: '7px 14px',
1488
+ borderRadius: 8,
1489
+ border: `1px solid ${primary}40`,
1490
+ background: `${primary}10`,
1491
+ color: primary,
1492
+ fontSize: 12,
1493
+ fontWeight: 600,
1494
+ cursor: seedingStarter ? 'not-allowed' : 'pointer',
1495
+ }}
1496
+ >
1497
+ <Sparkles size={14} />
1498
+ {seedingStarter ? 'Đang nạp mẫu câu…' : '✨ Nạp bộ mẫu câu gợi ý'}
1499
+ </button>
1500
+ </div>
1501
+ ) : (
1502
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
1503
+ {templates.map(tpl => (
1504
+ <div
1505
+ key={tpl.id}
1506
+ style={{
1507
+ display: 'flex',
1508
+ alignItems: 'flex-start',
1509
+ justifyContent: 'space-between',
1510
+ gap: 12,
1511
+ padding: '10px 12px',
1512
+ borderRadius: 9,
1513
+ border: `1px solid ${c.line}`,
1514
+ background: c.white,
1515
+ }}
1516
+ >
1517
+ <div style={{ minWidth: 0, flex: 1 }}>
1518
+ <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 3 }}>
1519
+ <span style={{ fontSize: 13, fontWeight: 600, color: c.ink }}>{tpl.title}</span>
1520
+ {tpl.shortcut && (
1521
+ <span
1522
+ style={{
1523
+ fontSize: 10.5,
1524
+ fontWeight: 600,
1525
+ padding: '1px 6px',
1526
+ borderRadius: 5,
1527
+ background: `${primary}14`,
1528
+ color: primary,
1529
+ }}
1530
+ >
1531
+ {tpl.shortcut}
1532
+ </span>
1533
+ )}
1534
+ </div>
1535
+ <div style={{ fontSize: 12, color: c.muted, lineHeight: 1.45, whiteSpace: 'pre-wrap' }}>
1536
+ {tpl.content}
1537
+ </div>
1538
+ </div>
1539
+ <div style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
1540
+ <button
1541
+ type="button"
1542
+ onClick={() => startEditTemplate(tpl)}
1543
+ aria-label="Sửa mẫu câu"
1544
+ style={{
1545
+ width: 28,
1546
+ height: 28,
1547
+ borderRadius: 6,
1548
+ border: 0,
1549
+ background: 'transparent',
1550
+ color: c.muted,
1551
+ display: 'inline-grid',
1552
+ placeItems: 'center',
1553
+ cursor: 'pointer',
1554
+ }}
1555
+ >
1556
+ <Edit3 size={14} />
1557
+ </button>
1558
+ <button
1559
+ type="button"
1560
+ onClick={() => void handleDeleteTemplate(tpl.id)}
1561
+ aria-label="Xóa mẫu câu"
1562
+ style={{
1563
+ width: 28,
1564
+ height: 28,
1565
+ borderRadius: 6,
1566
+ border: 0,
1567
+ background: 'transparent',
1568
+ color: '#ef4444',
1569
+ display: 'inline-grid',
1570
+ placeItems: 'center',
1571
+ cursor: 'pointer',
1572
+ }}
1573
+ >
1574
+ <Trash2 size={14} />
1575
+ </button>
1576
+ </div>
1577
+ </div>
1578
+ ))}
1579
+ </div>
1580
+ )}
1581
+ </div>
1582
+
1583
+ {/* Quick Reply Chips above Composer */}
1584
+ <div style={{ background: c.white, border: `1px solid ${c.line}`, borderRadius: 12, padding: isCompact ? 14 : 18 }}>
1585
+ <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 4 }}>
1586
+ <MessageSquarePlus size={15} color={primary} />
1587
+ <span style={{ fontSize: 13.5, fontWeight: 700, color: c.ink }}>
1588
+ Nút gợi ý nhanh trên khung chat (Quick Reply Chips)
1589
+ </span>
1590
+ </div>
1591
+ <div style={{ fontSize: 12, color: c.muted, marginBottom: 12 }}>
1592
+ Các nút câu ngắn hiển thị ngay phía trên ô nhập tin nhắn để nhân viên bấm 1 chạm.
1593
+ </div>
1594
+
1595
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 12 }}>
1596
+ {settings.inbox.quickReplies.map(chip => (
1597
+ <span
1598
+ key={chip}
1599
+ style={{
1600
+ display: 'inline-flex',
1601
+ alignItems: 'center',
1602
+ gap: 6,
1603
+ padding: '4px 10px',
1604
+ borderRadius: 999,
1605
+ background: `${primary}10`,
1606
+ color: primary,
1607
+ border: `1px solid ${primary}33`,
1608
+ fontSize: 12,
1609
+ fontWeight: 500,
1610
+ }}
1611
+ >
1612
+ <span>{chip}</span>
1613
+ <button
1614
+ type="button"
1615
+ onClick={() => handleRemoveQuickReply(chip)}
1616
+ aria-label={`Xóa ${chip}`}
1617
+ style={{
1618
+ border: 0,
1619
+ background: 'none',
1620
+ color: primary,
1621
+ padding: 0,
1622
+ cursor: 'pointer',
1623
+ display: 'inline-flex',
1624
+ }}
1625
+ >
1626
+ <X size={12} />
1627
+ </button>
1628
+ </span>
1629
+ ))}
1630
+ </div>
1631
+
1632
+ <div style={{ display: 'flex', gap: 8 }}>
1633
+ <input
1634
+ type="text"
1635
+ value={newQuickReply}
1636
+ onChange={e => setNewQuickReply(e.target.value)}
1637
+ onKeyDown={e => {
1638
+ if (e.key === 'Enter') {
1639
+ e.preventDefault();
1640
+ handleAddQuickReply();
1641
+ }
1642
+ }}
1643
+ placeholder="Nhập câu gợi ý ngắn (VD: Dạ shop đã nhận đơn ạ)..."
1644
+ style={{
1645
+ flex: 1,
1646
+ minWidth: 0,
1647
+ padding: '7px 10px',
1648
+ borderRadius: 8,
1649
+ border: `1px solid ${c.line}`,
1650
+ fontSize: isCompact ? 16 : 12.5,
1651
+ fontFamily: 'inherit',
1652
+ }}
1653
+ />
1654
+ <button
1655
+ type="button"
1656
+ onClick={handleAddQuickReply}
1657
+ style={{
1658
+ padding: '7px 14px',
1659
+ borderRadius: 8,
1660
+ border: `1px solid ${primary}40`,
1661
+ background: `${primary}12`,
1662
+ color: primary,
1663
+ fontSize: 12,
1664
+ fontWeight: 600,
1665
+ cursor: 'pointer',
1666
+ whiteSpace: 'nowrap',
1667
+ }}
1668
+ >
1669
+ + Thêm nút
1670
+ </button>
1671
+ </div>
1672
+ </div>
1673
+ </div>
1674
+ )}
1675
+
1676
+ {/* ─── TAB 3: HỘP THƯ & TỰ ĐỘNG HÓA ────────────────────────────────── */}
1677
+ {activeTab === 'inbox' && (
1678
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 780, margin: '0 auto' }}>
1679
+ <div style={{ background: c.white, border: `1px solid ${c.line}`, borderRadius: 12, padding: isCompact ? 14 : 18 }}>
1680
+ <div style={{ fontSize: 13.5, fontWeight: 700, color: c.ink, marginBottom: 12 }}>
1681
+ Phân công & Thông báo hộp thư
1682
+ </div>
1683
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
1684
+ <ToggleSwitch
1685
+ label="Tự động gán phụ trách cho nhân viên đầu tiên trả lời"
1686
+ description="Khi hội thoại chưa có người nhận, nhân viên nào gửi tin nhắn trả lời đầu tiên sẽ tự động trở thành người phụ trách."
1687
+ checked={settings.inbox.autoAssignOnFirstReply}
1688
+ onChange={v => updateInbox('autoAssignOnFirstReply', v)}
1689
+ primary={primary}
1690
+ />
1691
+ <ToggleSwitch
1692
+ label="Phát âm thanh thông báo khi có tin nhắn mới"
1693
+ description="Phát tiếng chuông nhẹ khi khách hàng gửi tin nhắn mới đến hộp thư."
1694
+ checked={settings.inbox.soundNotification}
1695
+ onChange={v => updateInbox('soundNotification', v)}
1696
+ primary={primary}
1697
+ />
1698
+ </div>
1699
+ </div>
1700
+
1701
+ <div style={{ background: c.white, border: `1px solid ${c.line}`, borderRadius: 12, padding: isCompact ? 14 : 18 }}>
1702
+ <div style={{ fontSize: 13.5, fontWeight: 700, color: c.ink, marginBottom: 12 }}>
1703
+ Tin nhắn chào mừng & Phản hồi vắng mặt
1704
+ </div>
1705
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
1706
+ <ToggleSwitch
1707
+ label="Bật tin nhắn chào mừng tự động cho khách mới"
1708
+ description="Tự động gửi lời chào ngay khi khách hàng bắt đầu cuộc trò chuyện lần đầu."
1709
+ checked={settings.inbox.welcomeMessageEnabled}
1710
+ onChange={v => updateInbox('welcomeMessageEnabled', v)}
1711
+ primary={primary}
1712
+ />
1713
+ {settings.inbox.welcomeMessageEnabled && (
1714
+ <textarea
1715
+ rows={2}
1716
+ value={settings.inbox.welcomeMessageText}
1717
+ onChange={e => updateInbox('welcomeMessageText', e.target.value)}
1718
+ style={{
1719
+ width: '100%',
1720
+ boxSizing: 'border-box',
1721
+ padding: '8px 10px',
1722
+ borderRadius: 8,
1723
+ border: `1px solid ${c.line}`,
1724
+ fontSize: isCompact ? 16 : 12.5,
1725
+ fontFamily: 'inherit',
1726
+ resize: 'vertical',
1727
+ }}
1728
+ />
1729
+ )}
1730
+
1731
+ <ToggleSwitch
1732
+ label="Bật tin nhắn báo vắng mặt ngoài giờ làm việc"
1733
+ description="Thông báo cho khách để lại thông tin khi nhắn tin ngoài khung giờ trực của cửa hàng."
1734
+ checked={settings.inbox.awayMessageEnabled}
1735
+ onChange={v => updateInbox('awayMessageEnabled', v)}
1736
+ primary={primary}
1737
+ />
1738
+ {settings.inbox.awayMessageEnabled && (
1739
+ <textarea
1740
+ rows={2}
1741
+ value={settings.inbox.awayMessageText}
1742
+ onChange={e => updateInbox('awayMessageText', e.target.value)}
1743
+ style={{
1744
+ width: '100%',
1745
+ boxSizing: 'border-box',
1746
+ padding: '8px 10px',
1747
+ borderRadius: 8,
1748
+ border: `1px solid ${c.line}`,
1749
+ fontSize: isCompact ? 16 : 12.5,
1750
+ fontFamily: 'inherit',
1751
+ resize: 'vertical',
1752
+ }}
1753
+ />
1754
+ )}
1755
+ </div>
1756
+ </div>
1757
+ </div>
1758
+ )}
1759
+
1760
+ {/* ─── TAB 4: KÊNH KẾT NỐI ──────────────────────────────────────────── */}
1761
+ {activeTab === 'channels' && (
1762
+ <div style={{ maxWidth: 780, margin: '0 auto' }}>
1763
+ <ChannelHubChannels apiUrl={apiUrl} token={token} />
1764
+ </div>
1765
+ )}
1766
+ </>
1767
+ )}
1768
+ </div>
1769
+
1770
+ {/* Footer Save Bar (shown on AI / Templates / Inbox tabs) */}
1771
+ {activeTab !== 'channels' && (
1772
+ <div
1773
+ style={{
1774
+ display: 'flex',
1775
+ alignItems: 'center',
1776
+ justifyContent: 'space-between',
1777
+ gap: 12,
1778
+ padding: isCompact ? '10px 14px' : '12px 22px',
1779
+ borderTop: `1px solid ${c.line}`,
1780
+ background: c.white,
1781
+ flexShrink: 0,
1782
+ }}
1783
+ >
1784
+ <div style={{ minHeight: 18, display: 'flex', alignItems: 'center' }}>
1785
+ {saveSuccess ? (
1786
+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600, color: '#16a34a' }}>
1787
+ <Check size={14} strokeWidth={2.5} /> Đã lưu cài đặt thành công
1788
+ </span>
1789
+ ) : error ? (
1790
+ <span style={{ fontSize: 12, color: '#dc2626' }}>{error}</span>
1791
+ ) : (
1792
+ <span style={{ fontSize: 11.5, color: c.muted }}>
1793
+ Thay đổi sẽ được áp dụng cho toàn bộ hộp thư của cửa hàng.
1794
+ </span>
1795
+ )}
1796
+ </div>
1797
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
1798
+ {onClose && (
1799
+ <button
1800
+ type="button"
1801
+ onClick={onClose}
1802
+ style={{
1803
+ padding: '7px 14px',
1804
+ borderRadius: 8,
1805
+ border: `1px solid ${c.line}`,
1806
+ background: c.white,
1807
+ color: c.ink,
1808
+ fontSize: 12.5,
1809
+ fontWeight: 600,
1810
+ cursor: 'pointer',
1811
+ }}
1812
+ >
1813
+ Đóng
1814
+ </button>
1815
+ )}
1816
+ <button
1817
+ type="button"
1818
+ onClick={() => void handleSaveSettings()}
1819
+ disabled={saving}
1820
+ style={{
1821
+ display: 'inline-flex',
1822
+ alignItems: 'center',
1823
+ gap: 6,
1824
+ padding: '7px 16px',
1825
+ borderRadius: 8,
1826
+ border: 0,
1827
+ background: saving ? '#94a3b8' : primary,
1828
+ color: '#fff',
1829
+ fontSize: 12.5,
1830
+ fontWeight: 600,
1831
+ cursor: saving ? 'not-allowed' : 'pointer',
1832
+ }}
1833
+ >
1834
+ {saving ? (
1835
+ <Loader2 size={14} style={{ animation: 'channelhub-spin .7s linear infinite' }} />
1836
+ ) : (
1837
+ <Save size={14} />
1838
+ )}
1839
+ <span>{saving ? 'Đang lưu…' : 'Lưu cài đặt'}</span>
1840
+ </button>
1841
+ </div>
1842
+ </div>
1843
+ )}
1844
+ </div>
1845
+ );
1846
+ }