@channelhub/widget 0.1.4 → 0.1.5
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.
- package/dist/ChannelHubInbox.d.ts.map +1 -1
- package/dist/api.d.ts +4 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/index.cjs +25 -25
- package/dist/index.js +894 -785
- package/dist/types.d.ts +43 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/ChannelHubInbox.tsx +118 -11
- package/src/api.ts +7 -0
- package/src/types.ts +53 -0
package/dist/index.cjs
CHANGED
|
@@ -1,114 +1,114 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),o=require("react"),Ne=require("react-dom");/**
|
|
2
2
|
* @license lucide-react v0.468.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
6
|
+
*/const it=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ke=(...t)=>t.filter((n,i,r)=>!!n&&n.trim()!==""&&r.indexOf(n)===i).join(" ").trim();/**
|
|
7
7
|
* @license lucide-react v0.468.0 - ISC
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/var
|
|
11
|
+
*/var rt={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
|
12
12
|
* @license lucide-react v0.468.0 - ISC
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the ISC license.
|
|
15
15
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const
|
|
16
|
+
*/const ot=o.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:i=2,absoluteStrokeWidth:r,className:c="",children:v,iconNode:m,...E},x)=>o.createElement("svg",{ref:x,...rt,width:n,height:n,stroke:t,strokeWidth:r?Number(i)*24/Number(n):i,className:Ke("lucide",c),...E},[...m.map(([b,B])=>o.createElement(b,B)),...Array.isArray(v)?v:[v]]));/**
|
|
17
17
|
* @license lucide-react v0.468.0 - ISC
|
|
18
18
|
*
|
|
19
19
|
* This source code is licensed under the ISC license.
|
|
20
20
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const
|
|
21
|
+
*/const D=(t,n)=>{const i=o.forwardRef(({className:r,...c},v)=>o.createElement(ot,{ref:v,iconNode:n,className:Ke(`lucide-${it(t)}`,r),...c}));return i.displayName=`${t}`,i};/**
|
|
22
22
|
* @license lucide-react v0.468.0 - ISC
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the ISC license.
|
|
25
25
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const
|
|
26
|
+
*/const Ee=D("CheckCheck",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);/**
|
|
27
27
|
* @license lucide-react v0.468.0 - ISC
|
|
28
28
|
*
|
|
29
29
|
* This source code is licensed under the ISC license.
|
|
30
30
|
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const
|
|
31
|
+
*/const qe=D("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
|
|
32
32
|
* @license lucide-react v0.468.0 - ISC
|
|
33
33
|
*
|
|
34
34
|
* This source code is licensed under the ISC license.
|
|
35
35
|
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const
|
|
36
|
+
*/const st=D("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
|
|
37
37
|
* @license lucide-react v0.468.0 - ISC
|
|
38
38
|
*
|
|
39
39
|
* This source code is licensed under the ISC license.
|
|
40
40
|
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const
|
|
41
|
+
*/const at=D("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
|
|
42
42
|
* @license lucide-react v0.468.0 - ISC
|
|
43
43
|
*
|
|
44
44
|
* This source code is licensed under the ISC license.
|
|
45
45
|
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
-
*/const
|
|
46
|
+
*/const lt=D("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
|
|
47
47
|
* @license lucide-react v0.468.0 - ISC
|
|
48
48
|
*
|
|
49
49
|
* This source code is licensed under the ISC license.
|
|
50
50
|
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
-
*/const
|
|
51
|
+
*/const Ve=D("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/**
|
|
52
52
|
* @license lucide-react v0.468.0 - ISC
|
|
53
53
|
*
|
|
54
54
|
* This source code is licensed under the ISC license.
|
|
55
55
|
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const
|
|
56
|
+
*/const dt=D("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
|
|
57
57
|
* @license lucide-react v0.468.0 - ISC
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const
|
|
61
|
+
*/const ct=D("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/**
|
|
62
62
|
* @license lucide-react v0.468.0 - ISC
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
65
65
|
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const
|
|
66
|
+
*/const ut=D("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/**
|
|
67
67
|
* @license lucide-react v0.468.0 - ISC
|
|
68
68
|
*
|
|
69
69
|
* This source code is licensed under the ISC license.
|
|
70
70
|
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const
|
|
71
|
+
*/const Ge=D("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
|
|
72
72
|
* @license lucide-react v0.468.0 - ISC
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const
|
|
76
|
+
*/const ht=D("Paperclip",[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]]);/**
|
|
77
77
|
* @license lucide-react v0.468.0 - ISC
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
80
80
|
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const
|
|
81
|
+
*/const pt=D("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
|
|
82
82
|
* @license lucide-react v0.468.0 - ISC
|
|
83
83
|
*
|
|
84
84
|
* This source code is licensed under the ISC license.
|
|
85
85
|
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const
|
|
86
|
+
*/const He=D("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
|
|
87
87
|
* @license lucide-react v0.468.0 - ISC
|
|
88
88
|
*
|
|
89
89
|
* This source code is licensed under the ISC license.
|
|
90
90
|
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const
|
|
91
|
+
*/const ft=D("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/**
|
|
92
92
|
* @license lucide-react v0.468.0 - ISC
|
|
93
93
|
*
|
|
94
94
|
* This source code is licensed under the ISC license.
|
|
95
95
|
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
-
*/const
|
|
96
|
+
*/const xt=D("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/**
|
|
97
97
|
* @license lucide-react v0.468.0 - ISC
|
|
98
98
|
*
|
|
99
99
|
* This source code is licensed under the ISC license.
|
|
100
100
|
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
-
*/const
|
|
101
|
+
*/const gt=D("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/**
|
|
102
102
|
* @license lucide-react v0.468.0 - ISC
|
|
103
103
|
*
|
|
104
104
|
* This source code is licensed under the ISC license.
|
|
105
105
|
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
-
*/const
|
|
106
|
+
*/const Se=D("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
|
|
107
107
|
* @license lucide-react v0.468.0 - ISC
|
|
108
108
|
*
|
|
109
109
|
* This source code is licensed under the ISC license.
|
|
110
110
|
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const ct=U("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);class Pe{constructor(n,i){this.apiUrl=n,this.token=i}async request(n,i,r){const d={authorization:`Bearer ${this.token}`,...r?{}:{"content-type":"application/json"},...i==null?void 0:i.headers},y=await fetch(`${this.apiUrl}${n}`,{...i,headers:d}),v=await y.json().catch(()=>null);if(!y.ok)throw new Error((v==null?void 0:v.message)??`Request failed (${y.status})`);return v}listConnections(){return this.request("/v1/connections")}listConversations(n){return this.request(`/v1/conversations${n?`?cursor=${encodeURIComponent(n)}`:""}`)}listMessages(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages${i?`?cursor=${encodeURIComponent(i)}`:""}`)}getMessage(n){return this.request(`/v1/messages/${encodeURIComponent(n)}`)}sendMessage(n,i,r){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages`,{method:"POST",headers:{"idempotency-key":crypto.randomUUID()},body:JSON.stringify({text:i,attachments:r})})}async markRead(n){const i=await fetch(`${this.apiUrl}/v1/conversations/${encodeURIComponent(n)}/mark-read`,{method:"POST",headers:{authorization:`Bearer ${this.token}`}});if(!i.ok&&i.status!==204)throw new Error(`markRead failed (${i.status})`)}listCannedResponses(n){const i=n!=null&&n.trim()?`?search=${encodeURIComponent(n)}`:"";return this.request(`/v1/canned-responses${i}`)}getNote(n){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`)}upsertNote(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`,{method:"PUT",body:JSON.stringify({content:i})})}async uploadAttachment(n){const i=new FormData;return i.append("file",n),this.request("/v1/attachments",{method:"POST",body:i},!0)}connectSSE(n){const i=`${this.apiUrl}/v1/events?token=${encodeURIComponent(this.token)}`;let r,d,y=!1;const v=()=>{r=new EventSource(i),r.addEventListener("message.new",W=>{n("message.new",JSON.parse(W.data))}),r.addEventListener("conversation.updated",W=>{n("conversation.updated",JSON.parse(W.data))}),r.onerror=()=>{r.close(),y||(d=setTimeout(v,5e3))}};return v(),()=>{y=!0,clearTimeout(d),r==null||r.close()}}}function Ne({src:t,alt:n="",fallback:i,style:r}){return t?e.jsx("img",{src:t,alt:n,style:{width:38,height:38,borderRadius:"50%",objectFit:"cover",...r}}):e.jsx("span",{style:{display:"grid",placeItems:"center",width:38,height:38,borderRadius:"50%",...r},children:i})}function pt({variant:t="ghost",style:n,...i}){return e.jsx("button",{...i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",border:t==="outline"?"1px solid #e7ebf2":0,borderRadius:8,cursor:"pointer",font:"inherit",background:t==="default"?"#2563eb":"transparent",...n}})}function ht({style:t,...n}){return e.jsx("input",{...n,style:{width:"100%",minWidth:0,border:0,outline:0,background:"transparent",font:"inherit",...t}})}const Ke=s.forwardRef(({children:t,style:n},i)=>e.jsx("div",{ref:i,style:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain",...n},children:t})),ut=s.forwardRef(function({style:n,...i},r){return e.jsx("textarea",{ref:r,...i,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",border:0,outline:0,background:"transparent",font:"inherit",...n}})}),l={ink:"#172033",muted:"#718096",line:"#e7ebf2",surface:"#f7f9fc",white:"#fff"},Be=[{icon:"😊",emojis:["😀","😁","😂","🤣","😊","😇","🙂","😉","😍","🥰","😘","😋","😎","🤩","😏","😒","😔","😢","😭","😤","😠","🤯","😱","🥳","😴","🤔","🤗","🫡","😮","🤧","🥺","😶","🫠","🤭","🤫"]},{icon:"👋",emojis:["👍","👎","👏","🙏","🤝","✌️","🤞","🫡","💪","🤜","👊","✊","🖐","👌","🤌","🤏","☝️","👆","👇","👉","👈","🤙","💅","🫶","❤️","🧡","💛","💚","💙","💜","🖤","💔","❣️","💕","💯"]},{icon:"🐱",emojis:["🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🙈","🐔","🐧","🐦","🦆","🦅","🦉","🦋","🐝","🐛","🐢","🦎","🐬","🦈","🐳","🐙","🦑"]},{icon:"🍕",emojis:["🍎","🍊","🍋","🍇","🍓","🍒","🥝","🥑","🍔","🍕","🌮","🍜","🍣","🍦","🎂","🍰","🧁","☕","🧋","🥤","🍺","🥂","🍾","🧃","🧊"]},{icon:"⚽",emojis:["⚽","🏀","🏈","⚾","🎾","🏐","🏓","🎮","🎲","🎯","🎳","🏆","🥇","🎖","🎁","🎉","🎊","🎈","🎭","🎨","🎬","🎵","🎸","🎹","🎺","🪗","🎻"]},{icon:"🌍",emojis:["🌍","🌈","⭐","🌙","☀️","⛅","🌊","🔥","💧","🌿","🌸","🌺","🌻","🍀","🌴","🏔","🏖","🏕","🌃","🏙","🌅","🌄","🌠","🌌","🌋","🏝"]}],Ie=s.createContext(""),qe=s.createContext("");function ft(){try{const t=new AudioContext,n=t.createOscillator(),i=t.createGain();n.connect(i),i.connect(t.destination),n.type="sine",n.frequency.setValueAtTime(880,t.currentTime),n.frequency.exponentialRampToValueAtTime(660,t.currentTime+.12),i.gain.setValueAtTime(.25,t.currentTime),i.gain.exponentialRampToValueAtTime(.001,t.currentTime+.35),n.start(t.currentTime),n.stop(t.currentTime+.35)}catch{}}function xt(t){if(!(t!=null&&t.metadata))return;const n=t.metadata,i=n.pageName??n.displayName??n.username??n.name;return typeof i=="string"&&i?i:void 0}function Ve(t){return t==="facebook"?"Facebook Messenger":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo OA":"Channel"}function We(t){return t==="facebook"?"Facebook":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo":String(t??"")}const gt=t=>{var i;const n={"application/pdf":"PDF","video/mp4":"Video MP4","audio/mpeg":"Audio MP3","audio/ogg":"Audio OGG","application/octet-stream":"Tệp đính kèm"};return t?n[t]??((i=t.split("/")[1])==null?void 0:i.toUpperCase())??"Tệp":"Tệp đính kèm"};function $e({status:t}){return t==="read"?e.jsx(Te,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):t==="delivered"?e.jsx(Te,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle",opacity:.5}}):t==="sent"?e.jsx(Fe,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):null}const yt=s.forwardRef(function({apiUrl:n,token:i,theme:r,height:d,defaultConversationId:y,disableAttachments:v,disableNotificationSound:W,hideKeyboardHint:f,locale:m="vi",onNewMessage:S,onConversationSelect:k},z){var ne,ue,fe,me,be;const C=s.useRef(new Pe(n,i)),[L,P]=s.useState([]),[K,T]=s.useState([]),[O,F]=s.useState(),[w,q]=s.useState(),Y=s.useRef(void 0),[b,$]=s.useState(""),[A,M]=s.useState({provider:"all",unreadOnly:!1}),[N,re]=s.useState(!1),j=s.useRef(null),J=s.useRef(null),[X,oe]=s.useState(null),[Z,se]=s.useState(!0),[c,I]=s.useState(""),[R,V]=s.useState(!1),H=(r==null?void 0:r.primaryColor)??"#2563eb",D=s.useMemo(()=>new Map(K.map(p=>[p.id,p])),[K]),E=s.useRef(null),[_,de]=s.useState(0),ye=s.useMemo(()=>{const p=new Set(K.map(x=>x.provider));return["facebook","instagram","telegram","zalo"].filter(x=>p.has(x))},[K]),ce=s.useMemo(()=>{var x;const p={};for(const a of L){const h=((x=D.get(a.connectionId))==null?void 0:x.provider)??"unknown";p[h]=(p[h]??0)+1}return p},[L,D]),G=s.useCallback(async p=>{try{const x=await C.current.listConversations(p);P(a=>p?[...a,...x.items]:x.items),F(x.nextCursor),!p&&x.items.length&&q(a=>a??(y?x.items.find(h=>h.id===y)??x.items[0]:x.items[0])),I("")}catch(x){I(x instanceof Error?x.message:"Không tải được hội thoại")}finally{se(!1)}},[y]);s.useEffect(()=>(C.current.listConnections().then(T).catch(()=>{}),G(),C.current.connectSSE((x,a)=>{if(x==="message.new"||x==="conversation.updated"){if(G(),x==="message.new"){const h=typeof a=="object"&&a?a:{},g=h.conversationId?String(h.conversationId):"",B=h.messageId?String(h.messageId):"";if((h.direction?String(h.direction):"")==="inbound"&&!W&&ft(),g&&g===Y.current&&B&&E.current){const je=E.current;C.current.getMessage(B).then(Je=>{je(Je)}).catch(()=>{})}S==null||S(g||Y.current||"")}}else x==="message.status_updated"&&de(h=>h+1)})),[G,S]),s.useEffect(()=>{Y.current=w==null?void 0:w.id},[w]),s.useEffect(()=>{w!=null&&w.unreadCount&&C.current.markRead(w.id).then(()=>G()).catch(()=>{})},[w==null?void 0:w.id]),s.useEffect(()=>{if(!N)return;function p(x){var a,h;(a=j.current)!=null&&a.contains(x.target)||(h=J.current)!=null&&h.contains(x.target)||re(!1)}return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[N]);const pe=s.useMemo(()=>{const p=b.toLowerCase().trim();return L.filter(x=>{var ee;const a=`${x.contactName??""} ${x.subject??""} ${x.providerConversationKey}`.toLowerCase(),h=((ee=D.get(x.connectionId))==null?void 0:ee.provider)??"unknown",g=A.provider==="all"||h===A.provider,B=!A.unreadOnly||(x.unreadCount??0)>0;return g&&B&&(!p||a.includes(p))})},[L,D,A,b]),ae=A.provider!=="all"||A.unreadOnly,Q=m==="en"?{today:"TODAY",loadOlder:"↑ Load older messages",loading:"Loading messages…",noMessages:"No messages in this conversation.",searchPlaceholder:"Search conversations…",unreadOnly:"Unread only",sendPlaceholder:"Write a message…",send:"Send",all:"All"}:{today:"HÔM NAY",loadOlder:"↑ Tải tin cũ hơn",loading:"Đang tải tin nhắn…",noMessages:"Chưa có tin nhắn trong hội thoại này.",searchPlaceholder:"Tìm kiếm hội thoại…",unreadOnly:"Chưa đọc",sendPlaceholder:"Viết tin nhắn…",send:"Gửi",all:"Tất cả"};s.useImperativeHandle(z,()=>({openConversation:p=>{const x=L.find(a=>a.id===p);x&&q(x)},refresh:()=>void G()}),[L,G]);const he={...u.frame,height:d??620,...d?{maxHeight:"none"}:{},fontFamily:(r==null?void 0:r.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",borderRadius:(r==null?void 0:r.borderRadius)??"16px",gridTemplateColumns:R?"minmax(260px, 300px) minmax(0, 1fr) 260px":"minmax(260px, 300px) minmax(0, 1fr)",transition:"grid-template-columns 220ms ease"};return Z?e.jsxs("div",{style:{...u.state,borderRadius:(r==null?void 0:r.borderRadius)??"16px"},children:[e.jsx(Se,{})," Đang tải hộp thư…"]}):c&&!L.length?e.jsxs("div",{style:{...u.state,color:"#b42318",borderRadius:(r==null?void 0:r.borderRadius)??"16px"},children:[e.jsx(tt,{size:16,strokeWidth:2})," ",c,e.jsx("button",{style:u.retry,onClick:()=>{se(!0),G()},children:"Thử lại"})]}):e.jsx(Ie.Provider,{value:n,children:e.jsx(qe.Provider,{value:i,children:e.jsxs("div",{style:he,onFocusCapture:()=>{const p=window.scrollY;requestAnimationFrame(()=>{window.scrollY!==p&&window.scrollTo({top:p,behavior:"instant"})})},children:[e.jsxs("aside",{style:u.sidebar,children:[e.jsxs("div",{style:u.brand,children:[e.jsx("div",{style:{...u.brandMark,background:H,overflow:"hidden",padding:0},children:(ne=r==null?void 0:r.branding)!=null&&ne.logoUrl?e.jsx("img",{src:r.branding.logoUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):((ue=r==null?void 0:r.branding)==null?void 0:ue.mark)??"C"}),e.jsxs("div",{children:[e.jsx("strong",{children:((fe=r==null?void 0:r.branding)==null?void 0:fe.name)??"Hộp thư"}),!((me=r==null?void 0:r.branding)!=null&&me.name)&&e.jsx("span",{style:u.eyebrow,children:"CHANNELHUB"})]}),e.jsx(pt,{"aria-label":"Tùy chọn",style:u.iconButton,children:e.jsx(Ue,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:u.search,children:[e.jsx(Re,{size:16,strokeWidth:2}),e.jsx(ht,{"aria-label":Q.searchPlaceholder,value:b,onChange:p=>$(p.target.value),placeholder:Q.searchPlaceholder}),b&&e.jsx("button",{style:u.clear,onClick:()=>$(""),"aria-label":"Xóa tìm kiếm",children:"×"})]}),ae&&e.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",padding:"0 14px 8px"},children:[A.provider!=="all"&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:H,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[e.jsx(ge,{provider:A.provider}),We(A.provider),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:H,padding:0,lineHeight:1,display:"flex"},onClick:()=>M(p=>({...p,provider:"all"})),"aria-label":"Xóa filter kênh",children:e.jsx(ve,{size:10})})]}),A.unreadOnly&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:H,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[Q.unreadOnly,e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:H,padding:0,lineHeight:1,display:"flex"},onClick:()=>M(p=>({...p,unreadOnly:!1})),"aria-label":"Xóa filter chưa đọc",children:e.jsx(ve,{size:10})})]}),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:l.muted,fontSize:11,padding:"2px 4px"},onClick:()=>M({provider:"all",unreadOnly:!1}),children:"Xóa tất cả"})]}),e.jsxs("div",{style:u.listHeader,children:[e.jsxs("span",{children:[pe.length," hội thoại"]}),e.jsx("button",{ref:j,style:{...u.iconButton,background:ae?`${H}14`:"transparent",color:ae?H:l.muted},"aria-label":"Bộ lọc",onClick:()=>{var p;if(!N){const x=(p=j.current)==null?void 0:p.getBoundingClientRect();x&&oe({top:x.bottom+6,left:x.left})}re(x=>!x)},children:e.jsx(lt,{size:15,strokeWidth:2})})]}),N&&X&&Ae.createPortal(e.jsxs("div",{ref:J,style:{position:"fixed",top:X.top,left:X.left,zIndex:9999,background:l.white,border:`1px solid ${l.line}`,borderRadius:10,padding:"12px 14px",boxShadow:"0 8px 24px rgba(23,32,51,.14)",minWidth:210,fontFamily:(r==null?void 0:r.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",fontSize:13},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:l.muted,letterSpacing:1,textTransform:"uppercase",marginBottom:8},children:"Kênh"}),["all",...ye].map(p=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:A.provider===p?`${H}0f`:"transparent"},children:[e.jsx("input",{type:"radio",name:"provider-filter",checked:A.provider===p,onChange:()=>M(x=>({...x,provider:p})),style:{accentColor:H}}),p==="all"?e.jsxs("span",{style:{color:l.ink},children:[Q.all," (",L.length,")"]}):e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,color:l.ink},children:[e.jsx(ge,{provider:p}),We(p)," ",e.jsxs("span",{style:{color:l.muted},children:["(",ce[p]??0,")"]})]})]},p)),e.jsx("div",{style:{borderTop:`1px solid ${l.line}`,margin:"8px 0 6px"}}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:A.unreadOnly?`${H}0f`:"transparent"},children:[e.jsx("input",{type:"checkbox",checked:A.unreadOnly,onChange:p=>M(x=>({...x,unreadOnly:p.target.checked})),style:{accentColor:H}}),e.jsx("span",{style:{color:l.ink},children:Q.unreadOnly})]})]}),document.body),e.jsxs(Ke,{style:u.conversationList,children:[pe.map(p=>{var x;return e.jsx(mt,{conversation:p,provider:(x=D.get(p.connectionId))==null?void 0:x.provider,selected:(w==null?void 0:w.id)===p.id,primary:H,onSelect:()=>{q(p),k==null||k(p.id),C.current.markRead(p.id).then(()=>G()).catch(()=>{})}},p.id)}),!pe.length&&e.jsxs("div",{style:u.emptySmall,children:[e.jsx("div",{style:u.emptyIcon,children:e.jsx(Re,{size:16,strokeWidth:2})}),e.jsx("strong",{children:"Không tìm thấy"}),e.jsx("span",{children:"Thử từ khóa hoặc bộ lọc khác."})]}),O&&e.jsx("button",{style:u.loadMore,onClick:()=>void G(O),children:"Xem thêm hội thoại"})]})]}),e.jsx("main",{style:u.main,children:w?e.jsx(bt,{conversation:w,provider:(be=D.get(w.connectionId))==null?void 0:be.provider,connection:D.get(w.connectionId),client:C.current,primary:H,error:c,onRegisterAppend:p=>{E.current=p},refreshKey:_,infoOpen:R,onToggleInfo:()=>V(p=>!p),t:Q,disableAttachments:v,hideKeyboardHint:f},w.id):e.jsx(wt,{})}),R&&w&&e.jsx(jt,{conversation:w,connection:D.get(w.connectionId),primary:H,onClose:()=>V(!1),client:C.current})]})})})});function mt({conversation:t,provider:n,selected:i,primary:r,onSelect:d}){const[y,v]=s.useState(!1),W=t.contactName??t.subject??t.providerConversationKey,f=t.unreadCount??0,m=t.lastMessageText??"",S=t.lastMessageDirection==="outbound"?"Bạn: ":"",k=m.length>60?m.slice(0,60)+"…":m,z=m?S+k:"";let C="transparent";i?C="#eef2ff":y?C="#f7f9fc":f>0&&(C="#f0f4ff");const L={...u.row,background:C,...i?{boxShadow:`inset 3px 0 0 ${r}`}:f>0&&!y?{boxShadow:`inset 3px 0 0 ${r}`}:{}};return e.jsxs("button",{onClick:d,style:L,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),children:[e.jsx(Ge,{name:W,color:r,image:t.contactPictureUrl,provider:n}),e.jsxs("span",{style:u.rowBody,children:[e.jsxs("span",{style:u.rowTop,children:[e.jsx("strong",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:f>0?700:500},children:W}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:[e.jsx("time",{style:{color:l.muted,fontSize:11,whiteSpace:"nowrap"},children:Ce(t.lastMessageAt)}),f>0&&e.jsx("span",{"aria-label":`${f} tin nhắn chưa đọc`,style:u.unreadBadge,children:f>99?"99+":f})]})]}),e.jsx("span",{style:{...u.rowBottom,color:f>0&&!i?"#4a5568":l.muted},children:e.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%"},children:z||e.jsx("span",{style:{opacity:.5},children:"Chưa có tin nhắn"})})})]})]})}function bt({conversation:t,provider:n,connection:i,client:r,primary:d,error:y,onRegisterAppend:v,refreshKey:W,infoOpen:f,onToggleInfo:m,t:S,disableAttachments:k,hideKeyboardHint:z}){var x;const[C,L]=s.useState([]),[P,K]=s.useState(),[T,O]=s.useState(""),[F,w]=s.useState(!0),[q,Y]=s.useState(!1),[b,$]=s.useState(""),A=s.useRef(null),M=t.contactName??t.subject??t.providerConversationKey,N=s.useRef(null),re=s.useRef(null),[j,J]=s.useState(null),[X,oe]=s.useState(!1),[Z,se]=s.useState(!1),[c,I]=s.useState(!1),[R,V]=s.useState(0),H=s.useRef(null),D=s.useRef(null),E=s.useRef(null),[_,de]=s.useState(!1),[ye,ce]=s.useState(""),[G,pe]=s.useState([]),ae=s.useRef(null),Q=s.useRef(null);s.useEffect(()=>()=>{j!=null&&j.objectUrl&&URL.revokeObjectURL(j.objectUrl)},[j==null?void 0:j.objectUrl]),s.useEffect(()=>{if(!c)return;function a(h){var g,B;(g=D.current)!=null&&g.contains(h.target)||(B=H.current)!=null&&B.contains(h.target)||I(!1)}return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[c]),s.useEffect(()=>{r.listCannedResponses().then(pe).catch(()=>{})},[r]),s.useEffect(()=>{if(!_)return;function a(h){var g,B;(g=Q.current)!=null&&g.contains(h.target)||(B=ae.current)!=null&&B.contains(h.target)||de(!1)}return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[_]);const he=s.useRef(!0),ne=s.useCallback(async(a,h)=>{h||(he.current=!a);try{const g=await r.listMessages(t.id,a);L(B=>a?[...g.items,...B]:g.items),K(g.nextCursor)}catch(g){$(g instanceof Error?g.message:"Không tải được tin nhắn")}finally{h||w(!1)}},[r,t.id]);s.useEffect(()=>{w(!0),ne()},[ne]),s.useEffect(()=>{W&&ne(void 0,!0)},[W]),s.useEffect(()=>{he.current&&requestAnimationFrame(()=>{const a=A.current;a&&(a.scrollTop=a.scrollHeight)})},[C]),s.useEffect(()=>(v==null||v(a=>{he.current=!0,L(h=>h.some(g=>g.id===a.id)?h:[...h,a])}),()=>{v==null||v(null)}),[v]);async function ue(a){var B;const h=(B=a.target.files)==null?void 0:B[0];if(!h)return;a.target.value="";const g=URL.createObjectURL(h);J({file:h,uploading:!0,objectUrl:g});try{const ee=await r.uploadAttachment(h);J({file:h,uploading:!1,url:ee.url,mimeType:ee.mimeType,attachmentType:ee.attachmentType,objectUrl:g})}catch{URL.revokeObjectURL(g),J(null),$("Không tải lên được tệp đính kèm")}}async function fe(a){a.preventDefault();const h=T.trim(),g=j!=null&&j.url?[{url:j.url,mimeType:j.mimeType??"application/octet-stream",type:j.attachmentType}]:[];if(!(!h&&!g.length||q)){Y(!0),$("");try{await r.sendMessage(t.id,h||void 0,g.length?g:void 0),j!=null&&j.objectUrl&&URL.revokeObjectURL(j.objectUrl),O(""),J(null),await ne()}catch(B){$(B instanceof Error?B.message:"Không gửi được tin nhắn")}finally{Y(!1)}}}function me(a){const h=E.current;if(!h){O(je=>je+a),I(!1);return}const g=h.selectionStart??T.length,B=h.selectionEnd??T.length,ee=T.slice(0,g)+a+T.slice(B);O(ee),I(!1),requestAnimationFrame(()=>{h.focus(),h.selectionStart=h.selectionEnd=g+a.length})}function be(a){O(a),de(!1),ce(""),requestAnimationFrame(()=>{const h=E.current;h&&(h.focus(),h.selectionStart=h.selectionEnd=a.length)})}const p=!q&&(T.trim().length>0||(j==null?void 0:j.url)!=null&&!j.uploading);return e.jsxs("section",{style:u.chat,children:[e.jsxs("header",{style:u.chatHeader,children:[e.jsx(Ge,{name:M,color:d,image:t.contactPictureUrl,provider:n}),e.jsxs("div",{style:u.contact,children:[e.jsx("strong",{style:u.contactName,children:M}),e.jsx("span",{style:u.contactMeta,children:xt(i)??Ve(n)})]}),e.jsxs("div",{style:u.headerActions,children:[e.jsx("button",{style:u.iconButton,"aria-label":"Thêm tùy chọn",children:e.jsx(Ue,{size:16,strokeWidth:2})}),e.jsx("button",{style:{...u.iconButton,background:f?`${d}14`:"transparent",color:f?d:l.muted},"aria-label":"Thông tin liên hệ",onClick:m,children:e.jsx(rt,{size:16,strokeWidth:2})})]})]}),e.jsxs(Ke,{ref:A,style:u.messageArea,children:[e.jsx("div",{style:u.day,children:S.today}),P&&e.jsx("button",{onClick:()=>void ne(P),style:u.historyButton,children:S.loadOlder}),F&&e.jsxs("div",{style:u.messageHint,children:[e.jsx(Se,{})," ",S.loading]}),!F&&!C.length&&e.jsx("div",{style:u.messageHint,children:S.noMessages}),C.map(a=>e.jsx(vt,{message:a,primary:d},a.id))]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",padding:"6px 14px 2px",borderTop:`1px solid ${l.line}`},children:["Cảm ơn bạn đã liên hệ 🙏","Mình sẽ kiểm tra ngay","Vui lòng chờ 1-2 phút"].map(a=>e.jsx("button",{type:"button",onClick:()=>O(a),style:{fontSize:11,padding:"3px 10px",borderRadius:999,background:`${d}0f`,color:d,border:`1px solid ${d}33`,cursor:"pointer",whiteSpace:"nowrap"},children:a},a))}),e.jsxs("form",{onSubmit:fe,style:{flex:"0 0 auto",padding:"8px 14px 12px",borderTop:`1px solid ${l.line}`,background:l.white,position:"relative"},children:[c&&e.jsxs("div",{ref:H,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:l.white,border:`1px solid ${l.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:280,overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${l.line}`,background:"#f9fafb"},children:Be.map((a,h)=>e.jsx("button",{type:"button",onClick:()=>V(h),style:{flex:1,border:0,background:"transparent",padding:"7px 2px",fontSize:16,cursor:"pointer",lineHeight:1,borderBottom:R===h?`2px solid ${d}`:"2px solid transparent",opacity:R===h?1:.5,transition:"opacity 100ms ease"},children:a.icon},h))}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:2,padding:8,maxHeight:180,overflowY:"auto"},children:(x=Be[R])==null?void 0:x.emojis.map((a,h)=>e.jsx("button",{type:"button",onClick:()=>me(a),style:{border:0,background:"transparent",padding:"5px 2px",fontSize:18,cursor:"pointer",borderRadius:6,lineHeight:1,transition:"background 80ms ease"},onMouseEnter:g=>{g.target.style.background="#f3f4f6"},onMouseLeave:g=>{g.target.style.background="transparent"},children:a},h))})]}),_&&e.jsxs("div",{ref:ae,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:l.white,border:`1px solid ${l.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:300,overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{padding:"8px 10px",borderBottom:`1px solid ${l.line}`},children:e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Tìm template…",value:ye,onChange:a=>ce(a.target.value),style:{width:"100%",boxSizing:"border-box",border:`1px solid ${l.line}`,borderRadius:7,padding:"5px 8px",fontSize:12,outline:"none",fontFamily:"inherit",color:l.ink}})}),e.jsx("div",{style:{maxHeight:220,overflowY:"auto"},children:(()=>{const a=ye.trim().toLowerCase(),h=a?G.filter(g=>g.title.toLowerCase().includes(a)||g.content.toLowerCase().includes(a)||(g.shortcut??"").toLowerCase().includes(a)):G;return h.length?h.map(g=>e.jsxs("button",{type:"button",onClick:()=>be(g.content),style:{display:"block",width:"100%",textAlign:"left",border:0,borderBottom:`1px solid ${l.line}`,background:"transparent",padding:"9px 12px",cursor:"pointer",fontFamily:"inherit"},onMouseEnter:B=>{B.currentTarget.style.background="#f7f9fc"},onMouseLeave:B=>{B.currentTarget.style.background="transparent"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:2},children:[e.jsx("span",{style:{fontSize:12,fontWeight:600,color:l.ink},children:g.title}),g.shortcut&&e.jsx("span",{style:{fontSize:10,color:d,background:`${d}18`,borderRadius:4,padding:"1px 5px"},children:g.shortcut})]}),e.jsx("div",{style:{fontSize:11,color:l.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.content})]},g.id)):e.jsx("div",{style:{padding:"24px 16px",textAlign:"center",color:l.muted,fontSize:12},children:G.length===0?"Chưa có template nào":"Không tìm thấy"})})()})]}),e.jsxs("div",{style:{border:`1.5px solid ${l.line}`,borderRadius:12,background:l.white,overflow:"hidden"},children:[j&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:`1px solid ${l.line}`,fontSize:12},children:[j.uploading?e.jsxs(e.Fragment,{children:[e.jsx(Se,{}),e.jsx("span",{style:{color:l.muted},children:"Đang tải lên…"})]}):j.attachmentType==="image"&&j.objectUrl?e.jsx("img",{src:j.objectUrl,alt:"",style:{height:48,width:48,objectFit:"cover",borderRadius:6}}):e.jsxs("span",{style:{color:l.muted},children:["📎 ",j.file.name," (",Math.round(j.file.size/1024)," KB)"]}),!j.uploading&&e.jsx("button",{type:"button",onClick:()=>{j!=null&&j.objectUrl&&URL.revokeObjectURL(j.objectUrl),J(null)},style:{marginLeft:"auto",border:0,background:"none",color:l.muted,cursor:"pointer",fontSize:16},"aria-label":"Xóa tệp đính kèm",children:"✕"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 8px",borderBottom:"1px solid #f3f4f6"},children:[e.jsx("button",{ref:D,type:"button",title:"Chèn emoji",onClick:()=>I(a=>!a),style:{...u.toolbarBtn,background:c?`${d}18`:"transparent",color:c?d:"#9ca3af"},children:e.jsx(dt,{size:13,strokeWidth:2})}),!k&&e.jsx("button",{type:"button",title:"Gửi ảnh / video","aria-label":"Gửi ảnh hoặc video",style:u.toolbarBtn,onClick:()=>{var a;return(a=N.current)==null?void 0:a.click()},children:e.jsx(nt,{size:13,strokeWidth:2})}),!k&&e.jsx("button",{type:"button",title:"Gửi tệp đính kèm","aria-label":"Gửi tệp đính kèm",style:u.toolbarBtn,onClick:()=>{var a;return(a=re.current)==null?void 0:a.click()},children:e.jsx(ot,{size:13,strokeWidth:2})}),!k&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:N,type:"file",style:{display:"none"},onChange:ue,accept:"image/*,video/mp4"}),e.jsx("input",{ref:re,type:"file",style:{display:"none"},onChange:ue,accept:".pdf,audio/mpeg,audio/ogg,application/octet-stream,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"})]}),e.jsx("button",{ref:Q,type:"button",title:"Template nhanh",onClick:()=>{de(a=>!a),ce("")},style:{...u.toolbarBtn,background:_?`${d}18`:"transparent",color:_?d:"#9ca3af"},children:e.jsx(ct,{size:13,strokeWidth:2})}),e.jsx("span",{style:{width:1,height:14,background:"#e5e7eb",margin:"0 2px"}}),e.jsx("button",{type:"button",title:"In đậm",onClick:()=>oe(a=>!a),style:{...u.toolbarBtn,fontWeight:700,fontSize:12,background:X?`${d}18`:"transparent",color:X?d:"#9ca3af",border:X?`1px solid ${d}33`:"1px solid transparent"},children:"B"}),e.jsx("button",{type:"button",title:"Nghiêng",onClick:()=>se(a=>!a),style:{...u.toolbarBtn,fontStyle:"italic",fontSize:12,background:Z?`${d}18`:"transparent",color:Z?d:"#9ca3af",border:Z?`1px solid ${d}33`:"1px solid transparent"},children:"I"})]}),e.jsx(ut,{ref:E,"aria-label":"Soạn tin nhắn",rows:2,value:T,onChange:a=>O(a.target.value),onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),fe(a))},placeholder:S.sendPlaceholder,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",minHeight:52,maxHeight:120,resize:"none",border:0,outline:0,background:"transparent",color:l.ink,padding:"8px 12px 4px",font:"inherit",fontSize:13,lineHeight:1.45,fontStyle:Z?"italic":"normal",fontWeight:X?700:400}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 8px 6px 12px"},children:[e.jsxs("span",{style:{fontSize:11,color:T.length>1e3?"#ef4444":T.length>900?"#f59e0b":"#9ca3af",fontWeight:T.length>1e3?600:400},children:[T.length,"/1000"]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[!z&&e.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:"↵ Gửi · ⇧↵ Xuống dòng"}),e.jsxs("button",{disabled:!p,"aria-label":"Gửi tin nhắn",style:{display:"flex",alignItems:"center",gap:5,padding:"5px 12px",border:0,borderRadius:999,fontSize:12,fontWeight:600,background:p?`linear-gradient(135deg,${d},#0ea5e9)`:"#e5e7eb",color:p?"#fff":"#9ca3af",cursor:p?"pointer":"not-allowed",boxShadow:p?"0 2px 8px rgba(37,99,235,0.25)":"none",transition:"all 150ms ease"},children:[q?e.jsx(De,{size:12,style:{animation:"channelhub-spin .7s linear infinite"}}):e.jsx(at,{size:12,strokeWidth:2}),S.send]})]})]})]})]}),(b||y)&&e.jsx("div",{role:"alert",style:u.error,children:b||y})]})}function vt({message:t,primary:n}){var O,F,w,q,Y;const i=s.useContext(Ie),r=s.useContext(qe),d=b=>b.startsWith("/v1/media/proxy")?`${i}${b}&tok=${encodeURIComponent(r)}`:b,y=t.direction==="outbound",v=((O=t.attachments)==null?void 0:O.filter(b=>b.type==="image"))??[],W=((F=t.attachments)==null?void 0:F.filter(b=>b.type==="sticker"))??[],f=((w=t.attachments)==null?void 0:w.filter(b=>b.type==="video"))??[],m=((q=t.attachments)==null?void 0:q.filter(b=>b.type==="audio"))??[],S=((Y=t.attachments)==null?void 0:Y.filter(b=>b.type==="file"))??[],[k,z]=s.useState(null),C=y?"flex-end":"flex-start",L=e.jsxs("time",{style:{display:"block",marginTop:4,fontSize:10,opacity:.65,textAlign:"right",letterSpacing:.2,userSelect:"none"},children:[Ce(t.occurredAt,!0),y&&e.jsxs(e.Fragment,{children:[" ",e.jsx($e,{status:t.status})]})]}),P=e.jsx("div",{style:{position:"absolute",bottom:6,right:8},children:e.jsxs("time",{style:{fontSize:10,color:"#fff",textShadow:"0 1px 3px rgba(0,0,0,.5)",letterSpacing:.2,userSelect:"none"},children:[Ce(t.occurredAt,!0),y&&e.jsxs(e.Fragment,{children:[" ",e.jsx($e,{status:t.status})]})]})}),K=y?{...u.bubbleOut,background:n,color:"#fff",border:"1px solid transparent"}:u.bubbleIn,T=!t.text&&m.length===0&&S.length===0;return e.jsxs("div",{style:{...u.messageLine,justifyContent:C,flexDirection:"column",alignItems:C},children:[W.map((b,$)=>e.jsxs("div",{style:{position:"relative",marginBottom:2},children:[e.jsx("img",{src:d(b.url),alt:"sticker",style:{display:"block",maxWidth:128,maxHeight:128,objectFit:"contain"}}),T&&v.length===0&&f.length===0&&$===W.length-1&&P]},`s${$}`)),v.map((b,$)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"zoom-in"},onClick:()=>z({url:d(b.url),kind:"image"}),children:[e.jsx("img",{src:d(b.url),alt:"",style:{display:"block",maxWidth:260,maxHeight:260,borderRadius:12,objectFit:"cover"}}),T&&$===v.length-1&&f.length===0&&P]},$)),f.map((b,$)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"pointer"},onClick:()=>z({url:d(b.url),kind:"video"}),children:[e.jsx("video",{src:d(b.url),style:{display:"block",maxWidth:260,maxHeight:200,borderRadius:12,objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:12,background:"rgba(0,0,0,.25)"},children:e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:"rgba(255,255,255,.9)",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(st,{size:16,fill:"#172033",color:"#172033",style:{marginLeft:2}})})}),T&&$===f.length-1&&P]},$)),(m.length>0||S.length>0||t.text||!v.length&&!f.length&&!W.length&&!t.text)&&e.jsxs("div",{style:K,children:[m.map((b,$)=>e.jsx("audio",{src:d(b.url),controls:!0,style:{display:"block",width:"100%",marginBottom:4}},$)),S.map((b,$)=>e.jsxs("a",{href:d(b.url),target:"_blank",rel:"noreferrer",style:{display:"block",fontSize:12,color:y?"#fff":"#2563eb",textDecoration:"underline",marginBottom:4},children:["📎 ",gt(b.mimeType)]},$)),t.text&&e.jsx("p",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t.text}),!m.length&&!S.length&&!t.text&&e.jsx("p",{style:{margin:0,opacity:.5},children:"[attachment]"}),L]}),k&&Ae.createPortal(e.jsxs("div",{onClick:()=>z(null),style:{position:"fixed",inset:0,zIndex:1e4,background:"rgba(0,0,0,.88)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"zoom-out"},children:[k.kind==="image"?e.jsx("img",{src:k.url,alt:"",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,objectFit:"contain",boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:b=>b.stopPropagation()}):e.jsx("video",{src:k.url,controls:!0,autoPlay:!0,style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:b=>b.stopPropagation()}),e.jsx("button",{onClick:()=>z(null),style:{position:"absolute",top:16,right:16,background:"rgba(255,255,255,.15)",border:"none",borderRadius:"50%",width:36,height:36,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff"},children:e.jsx(ve,{size:18})})]}),document.body)]})}function jt({conversation:t,connection:n,primary:i,onClose:r,client:d}){const y=t.contactName??t.subject??t.providerConversationKey,v=n==null?void 0:n.provider,[W,f]=s.useState({channel:!0,stats:!1,extra:!1}),m=F=>f(w=>({...w,[F]:!w[F]})),[S,k]=s.useState(""),[z,C]=s.useState(!1),[L,P]=s.useState(!1),[K,T]=s.useState("");s.useEffect(()=>{k(""),P(!1),T(""),d.getNote(t.id).then(F=>{F&&k(F.content)}).catch(()=>{})},[t.id,d]);async function O(){if(!(!S.trim()||z)){C(!0),T("");try{await d.upsertNote(t.id,S.trim()),P(!0),setTimeout(()=>P(!1),2e3)}catch{T("Lưu thất bại")}finally{C(!1)}}}return e.jsxs("aside",{style:u.infoPanel,children:[e.jsxs("div",{style:u.infoPanelHeader,children:[e.jsx("span",{style:{fontWeight:600,fontSize:13,color:l.ink},children:"Thông tin liên hệ"}),e.jsx("button",{style:u.iconButton,onClick:r,"aria-label":"Đóng",children:e.jsx(ve,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:{overflowY:"auto",flex:1},children:[e.jsxs("div",{style:u.infoPanelIdentity,children:[e.jsxs("span",{style:{...u.avatarWrap,width:48,height:48},children:[e.jsx(Ne,{src:t.contactPictureUrl,fallback:Ye(y),style:{...u.avatar,width:48,height:48,fontSize:16}}),e.jsx("span",{style:{...u.providerBadge,width:20,height:20},children:e.jsx(ge,{provider:v})})]}),e.jsx("strong",{style:{marginTop:10,fontSize:15,color:l.ink,textAlign:"center"},children:y}),e.jsx("span",{style:{fontSize:11,color:l.muted,fontFamily:"monospace",textAlign:"center"},children:t.providerConversationKey})]}),e.jsxs(ke,{label:"KÊNH",sectionKey:"channel",expanded:W.channel,onToggle:()=>m("channel"),children:[e.jsx(te,{label:"Nền tảng",children:e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5},children:[e.jsx(ge,{provider:v}),e.jsx("span",{children:Ve(v)})]})}),e.jsxs(te,{label:"ID hội thoại",children:[e.jsxs("span",{style:{fontFamily:"monospace",fontSize:11},children:[t.id.slice(0,8),"…"]}),e.jsx(kt,{value:t.id})]})]}),e.jsxs(ke,{label:"THỐNG KÊ",sectionKey:"stats",expanded:W.stats,onToggle:()=>m("stats"),children:[e.jsx(te,{label:"Tin nhắn",value:String(t.messageCount??0)}),(t.unreadCount??0)>0&&e.jsx(te,{label:"Chưa đọc",value:String(t.unreadCount),valueColor:"#ef4444"}),e.jsx(te,{label:"Gần nhất",value:t.lastMessageAt?new Date(t.lastMessageAt).toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit",year:"numeric"}):"—"}),e.jsx(te,{label:"Lần đầu",value:"—"})]}),e.jsxs(ke,{label:"THÔNG TIN BỔ SUNG",sectionKey:"extra",expanded:W.extra,onToggle:()=>m("extra"),children:[e.jsx(te,{label:"Điện thoại",value:"— chưa có",valueMuted:!0}),e.jsx(te,{label:"Email",value:"— chưa có",valueMuted:!0}),e.jsx(te,{label:"Nhãn",value:"— chưa có",valueMuted:!0})]}),e.jsxs("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:8},children:[e.jsx("button",{style:{...u.ghostButton,color:i,borderColor:`${i}33`},children:"Xem lịch sử"}),e.jsxs("div",{style:{border:"1.5px solid #fde68a",borderRadius:10,background:"#fffbeb",overflow:"hidden"},children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid #fde68a",fontSize:11,fontWeight:600,color:"#92400e"},children:"🔒 Ghi chú nội bộ"}),e.jsx("textarea",{value:S,onChange:F=>k(F.target.value),placeholder:"Nhập ghi chú...",rows:3,style:{display:"block",width:"100%",boxSizing:"border-box",border:0,outline:0,background:"transparent",resize:"none",padding:"8px 10px",font:"inherit",fontSize:12,color:l.ink,lineHeight:1.5}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 10px 6px"},children:[L?e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,fontSize:11,color:"#16a34a"},children:[e.jsx(Fe,{size:11,strokeWidth:2.5})," Đã lưu"]}):K?e.jsx("span",{style:{fontSize:11,color:"#ef4444"},children:K}):e.jsx("span",{}),e.jsx("button",{type:"button",onClick:()=>{O()},disabled:!S.trim()||z,style:{padding:"4px 12px",border:0,borderRadius:7,fontSize:12,fontWeight:600,background:S.trim()&&!z?"linear-gradient(135deg,#f59e0b,#fbbf24)":"#e5e7eb",color:S.trim()&&!z?"#fff":"#9ca3af",cursor:S.trim()&&!z?"pointer":"not-allowed"},children:z?"Đang lưu…":"Lưu ghi chú"})]})]})]})]})]})}function ke({label:t,children:n,sectionKey:i,expanded:r,onToggle:d}){const y=!!d,v=r??!0;return e.jsxs("div",{style:{borderTop:`1px solid ${l.line}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px 6px",fontSize:10,fontWeight:700,letterSpacing:1,color:l.muted,textTransform:"uppercase",cursor:y?"pointer":"default"},onClick:d,children:[e.jsx("span",{children:t}),y&&(v?e.jsx(Qe,{size:12,strokeWidth:2}):e.jsx(et,{size:12,strokeWidth:2}))]}),v&&n]})}function te({label:t,value:n,children:i,valueColor:r,valueMuted:d}){return e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"3px 16px",fontSize:12,gap:8},children:[e.jsx("span",{style:{color:l.muted,flexShrink:0},children:t}),e.jsx("span",{style:{color:r??(d?l.muted:l.ink),textAlign:"right",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:4},children:i??n})]})}function kt({value:t}){const[n,i]=s.useState(!1);return e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:l.muted,padding:2,lineHeight:1},title:"Sao chép",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{i(!0),setTimeout(()=>i(!1),1500)})},"aria-label":"Sao chép ID",children:n?"✓":"⎘"})}function wt(){return e.jsxs("div",{style:u.empty,children:[e.jsx("div",{style:u.emptyHero,children:e.jsx(it,{size:16,strokeWidth:2})}),e.jsx("h2",{children:"Chọn một hội thoại"}),e.jsx("p",{children:"Chọn hội thoại bên trái để xem và trả lời tin nhắn."})]})}function Ge({name:t,color:n,image:i,provider:r}){return e.jsxs("span",{style:u.avatarWrap,children:[e.jsx(St,{name:t,color:n,image:i}),r&&e.jsx("span",{style:u.providerBadge,children:e.jsx(ge,{provider:r})})]})}function St({name:t,color:n,image:i}){return e.jsx(Ne,{src:i,fallback:Ye(t),style:{...u.avatar,background:`${n}18`,color:n}})}function Se(){return e.jsx(De,{size:14,style:u.spinner,"aria-hidden":"true"})}function Ye(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}const Ct={livechat:"web"};function ge({provider:t}){const n=s.useContext(Ie),i=14;if(!t)return null;const r=Ct[t]??t;return e.jsx("img",{src:`${n}/static/logos/${r}.avif`,alt:t,width:i,height:i,style:{borderRadius:"50%",objectFit:"cover",display:"block"}})}function Ce(t,n=!1){if(!t)return"";const i=new Date(t);return i.toDateString()===new Date().toDateString()?i.toLocaleTimeString("vi-VN",{hour:"2-digit",minute:"2-digit"}):i.toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit"})}const u={frame:{display:"grid",gridTemplateRows:"minmax(0, 1fr)",height:620,maxHeight:"calc(100dvh - 220px)",minHeight:0,overflow:"hidden",border:`1px solid ${l.line}`,background:l.white,color:l.ink,boxShadow:"0 18px 50px rgba(31,45,72,.10)"},sidebar:{display:"flex",flexDirection:"column",minWidth:0,minHeight:0,borderRight:`1px solid ${l.line}`,background:l.white},brand:{display:"flex",alignItems:"center",gap:10,padding:"20px 18px 16px"},brandMark:{display:"grid",placeItems:"center",width:32,height:32,borderRadius:10,color:"#fff",fontWeight:800},eyebrow:{display:"block",marginTop:2,fontSize:9,letterSpacing:1.3,color:l.muted},iconButton:{display:"inline-grid",placeItems:"center",width:32,height:32,marginLeft:"auto",border:0,borderRadius:8,background:"transparent",color:l.muted,cursor:"pointer"},search:{display:"flex",alignItems:"center",gap:8,margin:"0 14px 12px",padding:"9px 10px",border:`1px solid ${l.line}`,borderRadius:9,color:l.muted,background:l.surface},clear:{border:0,background:"none",color:l.muted,cursor:"pointer",fontSize:18},listHeader:{display:"flex",alignItems:"center",padding:"10px 18px",borderTop:`1px solid ${l.line}`,borderBottom:`1px solid ${l.line}`,color:l.muted,fontSize:11,fontWeight:700,letterSpacing:.4,textTransform:"uppercase"},conversationList:{overflowY:"auto",flex:1,minHeight:0},row:{display:"flex",width:"100%",gap:11,padding:"10px 14px",border:0,borderBottom:`1px solid ${l.line}`,background:"transparent",textAlign:"left",cursor:"pointer",transition:"background 120ms ease"},avatarWrap:{position:"relative",flex:"0 0 auto",width:38,height:38},avatar:{flex:"0 0 auto",width:38,height:38,display:"grid",placeItems:"center",borderRadius:"50%",objectFit:"cover",fontSize:12,fontWeight:800},providerBadge:{position:"absolute",left:-3,bottom:-3,display:"grid",placeItems:"center",width:17,height:17,border:"2px solid #fff",borderRadius:"50%",background:"#fff",color:"#64748b"},rowBody:{minWidth:0,flex:1},rowTop:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:8,fontSize:13},rowBottom:{display:"flex",marginTop:4,fontSize:11,minWidth:0,overflow:"hidden",lineHeight:1.4},unreadBadge:{display:"inline-grid",placeItems:"center",minWidth:18,height:18,borderRadius:999,background:"#ef4444",color:"#fff",fontSize:10,fontWeight:800,padding:"0 5px"},loadMore:{width:"100%",border:0,background:"transparent",color:"#4c72ca",padding:14,cursor:"pointer",fontSize:12},emptySmall:{display:"grid",justifyItems:"center",gap:7,padding:"56px 24px",color:l.muted,fontSize:12,textAlign:"center"},emptyIcon:{display:"grid",placeItems:"center",width:40,height:40,borderRadius:12,background:l.surface},main:{minWidth:0,minHeight:0,overflow:"hidden",background:l.surface},chat:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},chatHeader:{flex:"0 0 auto",display:"flex",alignItems:"center",gap:10,padding:"0 16px 0 18px",height:56,borderBottom:`1px solid ${l.line}`,background:l.white},contact:{display:"grid",gap:3,minWidth:0,flex:1},contactName:{fontSize:14,fontWeight:600,color:l.ink,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},contactMeta:{display:"flex",alignItems:"center",gap:5,fontSize:11,color:l.muted},headerActions:{display:"flex",gap:2,marginLeft:"auto"},messageArea:{flex:1,minHeight:0,overflowY:"auto",overscrollBehavior:"contain",padding:"20px clamp(16px,5vw,56px)",background:"linear-gradient(180deg,#f9fbfe 0%,#f4f7fb 100%)"},day:{margin:"0 auto 18px",color:"#a1acbb",fontSize:10,letterSpacing:1.2,fontWeight:700,textAlign:"center"},historyButton:{display:"block",margin:"0 auto 18px",border:`1px solid ${l.line}`,borderRadius:20,padding:"6px 12px",background:l.white,color:l.muted,cursor:"pointer",fontSize:11},messageHint:{display:"flex",justifyContent:"center",alignItems:"center",gap:8,padding:40,color:l.muted,fontSize:12},messageLine:{display:"flex",marginBottom:10},bubbleOut:{maxWidth:"min(70%,480px)",padding:"9px 13px",borderRadius:"14px 14px 3px 14px",boxShadow:"0 2px 5px rgba(30,43,65,.03)",fontSize:14,lineHeight:1.55},bubbleIn:{maxWidth:"min(70%,480px)",padding:"9px 13px",borderRadius:"14px 14px 14px 3px",border:`1px solid ${l.line}`,background:l.surface,boxShadow:"0 2px 5px rgba(30,43,65,.03)",fontSize:14,lineHeight:1.55},error:{padding:"8px 18px",background:"#fff2f0",color:"#b42318",fontSize:12},empty:{display:"grid",placeItems:"center",alignContent:"center",height:"100%",padding:30,textAlign:"center",color:l.muted},emptyHero:{display:"grid",placeItems:"center",width:64,height:64,marginBottom:16,borderRadius:20,background:"#eaf0ff",color:"#5277d7"},state:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,minHeight:180,border:`1px solid ${l.line}`,background:l.white,color:l.muted,fontSize:13},retry:{border:0,borderRadius:7,padding:"7px 10px",background:"#eff4ff",color:"#315dbb",cursor:"pointer"},spinner:{display:"inline-block",width:14,height:14,border:"2px solid #dbe3f3",borderTopColor:"#5277d7",borderRadius:"50%",animation:"channelhub-spin .7s linear infinite"},toolbarBtn:{display:"inline-grid",placeItems:"center",width:26,height:26,border:"1px solid transparent",borderRadius:6,background:"transparent",color:"#9ca3af",cursor:"pointer",padding:0,lineHeight:1},infoPanel:{display:"flex",flexDirection:"column",borderLeft:`1px solid ${l.line}`,background:l.white,minHeight:0,overflow:"hidden"},infoPanelHeader:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 16px 12px",borderBottom:`1px solid ${l.line}`,flex:"0 0 auto"},infoPanelIdentity:{display:"flex",flexDirection:"column",alignItems:"center",padding:"20px 16px 16px",gap:4},ghostButton:{width:"100%",padding:"8px 12px",border:`1px solid ${l.line}`,borderRadius:8,background:"transparent",fontSize:12,cursor:"pointer",textAlign:"center"}},It={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"},zt={facebook:"facebook",instagram:"instagram",telegram:"telegram",zalo:"zalo",livechat:"web",whatsapp:"web"};function ie({provider:t,apiUrl:n,size:i=40}){const r=It[t]??"#f1f5f9",d=zt[t],y=n.replace(/\/$/,"");return e.jsx("div",{style:{width:i,height:i,borderRadius:Math.round(i*.28),background:r,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,overflow:"hidden"},children:d?e.jsx("img",{src:`${y}/static/logos/${d}.avif`,alt:t,width:Math.round(i*.65),height:Math.round(i*.65),style:{objectFit:"contain",display:"block"}}):e.jsx("span",{style:{fontSize:Math.round(i*.45),fontWeight:700,color:"#64748b",textTransform:"uppercase"},children:t.slice(0,1)})})}const xe={facebook:"Facebook",zalo:"Zalo OA",instagram:"Instagram",telegram:"Telegram",livechat:"Live Chat",whatsapp:"WhatsApp"},Tt={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"};function ze(t){const n=t.metadata;return String(n.displayName??n.pageName??n.username??n.name??t.externalAccountId)}function Rt(t){const n=xe[t.provider]??t.provider,i=String(t.metadata.username??t.metadata.pageName??"");return i?`${n} · ${i}`:n}const o={root:{background:"#fff",borderRadius:16,boxShadow:"0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06)",overflow:"hidden",minWidth:320,width:"100%",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif",fontSize:14,color:"#0f172a"},header:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},headerLeft:{display:"flex",alignItems:"center",gap:10},title:{fontSize:16,fontWeight:700,color:"#0f172a",lineHeight:1.3},subtitle:{fontSize:12,color:"#94a3b8",marginTop:1},divider:{height:1,background:"#f1f5f9",margin:"16px 0 0"},body:{padding:"16px 24px 24px"},backBtn:{width:32,height:32,borderRadius:8,border:"1px solid #e2e8f0",background:"#fff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:"#475569",flexShrink:0},addBtn:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",borderRadius:8,border:"none",background:"#2563eb",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},errorBanner:{margin:"12px 24px 0",padding:"10px 14px",borderRadius:10,background:"#fef2f2",border:"1px solid #fecaca",color:"#dc2626",fontSize:13},channelItem:{display:"flex",alignItems:"center",gap:12,padding:"12px 14px",borderRadius:12,border:"1px solid #f1f5f9",background:"#fafafa",marginBottom:8},channelInfo:{flex:1,minWidth:0},channelName:{fontSize:14,fontWeight:600,color:"#0f172a",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},channelMeta:{fontSize:12,color:"#94a3b8",marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},channelActions:{display:"flex",alignItems:"center",gap:8,flexShrink:0},badgeActive:{fontSize:11,fontWeight:600,padding:"2px 8px",borderRadius:999,background:"#d1fae5",color:"#059669"},badgeInactive:{fontSize:11,fontWeight:600,padding:"2px 8px",borderRadius:999,background:"#f1f5f9",color:"#94a3b8"},disconnectBtn:{fontSize:12,fontWeight:500,padding:"5px 10px",borderRadius:7,border:"1px solid #e2e8f0",background:"#fff",color:"#64748b",cursor:"pointer"},providerGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(130px, 1fr))",gap:10},providerCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"16px 12px 14px",borderRadius:12,borderWidth:"1.5px",borderStyle:"solid",borderColor:"#f1f5f9",background:"#fafafa",cursor:"pointer",textAlign:"center",boxShadow:"none",transform:"none"},providerName:{fontSize:13,fontWeight:600,color:"#0f172a",lineHeight:1.2},providerDesc:{fontSize:11,color:"#94a3b8",lineHeight:1.4},connectHeader:{display:"flex",alignItems:"center",gap:12,padding:"20px 24px 16px",borderBottom:"1px solid #f1f5f9"},connectTitle:{fontSize:15,fontWeight:700,color:"#0f172a"},connectDesc:{fontSize:12,color:"#94a3b8",marginTop:2,lineHeight:1.5},form:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},field:{display:"flex",flexDirection:"column",gap:6},label:{fontSize:13,fontWeight:600,color:"#374151"},labelHint:{fontSize:11,fontWeight:400,color:"#94a3b8",marginLeft:4},input:{padding:"9px 12px",borderRadius:8,border:"1.5px solid #e2e8f0",fontSize:13,color:"#0f172a",background:"#fff",outline:"none",fontFamily:"inherit",width:"100%",boxSizing:"border-box"},inputHint:{fontSize:11,color:"#94a3b8",lineHeight:1.5},infoBox:{display:"flex",gap:8,padding:"10px 12px",borderRadius:8,background:"#eff6ff",border:"1px solid #bfdbfe",color:"#1e40af",fontSize:13,lineHeight:1.5},formActions:{display:"flex",gap:8,flexWrap:"wrap"},btnPrimary:{flex:1,minWidth:120,padding:"10px 16px",borderRadius:9,border:"none",background:"#2563eb",color:"#fff",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"},btnSecondary:{padding:"10px 16px",borderRadius:9,border:"1.5px solid #e2e8f0",background:"#fff",color:"#64748b",fontSize:14,fontWeight:500,cursor:"pointer",fontFamily:"inherit"},resultBanner:{display:"flex",alignItems:"flex-start",gap:10,padding:"12px 14px",borderRadius:10,background:"#f0fdf4",border:"1px solid #bbf7d0",fontSize:13,color:"#166534",lineHeight:1.5},codeLabel:{fontSize:11,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:".05em",marginBottom:6},codeBlock:{background:"#0f172a",borderRadius:10,padding:"14px 16px",position:"relative",overflowX:"auto"},codePre:{fontFamily:"'JetBrains Mono', 'Fira Code', 'Courier New', monospace",fontSize:11.5,lineHeight:1.6,color:"#e2e8f0",whiteSpace:"pre-wrap",wordBreak:"break-all",margin:0},copyBtn:{position:"absolute",top:10,right:10,display:"flex",alignItems:"center",gap:4,padding:"4px 10px",borderRadius:6,border:"1px solid #334155",background:"#1e293b",color:"#94a3b8",fontSize:11,fontWeight:500,cursor:"pointer",fontFamily:"inherit"},secretRow:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",borderRadius:8,background:"#fefce8",border:"1px solid #fef08a"},secretLabel:{fontSize:12,fontWeight:600,color:"#854d0e",whiteSpace:"nowrap"},secretValue:{fontFamily:"'JetBrains Mono', monospace",fontSize:12,color:"#0f172a",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},oauthWaiting:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"40px 24px 48px",gap:16,textAlign:"center"},oauthTitle:{fontSize:16,fontWeight:700,color:"#0f172a"},oauthDesc:{fontSize:13,color:"#64748b",lineHeight:1.6,maxWidth:300},oauthCancel:{marginTop:8,padding:"10px 20px",borderRadius:9,border:"1.5px solid #e2e8f0",background:"#fff",color:"#64748b",fontSize:14,fontWeight:500,cursor:"pointer",fontFamily:"inherit"},empty:{display:"flex",flexDirection:"column",alignItems:"center",padding:"40px 24px 48px",gap:12,textAlign:"center"},emptyTitle:{fontSize:15,fontWeight:700,color:"#0f172a"},emptyDesc:{fontSize:13,color:"#94a3b8",lineHeight:1.6,maxWidth:280},emptyCta:{marginTop:4,display:"flex",alignItems:"center",gap:6,padding:"10px 20px",borderRadius:9,border:"none",background:"#2563eb",color:"#fff",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}};function Le(){return e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:e.jsx("path",{d:"M7 1v12M1 7h12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}function le(){return e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:e.jsx("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round"})})}function He(){return e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[e.jsx("rect",{x:"4",y:"4",width:"7",height:"7",rx:"1.5",stroke:"currentColor",strokeWidth:"1.3"}),e.jsx("path",{d:"M2.5 8H2a1 1 0 01-1-1V2a1 1 0 011-1h5a1 1 0 011 1v.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})]})}function Ee(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:e.jsx("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function Bt(){return e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{flexShrink:0},children:[e.jsx("circle",{cx:"5",cy:"6",r:"3.5",stroke:"#ca8a04",strokeWidth:"1.4"}),e.jsx("path",{d:"M8 7.5l4.5 4.5M10.5 10l1.5 1.5",stroke:"#ca8a04",strokeWidth:"1.4",strokeLinecap:"round"})]})}function Wt(){return e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{flexShrink:0,marginTop:1},children:[e.jsx("circle",{cx:"7",cy:"7",r:"6",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M7 6v5M7 4.5v.01",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}let Me=!1;function $t(){if(Me||typeof document>"u")return;Me=!0;const t=document.createElement("style");t.textContent="@keyframes ch-spin{to{transform:rotate(360deg)}}",document.head.appendChild(t)}function Lt({apiUrl:t,token:n,onConnectionChange:i}){const r=t.replace(/\/$/,""),[d,y]=s.useState([]),[v,W]=s.useState(!0),[f,m]=s.useState({name:"list"}),[S,k]=s.useState(null),[z,C]=s.useState(!1),[L,P]=s.useState(""),[K,T]=s.useState(""),[O,F]=s.useState(""),[w,q]=s.useState(""),[Y,b]=s.useState(!1),[$,A]=s.useState(!1),M=s.useRef(null);$t();const N=s.useCallback(async()=>{try{const c=await fetch(`${r}/v1/connections`,{headers:{authorization:`Bearer ${n}`}});if(!c.ok)throw new Error("Không tải được kênh");const I=await c.json();y(I),i==null||i(I)}catch(c){k(c instanceof Error?c.message:"Lỗi tải dữ liệu")}finally{W(!1)}},[r,n,i]);s.useEffect(()=>{N()},[N]),s.useEffect(()=>{if(!S)return;const c=setTimeout(()=>k(null),5e3);return()=>clearTimeout(c)},[S]),s.useEffect(()=>()=>{M.current&&window.removeEventListener("message",M.current)},[]);async function re(c,I){if(confirm(`Bạn chắc chắn muốn ngắt kết nối "${I}"?
|
|
111
|
+
*/const yt=D("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);class Xe{constructor(n,i){this.apiUrl=n,this.token=i}async request(n,i,r){const c={authorization:`Bearer ${this.token}`,...r?{}:{"content-type":"application/json"},...i==null?void 0:i.headers},v=await fetch(`${this.apiUrl}${n}`,{...i,headers:c}),m=await v.json().catch(()=>null);if(!v.ok)throw new Error((m==null?void 0:m.message)??`Request failed (${v.status})`);return m}listConnections(){return this.request("/v1/connections")}listConversations(n){return this.request(`/v1/conversations${n?`?cursor=${encodeURIComponent(n)}`:""}`)}listMessages(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages${i?`?cursor=${encodeURIComponent(i)}`:""}`)}getMessage(n){return this.request(`/v1/messages/${encodeURIComponent(n)}`)}sendMessage(n,i,r){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages`,{method:"POST",headers:{"idempotency-key":crypto.randomUUID()},body:JSON.stringify({text:i,attachments:r})})}async markRead(n){const i=await fetch(`${this.apiUrl}/v1/conversations/${encodeURIComponent(n)}/mark-read`,{method:"POST",headers:{authorization:`Bearer ${this.token}`}});if(!i.ok&&i.status!==204)throw new Error(`markRead failed (${i.status})`)}listCannedResponses(n){const i=n!=null&&n.trim()?`?search=${encodeURIComponent(n)}`:"";return this.request(`/v1/canned-responses${i}`)}getNote(n){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`)}patchContact(n,i){return this.request(`/v1/contacts/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify({externalId:i})})}upsertNote(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`,{method:"PUT",body:JSON.stringify({content:i})})}async uploadAttachment(n){const i=new FormData;return i.append("file",n),this.request("/v1/attachments",{method:"POST",body:i},!0)}connectSSE(n){const i=`${this.apiUrl}/v1/events?token=${encodeURIComponent(this.token)}`;let r,c,v=!1;const m=()=>{r=new EventSource(i),r.addEventListener("message.new",E=>{n("message.new",JSON.parse(E.data))}),r.addEventListener("conversation.updated",E=>{n("conversation.updated",JSON.parse(E.data))}),r.onerror=()=>{r.close(),v||(c=setTimeout(m,5e3))}};return m(),()=>{v=!0,clearTimeout(c),r==null||r.close()}}}function Je({src:t,alt:n="",fallback:i,style:r}){return t?e.jsx("img",{src:t,alt:n,style:{width:38,height:38,borderRadius:"50%",objectFit:"cover",...r}}):e.jsx("span",{style:{display:"grid",placeItems:"center",width:38,height:38,borderRadius:"50%",...r},children:i})}function mt({variant:t="ghost",style:n,...i}){return e.jsx("button",{...i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",border:t==="outline"?"1px solid #e7ebf2":0,borderRadius:8,cursor:"pointer",font:"inherit",background:t==="default"?"#2563eb":"transparent",...n}})}function bt({style:t,...n}){return e.jsx("input",{...n,style:{width:"100%",minWidth:0,border:0,outline:0,background:"transparent",font:"inherit",...t}})}const Ye=o.forwardRef(({children:t,style:n},i)=>e.jsx("div",{ref:i,style:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain",...n},children:t})),vt=o.forwardRef(function({style:n,...i},r){return e.jsx("textarea",{ref:r,...i,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",border:0,outline:0,background:"transparent",font:"inherit",...n}})});function jt(t){return{id:t.contactId??t.providerConversationKey,name:t.contactName,pictureUrl:t.contactPictureUrl,providerUserId:t.contactProviderUserId??t.providerConversationKey,...t.contactExternalId?{externalId:t.contactExternalId}:{}}}function Ce(t){return{conversation:t,contact:jt(t)}}class kt extends o.Component{constructor(){super(...arguments),this.state={caught:!1}}static getDerivedStateFromError(){return{caught:!0}}render(){return this.state.caught?null:this.props.children}}const a={ink:"#172033",muted:"#718096",line:"#e7ebf2",surface:"#f7f9fc",white:"#fff"},Me=[{icon:"😊",emojis:["😀","😁","😂","🤣","😊","😇","🙂","😉","😍","🥰","😘","😋","😎","🤩","😏","😒","😔","😢","😭","😤","😠","🤯","😱","🥳","😴","🤔","🤗","🫡","😮","🤧","🥺","😶","🫠","🤭","🤫"]},{icon:"👋",emojis:["👍","👎","👏","🙏","🤝","✌️","🤞","🫡","💪","🤜","👊","✊","🖐","👌","🤌","🤏","☝️","👆","👇","👉","👈","🤙","💅","🫶","❤️","🧡","💛","💚","💙","💜","🖤","💔","❣️","💕","💯"]},{icon:"🐱",emojis:["🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🙈","🐔","🐧","🐦","🦆","🦅","🦉","🦋","🐝","🐛","🐢","🦎","🐬","🦈","🐳","🐙","🦑"]},{icon:"🍕",emojis:["🍎","🍊","🍋","🍇","🍓","🍒","🥝","🥑","🍔","🍕","🌮","🍜","🍣","🍦","🎂","🍰","🧁","☕","🧋","🥤","🍺","🥂","🍾","🧃","🧊"]},{icon:"⚽",emojis:["⚽","🏀","🏈","⚾","🎾","🏐","🏓","🎮","🎲","🎯","🎳","🏆","🥇","🎖","🎁","🎉","🎊","🎈","🎭","🎨","🎬","🎵","🎸","🎹","🎺","🪗","🎻"]},{icon:"🌍",emojis:["🌍","🌈","⭐","🌙","☀️","⛅","🌊","🔥","💧","🌿","🌸","🌺","🌻","🍀","🌴","🏔","🏖","🏕","🌃","🏙","🌅","🌄","🌠","🌌","🌋","🏝"]}],Le=o.createContext(""),_e=o.createContext("");function wt(){try{const t=new AudioContext,n=t.createOscillator(),i=t.createGain();n.connect(i),i.connect(t.destination),n.type="sine",n.frequency.setValueAtTime(880,t.currentTime),n.frequency.exponentialRampToValueAtTime(660,t.currentTime+.12),i.gain.setValueAtTime(.25,t.currentTime),i.gain.exponentialRampToValueAtTime(.001,t.currentTime+.35),n.start(t.currentTime),n.stop(t.currentTime+.35)}catch{}}function St(t){if(!(t!=null&&t.metadata))return;const n=t.metadata,i=n.pageName??n.displayName??n.username??n.name;return typeof i=="string"&&i?i:void 0}function Ze(t){return t==="facebook"?"Facebook Messenger":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo OA":t==="livechat"?"Live Chat":"Channel"}function Ae(t){return t==="facebook"?"Facebook":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo":t==="livechat"?"Live Chat":String(t??"")}const Ct=t=>{var i;const n={"application/pdf":"PDF","video/mp4":"Video MP4","audio/mpeg":"Audio MP3","audio/ogg":"Audio OGG","application/octet-stream":"Tệp đính kèm"};return t?n[t]??((i=t.split("/")[1])==null?void 0:i.toUpperCase())??"Tệp":"Tệp đính kèm"};function Oe({status:t}){return t==="read"?e.jsx(Ee,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):t==="delivered"?e.jsx(Ee,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle",opacity:.5}}):t==="sent"?e.jsx(qe,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):null}const It=o.forwardRef(function({apiUrl:n,token:i,theme:r,height:c,defaultConversationId:v,disableAttachments:m,disableNotificationSound:E,hideKeyboardHint:x,locale:b="vi",extensions:B,onNewMessage:w,onConversationSelect:z},R){var ae,me,d,g,y;const T=o.useRef(new Xe(n,i)),[M,X]=o.useState([]),[F,$]=o.useState([]),[A,V]=o.useState(),[S,K]=o.useState(),u=o.useRef(void 0),[k,G]=o.useState(""),[C,P]=o.useState({provider:"all",unreadOnly:!1}),[te,de]=o.useState(!1),j=o.useRef(null),Q=o.useRef(null),[J,ce]=o.useState(null),[ie,h]=o.useState(!0),[I,W]=o.useState(""),[N,ne]=o.useState(!1),[Y,O]=o.useState(260),[re,oe]=o.useState(!1),U=(r==null?void 0:r.primaryColor)??"#2563eb",_=o.useMemo(()=>new Map(F.map(l=>[l.id,l])),[F]),ue=o.useRef(null),[ge,Ie]=o.useState(0),ke=o.useMemo(()=>{const l=new Set(F.map(p=>p.provider));return["facebook","instagram","telegram","zalo","livechat"].filter(p=>l.has(p))},[F]),we=o.useMemo(()=>{var p;const l={};for(const H of M){const L=((p=_.get(H.connectionId))==null?void 0:p.provider)??"unknown";l[L]=(l[L]??0)+1}return l},[M,_]);function ye(l){const p=l.clientX,H=Y;oe(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none";function L(fe){const be=Math.max(200,Math.min(480,H+(p-fe.clientX)));O(be)}function Z(){oe(!1),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",Z)}document.addEventListener("mousemove",L),document.addEventListener("mouseup",Z)}const q=o.useCallback(async l=>{try{const p=await T.current.listConversations(l);X(H=>l?[...H,...p.items]:p.items),V(p.nextCursor),!l&&p.items.length&&K(H=>H??(v?p.items.find(L=>L.id===v)??p.items[0]:p.items[0])),W("")}catch(p){W(p instanceof Error?p.message:"Không tải được hội thoại")}finally{h(!1)}},[v]);o.useEffect(()=>(T.current.listConnections().then($).catch(()=>{}),q(),T.current.connectSSE((p,H)=>{if(p==="message.new"||p==="conversation.updated"){if(q(),p==="message.new"){const L=typeof H=="object"&&H?H:{},Z=L.conversationId?String(L.conversationId):"",fe=L.messageId?String(L.messageId):"";if((L.direction?String(L.direction):"")==="inbound"&&!E&&wt(),Z&&Z===u.current&&fe&&ue.current){const tt=ue.current;T.current.getMessage(fe).then(nt=>{tt(nt)}).catch(()=>{})}w==null||w(Z||u.current||"")}}else p==="message.status_updated"&&Ie(L=>L+1)})),[q,w]),o.useEffect(()=>{u.current=S==null?void 0:S.id},[S]),o.useEffect(()=>{S!=null&&S.unreadCount&&T.current.markRead(S.id).then(()=>q()).catch(()=>{})},[S==null?void 0:S.id]),o.useEffect(()=>{if(!te)return;function l(p){var H,L;(H=j.current)!=null&&H.contains(p.target)||(L=Q.current)!=null&&L.contains(p.target)||de(!1)}return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[te]);const he=o.useMemo(()=>{const l=k.toLowerCase().trim();return M.filter(p=>{var be;const H=`${p.contactName??""} ${p.subject??""} ${p.providerConversationKey}`.toLowerCase(),L=((be=_.get(p.connectionId))==null?void 0:be.provider)??"unknown",Z=C.provider==="all"||L===C.provider,fe=!C.unreadOnly||(p.unreadCount??0)>0;return Z&&fe&&(!l||H.includes(l))})},[M,_,C,k]),pe=C.provider!=="all"||C.unreadOnly,se=b==="en"?{today:"TODAY",loadOlder:"↑ Load older messages",loading:"Loading messages…",noMessages:"No messages in this conversation.",searchPlaceholder:"Search conversations…",unreadOnly:"Unread only",sendPlaceholder:"Write a message…",send:"Send",all:"All"}:{today:"HÔM NAY",loadOlder:"↑ Tải tin cũ hơn",loading:"Đang tải tin nhắn…",noMessages:"Chưa có tin nhắn trong hội thoại này.",searchPlaceholder:"Tìm kiếm hội thoại…",unreadOnly:"Chưa đọc",sendPlaceholder:"Viết tin nhắn…",send:"Gửi",all:"Tất cả"};o.useImperativeHandle(R,()=>({openConversation:l=>{const p=M.find(H=>H.id===l);p&&K(p)},refresh:()=>void q()}),[M,q]);const ze={...f.frame,height:c??620,...c?{maxHeight:"none"}:{},fontFamily:(r==null?void 0:r.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",borderRadius:(r==null?void 0:r.borderRadius)??"16px",gridTemplateColumns:N?`minmax(260px, 300px) minmax(0, 1fr) ${Y}px`:"minmax(260px, 300px) minmax(0, 1fr)",transition:re?"none":"grid-template-columns 220ms ease"};return ie?e.jsxs("div",{style:{...f.state,borderRadius:(r==null?void 0:r.borderRadius)??"16px"},children:[e.jsx(Be,{})," Đang tải hộp thư…"]}):I&&!M.length?e.jsxs("div",{style:{...f.state,color:"#b42318",borderRadius:(r==null?void 0:r.borderRadius)??"16px"},children:[e.jsx(lt,{size:16,strokeWidth:2})," ",I,e.jsx("button",{style:f.retry,onClick:()=>{h(!0),q()},children:"Thử lại"})]}):e.jsx(Le.Provider,{value:n,children:e.jsx(_e.Provider,{value:i,children:e.jsxs("div",{style:ze,onFocusCapture:()=>{const l=window.scrollY;requestAnimationFrame(()=>{window.scrollY!==l&&window.scrollTo({top:l,behavior:"instant"})})},children:[e.jsxs("aside",{style:f.sidebar,children:[e.jsxs("div",{style:f.brand,children:[e.jsx("div",{style:{...f.brandMark,background:U,overflow:"hidden",padding:0},children:(ae=r==null?void 0:r.branding)!=null&&ae.logoUrl?e.jsx("img",{src:r.branding.logoUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):((me=r==null?void 0:r.branding)==null?void 0:me.mark)??"C"}),e.jsxs("div",{children:[e.jsx("strong",{children:((d=r==null?void 0:r.branding)==null?void 0:d.name)??"Hộp thư"}),!((g=r==null?void 0:r.branding)!=null&&g.name)&&e.jsx("span",{style:f.eyebrow,children:"CHANNELHUB"})]}),e.jsx(mt,{"aria-label":"Tùy chọn",style:f.iconButton,children:e.jsx(Ve,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:f.search,children:[e.jsx(He,{size:16,strokeWidth:2}),e.jsx(bt,{"aria-label":se.searchPlaceholder,value:k,onChange:l=>G(l.target.value),placeholder:se.searchPlaceholder}),k&&e.jsx("button",{style:f.clear,onClick:()=>G(""),"aria-label":"Xóa tìm kiếm",children:"×"})]}),pe&&e.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",padding:"0 14px 8px"},children:[C.provider!=="all"&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:U,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[e.jsx(je,{provider:C.provider}),Ae(C.provider),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:U,padding:0,lineHeight:1,display:"flex"},onClick:()=>P(l=>({...l,provider:"all"})),"aria-label":"Xóa filter kênh",children:e.jsx(Se,{size:10})})]}),C.unreadOnly&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:U,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[se.unreadOnly,e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:U,padding:0,lineHeight:1,display:"flex"},onClick:()=>P(l=>({...l,unreadOnly:!1})),"aria-label":"Xóa filter chưa đọc",children:e.jsx(Se,{size:10})})]}),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:a.muted,fontSize:11,padding:"2px 4px"},onClick:()=>P({provider:"all",unreadOnly:!1}),children:"Xóa tất cả"})]}),e.jsxs("div",{style:f.listHeader,children:[e.jsxs("span",{children:[he.length," hội thoại"]}),e.jsx("button",{ref:j,style:{...f.iconButton,background:pe?`${U}14`:"transparent",color:pe?U:a.muted},"aria-label":"Bộ lọc",onClick:()=>{var l;if(!te){const p=(l=j.current)==null?void 0:l.getBoundingClientRect();p&&ce({top:p.bottom+6,left:p.left})}de(p=>!p)},children:e.jsx(xt,{size:15,strokeWidth:2})})]}),te&&J&&Ne.createPortal(e.jsxs("div",{ref:Q,style:{position:"fixed",top:J.top,left:J.left,zIndex:9999,background:a.white,border:`1px solid ${a.line}`,borderRadius:10,padding:"12px 14px",boxShadow:"0 8px 24px rgba(23,32,51,.14)",minWidth:210,fontFamily:(r==null?void 0:r.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",fontSize:13},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:a.muted,letterSpacing:1,textTransform:"uppercase",marginBottom:8},children:"Kênh"}),["all",...ke].map(l=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:C.provider===l?`${U}0f`:"transparent"},children:[e.jsx("input",{type:"radio",name:"provider-filter",checked:C.provider===l,onChange:()=>P(p=>({...p,provider:l})),style:{accentColor:U}}),l==="all"?e.jsxs("span",{style:{color:a.ink},children:[se.all," (",M.length,")"]}):e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,color:a.ink},children:[e.jsx(je,{provider:l}),Ae(l)," ",e.jsxs("span",{style:{color:a.muted},children:["(",we[l]??0,")"]})]})]},l)),e.jsx("div",{style:{borderTop:`1px solid ${a.line}`,margin:"8px 0 6px"}}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:C.unreadOnly?`${U}0f`:"transparent"},children:[e.jsx("input",{type:"checkbox",checked:C.unreadOnly,onChange:l=>P(p=>({...p,unreadOnly:l.target.checked})),style:{accentColor:U}}),e.jsx("span",{style:{color:a.ink},children:se.unreadOnly})]})]}),document.body),e.jsxs(Ye,{style:f.conversationList,children:[he.map(l=>{var p;return e.jsx(zt,{conversation:l,provider:(p=_.get(l.connectionId))==null?void 0:p.provider,selected:(S==null?void 0:S.id)===l.id,primary:U,onSelect:()=>{K(l),z==null||z(l.id),T.current.markRead(l.id).then(()=>q()).catch(()=>{})}},l.id)}),!he.length&&e.jsxs("div",{style:f.emptySmall,children:[e.jsx("div",{style:f.emptyIcon,children:e.jsx(He,{size:16,strokeWidth:2})}),e.jsx("strong",{children:"Không tìm thấy"}),e.jsx("span",{children:"Thử từ khóa hoặc bộ lọc khác."})]}),A&&e.jsx("button",{style:f.loadMore,onClick:()=>void q(A),children:"Xem thêm hội thoại"})]})]}),e.jsx("main",{style:f.main,children:S?e.jsx(Tt,{conversation:S,provider:(y=_.get(S.connectionId))==null?void 0:y.provider,connection:_.get(S.connectionId),client:T.current,primary:U,error:I,onRegisterAppend:l=>{ue.current=l},refreshKey:ge,infoOpen:N,onToggleInfo:()=>ne(l=>!l),t:se,disableAttachments:m,hideKeyboardHint:x,extensions:B},S.id):e.jsx(Lt,{})}),N&&S&&e.jsx(Bt,{conversation:S,connection:_.get(S.connectionId),primary:U,onClose:()=>ne(!1),client:T.current,onStartResize:ye,extensions:B})]})})})});function zt({conversation:t,provider:n,selected:i,primary:r,onSelect:c}){const[v,m]=o.useState(!1),E=t.contactName??t.subject??t.providerConversationKey,x=t.unreadCount??0,b=t.lastMessageText??"",B=t.lastMessageDirection==="outbound"?"Bạn: ":"",w=b.length>60?b.slice(0,60)+"…":b,z=b?B+w:"";let R="transparent";i?R="#eef2ff":v?R="#f7f9fc":x>0&&(R="#f0f4ff");const T={...f.row,background:R,...i?{boxShadow:`inset 3px 0 0 ${r}`}:x>0&&!v?{boxShadow:`inset 3px 0 0 ${r}`}:{}};return e.jsxs("button",{onClick:c,style:T,onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),children:[e.jsx(Qe,{name:E,color:r,image:t.contactPictureUrl,provider:n}),e.jsxs("span",{style:f.rowBody,children:[e.jsxs("span",{style:f.rowTop,children:[e.jsx("strong",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:x>0?700:500},children:E}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:[e.jsx("time",{style:{color:a.muted,fontSize:11,whiteSpace:"nowrap"},children:We(t.lastMessageAt)}),x>0&&e.jsx("span",{"aria-label":`${x} tin nhắn chưa đọc`,style:f.unreadBadge,children:x>99?"99+":x})]})]}),e.jsx("span",{style:{...f.rowBottom,color:x>0&&!i?"#4a5568":a.muted},children:e.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%"},children:z||e.jsx("span",{style:{opacity:.5},children:"Chưa có tin nhắn"})})})]})]})}function Tt({conversation:t,provider:n,connection:i,client:r,primary:c,error:v,onRegisterAppend:m,refreshKey:E,infoOpen:x,onToggleInfo:b,t:B,disableAttachments:w,hideKeyboardHint:z,extensions:R}){var me;const[T,M]=o.useState([]),[X,F]=o.useState(),[$,A]=o.useState(""),[V,S]=o.useState(!0),[K,u]=o.useState(!1),[k,G]=o.useState(""),C=o.useRef(null),P=t.contactName??t.subject??t.providerConversationKey,te=o.useRef(null),de=o.useRef(null),[j,Q]=o.useState(null),[J,ce]=o.useState(!1),[ie,h]=o.useState(!1),[I,W]=o.useState(!1),[N,ne]=o.useState(0),Y=o.useRef(null),O=o.useRef(null),re=o.useRef(null),[oe,U]=o.useState(!1),[_,ue]=o.useState(""),[ge,Ie]=o.useState([]),ke=o.useRef(null),we=o.useRef(null);o.useEffect(()=>()=>{j!=null&&j.objectUrl&&URL.revokeObjectURL(j.objectUrl)},[j==null?void 0:j.objectUrl]),o.useEffect(()=>{if(!I)return;function d(g){var y,l;(y=O.current)!=null&&y.contains(g.target)||(l=Y.current)!=null&&l.contains(g.target)||W(!1)}return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[I]),o.useEffect(()=>{r.listCannedResponses().then(Ie).catch(()=>{})},[r]),o.useEffect(()=>{if(!oe)return;function d(g){var y,l;(y=we.current)!=null&&y.contains(g.target)||(l=ke.current)!=null&&l.contains(g.target)||U(!1)}return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[oe]);const ye=o.useRef(!0),q=o.useCallback(async(d,g)=>{g||(ye.current=!d);try{const y=await r.listMessages(t.id,d);M(l=>d?[...y.items,...l]:y.items),F(y.nextCursor)}catch(y){G(y instanceof Error?y.message:"Không tải được tin nhắn")}finally{g||S(!1)}},[r,t.id]);o.useEffect(()=>{S(!0),q()},[q]),o.useEffect(()=>{E&&q(void 0,!0)},[E]),o.useEffect(()=>{ye.current&&requestAnimationFrame(()=>{const d=C.current;d&&(d.scrollTop=d.scrollHeight)})},[T]),o.useEffect(()=>(m==null||m(d=>{ye.current=!0,M(g=>g.some(y=>y.id===d.id)?g:[...g,d])}),()=>{m==null||m(null)}),[m]);async function he(d){var l;const g=(l=d.target.files)==null?void 0:l[0];if(!g)return;d.target.value="";const y=URL.createObjectURL(g);Q({file:g,uploading:!0,objectUrl:y});try{const p=await r.uploadAttachment(g);Q({file:g,uploading:!1,url:p.url,mimeType:p.mimeType,attachmentType:p.attachmentType,objectUrl:y})}catch{URL.revokeObjectURL(y),Q(null),G("Không tải lên được tệp đính kèm")}}async function pe(d){d.preventDefault();const g=$.trim(),y=j!=null&&j.url?[{url:j.url,mimeType:j.mimeType??"application/octet-stream",type:j.attachmentType}]:[];if(!(!g&&!y.length||K)){u(!0),G("");try{await r.sendMessage(t.id,g||void 0,y.length?y:void 0),j!=null&&j.objectUrl&&URL.revokeObjectURL(j.objectUrl),A(""),Q(null),await q()}catch(l){G(l instanceof Error?l.message:"Không gửi được tin nhắn")}finally{u(!1)}}}function se(d){const g=re.current;if(!g){A(H=>H+d),W(!1);return}const y=g.selectionStart??$.length,l=g.selectionEnd??$.length,p=$.slice(0,y)+d+$.slice(l);A(p),W(!1),requestAnimationFrame(()=>{g.focus(),g.selectionStart=g.selectionEnd=y+d.length})}function ze(d){A(d),U(!1),ue(""),requestAnimationFrame(()=>{const g=re.current;g&&(g.focus(),g.selectionStart=g.selectionEnd=d.length)})}const ae=!K&&($.trim().length>0||(j==null?void 0:j.url)!=null&&!j.uploading);return e.jsxs("section",{style:f.chat,children:[e.jsxs("header",{style:f.chatHeader,children:[e.jsx(Qe,{name:P,color:c,image:t.contactPictureUrl,provider:n}),e.jsxs("div",{style:f.contact,children:[e.jsx("strong",{style:f.contactName,children:P}),e.jsx("span",{style:f.contactMeta,children:St(i)??Ze(n)})]}),e.jsxs("div",{style:f.headerActions,children:[e.jsx("button",{style:f.iconButton,"aria-label":"Thêm tùy chọn",children:e.jsx(Ve,{size:16,strokeWidth:2})}),e.jsx("button",{style:{...f.iconButton,background:x?`${c}14`:"transparent",color:x?c:a.muted},"aria-label":"Thông tin liên hệ",onClick:b,children:e.jsx(ut,{size:16,strokeWidth:2})})]})]}),e.jsxs(Ye,{ref:C,style:f.messageArea,children:[e.jsx("div",{style:f.day,children:B.today}),X&&e.jsx("button",{onClick:()=>void q(X),style:f.historyButton,children:B.loadOlder}),V&&e.jsxs("div",{style:f.messageHint,children:[e.jsx(Be,{})," ",B.loading]}),!V&&!T.length&&e.jsx("div",{style:f.messageHint,children:B.noMessages}),T.map((d,g)=>{const y=(R==null?void 0:R.flatMap(p=>p.messageEnrichments??[]))??[],l=d.direction==="inbound"&&y.length>0&&g>=T.length-15;return e.jsxs("div",{children:[e.jsx(Rt,{message:d,primary:c}),l&&y.map((p,H)=>{var Z;const L=(Z=d.text)==null?void 0:Z.match(p.pattern);return L?e.jsx(kt,{children:p.render(L,Ce(t))},H):null})]},d.id)})]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",padding:"6px 14px 2px",borderTop:`1px solid ${a.line}`},children:["Cảm ơn bạn đã liên hệ 🙏","Mình sẽ kiểm tra ngay","Vui lòng chờ 1-2 phút"].map(d=>e.jsx("button",{type:"button",onClick:()=>A(d),style:{fontSize:11,padding:"3px 10px",borderRadius:999,background:`${c}0f`,color:c,border:`1px solid ${c}33`,cursor:"pointer",whiteSpace:"nowrap"},children:d},d))}),e.jsxs("form",{onSubmit:pe,style:{flex:"0 0 auto",padding:"8px 14px 12px",borderTop:`1px solid ${a.line}`,background:a.white,position:"relative"},children:[I&&e.jsxs("div",{ref:Y,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:a.white,border:`1px solid ${a.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:280,overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${a.line}`,background:"#f9fafb"},children:Me.map((d,g)=>e.jsx("button",{type:"button",onClick:()=>ne(g),style:{flex:1,border:0,background:"transparent",padding:"7px 2px",fontSize:16,cursor:"pointer",lineHeight:1,borderBottom:N===g?`2px solid ${c}`:"2px solid transparent",opacity:N===g?1:.5,transition:"opacity 100ms ease"},children:d.icon},g))}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:2,padding:8,maxHeight:180,overflowY:"auto"},children:(me=Me[N])==null?void 0:me.emojis.map((d,g)=>e.jsx("button",{type:"button",onClick:()=>se(d),style:{border:0,background:"transparent",padding:"5px 2px",fontSize:18,cursor:"pointer",borderRadius:6,lineHeight:1,transition:"background 80ms ease"},onMouseEnter:y=>{y.target.style.background="#f3f4f6"},onMouseLeave:y=>{y.target.style.background="transparent"},children:d},g))})]}),oe&&e.jsxs("div",{ref:ke,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:a.white,border:`1px solid ${a.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:300,overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{padding:"8px 10px",borderBottom:`1px solid ${a.line}`},children:e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Tìm template…",value:_,onChange:d=>ue(d.target.value),style:{width:"100%",boxSizing:"border-box",border:`1px solid ${a.line}`,borderRadius:7,padding:"5px 8px",fontSize:12,outline:"none",fontFamily:"inherit",color:a.ink}})}),e.jsx("div",{style:{maxHeight:220,overflowY:"auto"},children:(()=>{const d=_.trim().toLowerCase(),g=d?ge.filter(y=>y.title.toLowerCase().includes(d)||y.content.toLowerCase().includes(d)||(y.shortcut??"").toLowerCase().includes(d)):ge;return g.length?g.map(y=>e.jsxs("button",{type:"button",onClick:()=>ze(y.content),style:{display:"block",width:"100%",textAlign:"left",border:0,borderBottom:`1px solid ${a.line}`,background:"transparent",padding:"9px 12px",cursor:"pointer",fontFamily:"inherit"},onMouseEnter:l=>{l.currentTarget.style.background="#f7f9fc"},onMouseLeave:l=>{l.currentTarget.style.background="transparent"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:2},children:[e.jsx("span",{style:{fontSize:12,fontWeight:600,color:a.ink},children:y.title}),y.shortcut&&e.jsx("span",{style:{fontSize:10,color:c,background:`${c}18`,borderRadius:4,padding:"1px 5px"},children:y.shortcut})]}),e.jsx("div",{style:{fontSize:11,color:a.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y.content})]},y.id)):e.jsx("div",{style:{padding:"24px 16px",textAlign:"center",color:a.muted,fontSize:12},children:ge.length===0?"Chưa có template nào":"Không tìm thấy"})})()})]}),e.jsxs("div",{style:{border:`1.5px solid ${a.line}`,borderRadius:12,background:a.white,overflow:"hidden"},children:[j&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:`1px solid ${a.line}`,fontSize:12},children:[j.uploading?e.jsxs(e.Fragment,{children:[e.jsx(Be,{}),e.jsx("span",{style:{color:a.muted},children:"Đang tải lên…"})]}):j.attachmentType==="image"&&j.objectUrl?e.jsx("img",{src:j.objectUrl,alt:"",style:{height:48,width:48,objectFit:"cover",borderRadius:6}}):e.jsxs("span",{style:{color:a.muted},children:["📎 ",j.file.name," (",Math.round(j.file.size/1024)," KB)"]}),!j.uploading&&e.jsx("button",{type:"button",onClick:()=>{j!=null&&j.objectUrl&&URL.revokeObjectURL(j.objectUrl),Q(null)},style:{marginLeft:"auto",border:0,background:"none",color:a.muted,cursor:"pointer",fontSize:16},"aria-label":"Xóa tệp đính kèm",children:"✕"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 8px",borderBottom:"1px solid #f3f4f6"},children:[e.jsx("button",{ref:O,type:"button",title:"Chèn emoji",onClick:()=>W(d=>!d),style:{...f.toolbarBtn,background:I?`${c}18`:"transparent",color:I?c:"#9ca3af"},children:e.jsx(gt,{size:13,strokeWidth:2})}),!w&&e.jsx("button",{type:"button",title:"Gửi ảnh / video","aria-label":"Gửi ảnh hoặc video",style:f.toolbarBtn,onClick:()=>{var d;return(d=te.current)==null?void 0:d.click()},children:e.jsx(dt,{size:13,strokeWidth:2})}),!w&&e.jsx("button",{type:"button",title:"Gửi tệp đính kèm","aria-label":"Gửi tệp đính kèm",style:f.toolbarBtn,onClick:()=>{var d;return(d=de.current)==null?void 0:d.click()},children:e.jsx(ht,{size:13,strokeWidth:2})}),!w&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:te,type:"file",style:{display:"none"},onChange:he,accept:"image/*,video/mp4"}),e.jsx("input",{ref:de,type:"file",style:{display:"none"},onChange:he,accept:".pdf,audio/mpeg,audio/ogg,application/octet-stream,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"})]}),e.jsx("button",{ref:we,type:"button",title:"Template nhanh",onClick:()=>{U(d=>!d),ue("")},style:{...f.toolbarBtn,background:oe?`${c}18`:"transparent",color:oe?c:"#9ca3af"},children:e.jsx(yt,{size:13,strokeWidth:2})}),e.jsx("span",{style:{width:1,height:14,background:"#e5e7eb",margin:"0 2px"}}),e.jsx("button",{type:"button",title:"In đậm",onClick:()=>ce(d=>!d),style:{...f.toolbarBtn,fontWeight:700,fontSize:12,background:J?`${c}18`:"transparent",color:J?c:"#9ca3af",border:J?`1px solid ${c}33`:"1px solid transparent"},children:"B"}),e.jsx("button",{type:"button",title:"Nghiêng",onClick:()=>h(d=>!d),style:{...f.toolbarBtn,fontStyle:"italic",fontSize:12,background:ie?`${c}18`:"transparent",color:ie?c:"#9ca3af",border:ie?`1px solid ${c}33`:"1px solid transparent"},children:"I"}),R==null?void 0:R.flatMap(d=>d.toolbarActions??[]).map((d,g)=>e.jsx("button",{type:"button",title:d.tooltip,style:f.toolbarBtn,onClick:()=>{const y=l=>A(p=>p+l);d.onClick({...Ce(t),insertText:y})},children:d.icon},g))]}),e.jsx(vt,{ref:re,"aria-label":"Soạn tin nhắn",rows:2,value:$,onChange:d=>A(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),pe(d))},placeholder:B.sendPlaceholder,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",minHeight:52,maxHeight:120,resize:"none",border:0,outline:0,background:"transparent",color:a.ink,padding:"8px 12px 4px",font:"inherit",fontSize:13,lineHeight:1.45,fontStyle:ie?"italic":"normal",fontWeight:J?700:400}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 8px 6px 12px"},children:[e.jsxs("span",{style:{fontSize:11,color:$.length>1e3?"#ef4444":$.length>900?"#f59e0b":"#9ca3af",fontWeight:$.length>1e3?600:400},children:[$.length,"/1000"]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[!z&&e.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:"↵ Gửi · ⇧↵ Xuống dòng"}),e.jsxs("button",{disabled:!ae,"aria-label":"Gửi tin nhắn",style:{display:"flex",alignItems:"center",gap:5,padding:"5px 12px",border:0,borderRadius:999,fontSize:12,fontWeight:600,background:ae?`linear-gradient(135deg,${c},#0ea5e9)`:"#e5e7eb",color:ae?"#fff":"#9ca3af",cursor:ae?"pointer":"not-allowed",boxShadow:ae?"0 2px 8px rgba(37,99,235,0.25)":"none",transition:"all 150ms ease"},children:[K?e.jsx(Ge,{size:12,style:{animation:"channelhub-spin .7s linear infinite"}}):e.jsx(ft,{size:12,strokeWidth:2}),B.send]})]})]})]})]}),(k||v)&&e.jsx("div",{role:"alert",style:f.error,children:k||v})]})}function Rt({message:t,primary:n}){var $,A,V,S,K;const i=o.useContext(Le),r=o.useContext(_e),c=u=>u.startsWith("/v1/media/proxy")?`${i}${u}&tok=${encodeURIComponent(r)}`:u,v=t.direction==="outbound",m=(($=t.attachments)==null?void 0:$.filter(u=>u.type==="image"))??[],E=((A=t.attachments)==null?void 0:A.filter(u=>u.type==="sticker"))??[],x=((V=t.attachments)==null?void 0:V.filter(u=>u.type==="video"))??[],b=((S=t.attachments)==null?void 0:S.filter(u=>u.type==="audio"))??[],B=((K=t.attachments)==null?void 0:K.filter(u=>u.type==="file"))??[],[w,z]=o.useState(null),R=v?"flex-end":"flex-start",T=e.jsxs("time",{style:{display:"block",marginTop:4,fontSize:10,opacity:.65,textAlign:"right",letterSpacing:.2,userSelect:"none"},children:[We(t.occurredAt,!0),v&&e.jsxs(e.Fragment,{children:[" ",e.jsx(Oe,{status:t.status})]})]}),M=e.jsx("div",{style:{position:"absolute",bottom:6,right:8},children:e.jsxs("time",{style:{fontSize:10,color:"#fff",textShadow:"0 1px 3px rgba(0,0,0,.5)",letterSpacing:.2,userSelect:"none"},children:[We(t.occurredAt,!0),v&&e.jsxs(e.Fragment,{children:[" ",e.jsx(Oe,{status:t.status})]})]})}),X=v?{...f.bubbleOut,background:n,color:"#fff",border:"1px solid transparent"}:f.bubbleIn,F=!t.text&&b.length===0&&B.length===0;return e.jsxs("div",{style:{...f.messageLine,justifyContent:R,flexDirection:"column",alignItems:R},children:[E.map((u,k)=>e.jsxs("div",{style:{position:"relative",marginBottom:2},children:[e.jsx("img",{src:c(u.url),alt:"sticker",style:{display:"block",maxWidth:128,maxHeight:128,objectFit:"contain"}}),F&&m.length===0&&x.length===0&&k===E.length-1&&M]},`s${k}`)),m.map((u,k)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"zoom-in"},onClick:()=>z({url:c(u.url),kind:"image"}),children:[e.jsx("img",{src:c(u.url),alt:"",style:{display:"block",maxWidth:260,maxHeight:260,borderRadius:12,objectFit:"cover"}}),F&&k===m.length-1&&x.length===0&&M]},k)),x.map((u,k)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"pointer"},onClick:()=>z({url:c(u.url),kind:"video"}),children:[e.jsx("video",{src:c(u.url),style:{display:"block",maxWidth:260,maxHeight:200,borderRadius:12,objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:12,background:"rgba(0,0,0,.25)"},children:e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",background:"rgba(255,255,255,.9)",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(pt,{size:16,fill:"#172033",color:"#172033",style:{marginLeft:2}})})}),F&&k===x.length-1&&M]},k)),(b.length>0||B.length>0||t.text||!m.length&&!x.length&&!E.length&&!t.text)&&e.jsxs("div",{style:X,children:[b.map((u,k)=>e.jsx("audio",{src:c(u.url),controls:!0,style:{display:"block",width:"100%",marginBottom:4}},k)),B.map((u,k)=>e.jsxs("a",{href:c(u.url),target:"_blank",rel:"noreferrer",style:{display:"block",fontSize:12,color:v?"#fff":"#2563eb",textDecoration:"underline",marginBottom:4},children:["📎 ",Ct(u.mimeType)]},k)),t.text&&e.jsx("p",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t.text}),!b.length&&!B.length&&!t.text&&e.jsx("p",{style:{margin:0,opacity:.5},children:"[attachment]"}),T]}),w&&Ne.createPortal(e.jsxs("div",{onClick:()=>z(null),style:{position:"fixed",inset:0,zIndex:1e4,background:"rgba(0,0,0,.88)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"zoom-out"},children:[w.kind==="image"?e.jsx("img",{src:w.url,alt:"",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,objectFit:"contain",boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:u=>u.stopPropagation()}):e.jsx("video",{src:w.url,controls:!0,autoPlay:!0,style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:u=>u.stopPropagation()}),e.jsx("button",{onClick:()=>z(null),style:{position:"absolute",top:16,right:16,background:"rgba(255,255,255,.15)",border:"none",borderRadius:"50%",width:36,height:36,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff"},children:e.jsx(Se,{size:18})})]}),document.body)]})}function Bt({conversation:t,connection:n,primary:i,onClose:r,client:c,onStartResize:v,extensions:m}){const E=t.contactName??t.subject??t.providerConversationKey,x=n==null?void 0:n.provider,[b,B]=o.useState({channel:!0,stats:!1,extra:!1}),w=u=>B(k=>({...k,[u]:!k[u]})),[z,R]=o.useState(""),[T,M]=o.useState(!1),[X,F]=o.useState(!1),[$,A]=o.useState(""),[V,S]=o.useState([]);o.useEffect(()=>{R(""),F(!1),A(""),c.getNote(t.id).then(u=>{u&&R(u.content)}).catch(()=>{})},[t.id,c]),o.useEffect(()=>{if(!(m!=null&&m.some(k=>k.contactInfoRows)))return;const u=Ce(t);S([]),Promise.allSettled(m.filter(k=>k.contactInfoRows).map(k=>k.contactInfoRows(u))).then(k=>{const G=k.filter(C=>C.status==="fulfilled").flatMap(C=>C.value);S(G)})},[t.id,m]);async function K(){if(!(!z.trim()||T)){M(!0),A("");try{await c.upsertNote(t.id,z.trim()),F(!0),setTimeout(()=>F(!1),2e3)}catch{A("Lưu thất bại")}finally{M(!1)}}}return e.jsxs("aside",{style:{...f.infoPanel,position:"relative"},children:[e.jsx("div",{onMouseDown:v,style:{position:"absolute",left:0,top:0,bottom:0,width:4,cursor:"col-resize",zIndex:1},onMouseEnter:u=>{u.currentTarget.style.background="rgba(0,0,0,0.07)"},onMouseLeave:u=>{u.currentTarget.style.background=""}}),e.jsxs("div",{style:f.infoPanelHeader,children:[e.jsx("span",{style:{fontWeight:600,fontSize:13,color:a.ink},children:"Thông tin liên hệ"}),e.jsx("button",{style:f.iconButton,onClick:r,"aria-label":"Đóng",children:e.jsx(Se,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:{overflowY:"auto",flex:1},children:[e.jsxs("div",{style:f.infoPanelIdentity,children:[e.jsxs("span",{style:{...f.avatarWrap,width:48,height:48},children:[e.jsx(Je,{src:t.contactPictureUrl,fallback:et(E),style:{...f.avatar,width:48,height:48,fontSize:16}}),e.jsx("span",{style:{...f.providerBadge,width:20,height:20},children:e.jsx(je,{provider:x})})]}),e.jsx("strong",{style:{marginTop:10,fontSize:15,color:a.ink,textAlign:"center"},children:E}),e.jsx("span",{style:{fontSize:11,color:a.muted,fontFamily:"monospace",textAlign:"center"},children:t.providerConversationKey})]}),e.jsxs(Te,{label:"KÊNH",sectionKey:"channel",expanded:b.channel,onToggle:()=>w("channel"),children:[e.jsx(ee,{label:"Nền tảng",children:e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5},children:[e.jsx(je,{provider:x}),e.jsx("span",{children:Ze(x)})]})}),e.jsxs(ee,{label:"ID hội thoại",children:[e.jsxs("span",{style:{fontFamily:"monospace",fontSize:11},children:[t.id.slice(0,8),"…"]}),e.jsx(Wt,{value:t.id})]})]}),e.jsxs(Te,{label:"THỐNG KÊ",sectionKey:"stats",expanded:b.stats,onToggle:()=>w("stats"),children:[e.jsx(ee,{label:"Tin nhắn",value:String(t.messageCount??0)}),(t.unreadCount??0)>0&&e.jsx(ee,{label:"Chưa đọc",value:String(t.unreadCount),valueColor:"#ef4444"}),e.jsx(ee,{label:"Gần nhất",value:t.lastMessageAt?new Date(t.lastMessageAt).toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit",year:"numeric"}):"—"}),e.jsx(ee,{label:"Lần đầu",value:"—"})]}),e.jsxs(Te,{label:"THÔNG TIN BỔ SUNG",sectionKey:"extra",expanded:b.extra,onToggle:()=>w("extra"),children:[e.jsx(ee,{label:"Điện thoại",value:"— chưa có",valueMuted:!0}),e.jsx(ee,{label:"Email",value:"— chưa có",valueMuted:!0}),e.jsx(ee,{label:"Nhãn",value:"— chưa có",valueMuted:!0}),V.map(u=>e.jsx(ee,{label:u.label,children:u.href?e.jsx("a",{href:u.href,target:"_blank",rel:"noopener noreferrer",style:{color:i,fontSize:12},children:u.value}):e.jsx("span",{style:{fontSize:12},children:u.value})},u.label))]}),e.jsxs("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:8},children:[e.jsx("button",{style:{...f.ghostButton,color:i,borderColor:`${i}33`},children:"Xem lịch sử"}),m==null?void 0:m.flatMap(u=>u.sidebarActions??[]).map((u,k)=>e.jsxs("button",{style:{...f.ghostButton,color:a.ink,borderColor:a.line,display:"flex",alignItems:"center",justifyContent:"center",gap:6},onClick:()=>{u.onClick(Ce(t))},children:[u.icon,u.label]},k)),e.jsxs("div",{style:{border:"1.5px solid #000",borderRadius:10,background:"#fff",overflow:"hidden"},children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid #fde68a",fontSize:11,fontWeight:600,color:"#92400e"},children:"Ghi chú nội bộ"}),e.jsx("textarea",{value:z,onChange:u=>R(u.target.value),placeholder:"Nhập ghi chú...",rows:3,style:{display:"block",width:"100%",boxSizing:"border-box",border:0,outline:0,background:"transparent",resize:"none",padding:"8px 10px",font:"inherit",fontSize:12,color:a.ink,lineHeight:1.5}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 10px 6px"},children:[X?e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,fontSize:11,color:"#16a34a"},children:[e.jsx(qe,{size:11,strokeWidth:2.5})," Đã lưu"]}):$?e.jsx("span",{style:{fontSize:11,color:"#ef4444"},children:$}):e.jsx("span",{}),e.jsx("button",{type:"button",onClick:()=>{K()},disabled:!z.trim()||T,style:{padding:"4px 12px",border:0,borderRadius:7,fontSize:12,fontWeight:600,background:z.trim()&&!T?"linear-gradient(135deg,#f59e0b,#fbbf24)":"#e5e7eb",color:z.trim()&&!T?"#fff":"#9ca3af",cursor:z.trim()&&!T?"pointer":"not-allowed"},children:T?"Đang lưu…":"Lưu ghi chú"})]})]})]})]})]})}function Te({label:t,children:n,sectionKey:i,expanded:r,onToggle:c}){const v=!!c,m=r??!0;return e.jsxs("div",{style:{borderTop:`1px solid ${a.line}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px 6px",fontSize:10,fontWeight:700,letterSpacing:1,color:a.muted,textTransform:"uppercase",cursor:v?"pointer":"default"},onClick:c,children:[e.jsx("span",{children:t}),v&&(m?e.jsx(st,{size:12,strokeWidth:2}):e.jsx(at,{size:12,strokeWidth:2}))]}),m&&n]})}function ee({label:t,value:n,children:i,valueColor:r,valueMuted:c}){return e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"3px 16px",fontSize:12,gap:8},children:[e.jsx("span",{style:{color:a.muted,flexShrink:0},children:t}),e.jsx("span",{style:{color:r??(c?a.muted:a.ink),textAlign:"right",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:4},children:i??n})]})}function Wt({value:t}){const[n,i]=o.useState(!1);return e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:a.muted,padding:2,lineHeight:1},title:"Sao chép",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{i(!0),setTimeout(()=>i(!1),1500)})},"aria-label":"Sao chép ID",children:n?"✓":"⎘"})}function Lt(){return e.jsxs("div",{style:f.empty,children:[e.jsx("div",{style:f.emptyHero,children:e.jsx(ct,{size:16,strokeWidth:2})}),e.jsx("h2",{children:"Chọn một hội thoại"}),e.jsx("p",{children:"Chọn hội thoại bên trái để xem và trả lời tin nhắn."})]})}function Qe({name:t,color:n,image:i,provider:r}){return e.jsxs("span",{style:f.avatarWrap,children:[e.jsx($t,{name:t,color:n,image:i}),r&&e.jsx("span",{style:f.providerBadge,children:e.jsx(je,{provider:r})})]})}function $t({name:t,color:n,image:i}){return e.jsx(Je,{src:i,fallback:et(t),style:{...f.avatar,background:`${n}18`,color:n}})}function Be(){return e.jsx(Ge,{size:14,style:f.spinner,"aria-hidden":"true"})}function et(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}const Et={livechat:"web"};function je({provider:t}){const n=o.useContext(Le),i=14;if(!t)return null;const r=Et[t]??t;return e.jsx("img",{src:`${n}/static/logos/${r}.avif`,alt:t,width:i,height:i,style:{borderRadius:"50%",objectFit:"cover",display:"block"}})}function We(t,n=!1){if(!t)return"";const i=new Date(t);return i.toDateString()===new Date().toDateString()?i.toLocaleTimeString("vi-VN",{hour:"2-digit",minute:"2-digit"}):i.toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit"})}const f={frame:{display:"grid",gridTemplateRows:"minmax(0, 1fr)",height:620,maxHeight:"calc(100dvh - 220px)",minHeight:0,overflow:"hidden",border:`1px solid ${a.line}`,background:a.white,color:a.ink,boxShadow:"0 18px 50px rgba(31,45,72,.10)"},sidebar:{display:"flex",flexDirection:"column",minWidth:0,minHeight:0,borderRight:`1px solid ${a.line}`,background:a.white},brand:{display:"flex",alignItems:"center",gap:10,padding:"20px 18px 16px"},brandMark:{display:"grid",placeItems:"center",width:32,height:32,borderRadius:10,color:"#fff",fontWeight:800},eyebrow:{display:"block",marginTop:2,fontSize:9,letterSpacing:1.3,color:a.muted},iconButton:{display:"inline-grid",placeItems:"center",width:32,height:32,marginLeft:"auto",border:0,borderRadius:8,background:"transparent",color:a.muted,cursor:"pointer"},search:{display:"flex",alignItems:"center",gap:8,margin:"0 14px 12px",padding:"9px 10px",border:`1px solid ${a.line}`,borderRadius:9,color:a.muted,background:a.surface},clear:{border:0,background:"none",color:a.muted,cursor:"pointer",fontSize:18},listHeader:{display:"flex",alignItems:"center",padding:"10px 18px",borderTop:`1px solid ${a.line}`,borderBottom:`1px solid ${a.line}`,color:a.muted,fontSize:11,fontWeight:700,letterSpacing:.4,textTransform:"uppercase"},conversationList:{overflowY:"auto",flex:1,minHeight:0},row:{display:"flex",width:"100%",gap:11,padding:"10px 14px",border:0,borderBottom:`1px solid ${a.line}`,background:"transparent",textAlign:"left",cursor:"pointer",transition:"background 120ms ease"},avatarWrap:{position:"relative",flex:"0 0 auto",width:38,height:38},avatar:{flex:"0 0 auto",width:38,height:38,display:"grid",placeItems:"center",borderRadius:"50%",objectFit:"cover",fontSize:12,fontWeight:800},providerBadge:{position:"absolute",left:-3,bottom:-3,display:"grid",placeItems:"center",width:17,height:17,border:"2px solid #fff",borderRadius:"50%",background:"#fff",color:"#64748b"},rowBody:{minWidth:0,flex:1},rowTop:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:8,fontSize:13},rowBottom:{display:"flex",marginTop:4,fontSize:11,minWidth:0,overflow:"hidden",lineHeight:1.4},unreadBadge:{display:"inline-grid",placeItems:"center",minWidth:18,height:18,borderRadius:999,background:"#ef4444",color:"#fff",fontSize:10,fontWeight:800,padding:"0 5px"},loadMore:{width:"100%",border:0,background:"transparent",color:"#4c72ca",padding:14,cursor:"pointer",fontSize:12},emptySmall:{display:"grid",justifyItems:"center",gap:7,padding:"56px 24px",color:a.muted,fontSize:12,textAlign:"center"},emptyIcon:{display:"grid",placeItems:"center",width:40,height:40,borderRadius:12,background:a.surface},main:{minWidth:0,minHeight:0,overflow:"hidden",background:a.surface},chat:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},chatHeader:{flex:"0 0 auto",display:"flex",alignItems:"center",gap:10,padding:"0 16px 0 18px",height:56,borderBottom:`1px solid ${a.line}`,background:a.white},contact:{display:"grid",gap:3,minWidth:0,flex:1},contactName:{fontSize:14,fontWeight:600,color:a.ink,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},contactMeta:{display:"flex",alignItems:"center",gap:5,fontSize:11,color:a.muted},headerActions:{display:"flex",gap:2,marginLeft:"auto"},messageArea:{flex:1,minHeight:0,overflowY:"auto",overscrollBehavior:"contain",padding:"20px clamp(16px,5vw,56px)",background:"linear-gradient(180deg,#f9fbfe 0%,#f4f7fb 100%)"},day:{margin:"0 auto 18px",color:"#a1acbb",fontSize:10,letterSpacing:1.2,fontWeight:700,textAlign:"center"},historyButton:{display:"block",margin:"0 auto 18px",border:`1px solid ${a.line}`,borderRadius:20,padding:"6px 12px",background:a.white,color:a.muted,cursor:"pointer",fontSize:11},messageHint:{display:"flex",justifyContent:"center",alignItems:"center",gap:8,padding:40,color:a.muted,fontSize:12},messageLine:{display:"flex",marginBottom:10},bubbleOut:{maxWidth:"min(70%,480px)",padding:"9px 13px",borderRadius:"14px 14px 3px 14px",boxShadow:"0 2px 5px rgba(30,43,65,.03)",fontSize:14,lineHeight:1.55},bubbleIn:{maxWidth:"min(70%,480px)",padding:"9px 13px",borderRadius:"14px 14px 14px 3px",border:`1px solid ${a.line}`,background:a.surface,boxShadow:"0 2px 5px rgba(30,43,65,.03)",fontSize:14,lineHeight:1.55},error:{padding:"8px 18px",background:"#fff2f0",color:"#b42318",fontSize:12},empty:{display:"grid",placeItems:"center",alignContent:"center",height:"100%",padding:30,textAlign:"center",color:a.muted},emptyHero:{display:"grid",placeItems:"center",width:64,height:64,marginBottom:16,borderRadius:20,background:"#eaf0ff",color:"#5277d7"},state:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,minHeight:180,border:`1px solid ${a.line}`,background:a.white,color:a.muted,fontSize:13},retry:{border:0,borderRadius:7,padding:"7px 10px",background:"#eff4ff",color:"#315dbb",cursor:"pointer"},spinner:{display:"inline-block",width:14,height:14,border:"2px solid #dbe3f3",borderTopColor:"#5277d7",borderRadius:"50%",animation:"channelhub-spin .7s linear infinite"},toolbarBtn:{display:"inline-grid",placeItems:"center",width:26,height:26,border:"1px solid transparent",borderRadius:6,background:"transparent",color:"#9ca3af",cursor:"pointer",padding:0,lineHeight:1},infoPanel:{display:"flex",flexDirection:"column",borderLeft:`1px solid ${a.line}`,background:a.white,minHeight:0,overflow:"hidden"},infoPanelHeader:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 16px 12px",borderBottom:`1px solid ${a.line}`,flex:"0 0 auto"},infoPanelIdentity:{display:"flex",flexDirection:"column",alignItems:"center",padding:"20px 16px 16px",gap:4},ghostButton:{width:"100%",padding:"8px 12px",border:`1px solid ${a.line}`,borderRadius:8,background:"transparent",fontSize:12,cursor:"pointer",textAlign:"center"}},Ht={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"},Mt={facebook:"facebook",instagram:"instagram",telegram:"telegram",zalo:"zalo",livechat:"web",whatsapp:"web"};function le({provider:t,apiUrl:n,size:i=40}){const r=Ht[t]??"#f1f5f9",c=Mt[t],v=n.replace(/\/$/,"");return e.jsx("div",{style:{width:i,height:i,borderRadius:Math.round(i*.28),background:r,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,overflow:"hidden"},children:c?e.jsx("img",{src:`${v}/static/logos/${c}.avif`,alt:t,width:Math.round(i*.65),height:Math.round(i*.65),style:{objectFit:"contain",display:"block"}}):e.jsx("span",{style:{fontSize:Math.round(i*.45),fontWeight:700,color:"#64748b",textTransform:"uppercase"},children:t.slice(0,1)})})}const ve={facebook:"Facebook",zalo:"Zalo OA",instagram:"Instagram",telegram:"Telegram",livechat:"Live Chat",whatsapp:"WhatsApp"},At={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"};function $e(t){const n=t.metadata;return String(n.displayName??n.pageName??n.username??n.name??t.externalAccountId)}function Ot(t){const n=ve[t.provider]??t.provider,i=String(t.metadata.username??t.metadata.pageName??"");return i?`${n} · ${i}`:n}const s={root:{background:"#fff",borderRadius:16,boxShadow:"0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06)",overflow:"hidden",minWidth:320,width:"100%",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif",fontSize:14,color:"#0f172a"},header:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},headerLeft:{display:"flex",alignItems:"center",gap:10},title:{fontSize:16,fontWeight:700,color:"#0f172a",lineHeight:1.3},subtitle:{fontSize:12,color:"#94a3b8",marginTop:1},divider:{height:1,background:"#f1f5f9",margin:"16px 0 0"},body:{padding:"16px 24px 24px"},backBtn:{width:32,height:32,borderRadius:8,border:"1px solid #e2e8f0",background:"#fff",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:"#475569",flexShrink:0},addBtn:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",borderRadius:8,border:"none",background:"#2563eb",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},errorBanner:{margin:"12px 24px 0",padding:"10px 14px",borderRadius:10,background:"#fef2f2",border:"1px solid #fecaca",color:"#dc2626",fontSize:13},channelItem:{display:"flex",alignItems:"center",gap:12,padding:"12px 14px",borderRadius:12,border:"1px solid #f1f5f9",background:"#fafafa",marginBottom:8},channelInfo:{flex:1,minWidth:0},channelName:{fontSize:14,fontWeight:600,color:"#0f172a",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},channelMeta:{fontSize:12,color:"#94a3b8",marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},channelActions:{display:"flex",alignItems:"center",gap:8,flexShrink:0},badgeActive:{fontSize:11,fontWeight:600,padding:"2px 8px",borderRadius:999,background:"#d1fae5",color:"#059669"},badgeInactive:{fontSize:11,fontWeight:600,padding:"2px 8px",borderRadius:999,background:"#f1f5f9",color:"#94a3b8"},disconnectBtn:{fontSize:12,fontWeight:500,padding:"5px 10px",borderRadius:7,border:"1px solid #e2e8f0",background:"#fff",color:"#64748b",cursor:"pointer"},providerGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(130px, 1fr))",gap:10},providerCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"16px 12px 14px",borderRadius:12,borderWidth:"1.5px",borderStyle:"solid",borderColor:"#f1f5f9",background:"#fafafa",cursor:"pointer",textAlign:"center",boxShadow:"none",transform:"none"},providerName:{fontSize:13,fontWeight:600,color:"#0f172a",lineHeight:1.2},providerDesc:{fontSize:11,color:"#94a3b8",lineHeight:1.4},connectHeader:{display:"flex",alignItems:"center",gap:12,padding:"20px 24px 16px",borderBottom:"1px solid #f1f5f9"},connectTitle:{fontSize:15,fontWeight:700,color:"#0f172a"},connectDesc:{fontSize:12,color:"#94a3b8",marginTop:2,lineHeight:1.5},form:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},field:{display:"flex",flexDirection:"column",gap:6},label:{fontSize:13,fontWeight:600,color:"#374151"},labelHint:{fontSize:11,fontWeight:400,color:"#94a3b8",marginLeft:4},input:{padding:"9px 12px",borderRadius:8,border:"1.5px solid #e2e8f0",fontSize:13,color:"#0f172a",background:"#fff",outline:"none",fontFamily:"inherit",width:"100%",boxSizing:"border-box"},inputHint:{fontSize:11,color:"#94a3b8",lineHeight:1.5},infoBox:{display:"flex",gap:8,padding:"10px 12px",borderRadius:8,background:"#eff6ff",border:"1px solid #bfdbfe",color:"#1e40af",fontSize:13,lineHeight:1.5},formActions:{display:"flex",gap:8,flexWrap:"wrap"},btnPrimary:{flex:1,minWidth:120,padding:"10px 16px",borderRadius:9,border:"none",background:"#2563eb",color:"#fff",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"},btnSecondary:{padding:"10px 16px",borderRadius:9,border:"1.5px solid #e2e8f0",background:"#fff",color:"#64748b",fontSize:14,fontWeight:500,cursor:"pointer",fontFamily:"inherit"},resultBanner:{display:"flex",alignItems:"flex-start",gap:10,padding:"12px 14px",borderRadius:10,background:"#f0fdf4",border:"1px solid #bbf7d0",fontSize:13,color:"#166534",lineHeight:1.5},codeLabel:{fontSize:11,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:".05em",marginBottom:6},codeBlock:{background:"#0f172a",borderRadius:10,padding:"14px 16px",position:"relative",overflowX:"auto"},codePre:{fontFamily:"'JetBrains Mono', 'Fira Code', 'Courier New', monospace",fontSize:11.5,lineHeight:1.6,color:"#e2e8f0",whiteSpace:"pre-wrap",wordBreak:"break-all",margin:0},copyBtn:{position:"absolute",top:10,right:10,display:"flex",alignItems:"center",gap:4,padding:"4px 10px",borderRadius:6,border:"1px solid #334155",background:"#1e293b",color:"#94a3b8",fontSize:11,fontWeight:500,cursor:"pointer",fontFamily:"inherit"},secretRow:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",borderRadius:8,background:"#fefce8",border:"1px solid #fef08a"},secretLabel:{fontSize:12,fontWeight:600,color:"#854d0e",whiteSpace:"nowrap"},secretValue:{fontFamily:"'JetBrains Mono', monospace",fontSize:12,color:"#0f172a",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},oauthWaiting:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"40px 24px 48px",gap:16,textAlign:"center"},oauthTitle:{fontSize:16,fontWeight:700,color:"#0f172a"},oauthDesc:{fontSize:13,color:"#64748b",lineHeight:1.6,maxWidth:300},oauthCancel:{marginTop:8,padding:"10px 20px",borderRadius:9,border:"1.5px solid #e2e8f0",background:"#fff",color:"#64748b",fontSize:14,fontWeight:500,cursor:"pointer",fontFamily:"inherit"},empty:{display:"flex",flexDirection:"column",alignItems:"center",padding:"40px 24px 48px",gap:12,textAlign:"center"},emptyTitle:{fontSize:15,fontWeight:700,color:"#0f172a"},emptyDesc:{fontSize:13,color:"#94a3b8",lineHeight:1.6,maxWidth:280},emptyCta:{marginTop:4,display:"flex",alignItems:"center",gap:6,padding:"10px 20px",borderRadius:9,border:"none",background:"#2563eb",color:"#fff",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"inherit"}};function Ue(){return e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:e.jsx("path",{d:"M7 1v12M1 7h12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}function xe(){return e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:e.jsx("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round"})})}function De(){return e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[e.jsx("rect",{x:"4",y:"4",width:"7",height:"7",rx:"1.5",stroke:"currentColor",strokeWidth:"1.3"}),e.jsx("path",{d:"M2.5 8H2a1 1 0 01-1-1V2a1 1 0 011-1h5a1 1 0 011 1v.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})]})}function Fe(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:e.jsx("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function Ut(){return e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{flexShrink:0},children:[e.jsx("circle",{cx:"5",cy:"6",r:"3.5",stroke:"#ca8a04",strokeWidth:"1.4"}),e.jsx("path",{d:"M8 7.5l4.5 4.5M10.5 10l1.5 1.5",stroke:"#ca8a04",strokeWidth:"1.4",strokeLinecap:"round"})]})}function Dt(){return e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{flexShrink:0,marginTop:1},children:[e.jsx("circle",{cx:"7",cy:"7",r:"6",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M7 6v5M7 4.5v.01",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}let Pe=!1;function Ft(){if(Pe||typeof document>"u")return;Pe=!0;const t=document.createElement("style");t.textContent="@keyframes ch-spin{to{transform:rotate(360deg)}}",document.head.appendChild(t)}function Pt({apiUrl:t,token:n,onConnectionChange:i}){const r=t.replace(/\/$/,""),[c,v]=o.useState([]),[m,E]=o.useState(!0),[x,b]=o.useState({name:"list"}),[B,w]=o.useState(null),[z,R]=o.useState(!1),[T,M]=o.useState(""),[X,F]=o.useState(""),[$,A]=o.useState(""),[V,S]=o.useState(""),[K,u]=o.useState(!1),[k,G]=o.useState(!1),C=o.useRef(null);Ft();const P=o.useCallback(async()=>{try{const h=await fetch(`${r}/v1/connections`,{headers:{authorization:`Bearer ${n}`}});if(!h.ok)throw new Error("Không tải được kênh");const I=await h.json();v(I),i==null||i(I)}catch(h){w(h instanceof Error?h.message:"Lỗi tải dữ liệu")}finally{E(!1)}},[r,n,i]);o.useEffect(()=>{P()},[P]),o.useEffect(()=>{if(!B)return;const h=setTimeout(()=>w(null),5e3);return()=>clearTimeout(h)},[B]),o.useEffect(()=>()=>{C.current&&window.removeEventListener("message",C.current)},[]);async function te(h,I){if(confirm(`Bạn chắc chắn muốn ngắt kết nối "${I}"?
|
|
112
112
|
|
|
113
|
-
Hành động này không thể hoàn tác.`))try{if(!(await fetch(`${r}/v1/connections/${
|
|
114
|
-
https://www.myshop.com`,spellCheck:!1}),e.jsx("div",{style:
|
|
113
|
+
Hành động này không thể hoàn tác.`))try{if(!(await fetch(`${r}/v1/connections/${h}`,{method:"DELETE",headers:{authorization:`Bearer ${n}`}})).ok)throw new Error("Không thể ngắt kết nối");await P()}catch(W){w(W instanceof Error?W.message:"Lỗi ngắt kết nối")}}async function de(){if(!T.trim()){w("Vui lòng nhập Bot Token");return}if(!/^\d+:[A-Za-z0-9_-]+$/.test(T.trim())){w("Token không đúng định dạng");return}R(!0),w(null);try{const h=await fetch(`${r}/v1/connect/telegram/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({botToken:T.trim(),displayName:X.trim()||void 0})}),I=await h.json();if(!h.ok||!I.connectionId)throw new Error(I.message??"Không thể kết nối Telegram");M(""),F(""),await P(),b({name:"list"})}catch(h){w(h instanceof Error?h.message:"Lỗi kết nối")}finally{R(!1)}}async function j(){if(!$.trim()){w("Vui lòng nhập tên widget");return}R(!0),w(null);try{const h=V.split(/[\n,]+/).map(N=>N.trim()).filter(Boolean),I=await fetch(`${r}/v1/connect/livechat/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({displayName:$.trim(),allowedDomains:h.length?h:void 0})}),W=await I.json();if(!I.ok||!W.connectionId||!W.embedScript)throw new Error(W.message??"Không thể tạo widget");A(""),S(""),await P(),b({name:"livechat-result",connectionId:W.connectionId,embedScript:W.embedScript,identitySecret:W.identitySecret??"",allowedDomains:W.allowedDomains??[]})}catch(h){w(h instanceof Error?h.message:"Lỗi tạo widget")}finally{R(!1)}}async function Q(h){w(null);try{const I=`${r}/static/oauth-popup.html`,W=await fetch(`${r}/v1/connect/${h}/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({callbackUrl:I})}),N=await W.json();if(!W.ok||!N.authorizationUrl)throw new Error(N.message??"Không thể bắt đầu kết nối");const ne=window.open(N.authorizationUrl,"channelhub-oauth","width=600,height=700,scrollbars=yes,resizable=yes");b({name:"oauth-waiting",provider:h,popup:ne}),C.current&&window.removeEventListener("message",C.current);const Y=O=>{if(O.data){if(O.data.type==="channelhub:oauth-select"){b({name:"oauth-select",provider:O.data.provider,sessionId:String(O.data.sessionId??""),pages:O.data.pages??[],popup:ne});return}O.data.type==="channelhub:oauth"&&(window.removeEventListener("message",Y),C.current=null,O.data.status==="active"?(P(),b({name:"list"})):(w("Kết nối thất bại: "+String(O.data.error??"Không xác định")),b({name:"list"})))}};C.current=Y,window.addEventListener("message",Y)}catch(I){w(I instanceof Error?I.message:"Lỗi kết nối"),b({name:"list"})}}function J(h,I){navigator.clipboard.writeText(h).then(()=>{I==="script"?(u(!0),setTimeout(()=>u(!1),2e3)):(G(!0),setTimeout(()=>G(!1),2e3))})}function ce(){const h=x.name==="oauth-waiting"||x.name==="oauth-select"?x.popup:null;if(h)try{h.close()}catch{}C.current&&(window.removeEventListener("message",C.current),C.current=null),b({name:"add"})}async function ie(h){if(x.name!=="oauth-select")return;const{provider:I,sessionId:W,popup:N}=x;R(!0),w(null);const ne={facebook:`${r}/v1/connect/facebook/select-page`,instagram:`${r}/v1/connect/instagram/select-account`,zalo:`${r}/v1/connect/zalo/select-oa`},Y={facebook:"pageId",instagram:"accountId",zalo:"oaId"};try{const O=await fetch(ne[I]??`${r}/v1/connect/${I}/select-page`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({sessionId:W,[Y[I]??"pageId"]:h})}),re=await O.json();if(!O.ok||!re.connectionId)throw new Error(re.message??"Không thể kết nối");if(N)try{N.postMessage({type:"channelhub:close-popup"},"*")}catch{}C.current&&(window.removeEventListener("message",C.current),C.current=null),await P(),b({name:"list"})}catch(O){w(O instanceof Error?O.message:"Lỗi kết nối")}finally{R(!1)}}return e.jsxs("div",{style:s.root,children:[B&&e.jsx("div",{style:s.errorBanner,children:B}),x.name==="list"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:s.header,children:[e.jsx("div",{style:s.headerLeft,children:e.jsxs("div",{children:[e.jsx("div",{style:s.title,children:"Kênh kết nối"}),e.jsx("div",{style:s.subtitle,children:m?"Đang tải…":`${c.filter(h=>h.status==="active").length} kênh đang hoạt động`})]})}),e.jsxs("button",{style:s.addBtn,onClick:()=>b({name:"add"}),children:[e.jsx(Ue,{}),e.jsx("span",{children:"Thêm kênh"})]})]}),e.jsx("div",{style:s.divider}),e.jsx("div",{style:s.body,children:!m&&c.length===0?e.jsxs("div",{style:s.empty,children:[e.jsx("div",{style:{width:64,height:64,borderRadius:16,background:"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(le,{provider:"livechat",apiUrl:r,size:40})}),e.jsx("div",{style:s.emptyTitle,children:"Chưa có kênh nào được kết nối"}),e.jsx("div",{style:s.emptyDesc,children:"Kết nối Facebook, Zalo OA, Telegram hoặc Live Chat để bắt đầu nhận tin nhắn từ khách hàng."}),e.jsxs("button",{style:s.emptyCta,onClick:()=>b({name:"add"}),children:[e.jsx(Ue,{}),"Kết nối kênh đầu tiên"]})]}):e.jsx("div",{children:c.map(h=>e.jsx(qt,{conn:h,apiUrl:r,onDisconnect:()=>void te(h.id,$e(h))},h.id))})})]}),x.name==="add"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:s.header,children:e.jsxs("div",{style:s.headerLeft,children:[e.jsx("button",{style:s.backBtn,onClick:()=>b({name:"list"}),children:e.jsx(xe,{})}),e.jsxs("div",{children:[e.jsx("div",{style:s.title,children:"Thêm kênh mới"}),e.jsx("div",{style:s.subtitle,children:"Chọn nền tảng bạn muốn kết nối"})]})]})}),e.jsx("div",{style:s.divider}),e.jsx("div",{style:s.body,children:e.jsx("div",{style:s.providerGrid,children:Vt.map(h=>e.jsx(Gt,{provider:h,apiUrl:r,onClick:()=>{h.type==="oauth"?Q(h.id):h.id==="telegram"?b({name:"connect-telegram"}):b({name:"connect-livechat"})}},h.id))})})]}),x.name==="connect-telegram"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:s.connectHeader,children:[e.jsx("button",{style:s.backBtn,onClick:()=>b({name:"add"}),children:e.jsx(xe,{})}),e.jsx(le,{provider:"telegram",apiUrl:r,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:s.connectTitle,children:"Kết nối Telegram Bot"}),e.jsx("div",{style:s.connectDesc,children:"Nhập Bot Token để bắt đầu nhận tin nhắn"})]})]}),e.jsxs("div",{style:s.form,children:[e.jsxs("div",{style:s.infoBox,children:[e.jsx(Dt,{}),e.jsxs("div",{children:["Tạo bot mới bằng cách nhắn tin cho ",e.jsx("strong",{children:"@BotFather"})," trên Telegram, dùng lệnh ",e.jsx("strong",{children:"/newbot"})," rồi sao chép token được cấp."]})]}),e.jsxs("div",{style:s.field,children:[e.jsxs("label",{style:s.label,children:["Bot Token ",e.jsx("span",{style:s.labelHint,children:"bắt buộc"})]}),e.jsx("input",{style:s.input,type:"text",value:T,onChange:h=>M(h.target.value),placeholder:"1234567890:AAExxxxxxxxxxxxxxxxxxxxxxxx",autoComplete:"off",spellCheck:!1}),e.jsxs("div",{style:s.inputHint,children:["Định dạng: ",e.jsx("code",{children:"số:ký_tự"}),", ví dụ: ",e.jsx("code",{children:"1234567890:AAExxxxxxxx"})]})]}),e.jsxs("div",{style:s.field,children:[e.jsxs("label",{style:s.label,children:["Tên hiển thị ",e.jsx("span",{style:s.labelHint,children:"tùy chọn"})]}),e.jsx("input",{style:s.input,type:"text",value:X,onChange:h=>F(h.target.value),placeholder:"VD: Bot hỗ trợ cửa hàng"})]}),e.jsxs("div",{style:s.formActions,children:[e.jsx("button",{style:s.btnSecondary,onClick:()=>b({name:"add"}),children:"Hủy"}),e.jsx("button",{style:s.btnPrimary,disabled:z,onClick:()=>void de(),children:z?"Đang kết nối…":"Kết nối Telegram"})]})]})]}),x.name==="connect-livechat"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:s.connectHeader,children:[e.jsx("button",{style:s.backBtn,onClick:()=>b({name:"add"}),children:e.jsx(xe,{})}),e.jsx(le,{provider:"livechat",apiUrl:r,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:s.connectTitle,children:"Tạo Live Chat Widget"}),e.jsx("div",{style:s.connectDesc,children:"Nhúng vào website để nhận tin nhắn từ khách hàng"})]})]}),e.jsxs("div",{style:s.form,children:[e.jsxs("div",{style:s.field,children:[e.jsxs("label",{style:s.label,children:["Tên widget ",e.jsx("span",{style:s.labelHint,children:"bắt buộc"})]}),e.jsx("input",{style:s.input,type:"text",value:$,onChange:h=>A(h.target.value),placeholder:"VD: Hỗ trợ website hanashop.vn"})]}),e.jsxs("div",{style:s.field,children:[e.jsxs("label",{style:s.label,children:["Tên miền được phép ",e.jsx("span",{style:s.labelHint,children:"tùy chọn"})]}),e.jsx("textarea",{style:{...s.input,resize:"vertical",minHeight:80,lineHeight:1.5},value:V,onChange:h=>S(h.target.value),placeholder:`https://myshop.com
|
|
114
|
+
https://www.myshop.com`,spellCheck:!1}),e.jsx("div",{style:s.inputHint,children:"Mỗi domain một dòng. Để trống để cho phép tất cả."})]}),e.jsxs("div",{style:s.formActions,children:[e.jsx("button",{style:s.btnSecondary,onClick:()=>b({name:"add"}),children:"Hủy"}),e.jsx("button",{style:s.btnPrimary,disabled:z,onClick:()=>void j(),children:z?"Đang tạo…":"Tạo widget"})]})]})]}),x.name==="livechat-result"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:s.connectHeader,children:[e.jsx("button",{style:s.backBtn,onClick:()=>b({name:"list"}),children:e.jsx(xe,{})}),e.jsx(le,{provider:"livechat",apiUrl:r,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:s.connectTitle,children:"Widget đã được tạo!"}),e.jsx("div",{style:s.connectDesc,children:"Sao chép mã nhúng và dán vào website của bạn"})]})]}),e.jsxs("div",{style:s.form,children:[e.jsxs("div",{style:s.resultBanner,children:[e.jsx("span",{style:{fontSize:16,flexShrink:0},children:"✅"}),e.jsxs("div",{children:[e.jsx("strong",{children:"Tạo thành công!"})," Dán đoạn script dưới đây vào thẻ ",e.jsx("code",{style:{background:"#dcfce7",padding:"1px 4px",borderRadius:4},children:"</body>"})," của website."]})]}),e.jsxs("div",{children:[e.jsx("div",{style:s.codeLabel,children:"Mã nhúng"}),e.jsxs("div",{style:s.codeBlock,children:[e.jsx("pre",{style:s.codePre,children:x.embedScript}),e.jsx("button",{style:{...s.copyBtn,...K?{background:"#166534",borderColor:"#166534",color:"#bbf7d0"}:{}},onClick:()=>J(x.embedScript,"script"),children:K?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{})," Đã sao chép"]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{})," Sao chép"]})})]})]}),x.identitySecret&&e.jsxs("div",{children:[e.jsxs("div",{style:s.codeLabel,children:["Identity Secret ",e.jsx("span",{style:{...s.labelHint,color:"#dc2626",fontWeight:600},children:"Lưu ngay — chỉ hiển thị một lần"})]}),e.jsxs("div",{style:s.secretRow,children:[e.jsx(Ut,{}),e.jsx("span",{style:s.secretLabel,children:"Secret:"}),e.jsx("span",{style:s.secretValue,children:x.identitySecret}),e.jsx("button",{onClick:()=>J(x.identitySecret,"secret"),style:{border:"none",background:"transparent",cursor:"pointer",color:k?"#059669":"#ca8a04",padding:2,display:"flex",alignItems:"center"},children:k?e.jsx(Fe,{}):e.jsx(De,{})})]}),e.jsx("div",{style:{...s.inputHint,marginTop:6},children:"Dùng secret này để xác thực danh tính người dùng (HMAC). Giữ bí mật — không chia sẻ nơi công khai."})]}),e.jsxs("div",{style:s.formActions,children:[e.jsx("button",{style:s.btnSecondary,onClick:()=>b({name:"list"}),children:"Về danh sách"}),e.jsx("button",{style:s.btnPrimary,onClick:()=>b({name:"add"}),children:"Thêm kênh khác"})]})]})]}),x.name==="oauth-waiting"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:s.header,children:e.jsxs("div",{style:s.headerLeft,children:[e.jsx("button",{style:s.backBtn,onClick:ce,children:e.jsx(xe,{})}),e.jsxs("div",{children:[e.jsxs("div",{style:s.title,children:["Đang xác thực ",ve[x.provider]]}),e.jsx("div",{style:s.subtitle,children:"Vui lòng hoàn thành trong cửa sổ bật lên"})]})]})}),e.jsxs("div",{style:s.oauthWaiting,children:[e.jsxs("div",{style:{position:"relative",width:72,height:72},children:[e.jsx("div",{style:{width:72,height:72,borderRadius:20,background:At[x.provider]??"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(le,{provider:x.provider,apiUrl:r,size:48})}),e.jsxs("svg",{width:92,height:92,viewBox:"0 0 92 92",fill:"none",style:{position:"absolute",top:-10,left:-10,animation:"ch-spin 1.2s linear infinite"},children:[e.jsx("circle",{cx:"46",cy:"46",r:"42",stroke:"#e2e8f0",strokeWidth:"3.5"}),e.jsx("circle",{cx:"46",cy:"46",r:"42",stroke:"#2563eb",strokeWidth:"3.5",strokeLinecap:"round",strokeDasharray:"66 198"})]})]}),e.jsxs("div",{style:s.oauthTitle,children:["Đang chờ xác thực với ",ve[x.provider]]}),e.jsx("div",{style:s.oauthDesc,children:"Một cửa sổ đăng nhập đã được mở. Vui lòng đăng nhập và cấp quyền truy cập để hoàn tất kết nối."}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,alignItems:"flex-start",width:"100%",maxWidth:280},children:[e.jsx(Re,{done:!0,label:`Đã mở cửa sổ ${ve[x.provider]}`}),e.jsx(Re,{active:!0,label:"Đang chờ bạn đăng nhập & cấp quyền"}),e.jsx(Re,{label:"Lưu kết nối & quay về"})]}),e.jsx("button",{style:s.oauthCancel,onClick:ce,children:"Hủy và quay lại"})]})]}),x.name==="oauth-select"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:s.connectHeader,children:[e.jsx("button",{style:s.backBtn,onClick:ce,children:e.jsx(xe,{})}),e.jsx(le,{provider:x.provider,apiUrl:r,size:44}),e.jsxs("div",{children:[e.jsxs("div",{style:s.connectTitle,children:["Chọn ",x.provider==="instagram"?"tài khoản":"trang"]}),e.jsxs("div",{style:s.connectDesc,children:["Chọn ",ve[x.provider]," bạn muốn kết nối với ChannelHub"]})]})]}),e.jsx("div",{style:s.body,children:x.pages.length===0?e.jsx("div",{style:{textAlign:"center",color:"#94a3b8",fontSize:13,padding:"24px 0"},children:"Không tìm thấy trang/tài khoản nào. Hãy thử lại."}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:x.pages.map(h=>e.jsxs("button",{disabled:z,onClick:()=>void ie(h.id),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderRadius:12,border:"1.5px solid #e2e8f0",background:"#fff",cursor:z?"not-allowed":"pointer",opacity:z?.6:1,textAlign:"left",fontFamily:"inherit",transition:"border-color .15s, background .15s"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#0f172a"},children:h.name}),e.jsx("div",{style:{fontSize:11,color:"#94a3b8",fontFamily:"monospace",marginTop:2},children:h.id})]}),e.jsx("span",{style:{fontSize:13,color:"#2563eb",fontWeight:500},children:z?"Đang kết nối…":"Chọn →"})]},h.id))})})]})]})}function Nt(t){const n=t.metadata;if(typeof n.pictureUrl=="string")return n.pictureUrl;if(t.provider==="facebook")return`https://graph.facebook.com/${t.externalAccountId}/picture?type=square`;if(t.provider==="instagram"){const i=typeof n.pageId=="string"?n.pageId:null;if(i)return`https://graph.facebook.com/${i}/picture?type=square`}return null}function Kt({conn:t,apiUrl:n,size:i=40}){const[r,c]=o.useState(!1),v=Nt(t),m=Math.round(i*.28);return v&&!r?e.jsx("img",{src:v,alt:$e(t),referrerPolicy:"no-referrer",onError:()=>c(!0),style:{width:i,height:i,borderRadius:m,objectFit:"cover",flexShrink:0,display:"block"}}):e.jsx(le,{provider:t.provider,apiUrl:n,size:i})}function qt({conn:t,apiUrl:n,onDisconnect:i}){const[r,c]=o.useState(!1);return e.jsxs("div",{style:s.channelItem,children:[e.jsx(Kt,{conn:t,apiUrl:n,size:40}),e.jsxs("div",{style:s.channelInfo,children:[e.jsx("div",{style:s.channelName,children:$e(t)}),e.jsx("div",{style:s.channelMeta,children:Ot(t)})]}),e.jsxs("div",{style:s.channelActions,children:[e.jsx("span",{style:t.status==="active"?s.badgeActive:s.badgeInactive,children:t.status==="active"?"Hoạt động":t.status}),e.jsx("button",{style:{...s.disconnectBtn,...r?{background:"#fef2f2",borderColor:"#fca5a5",color:"#dc2626"}:{}},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onClick:i,children:"Ngắt kết nối"})]})]})}const Vt=[{id:"facebook",name:"Facebook",desc:"Fanpage & Messenger",type:"oauth"},{id:"zalo",name:"Zalo OA",desc:"Official Account",type:"oauth"},{id:"instagram",name:"Instagram",desc:"DM & Comments",type:"oauth"},{id:"telegram",name:"Telegram",desc:"Bot token",type:"token"},{id:"livechat",name:"Live Chat",desc:"Website widget",type:"livechat"}];function Gt({provider:t,apiUrl:n,onClick:i}){const[r,c]=o.useState(!1);return e.jsxs("div",{style:{...s.providerCard,...r?{background:"#fff",borderColor:"#e2e8f0",boxShadow:"0 2px 8px rgba(0,0,0,.07)",transform:"translateY(-1px)"}:{}},onClick:i,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[e.jsx(le,{provider:t.id,apiUrl:n,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:s.providerName,children:t.name}),e.jsx("div",{style:s.providerDesc,children:t.desc})]})]})}function Re({done:t,active:n,label:i}){const r=t?"#059669":n?"#2563eb":"#cbd5e1";return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:13,color:t?"#059669":n?"#0f172a":"#94a3b8"},children:[e.jsx("div",{style:{width:10,height:10,borderRadius:"50%",background:r,flexShrink:0,...n?{boxShadow:"0 0 0 3px rgba(37,99,235,.2)"}:{}}}),i]})}console.log("[ChannelHub] widget v0.1.5 loaded");exports.ChannelHubChannels=Pt;exports.ChannelHubClient=Xe;exports.ChannelHubInbox=It;
|