@channelhub/widget 0.1.11 → 0.1.13

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