@channelhub/widget 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,135 +1,205 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),i=require("react"),Ct=require("react-dom");/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),i=require("react"),Lt=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 Lt=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),It=(...t)=>t.filter((n,o,r)=>!!n&&n.trim()!==""&&r.indexOf(n)===o).join(" ").trim();/**
6
+ */const Xt=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ht=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).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 Mt={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"};/**
11
+ */var Yt={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 Et=i.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:o=2,absoluteStrokeWidth:r,className:c="",children:w,iconNode:x,...$},v)=>i.createElement("svg",{ref:v,...Mt,width:n,height:n,stroke:t,strokeWidth:r?Number(o)*24/Number(n):o,className:It("lucide",c),...$},[...x.map(([f,W])=>i.createElement(f,W)),...Array.isArray(w)?w:[w]]));/**
16
+ */const Zt=i.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:d="",children:w,iconNode:v,...E},C)=>i.createElement("svg",{ref:C,...Yt,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:Ht("lucide",d),...E},[...v.map(([j,$])=>i.createElement(j,$)),...Array.isArray(w)?w:[w]]));/**
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 V=(t,n)=>{const o=i.forwardRef(({className:r,...c},w)=>i.createElement(Et,{ref:w,iconNode:n,className:It(`lucide-${Lt(t)}`,r),...c}));return o.displayName=`${t}`,o};/**
21
+ */const q=(t,n)=>{const r=i.forwardRef(({className:s,...d},w)=>i.createElement(Zt,{ref:w,iconNode:n,className:Ht(`lucide-${Xt(t)}`,s),...d}));return r.displayName=`${t}`,r};/**
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 Ht=V("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
26
+ */const Qt=q("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
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 pt=V("CheckCheck",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);/**
31
+ */const Dt=q("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/**
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 st=V("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
36
+ */const wt=q("CheckCheck",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);/**
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 nt=V("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
41
+ */const lt=q("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
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 At=V("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
46
+ */const ut=q("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
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 Ot=V("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"}]]);/**
51
+ */const en=q("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
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 zt=V("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"}]]);/**
56
+ */const tn=q("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"}]]);/**
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 Ut=V("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"}]]);/**
61
+ */const nn=q("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/**
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 Dt=V("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"}]]);/**
66
+ */const on=q("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"}]]);/**
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 Ft=V("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/**
71
+ */const rn=q("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"}]]);/**
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 Rt=V("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
76
+ */const Ot=q("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"}]]);/**
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 ft=V("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
81
+ */const sn=q("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/**
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 Pt=V("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"}]]);/**
86
+ */const an=q("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/**
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 Nt=V("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
91
+ */const st=q("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
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 gt=V("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
96
+ */const Ct=q("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
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 Kt=V("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"}]]);/**
101
+ */const ln=q("MessageSquarePlus",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/**
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 qt=V("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"}]]);/**
106
+ */const dn=q("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"}]]);/**
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 Vt=V("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"}]]);/**
111
+ */const cn=q("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/**
112
112
  * @license lucide-react v0.468.0 - ISC
113
113
  *
114
114
  * This source code is licensed under the ISC license.
115
115
  * See the LICENSE file in the root directory of this source tree.
116
- */const Gt=V("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/**
116
+ */const hn=q("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
117
117
  * @license lucide-react v0.468.0 - ISC
118
118
  *
119
119
  * This source code is licensed under the ISC license.
120
120
  * See the LICENSE file in the root directory of this source tree.
121
- */const xt=V("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/**
121
+ */const un=q("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
122
122
  * @license lucide-react v0.468.0 - ISC
123
123
  *
124
124
  * This source code is licensed under the ISC license.
125
125
  * See the LICENSE file in the root directory of this source tree.
126
- */const De=V("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
126
+ */const pn=q("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/**
127
127
  * @license lucide-react v0.468.0 - ISC
128
128
  *
129
129
  * This source code is licensed under the ISC license.
130
130
  * See the LICENSE file in the root directory of this source tree.
131
- */const Xt=V("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 Ze{constructor(n,o){this.apiUrl=n,this.token=o}async request(n,o,r){const c={authorization:`Bearer ${this.token}`,...r?{}:{"content-type":"application/json"},...o==null?void 0:o.headers},w=await fetch(`${this.apiUrl}${n}`,{...o,headers:c}),x=await w.json().catch(()=>null);if(!w.ok)throw new Error((x==null?void 0:x.message)??`Request failed (${w.status})`);return x}getSessionMe(){return this.request("/v1/auth/session/me")}assignConversation(n,o){return this.request(`/v1/conversations/${encodeURIComponent(n)}/assignee`,{method:"PUT",body:JSON.stringify({agent:o})})}listConnections(){return this.request("/v1/connections")}listConversations(n){return this.request(`/v1/conversations${n?`?cursor=${encodeURIComponent(n)}`:""}`)}listMessages(n,o){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages${o?`?cursor=${encodeURIComponent(o)}`:""}`)}getMessage(n){return this.request(`/v1/messages/${encodeURIComponent(n)}`)}sendMessage(n,o,r){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages`,{method:"POST",headers:{"idempotency-key":crypto.randomUUID()},body:JSON.stringify({text:o,attachments:r})})}async markRead(n){const o=await fetch(`${this.apiUrl}/v1/conversations/${encodeURIComponent(n)}/mark-read`,{method:"POST",headers:{authorization:`Bearer ${this.token}`}});if(!o.ok&&o.status!==204)throw new Error(`markRead failed (${o.status})`)}listCannedResponses(n){const o=n!=null&&n.trim()?`?search=${encodeURIComponent(n)}`:"";return this.request(`/v1/canned-responses${o}`)}getNote(n){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`)}patchContact(n,o){return this.request(`/v1/contacts/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify({externalId:o})})}upsertNote(n,o){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`,{method:"PUT",body:JSON.stringify({content:o})})}async uploadAttachment(n){const o=new FormData;return o.append("file",n),this.request("/v1/attachments",{method:"POST",body:o},!0)}connectSSE(n){const o=`${this.apiUrl}/v1/events?token=${encodeURIComponent(this.token)}`;let r,c,w=!1;const x=()=>{r=new EventSource(o),r.addEventListener("message.new",$=>{n("message.new",JSON.parse($.data))}),r.addEventListener("conversation.updated",$=>{n("conversation.updated",JSON.parse($.data))}),r.onerror=()=>{r.close(),w||(c=setTimeout(x,5e3))}};return x(),()=>{w=!0,clearTimeout(c),r==null||r.close()}}}function at({src:t,alt:n="",fallback:o,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:o})}function Yt({variant:t="ghost",style:n,...o}){return e.jsx("button",{...o,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 Jt({style:t,...n}){return e.jsx("input",{...n,style:{width:"100%",minWidth:0,border:0,outline:0,background:"transparent",font:"inherit",...t}})}const Wt=i.forwardRef(({children:t,style:n},o)=>e.jsx("div",{ref:o,style:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain",...n},children:t})),Zt=i.forwardRef(function({style:n,...o},r){return e.jsx("textarea",{ref:r,...o,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",border:0,outline:0,background:"transparent",font:"inherit",...n}})});function _t(t){return{id:t.contactId??t.providerConversationKey,name:t.contactName,pictureUrl:t.contactPictureUrl,providerUserId:t.contactProviderUserId??t.providerConversationKey,...t.contactExternalId?{externalId:t.contactExternalId}:{}}}function _e(t,n){return{conversation:t,contact:_t(t),provider:n==null?void 0:n.provider,recentMessages:n==null?void 0:n.recentMessages,linkContact:(n==null?void 0:n.linkContact)??(async()=>{}),refreshContactInfo:(n==null?void 0:n.refreshContactInfo)??(()=>{}),sendMessage:(n==null?void 0:n.sendMessage)??(async()=>{})}}class Qt extends i.Component{constructor(){super(...arguments),this.state={caught:!1}}static getDerivedStateFromError(){return{caught:!0}}render(){return this.state.caught?null:this.props.children}}const s={ink:"#172033",muted:"#718096",line:"#e7ebf2",surface:"#f7f9fc",white:"#fff"},bt=[{icon:"😊",emojis:["😀","😁","😂","🤣","😊","😇","🙂","😉","😍","🥰","😘","😋","😎","🤩","😏","😒","😔","😢","😭","😤","😠","🤯","😱","🥳","😴","🤔","🤗","🫡","😮","🤧","🥺","😶","🫠","🤭","🤫"]},{icon:"👋",emojis:["👍","👎","👏","🙏","🤝","✌️","🤞","🫡","💪","🤜","👊","✊","🖐","👌","🤌","🤏","☝️","👆","👇","👉","👈","🤙","💅","🫶","❤️","🧡","💛","💚","💙","💜","🖤","💔","❣️","💕","💯"]},{icon:"🐱",emojis:["🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🙈","🐔","🐧","🐦","🦆","🦅","🦉","🦋","🐝","🐛","🐢","🦎","🐬","🦈","🐳","🐙","🦑"]},{icon:"🍕",emojis:["🍎","🍊","🍋","🍇","🍓","🍒","🥝","🥑","🍔","🍕","🌮","🍜","🍣","🍦","🎂","🍰","🧁","☕","🧋","🥤","🍺","🥂","🍾","🧃","🧊"]},{icon:"⚽",emojis:["⚽","🏀","🏈","⚾","🎾","🏐","🏓","🎮","🎲","🎯","🎳","🏆","🥇","🎖","🎁","🎉","🎊","🎈","🎭","🎨","🎬","🎵","🎸","🎹","🎺","🪗","🎻"]},{icon:"🌍",emojis:["🌍","🌈","⭐","🌙","☀️","⛅","🌊","🔥","💧","🌿","🌸","🌺","🌻","🍀","🌴","🏔","🏖","🏕","🌃","🏙","🌅","🌄","🌠","🌌","🌋","🏝"]}],lt=i.createContext(""),Tt=i.createContext("");function en(){try{const t=new AudioContext,n=t.createOscillator(),o=t.createGain();n.connect(o),o.connect(t.destination),n.type="sine",n.frequency.setValueAtTime(880,t.currentTime),n.frequency.exponentialRampToValueAtTime(660,t.currentTime+.12),o.gain.setValueAtTime(.25,t.currentTime),o.gain.exponentialRampToValueAtTime(.001,t.currentTime+.35),n.start(t.currentTime),n.stop(t.currentTime+.35)}catch{}}function tn(t){if(!(t!=null&&t.metadata))return;const n=t.metadata,o=n.pageName??n.displayName??n.username??n.name;return typeof o=="string"&&o?o:void 0}function $t(t){return t==="facebook"?"Facebook Messenger":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo OA":t==="livechat"?"Live Chat":"Channel"}function yt(t){return t==="facebook"?"Facebook":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo":t==="livechat"?"Live Chat":String(t??"")}const nn=t=>{var o;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]??((o=t.split("/")[1])==null?void 0:o.toUpperCase())??"Tệp":"Tệp đính kèm"};function mt({status:t}){return t==="read"?e.jsx(pt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):t==="delivered"?e.jsx(pt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle",opacity:.5}}):t==="sent"?e.jsx(st,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):null}function it(t){const n=t.trim().split(/\s+/).filter(Boolean);return n.length<=2?t.trim():n.slice(-2).join(" ")}const on=i.forwardRef(function({apiUrl:n,token:o,theme:r,height:c,defaultConversationId:w,disableAttachments:x,disableNotificationSound:$,hideKeyboardHint:v,locale:f="vi",extensions:W,currentAgent:R,teamAgents:H,onNewMessage:B,onConversationSelect:S},N){var he,Xe,ct,ht,ut;const I=i.useRef(new Ze(n,o)),[L,G]=i.useState([]),[P,te]=i.useState([]),[K,T]=i.useState(),[g,k]=i.useState(),U=i.useRef(void 0),[E,X]=i.useState(""),[le,xe]=i.useState("all"),[ce,re]=i.useState(null),[q,j]=i.useState({provider:"all",unreadOnly:!1}),[Q,h]=i.useState(!1),M=i.useRef(null),O=i.useRef(null),[C,se]=i.useState(null),[oe,J]=i.useState(!0),[ae,Pe]=i.useState(""),be=i.useRef(null),[ve,$e]=i.useState(()=>typeof window<"u"?window.innerWidth:1200),Z=ve<640?"mobile":ve<1024?"tablet":"desktop",[Be,Se]=i.useState(()=>w?"chat":"list"),[ye,de]=i.useState(()=>typeof window<"u"&&window.innerWidth<1024?!1:!!(W!=null&&W.length)),Ce=i.useRef(Z),[Le,Me]=i.useState(280),[Ee,Ne]=i.useState(!1),[He,ke]=i.useState(0),Y=(r==null?void 0:r.primaryColor)??"#2563eb",ee=i.useMemo(()=>new Map(P.map(l=>[l.id,l])),[P]),Ie=i.useRef(null),[Ke,ze]=i.useState(0);i.useEffect(()=>{const l=be.current;if(!l||typeof ResizeObserver>"u")return;const u=new ResizeObserver(b=>{for(const z of b){const ie=z.contentRect.width;ie>0&&$e(ie)}});return u.observe(l),()=>u.disconnect()},[oe,ae]),i.useEffect(()=>{Ce.current==="desktop"&&Z!=="desktop"&&de(!1),Ce.current=Z},[Z]);const pe=i.useMemo(()=>L.filter(l=>l.id!==(g==null?void 0:g.id)&&(l.unreadCount??0)>0).length,[L,g==null?void 0:g.id]),_=R??ce??null;i.useEffect(()=>{I.current=new Ze(n,o),R||I.current.getSessionMe().then(l=>{l!=null&&l.agent&&re(l.agent)}).catch(()=>{})},[n,o,R]);const qe=i.useMemo(()=>{var u;const l=new Map;_!=null&&_.id&&l.set(_.id,_);for(const b of H??[])b!=null&&b.id&&!l.has(b.id)&&l.set(b.id,b);for(const b of L)(u=b.assignedAgent)!=null&&u.id&&!l.has(b.assignedAgent.id)&&l.set(b.assignedAgent.id,b.assignedAgent);return[...l.values()]},[_,H,L]),Qe=i.useCallback(async(l,u)=>{G(b=>b.map(z=>z.id===l.id?{...z,assignedAgent:u}:z)),k(b=>b&&b.id===l.id?{...b,assignedAgent:u}:b),ke(b=>b+1);try{const b=await I.current.assignConversation(l.id,u);G(z=>z.map(ie=>ie.id===l.id?{...ie,...b,assignedAgent:b.assignedAgent??u}:ie)),k(z=>z&&z.id===l.id?{...z,...b,assignedAgent:b.assignedAgent??u}:z),ke(z=>z+1)}catch{}},[]),Ae=i.useCallback(async(l,u)=>{l.contactId&&await I.current.patchContact(l.contactId,u),G(b=>b.map(z=>z.id===l.id?{...z,contactExternalId:u??void 0}:z)),k(b=>b&&b.id===l.id?{...b,contactExternalId:u??void 0}:b),ke(b=>b+1)},[]),fe=i.useCallback(()=>{ke(l=>l+1)},[]),ge=i.useMemo(()=>{const l=new Set(P.map(u=>u.provider));return["facebook","instagram","telegram","zalo","livechat"].filter(u=>l.has(u))},[P]),Ve=i.useMemo(()=>{var u;const l={};for(const b of L){const z=((u=ee.get(b.connectionId))==null?void 0:u.provider)??"unknown";l[z]=(l[z]??0)+1}return l},[L,ee]);function Ge(l){const u=l.clientX,b=Le;Ne(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none";function z(Re){const Oe=Math.max(200,Math.min(480,b+(u-Re.clientX)));Me(Oe)}function ie(){Ne(!1),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",ie)}document.addEventListener("mousemove",z),document.addEventListener("mouseup",ie)}const a=i.useCallback(async l=>{try{const u=await I.current.listConversations(l);G(b=>l?[...b,...u.items]:u.items),T(u.nextCursor),!l&&u.items.length&&k(b=>b??(w?u.items.find(z=>z.id===w)??u.items[0]:u.items[0])),Pe("")}catch(u){Pe(u instanceof Error?u.message:"Không tải được hội thoại")}finally{J(!1)}},[w]);i.useEffect(()=>(I.current.listConnections().then(te).catch(()=>{}),a(),I.current.connectSSE((u,b)=>{if(u==="message.new"||u==="conversation.updated"){if(a(),u==="message.new"){const z=typeof b=="object"&&b?b:{},ie=z.conversationId?String(z.conversationId):"",Re=z.messageId?String(z.messageId):"";if((z.direction?String(z.direction):"")==="inbound"&&!$&&en(),ie&&ie===U.current&&Re&&Ie.current){const Ye=Ie.current;I.current.getMessage(Re).then(Je=>{Ye(Je)}).catch(()=>{})}B==null||B(ie||U.current||"")}}else u==="message.status_updated"&&ze(z=>z+1)})),[a,B]),i.useEffect(()=>{U.current=g==null?void 0:g.id},[g]),i.useEffect(()=>{g!=null&&g.unreadCount&&I.current.markRead(g.id).then(()=>a()).catch(()=>{})},[g==null?void 0:g.id]),i.useEffect(()=>{if(!Q)return;function l(u){var b,z;(b=M.current)!=null&&b.contains(u.target)||(z=O.current)!=null&&z.contains(u.target)||h(!1)}return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[Q]);const p=i.useMemo(()=>{const l=_?L.filter(b=>{var z;return((z=b.assignedAgent)==null?void 0:z.id)===_.id}).length:0,u=L.filter(b=>!b.assignedAgent).length;return{all:L.length,mine:l,unassigned:u}},[L,_]),m=i.useMemo(()=>{const l=E.toLowerCase().trim();return L.filter(u=>{var Oe,Ye,Je;if(le==="mine"){if(!_||((Oe=u.assignedAgent)==null?void 0:Oe.id)!==_.id)return!1}else if(le==="unassigned"&&u.assignedAgent)return!1;const b=`${u.contactName??""} ${u.subject??""} ${u.providerConversationKey} ${((Ye=u.assignedAgent)==null?void 0:Ye.name)??""}`.toLowerCase(),z=((Je=ee.get(u.connectionId))==null?void 0:Je.provider)??"unknown",ie=q.provider==="all"||z===q.provider,Re=!q.unreadOnly||(u.unreadCount??0)>0;return ie&&Re&&(!l||b.includes(l))})},[L,ee,q,E,le,_]),A=q.provider!=="all"||q.unreadOnly,D=f==="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ả"};i.useImperativeHandle(N,()=>({openConversation:l=>{const u=L.find(b=>b.id===l);u&&(k(u),Se("chat"))},refresh:()=>void a()}),[L,a]);const F=Z==="mobile"?"minmax(0, 1fr)":Z==="tablet"?"minmax(240px, 270px) minmax(0, 1fr)":ye?`minmax(260px, 300px) minmax(0, 1fr) ${Le}px`:"minmax(260px, 300px) minmax(0, 1fr)",ne={...y.frame,position:"relative",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:F,transition:Ee?"none":"grid-template-columns 220ms ease"};if(oe)return e.jsxs("div",{style:{...y.state,borderRadius:(r==null?void 0:r.borderRadius)??"16px"},children:[e.jsx(ot,{})," Đang tải hộp thư…"]});if(ae&&!L.length)return e.jsxs("div",{style:{...y.state,color:"#b42318",borderRadius:(r==null?void 0:r.borderRadius)??"16px"},children:[e.jsx(Ot,{size:16,strokeWidth:2})," ",ae,e.jsx("button",{style:y.retry,onClick:()=>{J(!0),a()},children:"Thử lại"})]});const me=Z!=="mobile"||Be==="list"||!g,we=Z!=="mobile"||Be==="chat"&&!!g;return e.jsx(lt.Provider,{value:n,children:e.jsx(Tt.Provider,{value:o,children:e.jsxs("div",{ref:be,style:ne,onFocusCapture:()=>{const l=window.scrollY;requestAnimationFrame(()=>{window.scrollY!==l&&window.scrollTo({top:l,behavior:"instant"})})},children:[me&&e.jsxs("aside",{style:{...y.sidebar,...Z==="mobile"?{borderRight:0}:{}},children:[e.jsxs("div",{style:y.brand,children:[e.jsx("div",{style:{...y.brandMark,background:Y,overflow:"hidden",padding:0},children:(he=r==null?void 0:r.branding)!=null&&he.logoUrl?e.jsx("img",{src:r.branding.logoUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):((Xe=r==null?void 0:r.branding)==null?void 0:Xe.mark)??"C"}),e.jsxs("div",{children:[e.jsx("strong",{children:((ct=r==null?void 0:r.branding)==null?void 0:ct.name)??"Hộp thư"}),!((ht=r==null?void 0:r.branding)!=null&&ht.name)&&e.jsx("span",{style:y.eyebrow,children:"CHANNELHUB"})]}),e.jsx(Yt,{"aria-label":"Tùy chọn",style:y.iconButton,children:e.jsx(zt,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:y.search,children:[e.jsx(gt,{size:16,strokeWidth:2}),e.jsx(Jt,{"aria-label":D.searchPlaceholder,value:E,onChange:l=>X(l.target.value),placeholder:D.searchPlaceholder,style:{fontSize:Z==="mobile"?16:12}}),E&&e.jsx("button",{style:y.clear,onClick:()=>X(""),"aria-label":"Xóa tìm kiếm",children:"×"})]}),e.jsx("div",{role:"tablist","aria-label":"Lọc theo người phụ trách",style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:2,margin:"0 14px 10px",padding:3,borderRadius:9,border:`1px solid ${s.line}`,background:s.surface},children:[{key:"all",label:f==="en"?"All":"Tất cả",count:p.all},{key:"mine",label:f==="en"?"Mine":"Của tôi",count:p.mine},{key:"unassigned",label:f==="en"?"Unassigned":"Chưa nhận",count:p.unassigned}].map(l=>{const u=le===l.key;return e.jsxs("button",{type:"button",role:"tab","aria-selected":u,onClick:()=>xe(l.key),style:{border:0,borderRadius:6,padding:"5px 4px",fontSize:11,fontWeight:u?700:500,background:u?s.white:"transparent",color:u?Y:s.muted,boxShadow:u?"0 1px 3px rgba(23,32,51,.08)":"none",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",transition:"all 120ms ease"},children:[l.label," ",e.jsxs("span",{style:{opacity:.75},children:["(",l.count,")"]})]},l.key)})}),A&&e.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",padding:"0 14px 8px"},children:[q.provider!=="all"&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:Y,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[e.jsx(Fe,{provider:q.provider}),yt(q.provider),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:Y,padding:0,lineHeight:1,display:"flex"},onClick:()=>j(l=>({...l,provider:"all"})),"aria-label":"Xóa filter kênh",children:e.jsx(De,{size:10})})]}),q.unreadOnly&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:Y,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[D.unreadOnly,e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:Y,padding:0,lineHeight:1,display:"flex"},onClick:()=>j(l=>({...l,unreadOnly:!1})),"aria-label":"Xóa filter chưa đọc",children:e.jsx(De,{size:10})})]}),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:s.muted,fontSize:11,padding:"2px 4px"},onClick:()=>j({provider:"all",unreadOnly:!1}),children:"Xóa tất cả"})]}),e.jsxs("div",{style:y.listHeader,children:[e.jsxs("span",{children:[m.length," hội thoại"]}),e.jsx("button",{ref:M,style:{...y.iconButton,background:A?`${Y}14`:"transparent",color:A?Y:s.muted},"aria-label":"Bộ lọc",onClick:()=>{var l;if(!Q){const u=(l=M.current)==null?void 0:l.getBoundingClientRect();u&&se({top:u.bottom+6,left:u.left})}h(u=>!u)},children:e.jsx(qt,{size:15,strokeWidth:2})})]}),Q&&C&&Ct.createPortal(e.jsxs("div",{ref:O,style:{position:"fixed",top:C.top,left:Math.min(C.left,(typeof window<"u"?window.innerWidth:1200)-230),zIndex:9999,background:s.white,border:`1px solid ${s.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:s.muted,letterSpacing:1,textTransform:"uppercase",marginBottom:8},children:"Kênh"}),["all",...ge].map(l=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:q.provider===l?`${Y}0f`:"transparent"},children:[e.jsx("input",{type:"radio",name:"provider-filter",checked:q.provider===l,onChange:()=>j(u=>({...u,provider:l})),style:{accentColor:Y}}),l==="all"?e.jsxs("span",{style:{color:s.ink},children:[D.all," (",L.length,")"]}):e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,color:s.ink},children:[e.jsx(Fe,{provider:l}),yt(l)," ",e.jsxs("span",{style:{color:s.muted},children:["(",Ve[l]??0,")"]})]})]},l)),e.jsx("div",{style:{borderTop:`1px solid ${s.line}`,margin:"8px 0 6px"}}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:q.unreadOnly?`${Y}0f`:"transparent"},children:[e.jsx("input",{type:"checkbox",checked:q.unreadOnly,onChange:l=>j(u=>({...u,unreadOnly:l.target.checked})),style:{accentColor:Y}}),e.jsx("span",{style:{color:s.ink},children:D.unreadOnly})]})]}),document.body),e.jsxs(Wt,{style:y.conversationList,children:[m.map(l=>{var u;return e.jsx(rn,{conversation:l,provider:(u=ee.get(l.connectionId))==null?void 0:u.provider,selected:(g==null?void 0:g.id)===l.id,primary:Y,currentAgent:_,onSelect:()=>{k(l),Se("chat"),S==null||S(l.id),I.current.markRead(l.id).then(()=>a()).catch(()=>{})}},l.id)}),!m.length&&e.jsxs("div",{style:y.emptySmall,children:[e.jsx("div",{style:y.emptyIcon,children:e.jsx(gt,{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."})]}),K&&e.jsx("button",{style:y.loadMore,onClick:()=>void a(K),children:"Xem thêm hội thoại"})]})]}),we&&e.jsx("main",{style:y.main,children:g?e.jsx(sn,{conversation:g,provider:(ut=ee.get(g.connectionId))==null?void 0:ut.provider,connection:ee.get(g.connectionId),client:I.current,primary:Y,error:ae,onRegisterAppend:l=>{Ie.current=l},refreshKey:Ke,infoOpen:ye,onToggleInfo:()=>de(l=>!l),t:D,disableAttachments:x,hideKeyboardHint:v,extensions:W,currentAgent:_,teamAgents:qe,onAssignAgent:l=>Qe(g,l),onLinkContact:l=>Ae(g,l),onRefreshContactInfo:fe,layoutMode:Z,onBackToList:()=>Se("list"),totalUnreadCount:pe},g.id):e.jsx(dn,{})}),ye&&g&&(Z==="desktop"?e.jsx(jt,{conversation:g,connection:ee.get(g.connectionId),primary:Y,onClose:()=>de(!1),client:I.current,onStartResize:Ge,extensions:W,extRefreshKey:He,onLinkContact:l=>Ae(g,l),onRefreshContactInfo:fe,layoutMode:Z}):e.jsx("div",{onClick:()=>de(!1),style:{position:"absolute",inset:0,zIndex:50,background:"rgba(15, 23, 42, 0.32)",display:"flex",justifyContent:"flex-end"},children:e.jsx("div",{onClick:l=>l.stopPropagation(),style:{width:Z==="mobile"?"100%":"min(320px, 85%)",height:"100%",background:s.white,boxShadow:"-8px 0 24px rgba(15, 23, 42, 0.14)",display:"flex",flexDirection:"column"},children:e.jsx(jt,{conversation:g,connection:ee.get(g.connectionId),primary:Y,onClose:()=>de(!1),client:I.current,onStartResize:void 0,extensions:W,extRefreshKey:He,onLinkContact:l=>Ae(g,l),onRefreshContactInfo:fe,layoutMode:Z})})}))]})})})});function rn({conversation:t,provider:n,selected:o,primary:r,currentAgent:c,onSelect:w}){const[x,$]=i.useState(!1),v=t.contactName??t.subject??t.providerConversationKey,f=t.unreadCount??0,W=t.lastMessageText??"",R=t.lastMessageDirection==="outbound"?"Bạn: ":"",H=W.length>60?W.slice(0,60)+"…":W,B=W?R+H:"",S=t.assignedAgent??null,N=!!(S&&c&&S.id===c.id);let I="transparent";o?I="#eef2ff":x?I="#f7f9fc":f>0&&(I="#f0f4ff");const L={...y.row,background:I,...o?{boxShadow:`inset 3px 0 0 ${r}`}:f>0&&!x?{boxShadow:`inset 3px 0 0 ${r}`}:{}};return e.jsxs("button",{onClick:w,style:L,onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1),children:[e.jsx(Bt,{name:v,color:r,image:t.contactPictureUrl,provider:n}),e.jsxs("span",{style:y.rowBody,children:[e.jsxs("span",{style:y.rowTop,children:[e.jsx("strong",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:f>0?700:500},children:v}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:[e.jsx("time",{style:{color:s.muted,fontSize:11,whiteSpace:"nowrap"},children:rt(t.lastMessageAt)}),f>0&&e.jsx("span",{"aria-label":`${f} tin nhắn chưa đọc`,style:y.unreadBadge,children:f>99?"99+":f})]})]}),e.jsxs("span",{style:{...y.rowBottom,justifyContent:"space-between",alignItems:"center",gap:6,color:f>0&&!o?"#4a5568":s.muted},children:[e.jsx("span",{style:{flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:B||e.jsx("span",{style:{opacity:.5},children:"Chưa có tin nhắn"})}),S?e.jsxs("span",{title:`Phụ trách: ${S.name}${S.title?` (${S.title})`:""}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 6px 1px 2px",borderRadius:999,fontSize:10,fontWeight:600,flexShrink:0,background:N?`${r}18`:"#f1f5f9",color:N?r:"#475569",border:N?`1px solid ${r}33`:"1px solid #e2e8f0"},children:[e.jsx("span",{style:{width:14,height:14,borderRadius:"50%",background:N?r:"#64748b",color:"#fff",fontSize:8,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:S.avatarUrl?e.jsx("img",{src:S.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Te(S.name)}),e.jsx("span",{style:{maxWidth:68,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:it(S.name)})]}):f>0?e.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:999,fontSize:9.5,fontWeight:600,flexShrink:0,background:"#fef3c7",color:"#b45309"},children:"Chưa nhận"}):null]})]})]})}function sn({conversation:t,provider:n,connection:o,client:r,primary:c,error:w,onRegisterAppend:x,refreshKey:$,infoOpen:v,onToggleInfo:f,t:W,disableAttachments:R,hideKeyboardHint:H,extensions:B,currentAgent:S,teamAgents:N,onAssignAgent:I,onLinkContact:L,onRefreshContactInfo:G,layoutMode:P="desktop",onBackToList:te,totalUnreadCount:K=0}){var Ve,Ge;const[T,g]=i.useState([]),[k,U]=i.useState(),[E,X]=i.useState(""),[le,xe]=i.useState(!0),[ce,re]=i.useState(!1),[q,j]=i.useState(""),Q=i.useRef(null),h=t.contactName??t.subject??t.providerConversationKey,M=i.useRef(null),O=i.useRef(null),[C,se]=i.useState(null),[oe,J]=i.useState(!1),[ae,Pe]=i.useState(!1),[be,ve]=i.useState(!1),[$e,Z]=i.useState(0),Be=i.useRef(null),Se=i.useRef(null),ye=i.useRef(null),[de,Ce]=i.useState(!1),[Le,Me]=i.useState(""),[Ee,Ne]=i.useState([]),He=i.useRef(null),ke=i.useRef(null),[Y,ee]=i.useState(!1),Ie=i.useRef(null),Ke=i.useRef(null);i.useEffect(()=>{if(!Y)return;function a(p){var m,A;(m=Ie.current)!=null&&m.contains(p.target)||(A=Ke.current)!=null&&A.contains(p.target)||ee(!1)}return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[Y]),i.useEffect(()=>()=>{C!=null&&C.objectUrl&&URL.revokeObjectURL(C.objectUrl)},[C==null?void 0:C.objectUrl]),i.useEffect(()=>{if(!be)return;function a(p){var m,A;(m=Se.current)!=null&&m.contains(p.target)||(A=Be.current)!=null&&A.contains(p.target)||ve(!1)}return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[be]),i.useEffect(()=>{r.listCannedResponses().then(Ne).catch(()=>{})},[r]),i.useEffect(()=>{if(!de)return;function a(p){var m,A;(m=ke.current)!=null&&m.contains(p.target)||(A=He.current)!=null&&A.contains(p.target)||Ce(!1)}return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[de]);const ze=i.useRef(!0),pe=i.useCallback(async(a,p)=>{p||(ze.current=!a);try{const m=await r.listMessages(t.id,a);g(A=>a?[...m.items,...A]:m.items),U(m.nextCursor)}catch(m){j(m instanceof Error?m.message:"Không tải được tin nhắn")}finally{p||xe(!1)}},[r,t.id]);i.useEffect(()=>{xe(!0),pe()},[pe]),i.useEffect(()=>{$&&pe(void 0,!0)},[$]),i.useEffect(()=>{ze.current&&requestAnimationFrame(()=>{const a=Q.current;a&&(a.scrollTop=a.scrollHeight)})},[T]),i.useEffect(()=>(x==null||x(a=>{ze.current=!0,g(p=>p.some(m=>m.id===a.id)?p:[...p,a])}),()=>{x==null||x(null)}),[x]);async function _(a){var A;const p=(A=a.target.files)==null?void 0:A[0];if(!p)return;a.target.value="";const m=URL.createObjectURL(p);se({file:p,uploading:!0,objectUrl:m});try{const D=await r.uploadAttachment(p);se({file:p,uploading:!1,url:D.url,mimeType:D.mimeType,attachmentType:D.attachmentType,objectUrl:m})}catch{URL.revokeObjectURL(m),se(null),j("Không tải lên được tệp đính kèm")}}async function qe(a){a.preventDefault();const p=E.trim(),m=C!=null&&C.url?[{url:C.url,mimeType:C.mimeType??"application/octet-stream",type:C.attachmentType}]:[];if(!p&&!m.length||ce)return;re(!0),j(""),!t.assignedAgent&&S&&I(S);const A=`optimistic-${Date.now()}`;S&&(ze.current=!0,g(D=>[...D,{id:A,direction:"outbound",status:"sending",text:p||void 0,attachments:m.length?m:void 0,occurredAt:new Date().toISOString(),senderAgent:S}]));try{await r.sendMessage(t.id,p||void 0,m.length?m:void 0),C!=null&&C.objectUrl&&URL.revokeObjectURL(C.objectUrl),X(""),se(null),await pe(),S&&g(D=>{var me,we;const F=D.filter(he=>he.id!==A),ne=F.length-1;return ne>=0&&((me=F[ne])==null?void 0:me.direction)==="outbound"&&!((we=F[ne])!=null&&we.senderAgent)?F.map((he,Xe)=>Xe===ne?{...he,senderAgent:S}:he):F})}catch(D){g(F=>F.filter(ne=>ne.id!==A)),j(D instanceof Error?D.message:"Không gửi được tin nhắn")}finally{re(!1)}}function Qe(a){const p=ye.current;if(!p){X(F=>F+a),ve(!1);return}const m=p.selectionStart??E.length,A=p.selectionEnd??E.length,D=E.slice(0,m)+a+E.slice(A);X(D),ve(!1),requestAnimationFrame(()=>{p.focus(),p.selectionStart=p.selectionEnd=m+a.length})}function Ae(a){X(a),Ce(!1),Me(""),requestAnimationFrame(()=>{const p=ye.current;p&&(p.focus(),p.selectionStart=p.selectionEnd=a.length)})}const fe=!ce&&(E.trim().length>0||(C==null?void 0:C.url)!=null&&!C.uploading),ge=P==="desktop"?y.toolbarBtn:{...y.toolbarBtn,width:32,height:32};return e.jsxs("section",{style:y.chat,children:[e.jsxs("header",{style:{...y.chatHeader,...P==="mobile"?{padding:"0 10px 0 8px",gap:8}:{}},children:[P==="mobile"&&e.jsxs("button",{type:"button",onClick:te,"aria-label":"Quay lại danh sách",style:{...y.iconButton,width:36,height:36,marginLeft:0,position:"relative",flexShrink:0,color:s.ink},children:[e.jsx(Ht,{size:18,strokeWidth:2.2}),K>0&&e.jsx("span",{style:{position:"absolute",top:3,right:3,minWidth:15,height:15,borderRadius:999,background:"#ef4444",color:"#fff",fontSize:9,fontWeight:800,display:"inline-grid",placeItems:"center",padding:"0 3px",border:`1.5px solid ${s.white}`},children:K>99?"99+":K})]}),e.jsx(Bt,{name:h,color:c,image:t.contactPictureUrl,provider:n}),e.jsxs("div",{style:y.contact,children:[e.jsx("strong",{style:y.contactName,children:h}),e.jsx("span",{style:y.contactMeta,children:tn(o)??$t(n)})]}),e.jsxs("div",{style:{...y.headerActions,alignItems:"center",gap:6},children:[e.jsxs("div",{ref:Ie,style:{position:"relative",display:"inline-flex",alignItems:"center",gap:4},children:[!t.assignedAgent&&S?e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",borderRadius:999,border:`1px solid ${c}40`,background:`${c}0d`,overflow:"hidden"},children:[e.jsxs("button",{type:"button",onClick:()=>void I(S),style:{border:0,background:"transparent",color:c,padding:"4px 9px",fontSize:11.5,fontWeight:600,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:[e.jsx(xt,{size:12,strokeWidth:2.2}),e.jsx("span",{children:P==="mobile"?"+ Nhận":"+ Nhận phụ trách"})]}),((N==null?void 0:N.length)??0)>1&&e.jsx("button",{type:"button","aria-label":"Chọn nhân viên phụ trách",onClick:()=>ee(a=>!a),style:{border:0,borderLeft:`1px solid ${c}30`,background:"transparent",color:c,padding:"4px 6px",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:e.jsx(nt,{size:12,strokeWidth:2.2})})]}):e.jsxs("button",{type:"button",onClick:()=>ee(a=>!a),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 9px 3px 4px",borderRadius:999,border:`1px solid ${s.line}`,background:s.surface,color:s.ink,fontSize:11.5,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap"},children:[t.assignedAgent?e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{width:18,height:18,borderRadius:"50%",background:c,color:"#fff",fontSize:9,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:t.assignedAgent.avatarUrl?e.jsx("img",{src:t.assignedAgent.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Te(t.assignedAgent.name)}),P!=="mobile"&&e.jsx("span",{style:{color:s.muted,fontWeight:500},children:"Phụ trách:"}),e.jsx("span",{style:{maxWidth:P==="mobile"?76:110,overflow:"hidden",textOverflow:"ellipsis"},children:it(t.assignedAgent.name)})]}):e.jsxs(e.Fragment,{children:[e.jsx(Gt,{size:13,color:s.muted}),e.jsx("span",{style:{color:s.muted},children:"Chưa phân công"})]}),e.jsx(nt,{size:12,color:s.muted})]}),Y&&e.jsxs("div",{ref:Ke,style:{position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:200,minWidth:230,background:s.white,border:`1px solid ${s.line}`,borderRadius:11,boxShadow:"0 10px 28px rgba(23,32,51,.15)",padding:6,fontSize:12},children:[e.jsx("div",{style:{padding:"4px 8px 6px",fontSize:10,fontWeight:700,color:s.muted,letterSpacing:.8,textTransform:"uppercase"},children:"Người phụ trách hội thoại"}),S&&((Ve=t.assignedAgent)==null?void 0:Ve.id)!==S.id&&e.jsxs("button",{type:"button",onClick:()=>{ee(!1),I(S)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",border:0,borderRadius:7,background:`${c}10`,color:c,padding:"6px 8px",marginBottom:4,fontWeight:600,fontSize:12,cursor:"pointer",textAlign:"left"},children:[e.jsx(xt,{size:13}),e.jsxs("span",{children:["Nhận phụ trách cho tôi (",it(S.name),")"]})]}),e.jsx("div",{style:{maxHeight:200,overflowY:"auto"},children:(N??[]).map(a=>{var m;const p=((m=t.assignedAgent)==null?void 0:m.id)===a.id;return e.jsxs("button",{type:"button",onClick:()=>{ee(!1),I(a)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,width:"100%",border:0,borderRadius:7,background:p?"#f1f5f9":"transparent",color:s.ink,padding:"6px 8px",cursor:"pointer",textAlign:"left"},children:[e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[e.jsx("span",{style:{width:22,height:22,borderRadius:"50%",background:`${c}18`,color:c,fontSize:10,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:a.avatarUrl?e.jsx("img",{src:a.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Te(a.name)}),e.jsxs("span",{style:{minWidth:0},children:[e.jsx("span",{style:{display:"block",fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.name}),a.title&&e.jsx("span",{style:{display:"block",fontSize:10.5,color:s.muted},children:a.title})]})]}),p&&e.jsx(st,{size:13,color:c,strokeWidth:2.5})]},a.id)})}),t.assignedAgent&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{borderTop:`1px solid ${s.line}`,margin:"5px 0"}}),e.jsxs("button",{type:"button",onClick:()=>{ee(!1),I(null)},style:{display:"flex",alignItems:"center",gap:6,width:"100%",border:0,borderRadius:7,background:"transparent",color:"#b42318",padding:"6px 8px",fontSize:11.5,fontWeight:500,cursor:"pointer",textAlign:"left"},children:[e.jsx(De,{size:13}),e.jsx("span",{children:"Bỏ phân công (Chưa có người nhận)"})]})]})]})]}),P!=="mobile"&&e.jsx("button",{style:y.iconButton,"aria-label":"Thêm tùy chọn",children:e.jsx(zt,{size:16,strokeWidth:2})}),e.jsx("button",{style:{...y.iconButton,background:v?`${c}14`:"transparent",color:v?c:s.muted},"aria-label":"Thông tin liên hệ",onClick:f,children:e.jsx(Ft,{size:16,strokeWidth:2})})]})]}),e.jsxs(Wt,{ref:Q,style:y.messageArea,children:[e.jsx("div",{style:y.day,children:W.today}),k&&e.jsx("button",{onClick:()=>void pe(k),style:y.historyButton,children:W.loadOlder}),le&&e.jsxs("div",{style:y.messageHint,children:[e.jsx(ot,{})," ",W.loading]}),!le&&!T.length&&e.jsx("div",{style:y.messageHint,children:W.noMessages}),T.map((a,p)=>{const m=(B==null?void 0:B.flatMap(ne=>ne.messageEnrichments??[]))??[],A=a.direction==="inbound"&&m.length>0&&p>=T.length-15,D=A?_e(t,{provider:n,recentMessages:T.slice(-10),linkContact:L,refreshContactInfo:G,sendMessage:async(ne,me)=>{await r.sendMessage(t.id,ne,me),await pe(void 0,!0)}}):null,F=A&&D?m.map((ne,me)=>{var he;const we=(he=a.text)==null?void 0:he.match(ne.pattern);return we?e.jsx(Qt,{children:ne.render(we,D,a)},`${a.id}-${me}`):null}).filter(Boolean):[];return e.jsxs("div",{children:[e.jsx(an,{message:a,primary:c}),F.length>0&&e.jsx("div",{style:{maxWidth:"min(70%, 480px)",marginTop:-4,marginBottom:10,display:"flex",flexDirection:"column",gap:6},children:F})]},a.id)})]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"nowrap",overflowX:"auto",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",padding:"6px 14px 2px",borderTop:`1px solid ${s.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:()=>X(a),style:{fontSize:11,padding:"3px 10px",borderRadius:999,background:`${c}0f`,color:c,border:`1px solid ${c}33`,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},children:a},a))}),e.jsxs("form",{onSubmit:qe,style:{flex:"0 0 auto",padding:"8px 14px 12px",borderTop:`1px solid ${s.line}`,background:s.white,position:"relative"},children:[be&&e.jsxs("div",{ref:Be,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:s.white,border:`1px solid ${s.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:280,maxWidth:"calc(100vw - 28px)",overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${s.line}`,background:"#f9fafb"},children:bt.map((a,p)=>e.jsx("button",{type:"button",onClick:()=>Z(p),style:{flex:1,border:0,background:"transparent",padding:"7px 2px",fontSize:16,cursor:"pointer",lineHeight:1,borderBottom:$e===p?`2px solid ${c}`:"2px solid transparent",opacity:$e===p?1:.5,transition:"opacity 100ms ease"},children:a.icon},p))}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:2,padding:8,maxHeight:180,overflowY:"auto"},children:(Ge=bt[$e])==null?void 0:Ge.emojis.map((a,p)=>e.jsx("button",{type:"button",onClick:()=>Qe(a),style:{border:0,background:"transparent",padding:"5px 2px",fontSize:18,cursor:"pointer",borderRadius:6,lineHeight:1,transition:"background 80ms ease"},onMouseEnter:m=>{m.target.style.background="#f3f4f6"},onMouseLeave:m=>{m.target.style.background="transparent"},children:a},p))})]}),de&&e.jsxs("div",{ref:He,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:s.white,border:`1px solid ${s.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:300,maxWidth:"calc(100vw - 28px)",overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{padding:"8px 10px",borderBottom:`1px solid ${s.line}`},children:e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Tìm template…",value:Le,onChange:a=>Me(a.target.value),style:{width:"100%",boxSizing:"border-box",border:`1px solid ${s.line}`,borderRadius:7,padding:"5px 8px",fontSize:12,outline:"none",fontFamily:"inherit",color:s.ink}})}),e.jsx("div",{style:{maxHeight:220,overflowY:"auto"},children:(()=>{const a=Le.trim().toLowerCase(),p=a?Ee.filter(m=>m.title.toLowerCase().includes(a)||m.content.toLowerCase().includes(a)||(m.shortcut??"").toLowerCase().includes(a)):Ee;return p.length?p.map(m=>e.jsxs("button",{type:"button",onClick:()=>Ae(m.content),style:{display:"block",width:"100%",textAlign:"left",border:0,borderBottom:`1px solid ${s.line}`,background:"transparent",padding:"9px 12px",cursor:"pointer",fontFamily:"inherit"},onMouseEnter:A=>{A.currentTarget.style.background="#f7f9fc"},onMouseLeave:A=>{A.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:s.ink},children:m.title}),m.shortcut&&e.jsx("span",{style:{fontSize:10,color:c,background:`${c}18`,borderRadius:4,padding:"1px 5px"},children:m.shortcut})]}),e.jsx("div",{style:{fontSize:11,color:s.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.content})]},m.id)):e.jsx("div",{style:{padding:"24px 16px",textAlign:"center",color:s.muted,fontSize:12},children:Ee.length===0?"Chưa có template nào":"Không tìm thấy"})})()})]}),e.jsxs("div",{style:{border:`1.5px solid ${s.line}`,borderRadius:12,background:s.white,overflow:"hidden"},children:[C&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:`1px solid ${s.line}`,fontSize:12},children:[C.uploading?e.jsxs(e.Fragment,{children:[e.jsx(ot,{}),e.jsx("span",{style:{color:s.muted},children:"Đang tải lên…"})]}):C.attachmentType==="image"&&C.objectUrl?e.jsx("img",{src:C.objectUrl,alt:"",style:{height:48,width:48,objectFit:"cover",borderRadius:6}}):e.jsxs("span",{style:{color:s.muted},children:["📎 ",C.file.name," (",Math.round(C.file.size/1024)," KB)"]}),!C.uploading&&e.jsx("button",{type:"button",onClick:()=>{C!=null&&C.objectUrl&&URL.revokeObjectURL(C.objectUrl),se(null)},style:{marginLeft:"auto",border:0,background:"none",color:s.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:Se,type:"button",title:"Chèn emoji",onClick:()=>ve(a=>!a),style:{...ge,background:be?`${c}18`:"transparent",color:be?c:"#9ca3af"},children:e.jsx(Vt,{size:13,strokeWidth:2})}),!R&&e.jsx("button",{type:"button",title:"Gửi ảnh / video","aria-label":"Gửi ảnh hoặc video",style:ge,onClick:()=>{var a;return(a=M.current)==null?void 0:a.click()},children:e.jsx(Ut,{size:13,strokeWidth:2})}),!R&&e.jsx("button",{type:"button",title:"Gửi tệp đính kèm","aria-label":"Gửi tệp đính kèm",style:ge,onClick:()=>{var a;return(a=O.current)==null?void 0:a.click()},children:e.jsx(Pt,{size:13,strokeWidth:2})}),!R&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:M,type:"file",style:{display:"none"},onChange:_,accept:"image/*,video/mp4"}),e.jsx("input",{ref:O,type:"file",style:{display:"none"},onChange:_,accept:".pdf,audio/mpeg,audio/ogg,application/octet-stream,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"})]}),e.jsx("button",{ref:ke,type:"button",title:"Template nhanh",onClick:()=>{Ce(a=>!a),Me("")},style:{...ge,background:de?`${c}18`:"transparent",color:de?c:"#9ca3af"},children:e.jsx(Xt,{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:()=>J(a=>!a),style:{...ge,fontWeight:700,fontSize:12,background:oe?`${c}18`:"transparent",color:oe?c:"#9ca3af",border:oe?`1px solid ${c}33`:"1px solid transparent"},children:"B"}),e.jsx("button",{type:"button",title:"Nghiêng",onClick:()=>Pe(a=>!a),style:{...ge,fontStyle:"italic",fontSize:12,background:ae?`${c}18`:"transparent",color:ae?c:"#9ca3af",border:ae?`1px solid ${c}33`:"1px solid transparent"},children:"I"}),!!(B!=null&&B.some(a=>{var p;return(((p=a.toolbarActions)==null?void 0:p.length)??0)>0}))&&e.jsx("span",{style:{width:1,height:14,background:"#e5e7eb",margin:"0 4px"}}),B==null?void 0:B.flatMap(a=>a.toolbarActions??[]).map((a,p)=>e.jsxs("button",{type:"button",title:a.tooltip,style:a.label?{display:"inline-flex",alignItems:"center",gap:5,padding:"3px 9px",borderRadius:999,border:`1px solid ${c}33`,background:`${c}0f`,color:c,fontSize:11.5,fontWeight:600,cursor:"pointer",lineHeight:1.2,whiteSpace:"nowrap"}:ge,onClick:()=>{const m=D=>{X(F=>F&&!F.endsWith(" ")&&!F.endsWith(`
132
- `)?`${F} ${D}`:`${F}${D}`),requestAnimationFrame(()=>{var F;return(F=ye.current)==null?void 0:F.focus()})},A=_e(t,{provider:n,recentMessages:T.slice(-10),linkContact:L,refreshContactInfo:G,sendMessage:async(D,F)=>{await r.sendMessage(t.id,D,F),await pe(void 0,!0)}});a.onClick({...A,insertText:m})},children:[a.icon,a.label&&e.jsx("span",{children:a.label})]},p))]}),e.jsx(Zt,{ref:ye,"aria-label":"Soạn tin nhắn",rows:2,value:E,onChange:a=>X(a.target.value),onKeyDown:a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),qe(a))},placeholder:W.sendPlaceholder,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",minHeight:52,maxHeight:120,resize:"none",border:0,outline:0,background:"transparent",color:s.ink,padding:"8px 12px 4px",font:"inherit",fontSize:P==="mobile"?16:13,lineHeight:1.45,fontStyle:ae?"italic":"normal",fontWeight:oe?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:E.length>1e3?"#ef4444":E.length>900?"#f59e0b":"#9ca3af",fontWeight:E.length>1e3?600:400},children:[E.length,"/1000"]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[!H&&P==="desktop"&&e.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:"↵ Gửi · ⇧↵ Xuống dòng"}),e.jsxs("button",{disabled:!fe,"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:fe?`linear-gradient(135deg,${c},#0ea5e9)`:"#e5e7eb",color:fe?"#fff":"#9ca3af",cursor:fe?"pointer":"not-allowed",boxShadow:fe?"0 2px 8px rgba(37,99,235,0.25)":"none",transition:"all 150ms ease"},children:[ce?e.jsx(Rt,{size:12,style:{animation:"channelhub-spin .7s linear infinite"}}):e.jsx(Kt,{size:12,strokeWidth:2}),W.send]})]})]})]})]}),(q||w)&&e.jsx("div",{role:"alert",style:y.error,children:q||w})]})}function an({message:t,primary:n}){var P,te,K,T,g;const o=i.useContext(lt),r=i.useContext(Tt),c=k=>k.startsWith("/v1/media/proxy")?`${o}${k}&tok=${encodeURIComponent(r)}`:k,w=t.direction==="outbound",x=((P=t.attachments)==null?void 0:P.filter(k=>k.type==="image"))??[],$=((te=t.attachments)==null?void 0:te.filter(k=>k.type==="sticker"))??[],v=((K=t.attachments)==null?void 0:K.filter(k=>k.type==="video"))??[],f=((T=t.attachments)==null?void 0:T.filter(k=>k.type==="audio"))??[],W=((g=t.attachments)==null?void 0:g.filter(k=>k.type==="file"))??[],[R,H]=i.useState(null),B=w?"flex-end":"flex-start",S=w?t.senderAgent??null:null,N=e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:w?"flex-end":"flex-start",gap:5,marginTop:4,fontSize:10,opacity:.78,letterSpacing:.2,userSelect:"none"},children:[S&&e.jsxs("span",{title:S.title?`${S.name} (${S.title})`:S.name,style:{display:"inline-flex",alignItems:"center",gap:3.5,fontWeight:600},children:[e.jsx("span",{style:{width:14,height:14,borderRadius:"50%",background:"rgba(255,255,255,0.22)",color:"#fff",fontSize:8,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:S.avatarUrl?e.jsx("img",{src:S.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Te(S.name)}),e.jsx("span",{children:S.name}),e.jsx("span",{style:{opacity:.6},children:"•"})]}),e.jsxs("time",{children:[rt(t.occurredAt,!0),w&&e.jsxs(e.Fragment,{children:[" ",e.jsx(mt,{status:t.status})]})]})]}),I=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:[rt(t.occurredAt,!0),w&&e.jsxs(e.Fragment,{children:[" ",e.jsx(mt,{status:t.status})]})]})}),L=w?{...y.bubbleOut,background:n,color:"#fff",border:"1px solid transparent"}:y.bubbleIn,G=!t.text&&f.length===0&&W.length===0;return e.jsxs("div",{style:{...y.messageLine,justifyContent:B,flexDirection:"column",alignItems:B},children:[$.map((k,U)=>e.jsxs("div",{style:{position:"relative",marginBottom:2},children:[e.jsx("img",{src:c(k.url),alt:"sticker",style:{display:"block",maxWidth:128,maxHeight:128,objectFit:"contain"}}),G&&x.length===0&&v.length===0&&U===$.length-1&&I]},`s${U}`)),x.map((k,U)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"zoom-in"},onClick:()=>H({url:c(k.url),kind:"image"}),children:[e.jsx("img",{src:c(k.url),alt:"",style:{display:"block",maxWidth:260,maxHeight:260,borderRadius:12,objectFit:"cover"}}),G&&U===x.length-1&&v.length===0&&I]},U)),v.map((k,U)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"pointer"},onClick:()=>H({url:c(k.url),kind:"video"}),children:[e.jsx("video",{src:c(k.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(Nt,{size:16,fill:"#172033",color:"#172033",style:{marginLeft:2}})})}),G&&U===v.length-1&&I]},U)),(f.length>0||W.length>0||t.text||!x.length&&!v.length&&!$.length&&!t.text)&&e.jsxs("div",{style:L,children:[f.map((k,U)=>e.jsx("audio",{src:c(k.url),controls:!0,style:{display:"block",width:"100%",marginBottom:4}},U)),W.map((k,U)=>e.jsxs("a",{href:c(k.url),target:"_blank",rel:"noreferrer",style:{display:"block",fontSize:12,color:w?"#fff":"#2563eb",textDecoration:"underline",marginBottom:4},children:["📎 ",nn(k.mimeType)]},U)),t.text&&e.jsx("p",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t.text}),!f.length&&!W.length&&!t.text&&e.jsx("p",{style:{margin:0,opacity:.5},children:"[attachment]"}),N]}),R&&Ct.createPortal(e.jsxs("div",{onClick:()=>H(null),style:{position:"fixed",inset:0,zIndex:1e4,background:"rgba(0,0,0,.88)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"zoom-out"},children:[R.kind==="image"?e.jsx("img",{src:R.url,alt:"",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,objectFit:"contain",boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:k=>k.stopPropagation()}):e.jsx("video",{src:R.url,controls:!0,autoPlay:!0,style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:k=>k.stopPropagation()}),e.jsx("button",{onClick:()=>H(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(De,{size:18})})]}),document.body)]})}function jt({conversation:t,connection:n,primary:o,onClose:r,client:c,onStartResize:w,extensions:x,extRefreshKey:$,onLinkContact:v,onRefreshContactInfo:f,layoutMode:W="desktop"}){const R=t.contactName??t.subject??t.providerConversationKey,H=n==null?void 0:n.provider,B=!!(x!=null&&x.some(j=>j.contactInfoRows)),[S,N]=i.useState({channel:!0,stats:!1,extra:!0}),I=j=>N(Q=>({...Q,[j]:!Q[j]})),[L,G]=i.useState(""),[P,te]=i.useState(""),[K,T]=i.useState(!1),[g,k]=i.useState(!1),[U,E]=i.useState(""),[X,le]=i.useState([]),[xe,ce]=i.useState(!1);i.useEffect(()=>{G(""),te(""),k(!1),E(""),c.getNote(t.id).then(j=>{j&&(G(j.content),te(j.content))}).catch(()=>{})},[t.id,c]),i.useEffect(()=>{if(!B||!x)return;let j=!1;const Q=_e(t,{provider:H,linkContact:v,refreshContactInfo:f,sendMessage:async(h,M)=>{await c.sendMessage(t.id,h,M)}});return ce(!0),Promise.allSettled(x.filter(h=>h.contactInfoRows).map(h=>h.contactInfoRows(Q))).then(h=>{if(j)return;const M=h.filter(O=>O.status==="fulfilled").flatMap(O=>O.value);le(M),ce(!1)}),()=>{j=!0}},[t.id,t.contactExternalId,x,$,B,H,v,f,c]);const re=L.trim()!==P.trim()&&L.trim().length>0;async function q(){if(!(!re||K)){T(!0),E("");try{const j=L.trim();await c.upsertNote(t.id,j),te(j),k(!0),setTimeout(()=>k(!1),2e3)}catch{E("Lưu thất bại")}finally{T(!1)}}}return e.jsxs("aside",{style:{...y.infoPanel,position:"relative",...W!=="desktop"?{flex:1,borderLeft:0}:{}},children:[w&&e.jsx("div",{onMouseDown:w,style:{position:"absolute",left:0,top:0,bottom:0,width:4,cursor:"col-resize",zIndex:1},onMouseEnter:j=>{j.currentTarget.style.background="rgba(0,0,0,0.07)"},onMouseLeave:j=>{j.currentTarget.style.background=""}}),e.jsxs("div",{style:y.infoPanelHeader,children:[e.jsx("span",{style:{fontWeight:600,fontSize:13,color:s.ink},children:"Thông tin liên hệ"}),e.jsx("button",{style:y.iconButton,onClick:r,"aria-label":"Đóng",children:e.jsx(De,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:{overflowY:"auto",flex:1},children:[e.jsxs("div",{style:y.infoPanelIdentity,children:[e.jsxs("span",{style:{...y.avatarWrap,width:48,height:48},children:[e.jsx(at,{src:t.contactPictureUrl,fallback:Te(R),style:{...y.avatar,width:48,height:48,fontSize:16}}),e.jsx("span",{style:{...y.providerBadge,width:20,height:20},children:e.jsx(Fe,{provider:H})})]}),e.jsx("strong",{style:{marginTop:10,fontSize:15,color:s.ink,textAlign:"center"},children:R}),e.jsx("span",{style:{fontSize:11,color:s.muted,fontFamily:"monospace",textAlign:"center"},children:t.providerConversationKey})]}),e.jsxs(et,{label:"KÊNH",sectionKey:"channel",expanded:S.channel,onToggle:()=>I("channel"),children:[e.jsx(ue,{label:"Nền tảng",children:e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5},children:[e.jsx(Fe,{provider:H}),e.jsx("span",{children:$t(H)})]})}),e.jsxs(ue,{label:"ID hội thoại",children:[e.jsxs("span",{style:{fontFamily:"monospace",fontSize:11},children:[t.id.slice(0,8),"…"]}),e.jsx(ln,{value:t.id})]})]}),e.jsxs(et,{label:"THỐNG KÊ",sectionKey:"stats",expanded:S.stats,onToggle:()=>I("stats"),children:[e.jsx(ue,{label:"Tin nhắn",value:String(t.messageCount??0)}),(t.unreadCount??0)>0&&e.jsx(ue,{label:"Chưa đọc",value:String(t.unreadCount),valueColor:"#ef4444"}),e.jsx(ue,{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(ue,{label:"Lần đầu",value:"—"})]}),e.jsxs(et,{label:"THÔNG TIN BỔ SUNG",sectionKey:"extra",expanded:S.extra,onToggle:()=>I("extra"),children:[!B&&e.jsxs(e.Fragment,{children:[e.jsx(ue,{label:"Điện thoại",value:"— chưa có",valueMuted:!0}),e.jsx(ue,{label:"Email",value:"— chưa có",valueMuted:!0}),e.jsx(ue,{label:"Nhãn",value:"— chưa có",valueMuted:!0})]}),xe&&X.length===0&&e.jsx("div",{style:{fontSize:12,color:s.muted,padding:"6px 0"},children:"Đang tải hồ sơ CRM…"}),X.map(j=>e.jsx(ue,{label:j.label,children:e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,flexWrap:"wrap",justifyContent:"flex-end"},children:[j.onClick?e.jsx("button",{type:"button",onClick:j.onClick,style:{border:0,background:"none",padding:0,color:o,fontSize:12,fontWeight:600,cursor:"pointer",textDecoration:"underline"},children:j.value}):j.href?e.jsx("a",{href:j.href,target:"_blank",rel:"noopener noreferrer",style:{color:o,fontSize:12,fontWeight:600},children:j.value}):e.jsx("span",{style:{fontSize:12,fontWeight:500,color:s.ink},children:j.value}),j.badge&&e.jsx("span",{style:{fontSize:10.5,fontWeight:700,padding:"1px 7px",borderRadius:999,color:j.badge.color??o,background:j.badge.bg??`${o}14`},children:j.badge.text})]})},j.label))]}),e.jsxs("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:8},children:[!(x!=null&&x.length)&&e.jsx("button",{style:{...y.ghostButton,color:o,borderColor:`${o}33`},children:"Xem lịch sử"}),x==null?void 0:x.flatMap(j=>j.sidebarActions??[]).map((j,Q)=>{const h=j.variant==="primary";return e.jsxs("button",{style:{...y.ghostButton,background:h?o:"#fff",color:h?"#fff":s.ink,borderColor:h?o:s.line,fontWeight:h?700:600,display:"flex",alignItems:"center",justifyContent:"center",gap:6},onClick:()=>{const M=_e(t,{provider:H,linkContact:v,refreshContactInfo:f,sendMessage:async(O,C)=>{await c.sendMessage(t.id,O,C)}});j.onClick(M)},children:[j.icon,j.label]},Q)}),e.jsxs("div",{style:{border:`1px solid ${s.line}`,borderRadius:10,background:s.white,overflow:"hidden"},children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:`1px solid ${s.line}`,background:s.surface,fontSize:11,fontWeight:600,color:s.muted},children:"Ghi chú nội bộ"}),e.jsx("textarea",{value:L,onChange:j=>G(j.target.value),placeholder:"Nhập ghi chú...",rows:3,style:{display:"block",width:"100%",boxSizing:"border-box",border:0,outline:0,background:s.white,resize:"none",padding:"8px 10px",font:"inherit",fontSize:W==="mobile"?16:12,color:s.ink,lineHeight:1.5}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 10px 6px"},children:[g?e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,fontSize:11,color:"#16a34a"},children:[e.jsx(st,{size:11,strokeWidth:2.5})," Đã lưu"]}):U?e.jsx("span",{style:{fontSize:11,color:"#ef4444"},children:U}):e.jsx("span",{}),e.jsx("button",{type:"button",onClick:()=>{q()},disabled:!re||K,style:{padding:"4px 12px",border:0,borderRadius:7,fontSize:12,fontWeight:600,background:re&&!K?o:"#f1f5f9",color:re&&!K?"#fff":"#94a3b8",cursor:re&&!K?"pointer":"not-allowed"},children:K?"Đang lưu…":"Lưu ghi chú"})]})]})]})]})]})}function et({label:t,children:n,sectionKey:o,expanded:r,onToggle:c}){const w=!!c,x=r??!0;return e.jsxs("div",{style:{borderTop:`1px solid ${s.line}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px 6px",fontSize:10,fontWeight:700,letterSpacing:1,color:s.muted,textTransform:"uppercase",cursor:w?"pointer":"default"},onClick:c,children:[e.jsx("span",{children:t}),w&&(x?e.jsx(nt,{size:12,strokeWidth:2}):e.jsx(At,{size:12,strokeWidth:2}))]}),x&&n]})}function ue({label:t,value:n,children:o,valueColor:r,valueMuted:c}){return e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",padding:"5px 16px",fontSize:12,gap:10},children:[e.jsx("span",{style:{color:s.muted,flexShrink:0,lineHeight:1.4},children:t}),e.jsx("span",{style:{color:r??(c?s.muted:s.ink),textAlign:"right",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",flexWrap:"wrap",gap:4,lineHeight:1.4},children:o??n})]})}function ln({value:t}){const[n,o]=i.useState(!1);return e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:s.muted,padding:2,lineHeight:1},title:"Sao chép",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},"aria-label":"Sao chép ID",children:n?"✓":"⎘"})}function dn(){return e.jsxs("div",{style:y.empty,children:[e.jsx("div",{style:y.emptyHero,children:e.jsx(Dt,{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 Bt({name:t,color:n,image:o,provider:r}){return e.jsxs("span",{style:y.avatarWrap,children:[e.jsx(cn,{name:t,color:n,image:o}),r&&e.jsx("span",{style:y.providerBadge,children:e.jsx(Fe,{provider:r})})]})}function cn({name:t,color:n,image:o}){return e.jsx(at,{src:o,fallback:Te(t),style:{...y.avatar,background:`${n}18`,color:n}})}function ot(){return e.jsx(Rt,{size:14,style:y.spinner,"aria-hidden":"true"})}function Te(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}const hn={livechat:"web"};function Fe({provider:t}){const n=i.useContext(lt),o=14;if(!t)return null;const r=hn[t]??t;return e.jsx("img",{src:`${n}/static/logos/${r}.avif`,alt:t,width:o,height:o,style:{borderRadius:"50%",objectFit:"cover",display:"block"}})}function rt(t,n=!1){if(!t)return"";const o=new Date(t);return o.toDateString()===new Date().toDateString()?o.toLocaleTimeString("vi-VN",{hour:"2-digit",minute:"2-digit"}):o.toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit"})}const y={frame:{display:"grid",gridTemplateRows:"minmax(0, 1fr)",height:620,maxHeight:"calc(100dvh - 220px)",minHeight:0,overflow:"hidden",border:`1px solid ${s.line}`,background:s.white,color:s.ink,boxShadow:"0 18px 50px rgba(31,45,72,.10)"},sidebar:{display:"flex",flexDirection:"column",minWidth:0,minHeight:0,borderRight:`1px solid ${s.line}`,background:s.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:s.muted},iconButton:{display:"inline-grid",placeItems:"center",width:32,height:32,marginLeft:"auto",border:0,borderRadius:8,background:"transparent",color:s.muted,cursor:"pointer"},search:{display:"flex",alignItems:"center",gap:8,margin:"0 14px 12px",padding:"9px 10px",border:`1px solid ${s.line}`,borderRadius:9,color:s.muted,background:s.surface},clear:{border:0,background:"none",color:s.muted,cursor:"pointer",fontSize:18},listHeader:{display:"flex",alignItems:"center",padding:"10px 18px",borderTop:`1px solid ${s.line}`,borderBottom:`1px solid ${s.line}`,color:s.muted,fontSize:11,fontWeight:700,letterSpacing:.4,textTransform:"uppercase"},conversationList:{overflowY:"auto",flex:1,minHeight:0},row:{display:"flex",width:"100%",gap:11,padding:"16px 14px",border:0,borderBottom:`1px solid ${s.line}`,background:"transparent",textAlign:"left",cursor:"pointer",transition:"background 120ms ease"},avatarWrap:{position:"relative",flex:"0 0 auto",width:44,height:44},avatar:{flex:"0 0 auto",width:44,height:44,display:"grid",placeItems:"center",borderRadius:"50%",objectFit:"cover",fontSize:14,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:14},rowBottom:{display:"flex",marginTop:4,fontSize:12,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:s.muted,fontSize:12,textAlign:"center"},emptyIcon:{display:"grid",placeItems:"center",width:40,height:40,borderRadius:12,background:s.surface},main:{minWidth:0,minHeight:0,overflow:"hidden",background:s.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 ${s.line}`,background:s.white},contact:{display:"grid",gap:3,minWidth:0,flex:1},contactName:{fontSize:14,fontWeight:600,color:s.ink,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},contactMeta:{display:"flex",alignItems:"center",gap:5,fontSize:11,color:s.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 ${s.line}`,borderRadius:20,padding:"6px 12px",background:s.white,color:s.muted,cursor:"pointer",fontSize:11},messageHint:{display:"flex",justifyContent:"center",alignItems:"center",gap:8,padding:40,color:s.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 ${s.line}`,background:s.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:s.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 ${s.line}`,background:s.white,color:s.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 ${s.line}`,background:s.white,minHeight:0,overflow:"hidden"},infoPanelHeader:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 16px 12px",borderBottom:`1px solid ${s.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 ${s.line}`,borderRadius:8,background:"transparent",fontSize:12,cursor:"pointer",textAlign:"center"}},un={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"},pn={facebook:"facebook",instagram:"instagram",telegram:"telegram",zalo:"zalo",livechat:"web",whatsapp:"web"};function je({provider:t,apiUrl:n,size:o=40}){const r=un[t]??"#f1f5f9",c=pn[t],w=n.replace(/\/$/,"");return e.jsx("div",{style:{width:o,height:o,borderRadius:Math.round(o*.28),background:r,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,overflow:"hidden"},children:c?e.jsx("img",{src:`${w}/static/logos/${c}.avif`,alt:t,width:Math.round(o*.65),height:Math.round(o*.65),style:{objectFit:"contain",display:"block"}}):e.jsx("span",{style:{fontSize:Math.round(o*.45),fontWeight:700,color:"#64748b",textTransform:"uppercase"},children:t.slice(0,1)})})}const Ue={facebook:"Facebook",zalo:"Zalo OA",instagram:"Instagram",telegram:"Telegram",livechat:"Live Chat",whatsapp:"WhatsApp"},fn={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"};function dt(t){const n=t.metadata;return String(n.displayName??n.pageName??n.username??n.name??t.externalAccountId)}function gn(t){const n=t.metadata;switch(t.provider){case"facebook":return`Fanpage · ID ${t.externalAccountId}`;case"instagram":return`@${String(n.username??t.externalAccountId)}`;case"zalo":return`Zalo OA · ID ${t.externalAccountId}`;case"telegram":{const o=String(n.username??"");return o?`@${o}`:`Bot · ${t.externalAccountId}`}case"livechat":return`Widget ID: ${t.id}`;default:{const o=Ue[t.provider]??t.provider,r=String(n.username??n.pageName??"");return r?`${o} · ${r}`:o}}}const d={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 vt(){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 We(){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 kt(){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 wt(){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 xn(){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 bn(){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 St=!1;function yn(){if(St||typeof document>"u")return;St=!0;const t=document.createElement("style");t.textContent="@keyframes ch-spin{to{transform:rotate(360deg)}}",document.head.appendChild(t)}function mn({apiUrl:t,token:n,onConnectionChange:o}){const r=t.replace(/\/$/,""),[c,w]=i.useState([]),[x,$]=i.useState(!0),[v,f]=i.useState({name:"list"}),[W,R]=i.useState(null),[H,B]=i.useState(!1),[S,N]=i.useState(""),[I,L]=i.useState(""),[G,P]=i.useState(""),[te,K]=i.useState(""),[T,g]=i.useState(!1),[k,U]=i.useState(!1),E=i.useRef(null);yn();const X=i.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 M=await h.json();w(M),o==null||o(M)}catch(h){R(h instanceof Error?h.message:"Lỗi tải dữ liệu")}finally{$(!1)}},[r,n,o]);i.useEffect(()=>{X()},[X]),i.useEffect(()=>{if(!W)return;const h=setTimeout(()=>R(null),5e3);return()=>clearTimeout(h)},[W]),i.useEffect(()=>()=>{E.current&&window.removeEventListener("message",E.current)},[]);async function le(h,M){if(confirm(`Bạn chắc chắn muốn ngắt kết nối "${M}"?
131
+ */const gn=q("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
132
+ * @license lucide-react v0.468.0 - ISC
133
+ *
134
+ * This source code is licensed under the ISC license.
135
+ * See the LICENSE file in the root directory of this source tree.
136
+ */const zt=q("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
137
+ * @license lucide-react v0.468.0 - ISC
138
+ *
139
+ * This source code is licensed under the ISC license.
140
+ * See the LICENSE file in the root directory of this source tree.
141
+ */const fn=q("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"}]]);/**
142
+ * @license lucide-react v0.468.0 - ISC
143
+ *
144
+ * This source code is licensed under the ISC license.
145
+ * See the LICENSE file in the root directory of this source tree.
146
+ */const xn=q("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
147
+ * @license lucide-react v0.468.0 - ISC
148
+ *
149
+ * This source code is licensed under the ISC license.
150
+ * See the LICENSE file in the root directory of this source tree.
151
+ */const yn=q("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
152
+ * @license lucide-react v0.468.0 - ISC
153
+ *
154
+ * This source code is licensed under the ISC license.
155
+ * See the LICENSE file in the root directory of this source tree.
156
+ */const bn=q("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"}]]);/**
157
+ * @license lucide-react v0.468.0 - ISC
158
+ *
159
+ * This source code is licensed under the ISC license.
160
+ * See the LICENSE file in the root directory of this source tree.
161
+ */const mn=q("SlidersVertical",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/**
162
+ * @license lucide-react v0.468.0 - ISC
163
+ *
164
+ * This source code is licensed under the ISC license.
165
+ * See the LICENSE file in the root directory of this source tree.
166
+ */const vn=q("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"}]]);/**
167
+ * @license lucide-react v0.468.0 - ISC
168
+ *
169
+ * This source code is licensed under the ISC license.
170
+ * See the LICENSE file in the root directory of this source tree.
171
+ */const rt=q("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
172
+ * @license lucide-react v0.468.0 - ISC
173
+ *
174
+ * This source code is licensed under the ISC license.
175
+ * See the LICENSE file in the root directory of this source tree.
176
+ */const kn=q("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
177
+ * @license lucide-react v0.468.0 - ISC
178
+ *
179
+ * This source code is licensed under the ISC license.
180
+ * See the LICENSE file in the root directory of this source tree.
181
+ */const jn=q("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/**
182
+ * @license lucide-react v0.468.0 - ISC
183
+ *
184
+ * This source code is licensed under the ISC license.
185
+ * See the LICENSE file in the root directory of this source tree.
186
+ */const Rt=q("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/**
187
+ * @license lucide-react v0.468.0 - ISC
188
+ *
189
+ * This source code is licensed under the ISC license.
190
+ * See the LICENSE file in the root directory of this source tree.
191
+ */const Sn=q("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);/**
192
+ * @license lucide-react v0.468.0 - ISC
193
+ *
194
+ * This source code is licensed under the ISC license.
195
+ * See the LICENSE file in the root directory of this source tree.
196
+ */const Ke=q("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
197
+ * @license lucide-react v0.468.0 - ISC
198
+ *
199
+ * This source code is licensed under the ISC license.
200
+ * See the LICENSE file in the root directory of this source tree.
201
+ */const Pt=q("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"}]]),ze={ai:{mode:"off",tone:"friendly",debounceSeconds:5,autoPauseOnAgentAssign:!0,autoPauseOnAgentReply:!0,handoffOnPhone:!0,handoffOnComplaint:!0,schedule:"always",businessHours:{start:"08:00",end:"18:00"},provider:"openai",webhookUrl:"",webhookSecret:"",apiKey:"",model:"gpt-4o-mini",systemPrompt:"",parameters:{}},inbox:{autoAssignOnFirstReply:!0,soundNotification:!0,quickReplies:["Cảm ơn bạn đã liên hệ 🙏","Mình sẽ kiểm tra ngay","Vui lòng chờ 1-2 phút"],welcomeMessageEnabled:!1,welcomeMessageText:"Xin chào! Cảm ơn bạn đã nhắn tin cho cửa hàng. Nhân viên sẽ phản hồi ngay trong ít phút.",awayMessageEnabled:!1,awayMessageText:"Hiện cửa hàng đang ngoài giờ làm việc. Bạn vui lòng để lại Số điện thoại và yêu cầu, chúng mình sẽ liên hệ lại sớm nhất nhé!"},isPlatformManaged:!1};class Ze{constructor(n,r){this.apiUrl=n,this.token=r}async request(n,r,s){const d={authorization:`Bearer ${this.token}`,...s?{}:{"content-type":"application/json"},...r==null?void 0:r.headers},w=await fetch(`${this.apiUrl}${n}`,{...r,headers:d}),v=await w.json().catch(()=>null);if(!w.ok)throw new Error((v==null?void 0:v.message)??`Request failed (${w.status})`);return v}getSessionMe(){return this.request("/v1/auth/session/me")}assignConversation(n,r){return this.request(`/v1/conversations/${encodeURIComponent(n)}/assignee`,{method:"PUT",body:JSON.stringify({agent:r})})}listConnections(){return this.request("/v1/connections")}listConversations(n){return this.request(`/v1/conversations${n?`?cursor=${encodeURIComponent(n)}`:""}`)}listMessages(n,r){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages${r?`?cursor=${encodeURIComponent(r)}`:""}`)}getMessage(n){return this.request(`/v1/messages/${encodeURIComponent(n)}`)}sendMessage(n,r,s){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages`,{method:"POST",headers:{"idempotency-key":crypto.randomUUID()},body:JSON.stringify({text:r,attachments:s})})}async markRead(n){const r=await fetch(`${this.apiUrl}/v1/conversations/${encodeURIComponent(n)}/mark-read`,{method:"POST",headers:{authorization:`Bearer ${this.token}`}});if(!r.ok&&r.status!==204)throw new Error(`markRead failed (${r.status})`)}listCannedResponses(n){const r=n!=null&&n.trim()?`?search=${encodeURIComponent(n)}`:"";return this.request(`/v1/canned-responses${r}`)}createCannedResponse(n){return this.request("/v1/canned-responses",{method:"POST",body:JSON.stringify(n)})}updateCannedResponse(n,r){return this.request(`/v1/canned-responses/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async deleteCannedResponse(n){const r=await fetch(`${this.apiUrl}/v1/canned-responses/${encodeURIComponent(n)}`,{method:"DELETE",headers:{authorization:`Bearer ${this.token}`}});if(!r.ok&&r.status!==204)throw new Error(`deleteCannedResponse failed (${r.status})`)}settingsStorageKey(){return`channelhub_settings_${this.token.slice(0,12)}`}mergeWithDefaultSettings(n){var r,s,d;return{ai:{...ze.ai,...(n==null?void 0:n.ai)??{},businessHours:{...ze.ai.businessHours,...((r=n==null?void 0:n.ai)==null?void 0:r.businessHours)??{}},parameters:{...ze.ai.parameters,...((s=n==null?void 0:n.ai)==null?void 0:s.parameters)??{}}},inbox:{...ze.inbox,...(n==null?void 0:n.inbox)??{},quickReplies:Array.isArray((d=n==null?void 0:n.inbox)==null?void 0:d.quickReplies)?n.inbox.quickReplies:ze.inbox.quickReplies},isPlatformManaged:!!((n==null?void 0:n.isPlatformManaged)??ze.isPlatformManaged)}}async getSettings(){try{const n=await this.request("/v1/settings"),r=this.mergeWithDefaultSettings(n);try{typeof localStorage<"u"&&localStorage.setItem(this.settingsStorageKey(),JSON.stringify(r))}catch{}return r}catch{try{if(typeof localStorage<"u"){const n=localStorage.getItem(this.settingsStorageKey());if(n)return this.mergeWithDefaultSettings(JSON.parse(n))}}catch{}return this.mergeWithDefaultSettings(null)}}async updateSettings(n){var r,s;try{const d=await this.request("/v1/settings",{method:"PUT",body:JSON.stringify(n)}),w=this.mergeWithDefaultSettings(d);try{typeof localStorage<"u"&&localStorage.setItem(this.settingsStorageKey(),JSON.stringify(w))}catch{}return w}catch{const d=await this.getSettings(),w=this.mergeWithDefaultSettings({...d,...n,ai:{...d.ai,...n.ai??{},businessHours:{...d.ai.businessHours,...((r=n.ai)==null?void 0:r.businessHours)??{}},parameters:{...d.ai.parameters,...((s=n.ai)==null?void 0:s.parameters)??{}}},inbox:{...d.inbox,...n.inbox??{}}});try{typeof localStorage<"u"&&localStorage.setItem(this.settingsStorageKey(),JSON.stringify(w))}catch{}return w}}getNote(n){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`)}patchContact(n,r){return this.request(`/v1/contacts/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify({externalId:r})})}upsertNote(n,r){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`,{method:"PUT",body:JSON.stringify({content:r})})}async uploadAttachment(n){const r=new FormData;return r.append("file",n),this.request("/v1/attachments",{method:"POST",body:r},!0)}connectSSE(n){const r=`${this.apiUrl}/v1/events?token=${encodeURIComponent(this.token)}`;let s,d,w=!1;const v=()=>{s=new EventSource(r),s.addEventListener("message.new",E=>{n("message.new",JSON.parse(E.data))}),s.addEventListener("conversation.updated",E=>{n("conversation.updated",JSON.parse(E.data))}),s.onerror=()=>{s.close(),w||(d=setTimeout(v,5e3))}};return v(),()=>{w=!0,clearTimeout(d),s==null||s.close()}}}const wn={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"},Cn={facebook:"facebook",instagram:"instagram",telegram:"telegram",zalo:"zalo",livechat:"web",whatsapp:"web"};function qe({provider:t,apiUrl:n,size:r=40}){const s=wn[t]??"#f1f5f9",d=Cn[t],w=n.replace(/\/$/,"");return e.jsx("div",{style:{width:r,height:r,borderRadius:Math.round(r*.28),background:s,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,overflow:"hidden"},children:d?e.jsx("img",{src:`${w}/static/logos/${d}.avif`,alt:t,width:Math.round(r*.65),height:Math.round(r*.65),style:{objectFit:"contain",display:"block"}}):e.jsx("span",{style:{fontSize:Math.round(r*.45),fontWeight:700,color:"#64748b",textTransform:"uppercase"},children:t.slice(0,1)})})}const tt={facebook:"Facebook",zalo:"Zalo OA",instagram:"Instagram",telegram:"Telegram",livechat:"Live Chat",whatsapp:"WhatsApp"},zn={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"};function xt(t){const n=t.metadata;return String(n.displayName??n.pageName??n.username??n.name??t.externalAccountId)}function Rn(t){const n=t.metadata;switch(t.provider){case"facebook":return`Fanpage · ID ${t.externalAccountId}`;case"instagram":return`@${String(n.username??t.externalAccountId)}`;case"zalo":return`Zalo OA · ID ${t.externalAccountId}`;case"telegram":{const r=String(n.username??"");return r?`@${r}`:`Bot · ${t.externalAccountId}`}case"livechat":return`Widget ID: ${t.id}`;default:{const r=tt[t.provider]??t.provider,s=String(n.username??n.pageName??"");return s?`${r} · ${s}`:r}}}const u={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 It(){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 Ye(){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 Tt(){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 Wt(){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 In(){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 Tn(){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 $t=!1;function Wn(){if($t||typeof document>"u")return;$t=!0;const t=document.createElement("style");t.textContent="@keyframes ch-spin{to{transform:rotate(360deg)}}",document.head.appendChild(t)}function Ft({apiUrl:t,token:n,onConnectionChange:r}){const s=t.replace(/\/$/,""),[d,w]=i.useState([]),[v,E]=i.useState(!0),[C,j]=i.useState({name:"list"}),[$,p]=i.useState(null),[O,U]=i.useState(!1),[M,G]=i.useState(""),[N,b]=i.useState(""),[D,P]=i.useState(""),[ne,_]=i.useState(""),[B,Y]=i.useState(!1),[T,k]=i.useState(!1),F=i.useRef(null);Wn();const re=i.useCallback(async()=>{try{const g=await fetch(`${s}/v1/connections`,{headers:{authorization:`Bearer ${n}`}});if(!g.ok)throw new Error("Không tải được kênh");const L=await g.json();w(L),r==null||r(L)}catch(g){p(g instanceof Error?g.message:"Lỗi tải dữ liệu")}finally{E(!1)}},[s,n,r]);i.useEffect(()=>{re()},[re]),i.useEffect(()=>{if(!$)return;const g=setTimeout(()=>p(null),5e3);return()=>clearTimeout(g)},[$]),i.useEffect(()=>()=>{F.current&&window.removeEventListener("message",F.current)},[]);async function ue(g,L){if(confirm(`Bạn chắc chắn muốn ngắt kết nối "${L}"?
133
202
 
134
- 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 X()}catch(O){R(O instanceof Error?O.message:"Lỗi ngắt kết nối")}}async function xe(){if(!S.trim()){R("Vui lòng nhập Bot Token");return}if(!/^\d+:[A-Za-z0-9_-]+$/.test(S.trim())){R("Token không đúng định dạng");return}B(!0),R(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:S.trim(),displayName:I.trim()||void 0})}),M=await h.json();if(!h.ok||!M.connectionId)throw new Error(M.message??"Không thể kết nối Telegram");N(""),L(""),await X(),f({name:"list"})}catch(h){R(h instanceof Error?h.message:"Lỗi kết nối")}finally{B(!1)}}async function ce(){if(!G.trim()){R("Vui lòng nhập tên widget");return}B(!0),R(null);try{const h=te.split(/[\n,]+/).map(C=>C.trim()).filter(Boolean),M=await fetch(`${r}/v1/connect/livechat/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({displayName:G.trim(),allowedDomains:h.length?h:void 0})}),O=await M.json();if(!M.ok||!O.connectionId||!O.embedScript)throw new Error(O.message??"Không thể tạo widget");P(""),K(""),await X(),f({name:"livechat-result",connectionId:O.connectionId,embedScript:O.embedScript,identitySecret:O.identitySecret??"",allowedDomains:O.allowedDomains??[]})}catch(h){R(h instanceof Error?h.message:"Lỗi tạo widget")}finally{B(!1)}}async function re(h){R(null);try{const M=`${r}/static/oauth-popup.html`,O=await fetch(`${r}/v1/connect/${h}/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({callbackUrl:M})}),C=await O.json();if(!O.ok||!C.authorizationUrl)throw new Error(C.message??"Không thể bắt đầu kết nối");const se=window.open(C.authorizationUrl,"channelhub-oauth","width=600,height=700,scrollbars=yes,resizable=yes");f({name:"oauth-waiting",provider:h,popup:se}),E.current&&window.removeEventListener("message",E.current);const oe=J=>{if(J.data){if(J.data.type==="channelhub:oauth-select"){f({name:"oauth-select",provider:J.data.provider,sessionId:String(J.data.sessionId??""),pages:J.data.pages??[],popup:se});return}J.data.type==="channelhub:oauth"&&(window.removeEventListener("message",oe),E.current=null,J.data.status==="active"?(X(),f({name:"list"})):(R("Kết nối thất bại: "+String(J.data.error??"Không xác định")),f({name:"list"})))}};E.current=oe,window.addEventListener("message",oe)}catch(M){R(M instanceof Error?M.message:"Lỗi kết nối"),f({name:"list"})}}function q(h,M){navigator.clipboard.writeText(h).then(()=>{M==="script"?(g(!0),setTimeout(()=>g(!1),2e3)):(U(!0),setTimeout(()=>U(!1),2e3))})}function j(){const h=v.name==="oauth-waiting"||v.name==="oauth-select"?v.popup:null;if(h)try{h.close()}catch{}E.current&&(window.removeEventListener("message",E.current),E.current=null),f({name:"add"})}async function Q(h){if(v.name!=="oauth-select")return;const{provider:M,sessionId:O,popup:C}=v;B(!0),R(null);const se={facebook:`${r}/v1/connect/facebook/select-page`,instagram:`${r}/v1/connect/instagram/select-account`,zalo:`${r}/v1/connect/zalo/select-oa`},oe={facebook:"pageId",instagram:"accountId",zalo:"oaId"};try{const J=await fetch(se[M]??`${r}/v1/connect/${M}/select-page`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({sessionId:O,[oe[M]??"pageId"]:h})}),ae=await J.json();if(!J.ok||!ae.connectionId)throw new Error(ae.message??"Không thể kết nối");if(C)try{C.postMessage({type:"channelhub:close-popup"},"*")}catch{}E.current&&(window.removeEventListener("message",E.current),E.current=null),await X(),f({name:"list"})}catch(J){R(J instanceof Error?J.message:"Lỗi kết nối")}finally{B(!1)}}return e.jsxs("div",{style:d.root,children:[W&&e.jsx("div",{style:d.errorBanner,children:W}),v.name==="list"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:d.header,children:[e.jsx("div",{style:d.headerLeft,children:e.jsxs("div",{children:[e.jsx("div",{style:d.title,children:"Kênh kết nối"}),e.jsx("div",{style:d.subtitle,children:x?"Đang tải…":`${c.filter(h=>h.status==="active").length} kênh đang hoạt động`})]})}),e.jsxs("button",{style:d.addBtn,onClick:()=>f({name:"add"}),children:[e.jsx(vt,{}),e.jsx("span",{children:"Thêm kênh"})]})]}),e.jsx("div",{style:d.divider}),e.jsx("div",{style:d.body,children:!x&&c.length===0?e.jsxs("div",{style:d.empty,children:[e.jsx("div",{style:{width:64,height:64,borderRadius:16,background:"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(je,{provider:"livechat",apiUrl:r,size:40})}),e.jsx("div",{style:d.emptyTitle,children:"Chưa có kênh nào được kết nối"}),e.jsx("div",{style:d.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:d.emptyCta,onClick:()=>f({name:"add"}),children:[e.jsx(vt,{}),"Kết nối kênh đầu tiên"]})]}):e.jsx("div",{children:c.map(h=>e.jsx(kn,{conn:h,apiUrl:r,onDisconnect:()=>void le(h.id,dt(h))},h.id))})})]}),v.name==="add"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:d.header,children:e.jsxs("div",{style:d.headerLeft,children:[e.jsx("button",{style:d.backBtn,onClick:()=>f({name:"list"}),children:e.jsx(We,{})}),e.jsxs("div",{children:[e.jsx("div",{style:d.title,children:"Thêm kênh mới"}),e.jsx("div",{style:d.subtitle,children:"Chọn nền tảng bạn muốn kết nối"})]})]})}),e.jsx("div",{style:d.divider}),e.jsx("div",{style:d.body,children:e.jsx("div",{style:d.providerGrid,children:wn.map(h=>e.jsx(Sn,{provider:h,apiUrl:r,onClick:()=>{h.type==="oauth"?re(h.id):h.id==="telegram"?f({name:"connect-telegram"}):f({name:"connect-livechat"})}},h.id))})})]}),v.name==="connect-telegram"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:d.connectHeader,children:[e.jsx("button",{style:d.backBtn,onClick:()=>f({name:"add"}),children:e.jsx(We,{})}),e.jsx(je,{provider:"telegram",apiUrl:r,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:d.connectTitle,children:"Kết nối Telegram Bot"}),e.jsx("div",{style:d.connectDesc,children:"Nhập Bot Token để bắt đầu nhận tin nhắn"})]})]}),e.jsxs("div",{style:d.form,children:[e.jsxs("div",{style:d.infoBox,children:[e.jsx(bn,{}),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:d.field,children:[e.jsxs("label",{style:d.label,children:["Bot Token ",e.jsx("span",{style:d.labelHint,children:"bắt buộc"})]}),e.jsx("input",{style:d.input,type:"text",value:S,onChange:h=>N(h.target.value),placeholder:"1234567890:AAExxxxxxxxxxxxxxxxxxxxxxxx",autoComplete:"off",spellCheck:!1}),e.jsxs("div",{style:d.inputHint,children:["Định dạng: ",e.jsx("code",{children:"số:ký_tự"}),", ví dụ: ",e.jsx("code",{children:"1234567890:AAExxxxxxxx"})]})]}),e.jsxs("div",{style:d.field,children:[e.jsxs("label",{style:d.label,children:["Tên hiển thị ",e.jsx("span",{style:d.labelHint,children:"tùy chọn"})]}),e.jsx("input",{style:d.input,type:"text",value:I,onChange:h=>L(h.target.value),placeholder:"VD: Bot hỗ trợ cửa hàng"})]}),e.jsxs("div",{style:d.formActions,children:[e.jsx("button",{style:d.btnSecondary,onClick:()=>f({name:"add"}),children:"Hủy"}),e.jsx("button",{style:d.btnPrimary,disabled:H,onClick:()=>void xe(),children:H?"Đang kết nối…":"Kết nối Telegram"})]})]})]}),v.name==="connect-livechat"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:d.connectHeader,children:[e.jsx("button",{style:d.backBtn,onClick:()=>f({name:"add"}),children:e.jsx(We,{})}),e.jsx(je,{provider:"livechat",apiUrl:r,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:d.connectTitle,children:"Tạo Live Chat Widget"}),e.jsx("div",{style:d.connectDesc,children:"Nhúng vào website để nhận tin nhắn từ khách hàng"})]})]}),e.jsxs("div",{style:d.form,children:[e.jsxs("div",{style:d.field,children:[e.jsxs("label",{style:d.label,children:["Tên widget ",e.jsx("span",{style:d.labelHint,children:"bắt buộc"})]}),e.jsx("input",{style:d.input,type:"text",value:G,onChange:h=>P(h.target.value),placeholder:"VD: Hỗ trợ website hanashop.vn"})]}),e.jsxs("div",{style:d.field,children:[e.jsxs("label",{style:d.label,children:["Tên miền được phép ",e.jsx("span",{style:d.labelHint,children:"tùy chọn"})]}),e.jsx("textarea",{style:{...d.input,resize:"vertical",minHeight:80,lineHeight:1.5},value:te,onChange:h=>K(h.target.value),placeholder:`https://myshop.com
135
- https://www.myshop.com`,spellCheck:!1}),e.jsx("div",{style:d.inputHint,children:"Mỗi domain một dòng. Để trống để cho phép tất cả."})]}),e.jsxs("div",{style:d.formActions,children:[e.jsx("button",{style:d.btnSecondary,onClick:()=>f({name:"add"}),children:"Hủy"}),e.jsx("button",{style:d.btnPrimary,disabled:H,onClick:()=>void ce(),children:H?"Đang tạo…":"Tạo widget"})]})]})]}),v.name==="livechat-result"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:d.connectHeader,children:[e.jsx("button",{style:d.backBtn,onClick:()=>f({name:"list"}),children:e.jsx(We,{})}),e.jsx(je,{provider:"livechat",apiUrl:r,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:d.connectTitle,children:"Widget đã được tạo!"}),e.jsx("div",{style:d.connectDesc,children:"Sao chép mã nhúng và dán vào website của bạn"})]})]}),e.jsxs("div",{style:d.form,children:[e.jsxs("div",{style:d.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:d.codeLabel,children:"Mã nhúng"}),e.jsxs("div",{style:d.codeBlock,children:[e.jsx("pre",{style:d.codePre,children:v.embedScript}),e.jsx("button",{style:{...d.copyBtn,...T?{background:"#166534",borderColor:"#166534",color:"#bbf7d0"}:{}},onClick:()=>q(v.embedScript,"script"),children:T?e.jsxs(e.Fragment,{children:[e.jsx(wt,{})," Đã sao chép"]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{})," Sao chép"]})})]})]}),v.identitySecret&&e.jsxs("div",{children:[e.jsxs("div",{style:d.codeLabel,children:["Identity Secret ",e.jsx("span",{style:{...d.labelHint,color:"#dc2626",fontWeight:600},children:"Lưu ngay — chỉ hiển thị một lần"})]}),e.jsxs("div",{style:d.secretRow,children:[e.jsx(xn,{}),e.jsx("span",{style:d.secretLabel,children:"Secret:"}),e.jsx("span",{style:d.secretValue,children:v.identitySecret}),e.jsx("button",{onClick:()=>q(v.identitySecret,"secret"),style:{border:"none",background:"transparent",cursor:"pointer",color:k?"#059669":"#ca8a04",padding:2,display:"flex",alignItems:"center"},children:k?e.jsx(wt,{}):e.jsx(kt,{})})]}),e.jsx("div",{style:{...d.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:d.formActions,children:[e.jsx("button",{style:d.btnSecondary,onClick:()=>f({name:"list"}),children:"Về danh sách"}),e.jsx("button",{style:d.btnPrimary,onClick:()=>f({name:"add"}),children:"Thêm kênh khác"})]})]})]}),v.name==="oauth-waiting"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:d.header,children:e.jsxs("div",{style:d.headerLeft,children:[e.jsx("button",{style:d.backBtn,onClick:j,children:e.jsx(We,{})}),e.jsxs("div",{children:[e.jsxs("div",{style:d.title,children:["Đang xác thực ",Ue[v.provider]]}),e.jsx("div",{style:d.subtitle,children:"Vui lòng hoàn thành trong cửa sổ bật lên"})]})]})}),e.jsxs("div",{style:d.oauthWaiting,children:[e.jsxs("div",{style:{position:"relative",width:72,height:72},children:[e.jsx("div",{style:{width:72,height:72,borderRadius:20,background:fn[v.provider]??"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(je,{provider:v.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:d.oauthTitle,children:["Đang chờ xác thực với ",Ue[v.provider]]}),e.jsx("div",{style:d.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(tt,{done:!0,label:`Đã mở cửa sổ ${Ue[v.provider]}`}),e.jsx(tt,{active:!0,label:"Đang chờ bạn đăng nhập & cấp quyền"}),e.jsx(tt,{label:"Lưu kết nối & quay về"})]}),e.jsx("button",{style:d.oauthCancel,onClick:j,children:"Hủy và quay lại"})]})]}),v.name==="oauth-select"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:d.connectHeader,children:[e.jsx("button",{style:d.backBtn,onClick:j,children:e.jsx(We,{})}),e.jsx(je,{provider:v.provider,apiUrl:r,size:44}),e.jsxs("div",{children:[e.jsxs("div",{style:d.connectTitle,children:["Chọn ",v.provider==="instagram"?"tài khoản":"trang"]}),e.jsxs("div",{style:d.connectDesc,children:["Chọn ",Ue[v.provider]," bạn muốn kết nối với ChannelHub"]})]})]}),e.jsx("div",{style:d.body,children:v.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:v.pages.map(h=>e.jsxs("button",{disabled:H,onClick:()=>void Q(h.id),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderRadius:12,border:"1.5px solid #e2e8f0",background:"#fff",cursor:H?"not-allowed":"pointer",opacity:H?.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:H?"Đang kết nối…":"Chọn →"})]},h.id))})})]})]})}function jn(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 o=typeof n.pageId=="string"?n.pageId:null;if(o)return`https://graph.facebook.com/${o}/picture?type=square`}return null}function vn({conn:t,apiUrl:n,size:o=40}){const[r,c]=i.useState(!1),w=jn(t),x=Math.round(o*.28);return w&&!r?e.jsx("img",{src:w,alt:dt(t),referrerPolicy:"no-referrer",onError:()=>c(!0),style:{width:o,height:o,borderRadius:x,objectFit:"cover",flexShrink:0,display:"block"}}):e.jsx(je,{provider:t.provider,apiUrl:n,size:o})}function kn({conn:t,apiUrl:n,onDisconnect:o}){const[r,c]=i.useState(!1),[w,x]=i.useState(!1),[$,v]=i.useState(!1),f=t.provider==="livechat",W=n.replace(/\/$/,""),R=f?`<script src="${W}/static/livechat.js" data-widget-id="${t.id}" defer><\/script>`:null,H=()=>{R&&navigator.clipboard.writeText(R).then(()=>{v(!0),setTimeout(()=>v(!1),2e3)})};return e.jsxs("div",{style:{...d.channelItem,flexDirection:"column",alignItems:"stretch",gap:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e.jsx(vn,{conn:t,apiUrl:n,size:40}),e.jsxs("div",{style:d.channelInfo,children:[e.jsx("div",{style:d.channelName,children:dt(t)}),e.jsx("div",{style:{...d.channelMeta,userSelect:"text"},children:gn(t)})]}),e.jsxs("div",{style:d.channelActions,children:[e.jsx("span",{style:t.status==="active"?d.badgeActive:d.badgeInactive,children:t.status==="active"?"Hoạt động":t.status}),f&&e.jsx("button",{style:{...d.disconnectBtn,...w?{background:"#ede9fe",borderColor:"#c4b5fd",color:"#7c3aed"}:{}},onClick:()=>x(B=>!B),children:"Mã nhúng"}),e.jsx("button",{style:{...d.disconnectBtn,...r?{background:"#fef2f2",borderColor:"#fca5a5",color:"#dc2626"}:{}},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onClick:o,children:"Ngắt kết nối"})]})]}),f&&w&&R&&e.jsxs("div",{style:{marginTop:10,borderTop:"1px solid #f1f5f9",paddingTop:10},children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#7c3aed",marginBottom:6,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Mã nhúng — dán vào trước thẻ </body>"}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx("pre",{style:{margin:0,padding:"10px 12px",background:"#f8f7ff",border:"1px solid #e9d5ff",borderRadius:8,fontSize:12,color:"#3b0764",overflowX:"auto",fontFamily:"ui-monospace, SFMono-Regular, monospace",lineHeight:1.5,userSelect:"text"},children:R}),e.jsx("button",{onClick:H,style:{position:"absolute",top:6,right:6,fontSize:11,fontWeight:600,padding:"3px 10px",borderRadius:6,border:"1px solid",borderColor:$?"#059669":"#c4b5fd",background:$?"#d1fae5":"#fff",color:$?"#059669":"#7c3aed",cursor:"pointer"},children:$?"✓ Đã sao chép":"Sao chép"})]})]})]})}const wn=[{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 Sn({provider:t,apiUrl:n,onClick:o}){const[r,c]=i.useState(!1);return e.jsxs("div",{style:{...d.providerCard,...r?{background:"#fff",borderColor:"#e2e8f0",boxShadow:"0 2px 8px rgba(0,0,0,.07)",transform:"translateY(-1px)"}:{}},onClick:o,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[e.jsx(je,{provider:t.id,apiUrl:n,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:d.providerName,children:t.name}),e.jsx("div",{style:d.providerDesc,children:t.desc})]})]})}function tt({done:t,active:n,label:o}){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)"}:{}}}),o]})}function Cn(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}function In(t){if(!t)return"";const n=new Date(t);return n.toDateString()===new Date().toDateString()?n.toLocaleTimeString("vi-VN",{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit"})}function zn({apiUrl:t,token:n,theme:o,locale:r="vi",icon:c,onConversationSelect:w}){const x=(o==null?void 0:o.primaryColor)??"#2563eb",$=typeof c=="function"?c({size:20,color:"currentColor"}):c??e.jsx(ft,{size:20,strokeWidth:1.8}),v=i.useRef(new Ze(t,n)),[f,W]=i.useState(!1),[R,H]=i.useState([]),B=i.useRef(null),S=i.useRef(null),N=R.filter(T=>(T.unreadCount??0)>0),I=N.reduce((T,g)=>T+(g.unreadCount??0),0),L=i.useCallback(async()=>{try{const T=await v.current.listConversations();H(T.items)}catch{}},[]);i.useEffect(()=>(L(),v.current.connectSSE(g=>{(g==="message.new"||g==="conversation.updated")&&L()})),[L]),i.useEffect(()=>{if(!f)return;const T=g=>{var k,U;(k=B.current)!=null&&k.contains(g.target)||(U=S.current)!=null&&U.contains(g.target)||W(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[f]);const G=async T=>{if(W(!1),w==null||w(T.id,T),(T.unreadCount??0)>0)try{await v.current.markRead(T.id),H(g=>g.map(k=>k.id===T.id?{...k,unreadCount:0}:k))}catch{}},P=r==="en"?`${I} unread message${I!==1?"s":""}`:`${I} tin nhắn chưa đọc`,te=r==="en"?"No unread messages":"Không có tin nhắn mới",K=r==="en"?"Messages":"Tin nhắn";return e.jsxs("div",{style:{position:"relative",display:"inline-block",fontFamily:(o==null?void 0:o.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif"},children:[e.jsxs("button",{ref:B,"aria-label":P,"aria-haspopup":"true","aria-expanded":f,onClick:()=>W(T=>!T),style:{position:"relative",display:"inline-grid",placeItems:"center",width:40,height:40,border:0,borderRadius:"50%",background:f?`${x}18`:"transparent",color:f?x:"#6b7280",cursor:"pointer",transition:"background 150ms ease, color 150ms ease"},children:[$,I>0&&e.jsx("span",{"aria-hidden":"true",style:{position:"absolute",top:4,right:4,minWidth:16,height:16,borderRadius:999,background:"#ef4444",color:"#fff",fontSize:10,fontWeight:800,lineHeight:"16px",textAlign:"center",padding:"0 4px",border:"2px solid #fff",boxSizing:"border-box"},children:I>99?"99+":I})]}),f&&e.jsxs("div",{ref:S,role:"dialog","aria-label":K,style:{position:"absolute",top:"calc(100% + 8px)",right:0,zIndex:9999,width:360,maxHeight:480,background:"#fff",border:"1px solid #e7ebf2",borderRadius:14,boxShadow:"0 12px 40px rgba(23,32,51,.14)",overflow:"hidden",display:"flex",flexDirection:"column"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 10px",borderBottom:"1px solid #e7ebf2"},children:[e.jsx("span",{style:{fontSize:16,fontWeight:700,color:"#172033"},children:K}),I>0&&e.jsxs("span",{style:{fontSize:11,fontWeight:600,background:`${x}14`,color:x,borderRadius:999,padding:"2px 8px"},children:[I," ",r==="en"?"unread":"chưa đọc"]})]}),e.jsx("div",{style:{overflowY:"auto",flex:1},children:N.length===0?e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"40px 24px",color:"#9aa5b5"},children:[e.jsx(ft,{size:28,strokeWidth:1.5}),e.jsx("span",{style:{fontSize:13},children:te})]}):N.map(T=>e.jsx(Rn,{conversation:T,primary:x,apiUrl:t,onSelect:G},T.id))})]})]})}function Rn({conversation:t,primary:n,apiUrl:o,onSelect:r}){const[c,w]=i.useState(!1),x=t.contactName??t.providerConversationKey,$=t.unreadCount??0;return e.jsxs("button",{onClick:()=>r(t),onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),style:{display:"flex",width:"100%",gap:12,padding:"10px 16px",border:0,borderBottom:"1px solid #f1f5f9",background:c?"#f7f9fc":$>0?"#f0f4ff":"#fff",textAlign:"left",cursor:"pointer",transition:"background 100ms ease",alignItems:"center"},children:[e.jsxs("span",{style:{position:"relative",flex:"0 0 auto",width:42,height:42},children:[e.jsx(at,{src:t.contactPictureUrl,fallback:Cn(x),style:{width:42,height:42,borderRadius:"50%",objectFit:"cover",display:"grid",placeItems:"center",fontSize:13,fontWeight:800,background:`${n}18`,color:n}}),void 0]}),e.jsxs("span",{style:{flex:1,minWidth:0},children:[e.jsxs("span",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontSize:13,fontWeight:$>0?700:500,color:"#172033",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,flexShrink:0},children:[e.jsx("time",{style:{fontSize:11,color:"#9aa5b5",whiteSpace:"nowrap"},children:In(t.lastMessageAt)}),$>0&&e.jsx("span",{style:{display:"inline-grid",placeItems:"center",minWidth:18,height:18,borderRadius:999,background:"#ef4444",color:"#fff",fontSize:10,fontWeight:800,padding:"0 4px"},children:$>99?"99+":$})]})]}),e.jsxs("span",{style:{display:"block",marginTop:2,fontSize:12,color:$>0?"#374151":"#9aa5b5",fontWeight:$>0?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.lastMessageDirection==="outbound"&&e.jsx("span",{style:{color:"#9aa5b5"},children:"Bạn: "}),t.lastMessageText||e.jsx("span",{style:{opacity:.5},children:"Chưa có tin nhắn"})]})]})]})}console.log("[ChannelHub] widget v0.1.12 loaded");exports.ChannelHubChannels=mn;exports.ChannelHubClient=Ze;exports.ChannelHubInbox=on;exports.ChannelHubNotificationBell=zn;
203
+ Hành động này không thể hoàn tác.`))try{if(!(await fetch(`${s}/v1/connections/${g}`,{method:"DELETE",headers:{authorization:`Bearer ${n}`}})).ok)throw new Error("Không thể ngắt kết nối");await re()}catch(K){p(K instanceof Error?K.message:"Lỗi ngắt kết nối")}}async function se(){if(!M.trim()){p("Vui lòng nhập Bot Token");return}if(!/^\d+:[A-Za-z0-9_-]+$/.test(M.trim())){p("Token không đúng định dạng");return}U(!0),p(null);try{const g=await fetch(`${s}/v1/connect/telegram/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({botToken:M.trim(),displayName:N.trim()||void 0})}),L=await g.json();if(!g.ok||!L.connectionId)throw new Error(L.message??"Không thể kết nối Telegram");G(""),b(""),await re(),j({name:"list"})}catch(g){p(g instanceof Error?g.message:"Lỗi kết nối")}finally{U(!1)}}async function ae(){if(!D.trim()){p("Vui lòng nhập tên widget");return}U(!0),p(null);try{const g=ne.split(/[\n,]+/).map(Q=>Q.trim()).filter(Boolean),L=await fetch(`${s}/v1/connect/livechat/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({displayName:D.trim(),allowedDomains:g.length?g:void 0})}),K=await L.json();if(!L.ok||!K.connectionId||!K.embedScript)throw new Error(K.message??"Không thể tạo widget");P(""),_(""),await re(),j({name:"livechat-result",connectionId:K.connectionId,embedScript:K.embedScript,identitySecret:K.identitySecret??"",allowedDomains:K.allowedDomains??[]})}catch(g){p(g instanceof Error?g.message:"Lỗi tạo widget")}finally{U(!1)}}async function le(g){p(null);try{const L=`${s}/static/oauth-popup.html`,K=await fetch(`${s}/v1/connect/${g}/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({callbackUrl:L})}),Q=await K.json();if(!K.ok||!Q.authorizationUrl)throw new Error(Q.message??"Không thể bắt đầu kết nối");const de=window.open(Q.authorizationUrl,"channelhub-oauth","width=600,height=700,scrollbars=yes,resizable=yes");j({name:"oauth-waiting",provider:g,popup:de}),F.current&&window.removeEventListener("message",F.current);const pe=m=>{if(m.data){if(m.data.type==="channelhub:oauth-select"){j({name:"oauth-select",provider:m.data.provider,sessionId:String(m.data.sessionId??""),pages:m.data.pages??[],popup:de});return}m.data.type==="channelhub:oauth"&&(window.removeEventListener("message",pe),F.current=null,m.data.status==="active"?(re(),j({name:"list"})):(p("Kết nối thất bại: "+String(m.data.error??"Không xác định")),j({name:"list"})))}};F.current=pe,window.addEventListener("message",pe)}catch(L){p(L instanceof Error?L.message:"Lỗi kết nối"),j({name:"list"})}}function ke(g,L){navigator.clipboard.writeText(g).then(()=>{L==="script"?(Y(!0),setTimeout(()=>Y(!1),2e3)):(k(!0),setTimeout(()=>k(!1),2e3))})}function R(){const g=C.name==="oauth-waiting"||C.name==="oauth-select"?C.popup:null;if(g)try{g.close()}catch{}F.current&&(window.removeEventListener("message",F.current),F.current=null),j({name:"add"})}async function ie(g){if(C.name!=="oauth-select")return;const{provider:L,sessionId:K,popup:Q}=C;U(!0),p(null);const de={facebook:`${s}/v1/connect/facebook/select-page`,instagram:`${s}/v1/connect/instagram/select-account`,zalo:`${s}/v1/connect/zalo/select-oa`},pe={facebook:"pageId",instagram:"accountId",zalo:"oaId"};try{const m=await fetch(de[L]??`${s}/v1/connect/${L}/select-page`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({sessionId:K,[pe[L]??"pageId"]:g})}),ce=await m.json();if(!m.ok||!ce.connectionId)throw new Error(ce.message??"Không thể kết nối");if(Q)try{Q.postMessage({type:"channelhub:close-popup"},"*")}catch{}F.current&&(window.removeEventListener("message",F.current),F.current=null),await re(),j({name:"list"})}catch(m){p(m instanceof Error?m.message:"Lỗi kết nối")}finally{U(!1)}}return e.jsxs("div",{style:u.root,children:[$&&e.jsx("div",{style:u.errorBanner,children:$}),C.name==="list"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:u.header,children:[e.jsx("div",{style:u.headerLeft,children:e.jsxs("div",{children:[e.jsx("div",{style:u.title,children:"Kênh kết nối"}),e.jsx("div",{style:u.subtitle,children:v?"Đang tải…":`${d.filter(g=>g.status==="active").length} kênh đang hoạt động`})]})}),e.jsxs("button",{style:u.addBtn,onClick:()=>j({name:"add"}),children:[e.jsx(It,{}),e.jsx("span",{children:"Thêm kênh"})]})]}),e.jsx("div",{style:u.divider}),e.jsx("div",{style:u.body,children:!v&&d.length===0?e.jsxs("div",{style:u.empty,children:[e.jsx("div",{style:{width:64,height:64,borderRadius:16,background:"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(qe,{provider:"livechat",apiUrl:s,size:40})}),e.jsx("div",{style:u.emptyTitle,children:"Chưa có kênh nào được kết nối"}),e.jsx("div",{style:u.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:u.emptyCta,onClick:()=>j({name:"add"}),children:[e.jsx(It,{}),"Kết nối kênh đầu tiên"]})]}):e.jsx("div",{children:d.map(g=>e.jsx(Bn,{conn:g,apiUrl:s,onDisconnect:()=>void ue(g.id,xt(g))},g.id))})})]}),C.name==="add"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:u.header,children:e.jsxs("div",{style:u.headerLeft,children:[e.jsx("button",{style:u.backBtn,onClick:()=>j({name:"list"}),children:e.jsx(Ye,{})}),e.jsxs("div",{children:[e.jsx("div",{style:u.title,children:"Thêm kênh mới"}),e.jsx("div",{style:u.subtitle,children:"Chọn nền tảng bạn muốn kết nối"})]})]})}),e.jsx("div",{style:u.divider}),e.jsx("div",{style:u.body,children:e.jsx("div",{style:u.providerGrid,children:An.map(g=>e.jsx(En,{provider:g,apiUrl:s,onClick:()=>{g.type==="oauth"?le(g.id):g.id==="telegram"?j({name:"connect-telegram"}):j({name:"connect-livechat"})}},g.id))})})]}),C.name==="connect-telegram"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:u.connectHeader,children:[e.jsx("button",{style:u.backBtn,onClick:()=>j({name:"add"}),children:e.jsx(Ye,{})}),e.jsx(qe,{provider:"telegram",apiUrl:s,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:u.connectTitle,children:"Kết nối Telegram Bot"}),e.jsx("div",{style:u.connectDesc,children:"Nhập Bot Token để bắt đầu nhận tin nhắn"})]})]}),e.jsxs("div",{style:u.form,children:[e.jsxs("div",{style:u.infoBox,children:[e.jsx(Tn,{}),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:u.field,children:[e.jsxs("label",{style:u.label,children:["Bot Token ",e.jsx("span",{style:u.labelHint,children:"bắt buộc"})]}),e.jsx("input",{style:u.input,type:"text",value:M,onChange:g=>G(g.target.value),placeholder:"1234567890:AAExxxxxxxxxxxxxxxxxxxxxxxx",autoComplete:"off",spellCheck:!1}),e.jsxs("div",{style:u.inputHint,children:["Định dạng: ",e.jsx("code",{children:"số:ký_tự"}),", ví dụ: ",e.jsx("code",{children:"1234567890:AAExxxxxxxx"})]})]}),e.jsxs("div",{style:u.field,children:[e.jsxs("label",{style:u.label,children:["Tên hiển thị ",e.jsx("span",{style:u.labelHint,children:"tùy chọn"})]}),e.jsx("input",{style:u.input,type:"text",value:N,onChange:g=>b(g.target.value),placeholder:"VD: Bot hỗ trợ cửa hàng"})]}),e.jsxs("div",{style:u.formActions,children:[e.jsx("button",{style:u.btnSecondary,onClick:()=>j({name:"add"}),children:"Hủy"}),e.jsx("button",{style:u.btnPrimary,disabled:O,onClick:()=>void se(),children:O?"Đang kết nối…":"Kết nối Telegram"})]})]})]}),C.name==="connect-livechat"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:u.connectHeader,children:[e.jsx("button",{style:u.backBtn,onClick:()=>j({name:"add"}),children:e.jsx(Ye,{})}),e.jsx(qe,{provider:"livechat",apiUrl:s,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:u.connectTitle,children:"Tạo Live Chat Widget"}),e.jsx("div",{style:u.connectDesc,children:"Nhúng vào website để nhận tin nhắn từ khách hàng"})]})]}),e.jsxs("div",{style:u.form,children:[e.jsxs("div",{style:u.field,children:[e.jsxs("label",{style:u.label,children:["Tên widget ",e.jsx("span",{style:u.labelHint,children:"bắt buộc"})]}),e.jsx("input",{style:u.input,type:"text",value:D,onChange:g=>P(g.target.value),placeholder:"VD: Hỗ trợ website hanashop.vn"})]}),e.jsxs("div",{style:u.field,children:[e.jsxs("label",{style:u.label,children:["Tên miền được phép ",e.jsx("span",{style:u.labelHint,children:"tùy chọn"})]}),e.jsx("textarea",{style:{...u.input,resize:"vertical",minHeight:80,lineHeight:1.5},value:ne,onChange:g=>_(g.target.value),placeholder:`https://myshop.com
204
+ https://www.myshop.com`,spellCheck:!1}),e.jsx("div",{style:u.inputHint,children:"Mỗi domain một dòng. Để trống để cho phép tất cả."})]}),e.jsxs("div",{style:u.formActions,children:[e.jsx("button",{style:u.btnSecondary,onClick:()=>j({name:"add"}),children:"Hủy"}),e.jsx("button",{style:u.btnPrimary,disabled:O,onClick:()=>void ae(),children:O?"Đang tạo…":"Tạo widget"})]})]})]}),C.name==="livechat-result"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:u.connectHeader,children:[e.jsx("button",{style:u.backBtn,onClick:()=>j({name:"list"}),children:e.jsx(Ye,{})}),e.jsx(qe,{provider:"livechat",apiUrl:s,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:u.connectTitle,children:"Widget đã được tạo!"}),e.jsx("div",{style:u.connectDesc,children:"Sao chép mã nhúng và dán vào website của bạn"})]})]}),e.jsxs("div",{style:u.form,children:[e.jsxs("div",{style:u.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:u.codeLabel,children:"Mã nhúng"}),e.jsxs("div",{style:u.codeBlock,children:[e.jsx("pre",{style:u.codePre,children:C.embedScript}),e.jsx("button",{style:{...u.copyBtn,...B?{background:"#166534",borderColor:"#166534",color:"#bbf7d0"}:{}},onClick:()=>ke(C.embedScript,"script"),children:B?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{})," Đã sao chép"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tt,{})," Sao chép"]})})]})]}),C.identitySecret&&e.jsxs("div",{children:[e.jsxs("div",{style:u.codeLabel,children:["Identity Secret ",e.jsx("span",{style:{...u.labelHint,color:"#dc2626",fontWeight:600},children:"Lưu ngay — chỉ hiển thị một lần"})]}),e.jsxs("div",{style:u.secretRow,children:[e.jsx(In,{}),e.jsx("span",{style:u.secretLabel,children:"Secret:"}),e.jsx("span",{style:u.secretValue,children:C.identitySecret}),e.jsx("button",{onClick:()=>ke(C.identitySecret,"secret"),style:{border:"none",background:"transparent",cursor:"pointer",color:T?"#059669":"#ca8a04",padding:2,display:"flex",alignItems:"center"},children:T?e.jsx(Wt,{}):e.jsx(Tt,{})})]}),e.jsx("div",{style:{...u.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:u.formActions,children:[e.jsx("button",{style:u.btnSecondary,onClick:()=>j({name:"list"}),children:"Về danh sách"}),e.jsx("button",{style:u.btnPrimary,onClick:()=>j({name:"add"}),children:"Thêm kênh khác"})]})]})]}),C.name==="oauth-waiting"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:u.header,children:e.jsxs("div",{style:u.headerLeft,children:[e.jsx("button",{style:u.backBtn,onClick:R,children:e.jsx(Ye,{})}),e.jsxs("div",{children:[e.jsxs("div",{style:u.title,children:["Đang xác thực ",tt[C.provider]]}),e.jsx("div",{style:u.subtitle,children:"Vui lòng hoàn thành trong cửa sổ bật lên"})]})]})}),e.jsxs("div",{style:u.oauthWaiting,children:[e.jsxs("div",{style:{position:"relative",width:72,height:72},children:[e.jsx("div",{style:{width:72,height:72,borderRadius:20,background:zn[C.provider]??"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(qe,{provider:C.provider,apiUrl:s,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:u.oauthTitle,children:["Đang chờ xác thực với ",tt[C.provider]]}),e.jsx("div",{style:u.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(ct,{done:!0,label:`Đã mở cửa sổ ${tt[C.provider]}`}),e.jsx(ct,{active:!0,label:"Đang chờ bạn đăng nhập & cấp quyền"}),e.jsx(ct,{label:"Lưu kết nối & quay về"})]}),e.jsx("button",{style:u.oauthCancel,onClick:R,children:"Hủy và quay lại"})]})]}),C.name==="oauth-select"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:u.connectHeader,children:[e.jsx("button",{style:u.backBtn,onClick:R,children:e.jsx(Ye,{})}),e.jsx(qe,{provider:C.provider,apiUrl:s,size:44}),e.jsxs("div",{children:[e.jsxs("div",{style:u.connectTitle,children:["Chọn ",C.provider==="instagram"?"tài khoản":"trang"]}),e.jsxs("div",{style:u.connectDesc,children:["Chọn ",tt[C.provider]," bạn muốn kết nối với ChannelHub"]})]})]}),e.jsx("div",{style:u.body,children:C.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:C.pages.map(g=>e.jsxs("button",{disabled:O,onClick:()=>void ie(g.id),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderRadius:12,border:"1.5px solid #e2e8f0",background:"#fff",cursor:O?"not-allowed":"pointer",opacity:O?.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:g.name}),e.jsx("div",{style:{fontSize:11,color:"#94a3b8",fontFamily:"monospace",marginTop:2},children:g.id})]}),e.jsx("span",{style:{fontSize:13,color:"#2563eb",fontWeight:500},children:O?"Đang kết nối…":"Chọn →"})]},g.id))})})]})]})}function $n(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 r=typeof n.pageId=="string"?n.pageId:null;if(r)return`https://graph.facebook.com/${r}/picture?type=square`}return null}function Mn({conn:t,apiUrl:n,size:r=40}){const[s,d]=i.useState(!1),w=$n(t),v=Math.round(r*.28);return w&&!s?e.jsx("img",{src:w,alt:xt(t),referrerPolicy:"no-referrer",onError:()=>d(!0),style:{width:r,height:r,borderRadius:v,objectFit:"cover",flexShrink:0,display:"block"}}):e.jsx(qe,{provider:t.provider,apiUrl:n,size:r})}function Bn({conn:t,apiUrl:n,onDisconnect:r}){const[s,d]=i.useState(!1),[w,v]=i.useState(!1),[E,C]=i.useState(!1),j=t.provider==="livechat",$=n.replace(/\/$/,""),p=j?`<script src="${$}/static/livechat.js" data-widget-id="${t.id}" defer><\/script>`:null,O=()=>{p&&navigator.clipboard.writeText(p).then(()=>{C(!0),setTimeout(()=>C(!1),2e3)})};return e.jsxs("div",{style:{...u.channelItem,flexDirection:"column",alignItems:"stretch",gap:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e.jsx(Mn,{conn:t,apiUrl:n,size:40}),e.jsxs("div",{style:u.channelInfo,children:[e.jsx("div",{style:u.channelName,children:xt(t)}),e.jsx("div",{style:{...u.channelMeta,userSelect:"text"},children:Rn(t)})]}),e.jsxs("div",{style:u.channelActions,children:[e.jsx("span",{style:t.status==="active"?u.badgeActive:u.badgeInactive,children:t.status==="active"?"Hoạt động":t.status}),j&&e.jsx("button",{style:{...u.disconnectBtn,...w?{background:"#ede9fe",borderColor:"#c4b5fd",color:"#7c3aed"}:{}},onClick:()=>v(U=>!U),children:"Mã nhúng"}),e.jsx("button",{style:{...u.disconnectBtn,...s?{background:"#fef2f2",borderColor:"#fca5a5",color:"#dc2626"}:{}},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),onClick:r,children:"Ngắt kết nối"})]})]}),j&&w&&p&&e.jsxs("div",{style:{marginTop:10,borderTop:"1px solid #f1f5f9",paddingTop:10},children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#7c3aed",marginBottom:6,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Mã nhúng — dán vào trước thẻ </body>"}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx("pre",{style:{margin:0,padding:"10px 12px",background:"#f8f7ff",border:"1px solid #e9d5ff",borderRadius:8,fontSize:12,color:"#3b0764",overflowX:"auto",fontFamily:"ui-monospace, SFMono-Regular, monospace",lineHeight:1.5,userSelect:"text"},children:p}),e.jsx("button",{onClick:O,style:{position:"absolute",top:6,right:6,fontSize:11,fontWeight:600,padding:"3px 10px",borderRadius:6,border:"1px solid",borderColor:E?"#059669":"#c4b5fd",background:E?"#d1fae5":"#fff",color:E?"#059669":"#7c3aed",cursor:"pointer"},children:E?"✓ Đã sao chép":"Sao chép"})]})]})]})}const An=[{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 En({provider:t,apiUrl:n,onClick:r}){const[s,d]=i.useState(!1);return e.jsxs("div",{style:{...u.providerCard,...s?{background:"#fff",borderColor:"#e2e8f0",boxShadow:"0 2px 8px rgba(0,0,0,.07)",transform:"translateY(-1px)"}:{}},onClick:r,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[e.jsx(qe,{provider:t.id,apiUrl:n,size:44}),e.jsxs("div",{children:[e.jsx("div",{style:u.providerName,children:t.name}),e.jsx("div",{style:u.providerDesc,children:t.desc})]})]})}function ct({done:t,active:n,label:r}){const s=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:s,flexShrink:0,...n?{boxShadow:"0 0 0 3px rgba(37,99,235,.2)"}:{}}}),r]})}const a={ink:"#172033",muted:"#718096",line:"#e7ebf2",surface:"#f7f9fc",white:"#ffffff"},Ln=[{title:"Chào khách hàng",shortcut:"/chao",content:"Dạ chào Anh/Chị ạ! Em có thể hỗ trợ tư vấn sản phẩm hoặc kiểm tra đơn hàng gì cho mình hôm nay ạ?"},{title:"Báo phí giao hàng",shortcut:"/ship",content:"Dạ phí giao hàng tiêu chuẩn bên em là 25.000đ toàn quốc, miễn phí ship cho đơn hàng từ 300.000đ trở lên ạ."},{title:"Xin thông tin đặt hàng",shortcut:"/don",content:"Dạ để em lên đơn nhanh cho mình, Anh/Chị cho em xin: Họ tên + Số điện thoại + Địa chỉ nhận hàng nhé ạ!"},{title:"Cảm ơn khách hàng",shortcut:"/camon",content:"Dạ em cảm ơn Anh/Chị đã tin tưởng ủng hộ cửa hàng! Nếu cần hỗ trợ thêm bất kỳ thông tin gì, Anh/Chị cứ nhắn cho em nhé ạ 🙏"}];function De({checked:t,onChange:n,primary:r,label:s,description:d}){return e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:14,padding:"12px 14px",borderRadius:10,border:`1px solid ${a.line}`,background:a.white},children:[e.jsxs("div",{style:{minWidth:0,flex:1},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600,color:a.ink,lineHeight:1.35},children:s}),d&&e.jsx("div",{style:{fontSize:11.5,color:a.muted,marginTop:3,lineHeight:1.45},children:d})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":t,"aria-label":s,onClick:()=>n(!t),style:{position:"relative",width:40,height:22,borderRadius:999,border:0,padding:0,flexShrink:0,cursor:"pointer",background:t?r:"#cbd5e1",transition:"background 150ms ease"},children:e.jsx("span",{style:{position:"absolute",top:2,left:t?20:2,width:18,height:18,borderRadius:"50%",background:"#fff",boxShadow:"0 1px 3px rgba(15,23,42,.2)",transition:"left 150ms ease"}})})]})}const Hn=["ai","templates","inbox"];function Nt({apiUrl:t,token:n,theme:r,initialTab:s="ai",tabs:d,hideTechnicalAiConfig:w,customParameters:v,starterTemplates:E,onSettingsChange:C,onClose:j}){var ge,Ue,Je;const $=i.useRef(new Ze(t,n)),p=(r==null?void 0:r.primaryColor)??"#2563eb",O=(r==null?void 0:r.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif";i.useEffect(()=>{$.current=new Ze(t,n)},[t,n]);const U=d&&d.length>0?d.join(","):"",M=i.useMemo(()=>d&&d.length>0?d:Hn,[U]),[G,N]=i.useState(()=>M.includes(s)?s:M[0]);i.useEffect(()=>{M.includes(s)&&N(s)},[s]);const[b,D]=i.useState(ze),[P,ne]=i.useState(!0),[_,B]=i.useState(!1),[Y,T]=i.useState(!1),[k,F]=i.useState(""),[re,ue]=i.useState([]),[se,ae]=i.useState(!0),[le,ke]=i.useState(!1),[R,ie]=i.useState(null),[g,L]=i.useState(""),[K,Q]=i.useState(""),[de,pe]=i.useState(""),[m,ce]=i.useState(!1),[je,Oe]=i.useState(""),[Se,Ge]=i.useState("Shop ơi mẫu này còn hàng không, giá bao nhiêu ạ?"),[we,Be]=i.useState(!1),[ee,Pe]=i.useState(null),Re=i.useRef(null),[H,Ae]=i.useState(()=>typeof window<"u"?window.innerWidth<680:!1);i.useEffect(()=>{const o=Re.current;if(!o||typeof ResizeObserver>"u")return;const f=new ResizeObserver(x=>{for(const fe of x)fe.contentRect.width>0&&Ae(fe.contentRect.width<640)});return f.observe(o),()=>f.disconnect()},[]);const Ce=i.useCallback(async()=>{ne(!0);try{const o=await $.current.getSettings();if(v!=null&&v.length){const f={...o.ai.parameters};for(const x of v)f[x.key]===void 0&&x.defaultValue!==void 0&&(f[x.key]=x.defaultValue);o.ai.parameters=f}D(o)}catch(o){F(o instanceof Error?o.message:"Không tải được cài đặt")}finally{ne(!1)}},[v]),Ee=i.useCallback(async()=>{ae(!0);try{const o=await $.current.listCannedResponses();ue(o)}catch{}finally{ae(!1)}},[]);i.useEffect(()=>{Ce(),Ee()},[Ce,Ee]);async function X(o){const f=b;B(!0),F(""),T(!1);try{const x=await $.current.updateSettings({ai:f.ai,inbox:f.inbox});D(x),C==null||C(x),T(!0),setTimeout(()=>T(!1),2200)}catch(x){F(x instanceof Error?x.message:"Lưu cài đặt thất bại")}finally{B(!1)}}function Z(o,f){D(x=>({...x,ai:{...x.ai,[o]:f}}))}function ye(o,f){D(x=>({...x,inbox:{...x.inbox,[o]:f}}))}function Ie(o,f){D(x=>({...x,ai:{...x.ai,parameters:{...x.ai.parameters,[o]:f}}}))}function Te(){ie("new"),L(""),Q(""),pe("")}function Ve(o){ie(o.id),L(o.title),Q(o.shortcut??""),pe(o.content)}async function Fe(){if(!g.trim()||!de.trim()||m)return;ce(!0),F("");const o=K.trim()?K.trim().startsWith("/")?K.trim():`/${K.trim()}`:void 0;try{if(R==="new"){const f=await $.current.createCannedResponse({title:g.trim(),content:de.trim(),...o?{shortcut:o}:{}});ue(x=>[...x,f])}else if(R){const f=await $.current.updateCannedResponse(R,{title:g.trim(),content:de.trim(),shortcut:o??null});ue(x=>x.map(fe=>fe.id===f.id?f:fe))}ie(null)}catch(f){F(f instanceof Error?f.message:"Không lưu được mẫu câu")}finally{ce(!1)}}async function We(o){try{await $.current.deleteCannedResponse(o),ue(f=>f.filter(x=>x.id!==o)),R===o&&ie(null)}catch(f){F(f instanceof Error?f.message:"Không xóa được mẫu câu")}}async function _e(){if(le)return;ke(!0),F("");const o=E!=null&&E.length?E:Ln;try{const f=[];for(const x of o){const fe=await $.current.createCannedResponse({title:x.title,content:x.content,...x.shortcut?{shortcut:x.shortcut}:{}});f.push(fe)}ue(x=>[...x,...f])}catch(f){F(f instanceof Error?f.message:"Không nạp được bộ mẫu câu gợi ý")}finally{ke(!1)}}function Ne(){const o=je.trim();if(!o)return;if(b.inbox.quickReplies.includes(o)){Oe("");return}const f=[...b.inbox.quickReplies,o],x={...b,inbox:{...b.inbox,quickReplies:f}};D(x),Oe("")}function Le(o){const f=b.inbox.quickReplies.filter(x=>x!==o);D(x=>({...x,inbox:{...x.inbox,quickReplies:f}}))}const be=w!==void 0?w:!!b.isPlatformManaged,oe={ai:{label:"Trợ lý AI",icon:e.jsx(rt,{size:15})},templates:{label:"Mẫu câu trả lời nhanh",icon:e.jsx(Pt,{size:15})},inbox:{label:"Hộp thư & Tự động hóa",icon:e.jsx(Ot,{size:15})},channels:{label:"Kênh kết nối",icon:e.jsx(pn,{size:15})}};return e.jsxs("div",{ref:Re,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",maxHeight:"100%",background:a.white,color:a.ink,fontFamily:O,borderRadius:(r==null?void 0:r.borderRadius)??"16px",border:`1px solid ${a.line}`,overflow:"hidden",boxSizing:"border-box"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:H?"14px 16px":"16px 22px",borderBottom:`1px solid ${a.line}`,background:a.white,flexShrink:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,minWidth:0},children:[e.jsx("div",{style:{width:34,height:34,borderRadius:10,background:`${p}14`,color:p,display:"grid",placeItems:"center",flexShrink:0},children:e.jsx(mn,{size:17})}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:15,fontWeight:700,color:a.ink},children:"Cài đặt Hộp thư & Trợ lý AI"}),e.jsx("div",{style:{fontSize:11.5,color:a.muted},children:"Thiết lập tự động trả lời, mẫu câu gợi ý và quy trình phối hợp nhân viên"})]})]}),j&&e.jsx("button",{type:"button",onClick:j,"aria-label":"Đóng cài đặt",style:{width:32,height:32,borderRadius:8,border:0,background:"transparent",color:a.muted,display:"inline-grid",placeItems:"center",cursor:"pointer",flexShrink:0},children:e.jsx(Ke,{size:18})})]}),e.jsx("div",{role:"tablist","aria-label":"Danh mục cài đặt",style:{display:"flex",gap:4,padding:H?"8px 12px":"10px 22px",borderBottom:`1px solid ${a.line}`,background:a.surface,overflowX:"auto",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",flexShrink:0},children:M.map(o=>{const f=G===o,x=oe[o];return e.jsxs("button",{type:"button",role:"tab","aria-selected":f,onClick:()=>N(o),style:{display:"inline-flex",alignItems:"center",gap:7,padding:"7px 13px",borderRadius:8,border:f?`1px solid ${p}33`:"1px solid transparent",background:f?a.white:"transparent",color:f?p:a.muted,fontSize:12.5,fontWeight:f?700:600,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0,boxShadow:f?"0 1px 3px rgba(23,32,51,.06)":"none",transition:"all 120ms ease"},children:[x.icon,e.jsx("span",{children:x.label})]},o)})}),e.jsx("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:H?14:22,background:a.surface},children:P?e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:48,color:a.muted,fontSize:13},children:[e.jsx(st,{size:16,style:{animation:"channelhub-spin .7s linear infinite"}}),e.jsx("span",{children:"Đang tải cài đặt…"})]}):e.jsxs(e.Fragment,{children:[G==="ai"&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:780,margin:"0 auto"},children:[e.jsxs("div",{style:{background:a.white,border:`1px solid ${a.line}`,borderRadius:12,padding:H?14:18},children:[e.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:a.ink,marginBottom:4},children:"Chế độ hoạt động của Trợ lý AI"}),e.jsx("div",{style:{fontSize:12,color:a.muted,marginBottom:14},children:"Chọn mức độ tham gia của AI khi khách hàng nhắn tin đến các kênh của cửa hàng."}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:H?"1fr":"repeat(3, 1fr)",gap:10},children:[{mode:"off",title:"Tắt AI",badge:"Thủ công",desc:"Nhân viên trực tiếp trả lời 100% tin nhắn như bình thường.",icon:e.jsx(Ke,{size:16})},{mode:"copilot",title:"AI Copilot",badge:"Gợi ý cho nhân viên",desc:"AI soạn sẵn câu trả lời gợi ý, nhân viên kiểm tra và bấm duyệt mới gửi.",icon:e.jsx(rt,{size:16})},{mode:"autopilot",title:"AI Autopilot",badge:"Tự động trả lời",desc:"AI tự động phản hồi ngay cho các hội thoại chưa có nhân viên nhận phụ trách.",icon:e.jsx(Dt,{size:16})}].map(o=>{const f=b.ai.mode===o.mode;return e.jsxs("button",{type:"button",onClick:()=>Z("mode",o.mode),style:{textAlign:"left",padding:14,borderRadius:11,border:f?`2px solid ${p}`:`1px solid ${a.line}`,background:f?`${p}08`:a.white,cursor:"pointer",display:"flex",flexDirection:"column",gap:8,transition:"all 120ms ease"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{width:30,height:30,borderRadius:8,background:f?p:a.surface,color:f?"#fff":a.muted,display:"inline-grid",placeItems:"center"},children:o.icon}),e.jsx("span",{style:{fontSize:10.5,fontWeight:700,padding:"2px 8px",borderRadius:999,background:f?`${p}1a`:a.surface,color:f?p:a.muted},children:o.badge})]}),e.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:a.ink},children:o.title}),e.jsx("div",{style:{fontSize:11.5,color:a.muted,lineHeight:1.45},children:o.desc})]},o.mode)})})]}),v&&v.length>0&&e.jsxs("div",{style:{background:a.white,border:`1px solid ${a.line}`,borderRadius:12,padding:H?14:18},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[e.jsx(yn,{size:16,color:p}),e.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:a.ink},children:"Thiết lập nghiệp vụ cửa hàng"})]}),e.jsx("div",{style:{fontSize:12,color:a.muted,marginBottom:14},children:"Các tuỳ chỉnh dành riêng cho quy trình tư vấn và bán hàng của shop bạn."}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:v.map(o=>{const f=b.ai.parameters[o.key]??o.defaultValue;return o.type==="toggle"?e.jsx(De,{label:o.label,description:o.description,checked:!!f,onChange:x=>Ie(o.key,x),primary:p},o.key):o.type==="select"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[e.jsx("label",{style:{fontSize:12.5,fontWeight:600,color:a.ink},children:o.label}),o.description&&e.jsx("span",{style:{fontSize:11.5,color:a.muted},children:o.description}),e.jsx("select",{value:String(f??""),onChange:x=>Ie(o.key,x.target.value),style:{padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,background:a.white,color:a.ink,fontSize:H?16:12.5,fontFamily:"inherit"},children:(o.options??[]).map(x=>e.jsx("option",{value:x.value,children:x.label},x.value))})]},o.key):o.type==="textarea"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[e.jsx("label",{style:{fontSize:12.5,fontWeight:600,color:a.ink},children:o.label}),o.description&&e.jsx("span",{style:{fontSize:11.5,color:a.muted},children:o.description}),e.jsx("textarea",{rows:3,value:String(f??""),placeholder:o.placeholder,onChange:x=>Ie(o.key,x.target.value),style:{padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,background:a.white,color:a.ink,fontSize:H?16:12.5,fontFamily:"inherit",resize:"vertical"}})]},o.key):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[e.jsx("label",{style:{fontSize:12.5,fontWeight:600,color:a.ink},children:o.label}),o.description&&e.jsx("span",{style:{fontSize:11.5,color:a.muted},children:o.description}),e.jsx("input",{type:"text",value:String(f??""),placeholder:o.placeholder,onChange:x=>Ie(o.key,x.target.value),style:{padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,background:a.white,color:a.ink,fontSize:H?16:12.5,fontFamily:"inherit"}})]},o.key)})})]}),e.jsxs("div",{style:{background:a.white,border:`1px solid ${a.line}`,borderRadius:12,padding:H?14:18},children:[e.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:a.ink,marginBottom:4},children:"Phong cách giao tiếp & Quy tắc chuyển giao cho nhân viên"}),e.jsx("div",{style:{fontSize:12,color:a.muted,marginBottom:14},children:"Đảm bảo AI luôn nhường quyền ngay lập tức khi nhân viên vào cuộc hoặc khi khách hàng cần tư vấn sâu."}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:H?"1fr":"repeat(2, 1fr)",gap:12,marginBottom:14},children:[e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:a.ink,marginBottom:5},children:"Giọng điệu xưng hô"}),e.jsxs("select",{value:b.ai.tone,onChange:o=>Z("tone",o.target.value),style:{width:"100%",padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,background:a.white,color:a.ink,fontSize:H?16:12.5,fontFamily:"inherit"},children:[e.jsx("option",{value:"friendly",children:"Thân thiện, nhiệt tình (Dạ / Em - Anh/Chị)"}),e.jsx("option",{value:"professional",children:"Lịch sự, chuyên nghiệp (Cửa hàng - Quý khách)"}),e.jsx("option",{value:"concise",children:"Ngắn gọn, đi thẳng vào trọng tâm"})]})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:a.ink,marginBottom:5},children:"Thời gian chờ gom tin nhắn của khách (Debounce)"}),e.jsxs("select",{value:b.ai.debounceSeconds,onChange:o=>Z("debounceSeconds",Number(o.target.value)),style:{width:"100%",padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,background:a.white,color:a.ink,fontSize:H?16:12.5,fontFamily:"inherit"},children:[e.jsx("option",{value:3,children:"3 giây (Phản hồi nhanh)"}),e.jsx("option",{value:5,children:"5 giây (Khuyên dùng - gom đủ các câu ngắn)"}),e.jsx("option",{value:8,children:"8 giây (Chờ khách gõ nhiều dòng)"}),e.jsx("option",{value:10,children:"10 giây"})]})]})]}),e.jsxs("div",{style:{padding:12,borderRadius:10,border:`1px solid ${a.line}`,background:a.surface,marginBottom:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:10},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7},children:[e.jsx(nn,{size:15,color:p}),e.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:a.ink},children:"Khung giờ AI hoạt động"})]}),e.jsx("div",{style:{display:"flex",gap:6},children:[{key:"always",label:"Luôn bật 24/7"},{key:"outside_hours",label:"Chỉ bật ngoài giờ làm việc"}].map(o=>{const f=b.ai.schedule===o.key;return e.jsx("button",{type:"button",onClick:()=>Z("schedule",o.key),style:{padding:"5px 10px",borderRadius:7,border:f?`1px solid ${p}`:`1px solid ${a.line}`,background:f?`${p}12`:a.white,color:f?p:a.muted,fontSize:11.5,fontWeight:f?700:500,cursor:"pointer"},children:o.label},o.key)})})]}),b.ai.schedule==="outside_hours"&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginTop:10,fontSize:12,color:a.muted,flexWrap:"wrap"},children:[e.jsx("span",{children:"Giờ làm việc của nhân viên: Từ"}),e.jsx("input",{type:"time",value:b.ai.businessHours.start,onChange:o=>Z("businessHours",{...b.ai.businessHours,start:o.target.value}),style:{padding:"4px 8px",borderRadius:6,border:`1px solid ${a.line}`,fontSize:12}}),e.jsx("span",{children:"đến"}),e.jsx("input",{type:"time",value:b.ai.businessHours.end,onChange:o=>Z("businessHours",{...b.ai.businessHours,end:o.target.value}),style:{padding:"4px 8px",borderRadius:6,border:`1px solid ${a.line}`,fontSize:12}}),e.jsx("span",{children:"(AI sẽ tự trả lời ngoài khung giờ này)"})]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx(De,{label:"Tự động dừng AI khi có nhân viên nhận phụ trách",description:"Khi hội thoại đã được gán cho một nhân viên cụ thể, AI Autopilot sẽ ngừng trả lời tự động.",checked:b.ai.autoPauseOnAgentAssign,onChange:o=>Z("autoPauseOnAgentAssign",o),primary:p}),e.jsx(De,{label:"Tự động dừng AI ngay khi nhân viên nhắn tin vào hội thoại",description:"Tránh trường hợp nhân viên và AI cùng trả lời chồng chéo cho khách hàng.",checked:b.ai.autoPauseOnAgentReply,onChange:o=>Z("autoPauseOnAgentReply",o),primary:p}),e.jsx(De,{label:"Chuyển cho nhân viên khi khách để lại Số điện thoại",description:"Khi phát hiện số điện thoại trong tin nhắn, AI dừng lại và gắn cảnh báo để nhân viên chốt đơn.",checked:b.ai.handoffOnPhone,onChange:o=>Z("handoffOnPhone",o),primary:p}),e.jsx(De,{label:"Chuyển cho nhân viên khi khách khiếu nại hoặc yêu cầu gặp người thật",description:"Khi khách có dấu hiệu bức xúc hoặc yêu cầu gặp quản lý/nhân viên tư vấn.",checked:b.ai.handoffOnComplaint,onChange:o=>Z("handoffOnComplaint",o),primary:p})]})]}),!be&&e.jsxs("div",{style:{background:a.white,border:`1px solid ${a.line}`,borderRadius:12,padding:H?14:18},children:[e.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:a.ink,marginBottom:4},children:"Kiến thức cửa hàng & Kết nối nguồn AI"}),e.jsx("div",{style:{fontSize:12,color:a.muted,marginBottom:14},children:"Cung cấp thông tin sản phẩm, chính sách của shop và kết nối với mô hình AI hoặc Webhook của bạn."}),e.jsxs("div",{style:{marginBottom:14},children:[e.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:a.ink,marginBottom:5},children:"Hướng dẫn & Kiến thức cửa hàng (System Prompt)"}),e.jsx("textarea",{rows:4,value:b.ai.systemPrompt??"",onChange:o=>Z("systemPrompt",o.target.value),placeholder:"Ví dụ: Bạn là trợ lý tư vấn của Shop Thời Trang ABC. Phí ship đồng giá 25k, miễn phí ship từ 300k. Đổi trả trong 7 ngày...",style:{width:"100%",boxSizing:"border-box",padding:"9px 11px",borderRadius:8,border:`1px solid ${a.line}`,background:a.white,color:a.ink,fontSize:H?16:12.5,fontFamily:"inherit",lineHeight:1.5,resize:"vertical"}})]}),e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:a.ink,marginBottom:6},children:"Nguồn xử lý AI (Provider)"}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[{id:"openai",label:"OpenAI (GPT-4o)"},{id:"gemini",label:"Google Gemini"},{id:"anthropic",label:"Anthropic Claude"},{id:"webhook",label:"External Webhook (n8n / Dify)"}].map(o=>{const f=b.ai.provider===o.id;return e.jsx("button",{type:"button",onClick:()=>Z("provider",o.id),style:{padding:"6px 11px",borderRadius:8,border:f?`1px solid ${p}`:`1px solid ${a.line}`,background:f?`${p}12`:a.surface,color:f?p:a.ink,fontSize:12,fontWeight:f?700:500,cursor:"pointer"},children:o.label},o.id)})})]}),b.ai.provider==="webhook"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:H?"1fr":"2fr 1fr",gap:10},children:[e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:5},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:5,fontSize:12,fontWeight:600,color:a.ink},children:[e.jsx(Sn,{size:13,color:a.muted})," Webhook Endpoint URL"]}),e.jsx("button",{type:"button",onClick:()=>{const o=typeof window<"u"?window.location.origin:"http://localhost:3000";Z("webhookUrl",`${o}/api/mock-ai-webhook`)},style:{border:0,background:"none",color:p,fontSize:11,fontWeight:600,cursor:"pointer",padding:0,textDecoration:"underline"},children:"Dùng URL Mock Local để test"})]}),e.jsx("input",{type:"url",value:b.ai.webhookUrl??"",onChange:o=>Z("webhookUrl",o.target.value),placeholder:"https://n8n.yourshop.com/webhook/channelhub-ai",style:{width:"100%",boxSizing:"border-box",padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,fontSize:H?16:12.5,fontFamily:"inherit"}})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:a.ink,marginBottom:5},children:"Webhook Secret (Tùy chọn)"}),e.jsx("input",{type:"password",value:b.ai.webhookSecret??"",onChange:o=>Z("webhookSecret",o.target.value),placeholder:"whsec_...",style:{width:"100%",boxSizing:"border-box",padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,fontSize:H?16:12.5,fontFamily:"inherit"}})]})]}),e.jsxs("div",{style:{borderRadius:10,border:`1px solid ${a.line}`,background:a.surface,padding:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:8,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:12,fontWeight:700,color:a.ink},children:"🧪 Kiểm tra gọi Webhook & Phản hồi tự động"}),e.jsxs("span",{style:{fontSize:11,color:a.muted},children:["Event: ",e.jsx("code",{style:{background:"#e2e8f0",padding:"1px 5px",borderRadius:4},children:"ai.reply_requested"})]})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexDirection:H?"column":"row"},children:[e.jsx("input",{type:"text",value:Se,onChange:o=>Ge(o.target.value),placeholder:"Nhập tin nhắn giả lập của khách hàng...",style:{flex:1,padding:"7px 10px",borderRadius:8,border:`1px solid ${a.line}`,background:a.white,fontSize:H?16:12,fontFamily:"inherit"}}),e.jsx("button",{type:"button",disabled:we||!((ge=b.ai.webhookUrl)!=null&&ge.trim()),onClick:async()=>{var fe;const o=(fe=b.ai.webhookUrl)==null?void 0:fe.trim();if(!o)return;Be(!0),Pe(null);const f=performance.now(),x={event:"ai.reply_requested",conversation:{id:"conv_test_001",provider:"facebook",assignedAgent:null},contact:{name:"Khách hàng Test",providerUserId:"psid_998877",externalId:"CRM_01"},unansweredText:Se,recentMessages:[{direction:"inbound",text:Se,occurredAt:new Date().toISOString()}],aiConfig:{tone:b.ai.tone,handoffOnPhone:b.ai.handoffOnPhone,handoffOnComplaint:b.ai.handoffOnComplaint,parameters:b.ai.parameters}};try{let ve;typeof window<"u"&&window.location.origin?ve=await fetch("/api/mock-ai-webhook",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({...x,_proxyWebhookUrl:o,_proxyWebhookSecret:b.ai.webhookSecret??""})}):ve=await fetch(o,{method:"POST",headers:{"content-type":"application/json","x-channelhub-event":"ai.reply_requested"},body:JSON.stringify(x)});const h=Math.round(performance.now()-f),S=await ve.json().catch(()=>({}));Pe({ok:ve.ok,status:ve.status,latencyMs:h,response:S})}catch(ve){Pe({ok:!1,status:0,latencyMs:Math.round(performance.now()-f),response:{error:ve instanceof Error?ve.message:"Lỗi kết nối Webhook"}})}finally{Be(!1)}},style:{padding:"7px 14px",borderRadius:8,border:0,background:(Ue=b.ai.webhookUrl)!=null&&Ue.trim()?p:"#cbd5e1",color:"#fff",fontSize:12,fontWeight:600,cursor:(Je=b.ai.webhookUrl)!=null&&Je.trim()?"pointer":"not-allowed",whiteSpace:"nowrap"},children:we?"Đang gọi Webhook…":"🚀 Gửi test tới Webhook"})]}),ee&&e.jsxs("div",{style:{marginTop:10,padding:"10px 12px",borderRadius:8,background:ee.ok?"#f0fdf4":"#fef2f2",border:`1px solid ${ee.ok?"#bbf7d0":"#fecaca"}`,fontSize:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6},children:[e.jsx("strong",{style:{color:ee.ok?"#15803d":"#b91c1c"},children:ee.ok?`✓ Webhook phản hồi thành công (HTTP ${ee.status})`:`✕ Lỗi gọi Webhook (HTTP ${ee.status})`}),e.jsxs("span",{style:{fontSize:11,color:a.muted},children:[ee.latencyMs," ms"]})]}),!!(ee.response.text??ee.response.replyText)&&e.jsxs("div",{style:{marginBottom:4,color:a.ink},children:[e.jsx("strong",{children:"Tin nhắn sẽ tự động rep khách:"})," ",e.jsx("span",{style:{background:"#fff",padding:"2px 6px",borderRadius:4,border:`1px solid ${a.line}`},children:String(ee.response.text??ee.response.replyText)})]}),!!ee.response.internalNote&&e.jsxs("div",{style:{marginBottom:4,color:a.muted,fontSize:11.5},children:[e.jsx("strong",{children:"Ghi chú nội bộ tự động lưu:"})," ",String(ee.response.internalNote)]}),e.jsx("pre",{style:{margin:"6px 0 0",padding:8,borderRadius:6,background:"#0f172a",color:"#e2e8f0",fontSize:11,overflowX:"auto"},children:JSON.stringify(ee.response,null,2)})]})]})]}):e.jsxs("div",{style:{display:"grid",gridTemplateColumns:H?"1fr":"2fr 1fr",gap:10},children:[e.jsxs("div",{children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:5,fontSize:12,fontWeight:600,color:a.ink,marginBottom:5},children:[e.jsx(an,{size:13,color:a.muted})," API Key (",b.ai.provider.toUpperCase(),")"]}),e.jsx("input",{type:"password",value:b.ai.apiKey??"",onChange:o=>Z("apiKey",o.target.value),placeholder:"sk-...",style:{width:"100%",boxSizing:"border-box",padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,fontSize:H?16:12.5,fontFamily:"inherit"}})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:12,fontWeight:600,color:a.ink,marginBottom:5},children:"Model"}),e.jsx("input",{type:"text",value:b.ai.model??"",onChange:o=>Z("model",o.target.value),placeholder:b.ai.provider==="gemini"?"gemini-2.0-flash":b.ai.provider==="anthropic"?"claude-3-5-haiku-latest":"gpt-4o-mini",style:{width:"100%",boxSizing:"border-box",padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,fontSize:H?16:12.5,fontFamily:"inherit"}})]})]})]})]}),G==="templates"&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:780,margin:"0 auto"},children:[e.jsxs("div",{style:{background:a.white,border:`1px solid ${a.line}`,borderRadius:12,padding:H?14:18},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginBottom:14,flexWrap:"wrap"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:a.ink},children:"Thư viện mẫu câu trả lời nhanh (⚡ Template)"}),e.jsx("div",{style:{fontSize:12,color:a.muted,marginTop:2},children:"Nhân viên bấm biểu tượng ⚡ trên khung chat để chèn nhanh các câu trả lời chuẩn của shop."})]}),e.jsxs("button",{type:"button",onClick:Te,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"7px 12px",borderRadius:8,border:0,background:p,color:"#fff",fontSize:12,fontWeight:600,cursor:"pointer"},children:[e.jsx(un,{size:14})," Thêm mẫu câu"]})]}),R&&e.jsxs("div",{style:{padding:14,borderRadius:10,border:`1px solid ${p}40`,background:`${p}06`,marginBottom:14,display:"flex",flexDirection:"column",gap:10},children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:700,color:p},children:R==="new"?"Tạo mẫu câu mới":"Chỉnh sửa mẫu câu"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:H?"1fr":"2fr 1fr",gap:10},children:[e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:11.5,fontWeight:600,color:a.ink,marginBottom:4},children:"Tiêu đề mẫu câu *"}),e.jsx("input",{type:"text",value:g,onChange:o=>L(o.target.value),placeholder:"Ví dụ: Báo giá phí ship",style:{width:"100%",boxSizing:"border-box",padding:"7px 10px",borderRadius:7,border:`1px solid ${a.line}`,background:a.white,fontSize:H?16:12.5,fontFamily:"inherit"}})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:11.5,fontWeight:600,color:a.ink,marginBottom:4},children:"Phím tắt (Tùy chọn)"}),e.jsx("input",{type:"text",value:K,onChange:o=>Q(o.target.value),placeholder:"/ship",style:{width:"100%",boxSizing:"border-box",padding:"7px 10px",borderRadius:7,border:`1px solid ${a.line}`,background:a.white,fontSize:H?16:12.5,fontFamily:"inherit"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:11.5,fontWeight:600,color:a.ink,marginBottom:4},children:"Nội dung tin nhắn *"}),e.jsx("textarea",{rows:3,value:de,onChange:o=>pe(o.target.value),placeholder:"Nhập nội dung tin nhắn mẫu...",style:{width:"100%",boxSizing:"border-box",padding:"8px 10px",borderRadius:7,border:`1px solid ${a.line}`,background:a.white,fontSize:H?16:12.5,fontFamily:"inherit",resize:"vertical"}})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:()=>ie(null),style:{padding:"6px 12px",borderRadius:7,border:`1px solid ${a.line}`,background:a.white,color:a.muted,fontSize:12,fontWeight:600,cursor:"pointer"},children:"Hủy"}),e.jsx("button",{type:"button",onClick:()=>void Fe(),disabled:!g.trim()||!de.trim()||m,style:{padding:"6px 14px",borderRadius:7,border:0,background:!g.trim()||!de.trim()||m?"#cbd5e1":p,color:"#fff",fontSize:12,fontWeight:600,cursor:!g.trim()||!de.trim()||m?"not-allowed":"pointer"},children:m?"Đang lưu…":"Lưu mẫu câu"})]})]}),se?e.jsx("div",{style:{padding:24,textAlign:"center",color:a.muted,fontSize:12.5},children:"Đang tải danh sách mẫu câu…"}):re.length===0?e.jsxs("div",{style:{padding:"28px 16px",textAlign:"center",borderRadius:10,border:`1px dashed ${a.line}`,background:a.surface},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600,color:a.ink,marginBottom:4},children:"Chưa có mẫu câu trả lời nhanh nào"}),e.jsx("div",{style:{fontSize:12,color:a.muted,marginBottom:14},children:"Bạn có thể tạo mới hoặc nạp ngay bộ mẫu câu bán hàng phổ biến bên dưới."}),e.jsxs("button",{type:"button",onClick:()=>void _e(),disabled:le,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"7px 14px",borderRadius:8,border:`1px solid ${p}40`,background:`${p}10`,color:p,fontSize:12,fontWeight:600,cursor:le?"not-allowed":"pointer"},children:[e.jsx(rt,{size:14}),le?"Đang nạp mẫu câu…":"✨ Nạp bộ mẫu câu gợi ý"]})]}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:re.map(o=>e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,padding:"10px 12px",borderRadius:9,border:`1px solid ${a.line}`,background:a.white},children:[e.jsxs("div",{style:{minWidth:0,flex:1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,marginBottom:3},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:a.ink},children:o.title}),o.shortcut&&e.jsx("span",{style:{fontSize:10.5,fontWeight:600,padding:"1px 6px",borderRadius:5,background:`${p}14`,color:p},children:o.shortcut})]}),e.jsx("div",{style:{fontSize:12,color:a.muted,lineHeight:1.45,whiteSpace:"pre-wrap"},children:o.content})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:[e.jsx("button",{type:"button",onClick:()=>Ve(o),"aria-label":"Sửa mẫu câu",style:{width:28,height:28,borderRadius:6,border:0,background:"transparent",color:a.muted,display:"inline-grid",placeItems:"center",cursor:"pointer"},children:e.jsx(cn,{size:14})}),e.jsx("button",{type:"button",onClick:()=>void We(o.id),"aria-label":"Xóa mẫu câu",style:{width:28,height:28,borderRadius:6,border:0,background:"transparent",color:"#ef4444",display:"inline-grid",placeItems:"center",cursor:"pointer"},children:e.jsx(kn,{size:14})})]})]},o.id))})]}),e.jsxs("div",{style:{background:a.white,border:`1px solid ${a.line}`,borderRadius:12,padding:H?14:18},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,marginBottom:4},children:[e.jsx(ln,{size:15,color:p}),e.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:a.ink},children:"Nút gợi ý nhanh trên khung chat (Quick Reply Chips)"})]}),e.jsx("div",{style:{fontSize:12,color:a.muted,marginBottom:12},children:"Các nút câu ngắn hiển thị ngay phía trên ô nhập tin nhắn để nhân viên bấm 1 chạm."}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:12},children:b.inbox.quickReplies.map(o=>e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",borderRadius:999,background:`${p}10`,color:p,border:`1px solid ${p}33`,fontSize:12,fontWeight:500},children:[e.jsx("span",{children:o}),e.jsx("button",{type:"button",onClick:()=>Le(o),"aria-label":`Xóa ${o}`,style:{border:0,background:"none",color:p,padding:0,cursor:"pointer",display:"inline-flex"},children:e.jsx(Ke,{size:12})})]},o))}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("input",{type:"text",value:je,onChange:o=>Oe(o.target.value),onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),Ne())},placeholder:"Nhập câu gợi ý ngắn (VD: Dạ shop đã nhận đơn ạ)...",style:{flex:1,minWidth:0,padding:"7px 10px",borderRadius:8,border:`1px solid ${a.line}`,fontSize:H?16:12.5,fontFamily:"inherit"}}),e.jsx("button",{type:"button",onClick:Ne,style:{padding:"7px 14px",borderRadius:8,border:`1px solid ${p}40`,background:`${p}12`,color:p,fontSize:12,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap"},children:"+ Thêm nút"})]})]})]}),G==="inbox"&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16,maxWidth:780,margin:"0 auto"},children:[e.jsxs("div",{style:{background:a.white,border:`1px solid ${a.line}`,borderRadius:12,padding:H?14:18},children:[e.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:a.ink,marginBottom:12},children:"Phân công & Thông báo hộp thư"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[e.jsx(De,{label:"Tự động gán phụ trách cho nhân viên đầu tiên trả lời",description:"Khi hội thoại chưa có người nhận, nhân viên nào gửi tin nhắn trả lời đầu tiên sẽ tự động trở thành người phụ trách.",checked:b.inbox.autoAssignOnFirstReply,onChange:o=>ye("autoAssignOnFirstReply",o),primary:p}),e.jsx(De,{label:"Phát âm thanh thông báo khi có tin nhắn mới",description:"Phát tiếng chuông nhẹ khi khách hàng gửi tin nhắn mới đến hộp thư.",checked:b.inbox.soundNotification,onChange:o=>ye("soundNotification",o),primary:p})]})]}),e.jsxs("div",{style:{background:a.white,border:`1px solid ${a.line}`,borderRadius:12,padding:H?14:18},children:[e.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:a.ink,marginBottom:12},children:"Tin nhắn chào mừng & Phản hồi vắng mặt"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsx(De,{label:"Bật tin nhắn chào mừng tự động cho khách mới",description:"Tự động gửi lời chào ngay khi khách hàng bắt đầu cuộc trò chuyện lần đầu.",checked:b.inbox.welcomeMessageEnabled,onChange:o=>ye("welcomeMessageEnabled",o),primary:p}),b.inbox.welcomeMessageEnabled&&e.jsx("textarea",{rows:2,value:b.inbox.welcomeMessageText,onChange:o=>ye("welcomeMessageText",o.target.value),style:{width:"100%",boxSizing:"border-box",padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,fontSize:H?16:12.5,fontFamily:"inherit",resize:"vertical"}}),e.jsx(De,{label:"Bật tin nhắn báo vắng mặt ngoài giờ làm việc",description:"Thông báo cho khách để lại thông tin khi nhắn tin ngoài khung giờ trực của cửa hàng.",checked:b.inbox.awayMessageEnabled,onChange:o=>ye("awayMessageEnabled",o),primary:p}),b.inbox.awayMessageEnabled&&e.jsx("textarea",{rows:2,value:b.inbox.awayMessageText,onChange:o=>ye("awayMessageText",o.target.value),style:{width:"100%",boxSizing:"border-box",padding:"8px 10px",borderRadius:8,border:`1px solid ${a.line}`,fontSize:H?16:12.5,fontFamily:"inherit",resize:"vertical"}})]})]})]}),G==="channels"&&e.jsx("div",{style:{maxWidth:780,margin:"0 auto"},children:e.jsx(Ft,{apiUrl:t,token:n})})]})}),G!=="channels"&&e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:H?"10px 14px":"12px 22px",borderTop:`1px solid ${a.line}`,background:a.white,flexShrink:0},children:[e.jsx("div",{style:{minHeight:18,display:"flex",alignItems:"center"},children:Y?e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,fontWeight:600,color:"#16a34a"},children:[e.jsx(lt,{size:14,strokeWidth:2.5})," Đã lưu cài đặt thành công"]}):k?e.jsx("span",{style:{fontSize:12,color:"#dc2626"},children:k}):e.jsx("span",{style:{fontSize:11.5,color:a.muted},children:"Thay đổi sẽ được áp dụng cho toàn bộ hộp thư của cửa hàng."})}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[j&&e.jsx("button",{type:"button",onClick:j,style:{padding:"7px 14px",borderRadius:8,border:`1px solid ${a.line}`,background:a.white,color:a.ink,fontSize:12.5,fontWeight:600,cursor:"pointer"},children:"Đóng"}),e.jsxs("button",{type:"button",onClick:()=>void X(),disabled:_,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"7px 16px",borderRadius:8,border:0,background:_?"#94a3b8":p,color:"#fff",fontSize:12.5,fontWeight:600,cursor:_?"not-allowed":"pointer"},children:[_?e.jsx(st,{size:14,style:{animation:"channelhub-spin .7s linear infinite"}}):e.jsx(gn,{size:14}),e.jsx("span",{children:_?"Đang lưu…":"Lưu cài đặt"})]})]})]})]})}function yt({src:t,alt:n="",fallback:r,style:s}){return t?e.jsx("img",{src:t,alt:n,style:{width:38,height:38,borderRadius:"50%",objectFit:"cover",...s}}):e.jsx("span",{style:{display:"grid",placeItems:"center",width:38,height:38,borderRadius:"50%",...s},children:r})}function Dn({variant:t="ghost",style:n,...r}){return e.jsx("button",{...r,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 On({style:t,...n}){return e.jsx("input",{...n,style:{width:"100%",minWidth:0,border:0,outline:0,background:"transparent",font:"inherit",...t}})}const Ut=i.forwardRef(({children:t,style:n},r)=>e.jsx("div",{ref:r,style:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain",...n},children:t})),Pn=i.forwardRef(function({style:n,...r},s){return e.jsx("textarea",{ref:s,...r,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",border:0,outline:0,background:"transparent",font:"inherit",...n}})});function Fn(t){return{id:t.contactId??t.providerConversationKey,name:t.contactName,pictureUrl:t.contactPictureUrl,providerUserId:t.contactProviderUserId??t.providerConversationKey,...t.contactExternalId?{externalId:t.contactExternalId}:{}}}function at(t,n){return{conversation:t,contact:Fn(t),provider:n==null?void 0:n.provider,recentMessages:n==null?void 0:n.recentMessages,linkContact:(n==null?void 0:n.linkContact)??(async()=>{}),refreshContactInfo:(n==null?void 0:n.refreshContactInfo)??(()=>{}),sendMessage:(n==null?void 0:n.sendMessage)??(async()=>{})}}class Nn extends i.Component{constructor(){super(...arguments),this.state={caught:!1}}static getDerivedStateFromError(){return{caught:!0}}render(){return this.state.caught?null:this.props.children}}const c={ink:"#172033",muted:"#718096",line:"#e7ebf2",surface:"#f7f9fc",white:"#fff"},Mt=[{icon:"😊",emojis:["😀","😁","😂","🤣","😊","😇","🙂","😉","😍","🥰","😘","😋","😎","🤩","😏","😒","😔","😢","😭","😤","😠","🤯","😱","🥳","😴","🤔","🤗","🫡","😮","🤧","🥺","😶","🫠","🤭","🤫"]},{icon:"👋",emojis:["👍","👎","👏","🙏","🤝","✌️","🤞","🫡","💪","🤜","👊","✊","🖐","👌","🤌","🤏","☝️","👆","👇","👉","👈","🤙","💅","🫶","❤️","🧡","💛","💚","💙","💜","🖤","💔","❣️","💕","💯"]},{icon:"🐱",emojis:["🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🙈","🐔","🐧","🐦","🦆","🦅","🦉","🦋","🐝","🐛","🐢","🦎","🐬","🦈","🐳","🐙","🦑"]},{icon:"🍕",emojis:["🍎","🍊","🍋","🍇","🍓","🍒","🥝","🥑","🍔","🍕","🌮","🍜","🍣","🍦","🎂","🍰","🧁","☕","🧋","🥤","🍺","🥂","🍾","🧃","🧊"]},{icon:"⚽",emojis:["⚽","🏀","🏈","⚾","🎾","🏐","🏓","🎮","🎲","🎯","🎳","🏆","🥇","🎖","🎁","🎉","🎊","🎈","🎭","🎨","🎬","🎵","🎸","🎹","🎺","🪗","🎻"]},{icon:"🌍",emojis:["🌍","🌈","⭐","🌙","☀️","⛅","🌊","🔥","💧","🌿","🌸","🌺","🌻","🍀","🌴","🏔","🏖","🏕","🌃","🏙","🌅","🌄","🌠","🌌","🌋","🏝"]}],bt=i.createContext(""),qt=i.createContext("");function Un(){try{const t=new AudioContext,n=t.createOscillator(),r=t.createGain();n.connect(r),r.connect(t.destination),n.type="sine",n.frequency.setValueAtTime(880,t.currentTime),n.frequency.exponentialRampToValueAtTime(660,t.currentTime+.12),r.gain.setValueAtTime(.25,t.currentTime),r.gain.exponentialRampToValueAtTime(.001,t.currentTime+.35),n.start(t.currentTime),n.stop(t.currentTime+.35)}catch{}}function qn(t){if(!(t!=null&&t.metadata))return;const n=t.metadata,r=n.pageName??n.displayName??n.username??n.name;return typeof r=="string"&&r?r:void 0}function Kt(t){return t==="facebook"?"Facebook Messenger":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo OA":t==="livechat"?"Live Chat":"Channel"}function Bt(t){return t==="facebook"?"Facebook":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo":t==="livechat"?"Live Chat":String(t??"")}const Kn=t=>{var r;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]??((r=t.split("/")[1])==null?void 0:r.toUpperCase())??"Tệp":"Tệp đính kèm"};function At({status:t}){return t==="read"?e.jsx(wt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):t==="delivered"?e.jsx(wt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle",opacity:.5}}):t==="sent"?e.jsx(lt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):null}function pt(t){const n=t.trim().split(/\s+/).filter(Boolean);return n.length<=2?t.trim():n.slice(-2).join(" ")}const Vn=i.forwardRef(function({apiUrl:n,token:r,theme:s,height:d,defaultConversationId:w,disableAttachments:v,disableNotificationSound:E,hideKeyboardHint:C,hideSettingsButton:j,settingsConfig:$,locale:p="vi",extensions:O,currentAgent:U,teamAgents:M,onNewMessage:G,onConversationSelect:N},b){var mt,vt,kt,jt,St;const D=i.useRef(new Ze(n,r)),[P,ne]=i.useState([]),[_,B]=i.useState([]),[Y,T]=i.useState(),[k,F]=i.useState(),re=i.useRef(void 0),[ue,se]=i.useState(""),[ae,le]=i.useState("all"),[ke,R]=i.useState(null),[ie,g]=i.useState(ze),L=i.useRef(ze),[K,Q]=i.useState(null),[de,pe]=i.useState(0),[m,ce]=i.useState({provider:"all",unreadOnly:!1}),[je,Oe]=i.useState(!1),Se=i.useRef(null),Ge=i.useRef(null),[we,Be]=i.useState(null),[ee,Pe]=i.useState(!0),[Re,H]=i.useState(""),Ae=i.useRef(null),[Ce,Ee]=i.useState(()=>typeof window<"u"?window.innerWidth:1200),X=Ce<640?"mobile":Ce<1024?"tablet":"desktop",[Z,ye]=i.useState(()=>w?"chat":"list"),[Ie,Te]=i.useState(()=>typeof window<"u"&&window.innerWidth<1024?!1:!!(O!=null&&O.length)),Ve=i.useRef(X),[Fe,We]=i.useState(280),[_e,Ne]=i.useState(!1),[Le,be]=i.useState(0),oe=(s==null?void 0:s.primaryColor)??"#2563eb",ge=i.useMemo(()=>new Map(_.map(l=>[l.id,l])),[_]),Ue=i.useRef(null),[Je,o]=i.useState(0);i.useEffect(()=>{const l=Ae.current;if(!l||typeof ResizeObserver>"u")return;const y=new ResizeObserver(z=>{for(const A of z){const xe=A.contentRect.width;xe>0&&Ee(xe)}});return y.observe(l),()=>y.disconnect()},[ee,Re]),i.useEffect(()=>{Ve.current==="desktop"&&X!=="desktop"&&Te(!1),Ve.current=X},[X]);const f=i.useMemo(()=>P.filter(l=>l.id!==(k==null?void 0:k.id)&&(l.unreadCount??0)>0).length,[P,k==null?void 0:k.id]),x=U??ke??null;i.useEffect(()=>{D.current=new Ze(n,r),D.current.getSettings().then(l=>{g(l),L.current=l}).catch(()=>{}),U||D.current.getSessionMe().then(l=>{l!=null&&l.agent&&R(l.agent)}).catch(()=>{})},[n,r,U]),i.useEffect(()=>{L.current=ie},[ie]);const fe=i.useMemo(()=>{var y;const l=new Map;x!=null&&x.id&&l.set(x.id,x);for(const z of M??[])z!=null&&z.id&&!l.has(z.id)&&l.set(z.id,z);for(const z of P)(y=z.assignedAgent)!=null&&y.id&&!l.has(z.assignedAgent.id)&&l.set(z.assignedAgent.id,z.assignedAgent);return[...l.values()]},[x,M,P]),ve=i.useCallback(async(l,y)=>{ne(z=>z.map(A=>A.id===l.id?{...A,assignedAgent:y}:A)),F(z=>z&&z.id===l.id?{...z,assignedAgent:y}:z),be(z=>z+1);try{const z=await D.current.assignConversation(l.id,y);ne(A=>A.map(xe=>xe.id===l.id?{...xe,...z,assignedAgent:z.assignedAgent??y}:xe)),F(A=>A&&A.id===l.id?{...A,...z,assignedAgent:z.assignedAgent??y}:A),be(A=>A+1)}catch{}},[]),h=i.useCallback(async(l,y)=>{l.contactId&&await D.current.patchContact(l.contactId,y),ne(z=>z.map(A=>A.id===l.id?{...A,contactExternalId:y??void 0}:A)),F(z=>z&&z.id===l.id?{...z,contactExternalId:y??void 0}:z),be(z=>z+1)},[]),S=i.useCallback(()=>{be(l=>l+1)},[]),W=i.useMemo(()=>{const l=new Set(_.map(y=>y.provider));return["facebook","instagram","telegram","zalo","livechat"].filter(y=>l.has(y))},[_]),J=i.useMemo(()=>{var y;const l={};for(const z of P){const A=((y=ge.get(z.connectionId))==null?void 0:y.provider)??"unknown";l[A]=(l[A]??0)+1}return l},[P,ge]);function te(l){const y=l.clientX,z=Fe;Ne(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none";function A(Xe){const et=Math.max(200,Math.min(480,z+(y-Xe.clientX)));We(et)}function xe(){Ne(!1),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",A),document.removeEventListener("mouseup",xe)}document.addEventListener("mousemove",A),document.addEventListener("mouseup",xe)}const V=i.useCallback(async l=>{try{const y=await D.current.listConversations(l);ne(z=>l?[...z,...y.items]:y.items),T(y.nextCursor),!l&&y.items.length&&F(z=>z??(w?y.items.find(A=>A.id===w)??y.items[0]:y.items[0])),H("")}catch(y){H(y instanceof Error?y.message:"Không tải được hội thoại")}finally{Pe(!1)}},[w]);i.useEffect(()=>(D.current.listConnections().then(B).catch(()=>{}),V(),D.current.connectSSE((y,z)=>{if(y==="message.new"||y==="conversation.updated"){if(V(),y==="message.new"){const A=typeof z=="object"&&z?z:{},xe=A.conversationId?String(A.conversationId):"",Xe=A.messageId?String(A.messageId):"";if((A.direction?String(A.direction):"")==="inbound"&&!E&&L.current.inbox.soundNotification&&Un(),xe&&xe===re.current&&Xe&&Ue.current){const it=Ue.current;D.current.getMessage(Xe).then(ot=>{it(ot)}).catch(()=>{})}G==null||G(xe||re.current||"")}}else y==="message.status_updated"&&o(A=>A+1)})),[V,G,E]),i.useEffect(()=>{re.current=k==null?void 0:k.id},[k]),i.useEffect(()=>{k!=null&&k.unreadCount&&D.current.markRead(k.id).then(()=>V()).catch(()=>{})},[k==null?void 0:k.id]),i.useEffect(()=>{if(!je)return;function l(y){var z,A;(z=Se.current)!=null&&z.contains(y.target)||(A=Ge.current)!=null&&A.contains(y.target)||Oe(!1)}return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[je]);const he=i.useMemo(()=>{const l=x?P.filter(z=>{var A;return((A=z.assignedAgent)==null?void 0:A.id)===x.id}).length:0,y=P.filter(z=>!z.assignedAgent).length;return{all:P.length,mine:l,unassigned:y}},[P,x]),$e=i.useMemo(()=>{const l=ue.toLowerCase().trim();return P.filter(y=>{var et,it,ot;if(ae==="mine"){if(!x||((et=y.assignedAgent)==null?void 0:et.id)!==x.id)return!1}else if(ae==="unassigned"&&y.assignedAgent)return!1;const z=`${y.contactName??""} ${y.subject??""} ${y.providerConversationKey} ${((it=y.assignedAgent)==null?void 0:it.name)??""}`.toLowerCase(),A=((ot=ge.get(y.connectionId))==null?void 0:ot.provider)??"unknown",xe=m.provider==="all"||A===m.provider,Xe=!m.unreadOnly||(y.unreadCount??0)>0;return xe&&Xe&&(!l||z.includes(l))})},[P,ge,m,ue,ae,x]),He=m.provider!=="all"||m.unreadOnly,me=p==="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ả"};i.useImperativeHandle(b,()=>({openConversation:l=>{const y=P.find(z=>z.id===l);y&&(F(y),ye("chat"))},refresh:()=>void V()}),[P,V]);const dt=X==="mobile"?"minmax(0, 1fr)":X==="tablet"?"minmax(240px, 270px) minmax(0, 1fr)":Ie?`minmax(260px, 300px) minmax(0, 1fr) ${Fe}px`:"minmax(260px, 300px) minmax(0, 1fr)",Gt={...I.frame,position:"relative",height:d??620,...d?{maxHeight:"none"}:{},fontFamily:(s==null?void 0:s.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",borderRadius:(s==null?void 0:s.borderRadius)??"16px",gridTemplateColumns:dt,transition:_e?"none":"grid-template-columns 220ms ease"};if(ee)return e.jsxs("div",{style:{...I.state,borderRadius:(s==null?void 0:s.borderRadius)??"16px"},children:[e.jsx(gt,{})," Đang tải hộp thư…"]});if(Re&&!P.length)return e.jsxs("div",{style:{...I.state,color:"#b42318",borderRadius:(s==null?void 0:s.borderRadius)??"16px"},children:[e.jsx(tn,{size:16,strokeWidth:2})," ",Re,e.jsx("button",{style:I.retry,onClick:()=>{Pe(!0),V()},children:"Thử lại"})]});const _t=X!=="mobile"||Z==="list"||!k,Jt=X!=="mobile"||Z==="chat"&&!!k;return e.jsx(bt.Provider,{value:n,children:e.jsx(qt.Provider,{value:r,children:e.jsxs("div",{ref:Ae,style:Gt,onFocusCapture:()=>{const l=window.scrollY;requestAnimationFrame(()=>{window.scrollY!==l&&window.scrollTo({top:l,behavior:"instant"})})},children:[_t&&e.jsxs("aside",{style:{...I.sidebar,...X==="mobile"?{borderRight:0}:{}},children:[e.jsxs("div",{style:I.brand,children:[e.jsx("div",{style:{...I.brandMark,background:oe,overflow:"hidden",padding:0},children:(mt=s==null?void 0:s.branding)!=null&&mt.logoUrl?e.jsx("img",{src:s.branding.logoUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):((vt=s==null?void 0:s.branding)==null?void 0:vt.mark)??"C"}),e.jsxs("div",{children:[e.jsx("strong",{children:((kt=s==null?void 0:s.branding)==null?void 0:kt.name)??"Hộp thư"}),!((jt=s==null?void 0:s.branding)!=null&&jt.name)&&e.jsx("span",{style:I.eyebrow,children:"CHANNELHUB"})]}),!j&&e.jsx(Dn,{"aria-label":"Cài đặt",title:"Cài đặt Hộp thư & Trợ lý AI",style:I.iconButton,onClick:()=>Q("ai"),children:e.jsx(xn,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:I.search,children:[e.jsx(zt,{size:16,strokeWidth:2}),e.jsx(On,{"aria-label":me.searchPlaceholder,value:ue,onChange:l=>se(l.target.value),placeholder:me.searchPlaceholder,style:{fontSize:X==="mobile"?16:12}}),ue&&e.jsx("button",{style:I.clear,onClick:()=>se(""),"aria-label":"Xóa tìm kiếm",children:"×"})]}),e.jsx("div",{role:"tablist","aria-label":"Lọc theo người phụ trách",style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:2,margin:"0 14px 10px",padding:3,borderRadius:9,border:`1px solid ${c.line}`,background:c.surface},children:[{key:"all",label:p==="en"?"All":"Tất cả",count:he.all},{key:"mine",label:p==="en"?"Mine":"Của tôi",count:he.mine},{key:"unassigned",label:p==="en"?"Unassigned":"Chưa nhận",count:he.unassigned}].map(l=>{const y=ae===l.key;return e.jsxs("button",{type:"button",role:"tab","aria-selected":y,onClick:()=>le(l.key),style:{border:0,borderRadius:6,padding:"5px 4px",fontSize:11,fontWeight:y?700:500,background:y?c.white:"transparent",color:y?oe:c.muted,boxShadow:y?"0 1px 3px rgba(23,32,51,.08)":"none",cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",transition:"all 120ms ease"},children:[l.label," ",e.jsxs("span",{style:{opacity:.75},children:["(",l.count,")"]})]},l.key)})}),He&&e.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",padding:"0 14px 8px"},children:[m.provider!=="all"&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:oe,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[e.jsx(nt,{provider:m.provider}),Bt(m.provider),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:oe,padding:0,lineHeight:1,display:"flex"},onClick:()=>ce(l=>({...l,provider:"all"})),"aria-label":"Xóa filter kênh",children:e.jsx(Ke,{size:10})})]}),m.unreadOnly&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:oe,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[me.unreadOnly,e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:oe,padding:0,lineHeight:1,display:"flex"},onClick:()=>ce(l=>({...l,unreadOnly:!1})),"aria-label":"Xóa filter chưa đọc",children:e.jsx(Ke,{size:10})})]}),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:c.muted,fontSize:11,padding:"2px 4px"},onClick:()=>ce({provider:"all",unreadOnly:!1}),children:"Xóa tất cả"})]}),e.jsxs("div",{style:I.listHeader,children:[e.jsxs("span",{children:[$e.length," hội thoại"]}),e.jsx("button",{ref:Se,style:{...I.iconButton,background:He?`${oe}14`:"transparent",color:He?oe:c.muted},"aria-label":"Bộ lọc",onClick:()=>{var l;if(!je){const y=(l=Se.current)==null?void 0:l.getBoundingClientRect();y&&Be({top:y.bottom+6,left:y.left})}Oe(y=>!y)},children:e.jsx(bn,{size:15,strokeWidth:2})})]}),je&&we&&Lt.createPortal(e.jsxs("div",{ref:Ge,style:{position:"fixed",top:we.top,left:Math.min(we.left,(typeof window<"u"?window.innerWidth:1200)-230),zIndex:9999,background:c.white,border:`1px solid ${c.line}`,borderRadius:10,padding:"12px 14px",boxShadow:"0 8px 24px rgba(23,32,51,.14)",minWidth:210,fontFamily:(s==null?void 0:s.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",fontSize:13},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:c.muted,letterSpacing:1,textTransform:"uppercase",marginBottom:8},children:"Kênh"}),["all",...W].map(l=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:m.provider===l?`${oe}0f`:"transparent"},children:[e.jsx("input",{type:"radio",name:"provider-filter",checked:m.provider===l,onChange:()=>ce(y=>({...y,provider:l})),style:{accentColor:oe}}),l==="all"?e.jsxs("span",{style:{color:c.ink},children:[me.all," (",P.length,")"]}):e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,color:c.ink},children:[e.jsx(nt,{provider:l}),Bt(l)," ",e.jsxs("span",{style:{color:c.muted},children:["(",J[l]??0,")"]})]})]},l)),e.jsx("div",{style:{borderTop:`1px solid ${c.line}`,margin:"8px 0 6px"}}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:m.unreadOnly?`${oe}0f`:"transparent"},children:[e.jsx("input",{type:"checkbox",checked:m.unreadOnly,onChange:l=>ce(y=>({...y,unreadOnly:l.target.checked})),style:{accentColor:oe}}),e.jsx("span",{style:{color:c.ink},children:me.unreadOnly})]})]}),document.body),e.jsxs(Ut,{style:I.conversationList,children:[$e.map(l=>{var y;return e.jsx(Gn,{conversation:l,provider:(y=ge.get(l.connectionId))==null?void 0:y.provider,selected:(k==null?void 0:k.id)===l.id,primary:oe,currentAgent:x,onSelect:()=>{F(l),ye("chat"),N==null||N(l.id),D.current.markRead(l.id).then(()=>V()).catch(()=>{})}},l.id)}),!$e.length&&e.jsxs("div",{style:I.emptySmall,children:[e.jsx("div",{style:I.emptyIcon,children:e.jsx(zt,{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."})]}),Y&&e.jsx("button",{style:I.loadMore,onClick:()=>void V(Y),children:"Xem thêm hội thoại"})]})]}),Jt&&e.jsx("main",{style:I.main,children:k?e.jsx(_n,{conversation:k,provider:(St=ge.get(k.connectionId))==null?void 0:St.provider,connection:ge.get(k.connectionId),client:D.current,primary:oe,error:Re,onRegisterAppend:l=>{Ue.current=l},refreshKey:Je,infoOpen:Ie,onToggleInfo:()=>Te(l=>!l),t:me,disableAttachments:v,hideKeyboardHint:C,extensions:O,currentAgent:x,teamAgents:fe,onAssignAgent:l=>ve(k,l),onLinkContact:l=>h(k,l),onRefreshContactInfo:S,layoutMode:X,onBackToList:()=>ye("list"),totalUnreadCount:f,tenantSettings:ie,templateRefreshKey:de,onOpenSettings:j?void 0:l=>Q(l)},k.id):e.jsx(Yn,{})}),Ie&&k&&(X==="desktop"?e.jsx(Et,{conversation:k,connection:ge.get(k.connectionId),primary:oe,onClose:()=>Te(!1),client:D.current,onStartResize:te,extensions:O,extRefreshKey:Le,onLinkContact:l=>h(k,l),onRefreshContactInfo:S,layoutMode:X}):e.jsx("div",{onClick:()=>Te(!1),style:{position:"absolute",inset:0,zIndex:50,background:"rgba(15, 23, 42, 0.32)",display:"flex",justifyContent:"flex-end"},children:e.jsx("div",{onClick:l=>l.stopPropagation(),style:{width:X==="mobile"?"100%":"min(320px, 85%)",height:"100%",background:c.white,boxShadow:"-8px 0 24px rgba(15, 23, 42, 0.14)",display:"flex",flexDirection:"column"},children:e.jsx(Et,{conversation:k,connection:ge.get(k.connectionId),primary:oe,onClose:()=>Te(!1),client:D.current,onStartResize:void 0,extensions:O,extRefreshKey:Le,onLinkContact:l=>h(k,l),onRefreshContactInfo:S,layoutMode:X})})})),K&&e.jsx("div",{onClick:()=>{Q(null),pe(l=>l+1)},style:{position:"absolute",inset:0,zIndex:80,background:"rgba(15, 23, 42, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:X==="mobile"?0:18},children:e.jsx("div",{onClick:l=>l.stopPropagation(),style:{width:X==="mobile"?"100%":"min(840px, 100%)",height:X==="mobile"?"100%":"min(620px, 100%)",boxShadow:"0 24px 60px rgba(15, 23, 42, 0.25)",borderRadius:X==="mobile"?0:(s==null?void 0:s.borderRadius)??"16px",overflow:"hidden",display:"flex"},children:e.jsx(Nt,{apiUrl:n,token:r,theme:{...s,borderRadius:X==="mobile"?"0px":(s==null?void 0:s.borderRadius)??"16px"},initialTab:K,tabs:$==null?void 0:$.tabs,hideTechnicalAiConfig:$==null?void 0:$.hideTechnicalAiConfig,customParameters:$==null?void 0:$.customParameters,starterTemplates:$==null?void 0:$.starterTemplates,onSettingsChange:l=>{g(l),L.current=l},onClose:()=>{Q(null),pe(l=>l+1)}})})})]})})})});function Gn({conversation:t,provider:n,selected:r,primary:s,currentAgent:d,onSelect:w}){const[v,E]=i.useState(!1),C=t.contactName??t.subject??t.providerConversationKey,j=t.unreadCount??0,$=t.lastMessageText??"",p=t.lastMessageDirection==="outbound"?"Bạn: ":"",O=$.length>60?$.slice(0,60)+"…":$,U=$?p+O:"",M=t.assignedAgent??null,G=!!(M&&d&&M.id===d.id);let N="transparent";r?N="#eef2ff":v?N="#f7f9fc":j>0&&(N="#f0f4ff");const b={...I.row,background:N,...r?{boxShadow:`inset 3px 0 0 ${s}`}:j>0&&!v?{boxShadow:`inset 3px 0 0 ${s}`}:{}};return e.jsxs("button",{onClick:w,style:b,onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),children:[e.jsx(Vt,{name:C,color:s,image:t.contactPictureUrl,provider:n}),e.jsxs("span",{style:I.rowBody,children:[e.jsxs("span",{style:I.rowTop,children:[e.jsx("strong",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:j>0?700:500},children:C}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:[e.jsx("time",{style:{color:c.muted,fontSize:11,whiteSpace:"nowrap"},children:ft(t.lastMessageAt)}),j>0&&e.jsx("span",{"aria-label":`${j} tin nhắn chưa đọc`,style:I.unreadBadge,children:j>99?"99+":j})]})]}),e.jsxs("span",{style:{...I.rowBottom,justifyContent:"space-between",alignItems:"center",gap:6,color:j>0&&!r?"#4a5568":c.muted},children:[e.jsx("span",{style:{flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:U||e.jsx("span",{style:{opacity:.5},children:"Chưa có tin nhắn"})}),M?e.jsxs("span",{title:`Phụ trách: ${M.name}${M.title?` (${M.title})`:""}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 6px 1px 2px",borderRadius:999,fontSize:10,fontWeight:600,flexShrink:0,background:G?`${s}18`:"#f1f5f9",color:G?s:"#475569",border:G?`1px solid ${s}33`:"1px solid #e2e8f0"},children:[e.jsx("span",{style:{width:14,height:14,borderRadius:"50%",background:G?s:"#64748b",color:"#fff",fontSize:8,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:M.avatarUrl?e.jsx("img",{src:M.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Qe(M.name)}),e.jsx("span",{style:{maxWidth:68,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:pt(M.name)})]}):j>0?e.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:999,fontSize:9.5,fontWeight:600,flexShrink:0,background:"#fef3c7",color:"#b45309"},children:"Chưa nhận"}):null]})]})]})}function _n({conversation:t,provider:n,connection:r,client:s,primary:d,error:w,onRegisterAppend:v,refreshKey:E,infoOpen:C,onToggleInfo:j,t:$,disableAttachments:p,hideKeyboardHint:O,extensions:U,currentAgent:M,teamAgents:G,onAssignAgent:N,onLinkContact:b,onRefreshContactInfo:D,layoutMode:P="desktop",onBackToList:ne,totalUnreadCount:_=0,tenantSettings:B=ze,templateRefreshKey:Y=0,onOpenSettings:T}){var x,fe,ve;const[k,F]=i.useState([]),[re,ue]=i.useState(),[se,ae]=i.useState(""),[le,ke]=i.useState(!0),[R,ie]=i.useState(!1),[g,L]=i.useState(""),K=i.useRef(null),Q=t.contactName??t.subject??t.providerConversationKey,de=i.useRef(null),pe=i.useRef(null),[m,ce]=i.useState(null),[je,Oe]=i.useState(!1),[Se,Ge]=i.useState(!1),[we,Be]=i.useState(!1),[ee,Pe]=i.useState(0),Re=i.useRef(null),H=i.useRef(null),Ae=i.useRef(null),[Ce,Ee]=i.useState(!1),[X,Z]=i.useState(""),[ye,Ie]=i.useState([]),Te=i.useRef(null),Ve=i.useRef(null),[Fe,We]=i.useState(!1),_e=i.useRef(null),Ne=i.useRef(null);i.useEffect(()=>{if(!Fe)return;function h(S){var W,J;(W=_e.current)!=null&&W.contains(S.target)||(J=Ne.current)!=null&&J.contains(S.target)||We(!1)}return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[Fe]),i.useEffect(()=>()=>{m!=null&&m.objectUrl&&URL.revokeObjectURL(m.objectUrl)},[m==null?void 0:m.objectUrl]),i.useEffect(()=>{if(!we)return;function h(S){var W,J;(W=H.current)!=null&&W.contains(S.target)||(J=Re.current)!=null&&J.contains(S.target)||Be(!1)}return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[we]),i.useEffect(()=>{s.listCannedResponses().then(Ie).catch(()=>{})},[s,Y]),i.useEffect(()=>{if(!Ce)return;function h(S){var W,J;(W=Ve.current)!=null&&W.contains(S.target)||(J=Te.current)!=null&&J.contains(S.target)||Ee(!1)}return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[Ce]);const Le=i.useRef(!0),be=i.useCallback(async(h,S)=>{S||(Le.current=!h);try{const W=await s.listMessages(t.id,h);F(J=>h?[...W.items,...J]:W.items),ue(W.nextCursor)}catch(W){L(W instanceof Error?W.message:"Không tải được tin nhắn")}finally{S||ke(!1)}},[s,t.id]);i.useEffect(()=>{ke(!0),be()},[be]),i.useEffect(()=>{E&&be(void 0,!0)},[E]),i.useEffect(()=>{Le.current&&requestAnimationFrame(()=>{const h=K.current;h&&(h.scrollTop=h.scrollHeight)})},[k]),i.useEffect(()=>(v==null||v(h=>{Le.current=!0,F(S=>S.some(W=>W.id===h.id)?S:[...S,h])}),()=>{v==null||v(null)}),[v]);async function oe(h){var J;const S=(J=h.target.files)==null?void 0:J[0];if(!S)return;h.target.value="";const W=URL.createObjectURL(S);ce({file:S,uploading:!0,objectUrl:W});try{const te=await s.uploadAttachment(S);ce({file:S,uploading:!1,url:te.url,mimeType:te.mimeType,attachmentType:te.attachmentType,objectUrl:W})}catch{URL.revokeObjectURL(W),ce(null),L("Không tải lên được tệp đính kèm")}}async function ge(h){h.preventDefault();const S=se.trim(),W=m!=null&&m.url?[{url:m.url,mimeType:m.mimeType??"application/octet-stream",type:m.attachmentType}]:[];if(!S&&!W.length||R)return;ie(!0),L(""),!t.assignedAgent&&M&&B.inbox.autoAssignOnFirstReply&&N(M);const J=`optimistic-${Date.now()}`;M&&(Le.current=!0,F(te=>[...te,{id:J,direction:"outbound",status:"sending",text:S||void 0,attachments:W.length?W:void 0,occurredAt:new Date().toISOString(),senderAgent:M}]));try{await s.sendMessage(t.id,S||void 0,W.length?W:void 0),m!=null&&m.objectUrl&&URL.revokeObjectURL(m.objectUrl),ae(""),ce(null),await be(),M&&F(te=>{var $e,He;const V=te.filter(me=>me.id!==J),he=V.length-1;return he>=0&&(($e=V[he])==null?void 0:$e.direction)==="outbound"&&!((He=V[he])!=null&&He.senderAgent)?V.map((me,dt)=>dt===he?{...me,senderAgent:M}:me):V})}catch(te){F(V=>V.filter(he=>he.id!==J)),L(te instanceof Error?te.message:"Không gửi được tin nhắn")}finally{ie(!1)}}function Ue(h){const S=Ae.current;if(!S){ae(V=>V+h),Be(!1);return}const W=S.selectionStart??se.length,J=S.selectionEnd??se.length,te=se.slice(0,W)+h+se.slice(J);ae(te),Be(!1),requestAnimationFrame(()=>{S.focus(),S.selectionStart=S.selectionEnd=W+h.length})}function Je(h){ae(h),Ee(!1),Z(""),requestAnimationFrame(()=>{const S=Ae.current;S&&(S.focus(),S.selectionStart=S.selectionEnd=h.length)})}const o=!R&&(se.trim().length>0||(m==null?void 0:m.url)!=null&&!m.uploading),f=P==="desktop"?I.toolbarBtn:{...I.toolbarBtn,width:32,height:32};return e.jsxs("section",{style:I.chat,children:[e.jsxs("header",{style:{...I.chatHeader,...P==="mobile"?{padding:"0 10px 0 8px",gap:8}:{}},children:[P==="mobile"&&e.jsxs("button",{type:"button",onClick:ne,"aria-label":"Quay lại danh sách",style:{...I.iconButton,width:36,height:36,marginLeft:0,position:"relative",flexShrink:0,color:c.ink},children:[e.jsx(Qt,{size:18,strokeWidth:2.2}),_>0&&e.jsx("span",{style:{position:"absolute",top:3,right:3,minWidth:15,height:15,borderRadius:999,background:"#ef4444",color:"#fff",fontSize:9,fontWeight:800,display:"inline-grid",placeItems:"center",padding:"0 3px",border:`1.5px solid ${c.white}`},children:_>99?"99+":_})]}),e.jsx(Vt,{name:Q,color:d,image:t.contactPictureUrl,provider:n}),e.jsxs("div",{style:I.contact,children:[e.jsx("strong",{style:I.contactName,children:Q}),e.jsx("span",{style:I.contactMeta,children:qn(r)??Kt(n)})]}),e.jsxs("div",{style:{...I.headerActions,alignItems:"center",gap:6},children:[e.jsxs("div",{ref:_e,style:{position:"relative",display:"inline-flex",alignItems:"center",gap:4},children:[!t.assignedAgent&&M?e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",borderRadius:999,border:`1px solid ${d}40`,background:`${d}0d`,overflow:"hidden"},children:[e.jsxs("button",{type:"button",onClick:()=>void N(M),style:{border:0,background:"transparent",color:d,padding:"4px 9px",fontSize:11.5,fontWeight:600,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:[e.jsx(Rt,{size:12,strokeWidth:2.2}),e.jsx("span",{children:P==="mobile"?"+ Nhận":"+ Nhận phụ trách"})]}),((G==null?void 0:G.length)??0)>1&&e.jsx("button",{type:"button","aria-label":"Chọn nhân viên phụ trách",onClick:()=>We(h=>!h),style:{border:0,borderLeft:`1px solid ${d}30`,background:"transparent",color:d,padding:"4px 6px",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:e.jsx(ut,{size:12,strokeWidth:2.2})})]}):e.jsxs("button",{type:"button",onClick:()=>We(h=>!h),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 9px 3px 4px",borderRadius:999,border:`1px solid ${c.line}`,background:c.surface,color:c.ink,fontSize:11.5,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap"},children:[t.assignedAgent?e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{width:18,height:18,borderRadius:"50%",background:d,color:"#fff",fontSize:9,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:t.assignedAgent.avatarUrl?e.jsx("img",{src:t.assignedAgent.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Qe(t.assignedAgent.name)}),P!=="mobile"&&e.jsx("span",{style:{color:c.muted,fontWeight:500},children:"Phụ trách:"}),e.jsx("span",{style:{maxWidth:P==="mobile"?76:110,overflow:"hidden",textOverflow:"ellipsis"},children:pt(t.assignedAgent.name)})]}):e.jsxs(e.Fragment,{children:[e.jsx(jn,{size:13,color:c.muted}),e.jsx("span",{style:{color:c.muted},children:"Chưa phân công"})]}),e.jsx(ut,{size:12,color:c.muted})]}),Fe&&e.jsxs("div",{ref:Ne,style:{position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:200,minWidth:230,background:c.white,border:`1px solid ${c.line}`,borderRadius:11,boxShadow:"0 10px 28px rgba(23,32,51,.15)",padding:6,fontSize:12},children:[e.jsx("div",{style:{padding:"4px 8px 6px",fontSize:10,fontWeight:700,color:c.muted,letterSpacing:.8,textTransform:"uppercase"},children:"Người phụ trách hội thoại"}),M&&((x=t.assignedAgent)==null?void 0:x.id)!==M.id&&e.jsxs("button",{type:"button",onClick:()=>{We(!1),N(M)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",border:0,borderRadius:7,background:`${d}10`,color:d,padding:"6px 8px",marginBottom:4,fontWeight:600,fontSize:12,cursor:"pointer",textAlign:"left"},children:[e.jsx(Rt,{size:13}),e.jsxs("span",{children:["Nhận phụ trách cho tôi (",pt(M.name),")"]})]}),e.jsx("div",{style:{maxHeight:200,overflowY:"auto"},children:(G??[]).map(h=>{var W;const S=((W=t.assignedAgent)==null?void 0:W.id)===h.id;return e.jsxs("button",{type:"button",onClick:()=>{We(!1),N(h)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,width:"100%",border:0,borderRadius:7,background:S?"#f1f5f9":"transparent",color:c.ink,padding:"6px 8px",cursor:"pointer",textAlign:"left"},children:[e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[e.jsx("span",{style:{width:22,height:22,borderRadius:"50%",background:`${d}18`,color:d,fontSize:10,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:h.avatarUrl?e.jsx("img",{src:h.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Qe(h.name)}),e.jsxs("span",{style:{minWidth:0},children:[e.jsx("span",{style:{display:"block",fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:h.name}),h.title&&e.jsx("span",{style:{display:"block",fontSize:10.5,color:c.muted},children:h.title})]})]}),S&&e.jsx(lt,{size:13,color:d,strokeWidth:2.5})]},h.id)})}),t.assignedAgent&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{borderTop:`1px solid ${c.line}`,margin:"5px 0"}}),e.jsxs("button",{type:"button",onClick:()=>{We(!1),N(null)},style:{display:"flex",alignItems:"center",gap:6,width:"100%",border:0,borderRadius:7,background:"transparent",color:"#b42318",padding:"6px 8px",fontSize:11.5,fontWeight:500,cursor:"pointer",textAlign:"left"},children:[e.jsx(Ke,{size:13}),e.jsx("span",{children:"Bỏ phân công (Chưa có người nhận)"})]})]})]})]}),P!=="mobile"&&e.jsx("button",{style:I.iconButton,"aria-label":"Thêm tùy chọn",children:e.jsx(on,{size:16,strokeWidth:2})}),e.jsx("button",{style:{...I.iconButton,background:C?`${d}14`:"transparent",color:C?d:c.muted},"aria-label":"Thông tin liên hệ",onClick:j,children:e.jsx(sn,{size:16,strokeWidth:2})})]})]}),e.jsxs(Ut,{ref:K,style:I.messageArea,children:[e.jsx("div",{style:I.day,children:$.today}),re&&e.jsx("button",{onClick:()=>void be(re),style:I.historyButton,children:$.loadOlder}),le&&e.jsxs("div",{style:I.messageHint,children:[e.jsx(gt,{})," ",$.loading]}),!le&&!k.length&&e.jsx("div",{style:I.messageHint,children:$.noMessages}),k.map((h,S)=>{const W=(U==null?void 0:U.flatMap(he=>he.messageEnrichments??[]))??[],J=h.direction==="inbound"&&W.length>0&&S>=k.length-15,te=J?at(t,{provider:n,recentMessages:k.slice(-10),linkContact:b,refreshContactInfo:D,sendMessage:async(he,$e)=>{await s.sendMessage(t.id,he,$e),await be(void 0,!0)}}):null,V=J&&te?W.map((he,$e)=>{var me;const He=(me=h.text)==null?void 0:me.match(he.pattern);return He?e.jsx(Nn,{children:he.render(He,te,h)},`${h.id}-${$e}`):null}).filter(Boolean):[];return e.jsxs("div",{children:[e.jsx(Jn,{message:h,primary:d}),V.length>0&&e.jsx("div",{style:{maxWidth:"min(70%, 480px)",marginTop:-4,marginBottom:10,display:"flex",flexDirection:"column",gap:6},children:V})]},h.id)})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"nowrap",overflowX:"auto",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",padding:"6px 14px 2px",borderTop:`1px solid ${c.line}`},children:[B.ai.mode!=="off"&&e.jsxs("button",{type:"button",onClick:()=>T==null?void 0:T("ai"),title:"Cấu hình Trợ lý AI",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:10.5,fontWeight:700,padding:"3px 9px",borderRadius:999,background:B.ai.mode==="autopilot"?"#ecfdf5":"#f5f3ff",color:B.ai.mode==="autopilot"?"#059669":"#7c3aed",border:B.ai.mode==="autopilot"?"1px solid #a7f3d0":"1px solid #ddd6fe",cursor:T?"pointer":"default",whiteSpace:"nowrap",flexShrink:0},children:[B.ai.mode==="autopilot"?e.jsx(Dt,{size:11}):e.jsx(rt,{size:11}),e.jsx("span",{children:B.ai.mode==="autopilot"?"AI Autopilot":"AI Copilot"})]}),((fe=B.inbox.quickReplies)!=null&&fe.length?B.inbox.quickReplies:["Cảm ơn bạn đã liên hệ 🙏","Mình sẽ kiểm tra ngay","Vui lòng chờ 1-2 phút"]).map(h=>e.jsx("button",{type:"button",onClick:()=>ae(h),style:{fontSize:11,padding:"3px 10px",borderRadius:999,background:`${d}0f`,color:d,border:`1px solid ${d}33`,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},children:h},h))]}),e.jsxs("form",{onSubmit:ge,style:{flex:"0 0 auto",padding:"8px 14px 12px",borderTop:`1px solid ${c.line}`,background:c.white,position:"relative"},children:[we&&e.jsxs("div",{ref:Re,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:c.white,border:`1px solid ${c.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:280,maxWidth:"calc(100vw - 28px)",overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${c.line}`,background:"#f9fafb"},children:Mt.map((h,S)=>e.jsx("button",{type:"button",onClick:()=>Pe(S),style:{flex:1,border:0,background:"transparent",padding:"7px 2px",fontSize:16,cursor:"pointer",lineHeight:1,borderBottom:ee===S?`2px solid ${d}`:"2px solid transparent",opacity:ee===S?1:.5,transition:"opacity 100ms ease"},children:h.icon},S))}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:2,padding:8,maxHeight:180,overflowY:"auto"},children:(ve=Mt[ee])==null?void 0:ve.emojis.map((h,S)=>e.jsx("button",{type:"button",onClick:()=>Ue(h),style:{border:0,background:"transparent",padding:"5px 2px",fontSize:18,cursor:"pointer",borderRadius:6,lineHeight:1,transition:"background 80ms ease"},onMouseEnter:W=>{W.target.style.background="#f3f4f6"},onMouseLeave:W=>{W.target.style.background="transparent"},children:h},S))})]}),Ce&&e.jsxs("div",{ref:Te,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:c.white,border:`1px solid ${c.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:300,maxWidth:"calc(100vw - 28px)",overflow:"hidden",fontFamily:"inherit"},children:[e.jsxs("div",{style:{padding:"8px 10px",borderBottom:`1px solid ${c.line}`,display:"flex",alignItems:"center",gap:6},children:[e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Tìm template…",value:X,onChange:h=>Z(h.target.value),style:{flex:1,minWidth:0,boxSizing:"border-box",border:`1px solid ${c.line}`,borderRadius:7,padding:"5px 8px",fontSize:12,outline:"none",fontFamily:"inherit",color:c.ink}}),T&&e.jsx("button",{type:"button",onClick:()=>{Ee(!1),T("templates")},style:{border:`1px solid ${d}33`,background:`${d}0f`,color:d,borderRadius:7,padding:"5px 8px",fontSize:11,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},children:"+ Quản lý mẫu câu"})]}),e.jsx("div",{style:{maxHeight:220,overflowY:"auto"},children:(()=>{const h=X.trim().toLowerCase(),S=h?ye.filter(W=>W.title.toLowerCase().includes(h)||W.content.toLowerCase().includes(h)||(W.shortcut??"").toLowerCase().includes(h)):ye;return S.length?S.map(W=>e.jsxs("button",{type:"button",onClick:()=>Je(W.content),style:{display:"block",width:"100%",textAlign:"left",border:0,borderBottom:`1px solid ${c.line}`,background:"transparent",padding:"9px 12px",cursor:"pointer",fontFamily:"inherit"},onMouseEnter:J=>{J.currentTarget.style.background="#f7f9fc"},onMouseLeave:J=>{J.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:c.ink},children:W.title}),W.shortcut&&e.jsx("span",{style:{fontSize:10,color:d,background:`${d}18`,borderRadius:4,padding:"1px 5px"},children:W.shortcut})]}),e.jsx("div",{style:{fontSize:11,color:c.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:W.content})]},W.id)):e.jsx("div",{style:{padding:"24px 16px",textAlign:"center",color:c.muted,fontSize:12},children:ye.length===0?"Chưa có template nào":"Không tìm thấy"})})()})]}),e.jsxs("div",{style:{border:`1.5px solid ${c.line}`,borderRadius:12,background:c.white,overflow:"hidden"},children:[m&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:`1px solid ${c.line}`,fontSize:12},children:[m.uploading?e.jsxs(e.Fragment,{children:[e.jsx(gt,{}),e.jsx("span",{style:{color:c.muted},children:"Đang tải lên…"})]}):m.attachmentType==="image"&&m.objectUrl?e.jsx("img",{src:m.objectUrl,alt:"",style:{height:48,width:48,objectFit:"cover",borderRadius:6}}):e.jsxs("span",{style:{color:c.muted},children:["📎 ",m.file.name," (",Math.round(m.file.size/1024)," KB)"]}),!m.uploading&&e.jsx("button",{type:"button",onClick:()=>{m!=null&&m.objectUrl&&URL.revokeObjectURL(m.objectUrl),ce(null)},style:{marginLeft:"auto",border:0,background:"none",color:c.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:H,type:"button",title:"Chèn emoji",onClick:()=>Be(h=>!h),style:{...f,background:we?`${d}18`:"transparent",color:we?d:"#9ca3af"},children:e.jsx(vn,{size:13,strokeWidth:2})}),!p&&e.jsx("button",{type:"button",title:"Gửi ảnh / video","aria-label":"Gửi ảnh hoặc video",style:f,onClick:()=>{var h;return(h=de.current)==null?void 0:h.click()},children:e.jsx(rn,{size:13,strokeWidth:2})}),!p&&e.jsx("button",{type:"button",title:"Gửi tệp đính kèm","aria-label":"Gửi tệp đính kèm",style:f,onClick:()=>{var h;return(h=pe.current)==null?void 0:h.click()},children:e.jsx(dn,{size:13,strokeWidth:2})}),!p&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:de,type:"file",style:{display:"none"},onChange:oe,accept:"image/*,video/mp4"}),e.jsx("input",{ref:pe,type:"file",style:{display:"none"},onChange:oe,accept:".pdf,audio/mpeg,audio/ogg,application/octet-stream,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"})]}),e.jsx("button",{ref:Ve,type:"button",title:"Template nhanh",onClick:()=>{Ee(h=>!h),Z("")},style:{...f,background:Ce?`${d}18`:"transparent",color:Ce?d:"#9ca3af"},children:e.jsx(Pt,{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(h=>!h),style:{...f,fontWeight:700,fontSize:12,background:je?`${d}18`:"transparent",color:je?d:"#9ca3af",border:je?`1px solid ${d}33`:"1px solid transparent"},children:"B"}),e.jsx("button",{type:"button",title:"Nghiêng",onClick:()=>Ge(h=>!h),style:{...f,fontStyle:"italic",fontSize:12,background:Se?`${d}18`:"transparent",color:Se?d:"#9ca3af",border:Se?`1px solid ${d}33`:"1px solid transparent"},children:"I"}),!!(U!=null&&U.some(h=>{var S;return(((S=h.toolbarActions)==null?void 0:S.length)??0)>0}))&&e.jsx("span",{style:{width:1,height:14,background:"#e5e7eb",margin:"0 4px"}}),U==null?void 0:U.flatMap(h=>h.toolbarActions??[]).map((h,S)=>e.jsxs("button",{type:"button",title:h.tooltip,style:h.label?{display:"inline-flex",alignItems:"center",gap:5,padding:"3px 9px",borderRadius:999,border:`1px solid ${d}33`,background:`${d}0f`,color:d,fontSize:11.5,fontWeight:600,cursor:"pointer",lineHeight:1.2,whiteSpace:"nowrap"}:f,onClick:()=>{const W=te=>{ae(V=>V&&!V.endsWith(" ")&&!V.endsWith(`
205
+ `)?`${V} ${te}`:`${V}${te}`),requestAnimationFrame(()=>{var V;return(V=Ae.current)==null?void 0:V.focus()})},J=at(t,{provider:n,recentMessages:k.slice(-10),linkContact:b,refreshContactInfo:D,sendMessage:async(te,V)=>{await s.sendMessage(t.id,te,V),await be(void 0,!0)}});h.onClick({...J,insertText:W})},children:[h.icon,h.label&&e.jsx("span",{children:h.label})]},S))]}),e.jsx(Pn,{ref:Ae,"aria-label":"Soạn tin nhắn",rows:2,value:se,onChange:h=>ae(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),ge(h))},placeholder:$.sendPlaceholder,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",minHeight:52,maxHeight:120,resize:"none",border:0,outline:0,background:"transparent",color:c.ink,padding:"8px 12px 4px",font:"inherit",fontSize:P==="mobile"?16:13,lineHeight:1.45,fontStyle:Se?"italic":"normal",fontWeight:je?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:se.length>1e3?"#ef4444":se.length>900?"#f59e0b":"#9ca3af",fontWeight:se.length>1e3?600:400},children:[se.length,"/1000"]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[!O&&P==="desktop"&&e.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:"↵ Gửi · ⇧↵ Xuống dòng"}),e.jsxs("button",{disabled:!o,"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:o?`linear-gradient(135deg,${d},#0ea5e9)`:"#e5e7eb",color:o?"#fff":"#9ca3af",cursor:o?"pointer":"not-allowed",boxShadow:o?"0 2px 8px rgba(37,99,235,0.25)":"none",transition:"all 150ms ease"},children:[R?e.jsx(st,{size:12,style:{animation:"channelhub-spin .7s linear infinite"}}):e.jsx(fn,{size:12,strokeWidth:2}),$.send]})]})]})]})]}),(g||w)&&e.jsx("div",{role:"alert",style:I.error,children:g||w})]})}function Jn({message:t,primary:n}){var P,ne,_,B,Y;const r=i.useContext(bt),s=i.useContext(qt),d=T=>T.startsWith("/v1/media/proxy")?`${r}${T}&tok=${encodeURIComponent(s)}`:T,w=t.direction==="outbound",v=((P=t.attachments)==null?void 0:P.filter(T=>T.type==="image"))??[],E=((ne=t.attachments)==null?void 0:ne.filter(T=>T.type==="sticker"))??[],C=((_=t.attachments)==null?void 0:_.filter(T=>T.type==="video"))??[],j=((B=t.attachments)==null?void 0:B.filter(T=>T.type==="audio"))??[],$=((Y=t.attachments)==null?void 0:Y.filter(T=>T.type==="file"))??[],[p,O]=i.useState(null),U=w?"flex-end":"flex-start",M=w?t.senderAgent??null:null,G=e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:w?"flex-end":"flex-start",gap:5,marginTop:4,fontSize:10,opacity:.78,letterSpacing:.2,userSelect:"none"},children:[M&&e.jsxs("span",{title:M.title?`${M.name} (${M.title})`:M.name,style:{display:"inline-flex",alignItems:"center",gap:3.5,fontWeight:600},children:[e.jsx("span",{style:{width:14,height:14,borderRadius:"50%",background:"rgba(255,255,255,0.22)",color:"#fff",fontSize:8,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:M.avatarUrl?e.jsx("img",{src:M.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Qe(M.name)}),e.jsx("span",{children:M.name}),e.jsx("span",{style:{opacity:.6},children:"•"})]}),e.jsxs("time",{children:[ft(t.occurredAt,!0),w&&e.jsxs(e.Fragment,{children:[" ",e.jsx(At,{status:t.status})]})]})]}),N=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:[ft(t.occurredAt,!0),w&&e.jsxs(e.Fragment,{children:[" ",e.jsx(At,{status:t.status})]})]})}),b=w?{...I.bubbleOut,background:n,color:"#fff",border:"1px solid transparent"}:I.bubbleIn,D=!t.text&&j.length===0&&$.length===0;return e.jsxs("div",{style:{...I.messageLine,justifyContent:U,flexDirection:"column",alignItems:U},children:[E.map((T,k)=>e.jsxs("div",{style:{position:"relative",marginBottom:2},children:[e.jsx("img",{src:d(T.url),alt:"sticker",style:{display:"block",maxWidth:128,maxHeight:128,objectFit:"contain"}}),D&&v.length===0&&C.length===0&&k===E.length-1&&N]},`s${k}`)),v.map((T,k)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"zoom-in"},onClick:()=>O({url:d(T.url),kind:"image"}),children:[e.jsx("img",{src:d(T.url),alt:"",style:{display:"block",maxWidth:260,maxHeight:260,borderRadius:12,objectFit:"cover"}}),D&&k===v.length-1&&C.length===0&&N]},k)),C.map((T,k)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"pointer"},onClick:()=>O({url:d(T.url),kind:"video"}),children:[e.jsx("video",{src:d(T.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(hn,{size:16,fill:"#172033",color:"#172033",style:{marginLeft:2}})})}),D&&k===C.length-1&&N]},k)),(j.length>0||$.length>0||t.text||!v.length&&!C.length&&!E.length&&!t.text)&&e.jsxs("div",{style:b,children:[j.map((T,k)=>e.jsx("audio",{src:d(T.url),controls:!0,style:{display:"block",width:"100%",marginBottom:4}},k)),$.map((T,k)=>e.jsxs("a",{href:d(T.url),target:"_blank",rel:"noreferrer",style:{display:"block",fontSize:12,color:w?"#fff":"#2563eb",textDecoration:"underline",marginBottom:4},children:["📎 ",Kn(T.mimeType)]},k)),t.text&&e.jsx("p",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t.text}),!j.length&&!$.length&&!t.text&&e.jsx("p",{style:{margin:0,opacity:.5},children:"[attachment]"}),G]}),p&&Lt.createPortal(e.jsxs("div",{onClick:()=>O(null),style:{position:"fixed",inset:0,zIndex:1e4,background:"rgba(0,0,0,.88)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"zoom-out"},children:[p.kind==="image"?e.jsx("img",{src:p.url,alt:"",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,objectFit:"contain",boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:T=>T.stopPropagation()}):e.jsx("video",{src:p.url,controls:!0,autoPlay:!0,style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:T=>T.stopPropagation()}),e.jsx("button",{onClick:()=>O(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(Ke,{size:18})})]}),document.body)]})}function Et({conversation:t,connection:n,primary:r,onClose:s,client:d,onStartResize:w,extensions:v,extRefreshKey:E,onLinkContact:C,onRefreshContactInfo:j,layoutMode:$="desktop"}){const p=t.contactName??t.subject??t.providerConversationKey,O=n==null?void 0:n.provider,U=!!(v!=null&&v.some(R=>R.contactInfoRows)),[M,G]=i.useState({channel:!0,stats:!1,extra:!0}),N=R=>G(ie=>({...ie,[R]:!ie[R]})),[b,D]=i.useState(""),[P,ne]=i.useState(""),[_,B]=i.useState(!1),[Y,T]=i.useState(!1),[k,F]=i.useState(""),[re,ue]=i.useState([]),[se,ae]=i.useState(!1);i.useEffect(()=>{D(""),ne(""),T(!1),F(""),d.getNote(t.id).then(R=>{R&&(D(R.content),ne(R.content))}).catch(()=>{})},[t.id,d]),i.useEffect(()=>{if(!U||!v)return;let R=!1;const ie=at(t,{provider:O,linkContact:C,refreshContactInfo:j,sendMessage:async(g,L)=>{await d.sendMessage(t.id,g,L)}});return ae(!0),Promise.allSettled(v.filter(g=>g.contactInfoRows).map(g=>g.contactInfoRows(ie))).then(g=>{if(R)return;const L=g.filter(K=>K.status==="fulfilled").flatMap(K=>K.value);ue(L),ae(!1)}),()=>{R=!0}},[t.id,t.contactExternalId,v,E,U,O,C,j,d]);const le=b.trim()!==P.trim()&&b.trim().length>0;async function ke(){if(!(!le||_)){B(!0),F("");try{const R=b.trim();await d.upsertNote(t.id,R),ne(R),T(!0),setTimeout(()=>T(!1),2e3)}catch{F("Lưu thất bại")}finally{B(!1)}}}return e.jsxs("aside",{style:{...I.infoPanel,position:"relative",...$!=="desktop"?{flex:1,borderLeft:0}:{}},children:[w&&e.jsx("div",{onMouseDown:w,style:{position:"absolute",left:0,top:0,bottom:0,width:4,cursor:"col-resize",zIndex:1},onMouseEnter:R=>{R.currentTarget.style.background="rgba(0,0,0,0.07)"},onMouseLeave:R=>{R.currentTarget.style.background=""}}),e.jsxs("div",{style:I.infoPanelHeader,children:[e.jsx("span",{style:{fontWeight:600,fontSize:13,color:c.ink},children:"Thông tin liên hệ"}),e.jsx("button",{style:I.iconButton,onClick:s,"aria-label":"Đóng",children:e.jsx(Ke,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:{overflowY:"auto",flex:1},children:[e.jsxs("div",{style:I.infoPanelIdentity,children:[e.jsxs("span",{style:{...I.avatarWrap,width:48,height:48},children:[e.jsx(yt,{src:t.contactPictureUrl,fallback:Qe(p),style:{...I.avatar,width:48,height:48,fontSize:16}}),e.jsx("span",{style:{...I.providerBadge,width:20,height:20},children:e.jsx(nt,{provider:O})})]}),e.jsx("strong",{style:{marginTop:10,fontSize:15,color:c.ink,textAlign:"center"},children:p}),e.jsx("span",{style:{fontSize:11,color:c.muted,fontFamily:"monospace",textAlign:"center"},children:t.providerConversationKey})]}),e.jsxs(ht,{label:"KÊNH",sectionKey:"channel",expanded:M.channel,onToggle:()=>N("channel"),children:[e.jsx(Me,{label:"Nền tảng",children:e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5},children:[e.jsx(nt,{provider:O}),e.jsx("span",{children:Kt(O)})]})}),e.jsxs(Me,{label:"ID hội thoại",children:[e.jsxs("span",{style:{fontFamily:"monospace",fontSize:11},children:[t.id.slice(0,8),"…"]}),e.jsx(Xn,{value:t.id})]})]}),e.jsxs(ht,{label:"THỐNG KÊ",sectionKey:"stats",expanded:M.stats,onToggle:()=>N("stats"),children:[e.jsx(Me,{label:"Tin nhắn",value:String(t.messageCount??0)}),(t.unreadCount??0)>0&&e.jsx(Me,{label:"Chưa đọc",value:String(t.unreadCount),valueColor:"#ef4444"}),e.jsx(Me,{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(Me,{label:"Lần đầu",value:"—"})]}),e.jsxs(ht,{label:"THÔNG TIN BỔ SUNG",sectionKey:"extra",expanded:M.extra,onToggle:()=>N("extra"),children:[!U&&e.jsxs(e.Fragment,{children:[e.jsx(Me,{label:"Điện thoại",value:"— chưa có",valueMuted:!0}),e.jsx(Me,{label:"Email",value:"— chưa có",valueMuted:!0}),e.jsx(Me,{label:"Nhãn",value:"— chưa có",valueMuted:!0})]}),se&&re.length===0&&e.jsx("div",{style:{fontSize:12,color:c.muted,padding:"6px 0"},children:"Đang tải hồ sơ CRM…"}),re.map(R=>e.jsx(Me,{label:R.label,children:e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,flexWrap:"wrap",justifyContent:"flex-end"},children:[R.onClick?e.jsx("button",{type:"button",onClick:R.onClick,style:{border:0,background:"none",padding:0,color:r,fontSize:12,fontWeight:600,cursor:"pointer",textDecoration:"underline"},children:R.value}):R.href?e.jsx("a",{href:R.href,target:"_blank",rel:"noopener noreferrer",style:{color:r,fontSize:12,fontWeight:600},children:R.value}):e.jsx("span",{style:{fontSize:12,fontWeight:500,color:c.ink},children:R.value}),R.badge&&e.jsx("span",{style:{fontSize:10.5,fontWeight:700,padding:"1px 7px",borderRadius:999,color:R.badge.color??r,background:R.badge.bg??`${r}14`},children:R.badge.text})]})},R.label))]}),e.jsxs("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:8},children:[!(v!=null&&v.length)&&e.jsx("button",{style:{...I.ghostButton,color:r,borderColor:`${r}33`},children:"Xem lịch sử"}),v==null?void 0:v.flatMap(R=>R.sidebarActions??[]).map((R,ie)=>{const g=R.variant==="primary";return e.jsxs("button",{style:{...I.ghostButton,background:g?r:"#fff",color:g?"#fff":c.ink,borderColor:g?r:c.line,fontWeight:g?700:600,display:"flex",alignItems:"center",justifyContent:"center",gap:6},onClick:()=>{const L=at(t,{provider:O,linkContact:C,refreshContactInfo:j,sendMessage:async(K,Q)=>{await d.sendMessage(t.id,K,Q)}});R.onClick(L)},children:[R.icon,R.label]},ie)}),e.jsxs("div",{style:{border:`1px solid ${c.line}`,borderRadius:10,background:c.white,overflow:"hidden"},children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:`1px solid ${c.line}`,background:c.surface,fontSize:11,fontWeight:600,color:c.muted},children:"Ghi chú nội bộ"}),e.jsx("textarea",{value:b,onChange:R=>D(R.target.value),placeholder:"Nhập ghi chú...",rows:3,style:{display:"block",width:"100%",boxSizing:"border-box",border:0,outline:0,background:c.white,resize:"none",padding:"8px 10px",font:"inherit",fontSize:$==="mobile"?16:12,color:c.ink,lineHeight:1.5}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 10px 6px"},children:[Y?e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,fontSize:11,color:"#16a34a"},children:[e.jsx(lt,{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:()=>{ke()},disabled:!le||_,style:{padding:"4px 12px",border:0,borderRadius:7,fontSize:12,fontWeight:600,background:le&&!_?r:"#f1f5f9",color:le&&!_?"#fff":"#94a3b8",cursor:le&&!_?"pointer":"not-allowed"},children:_?"Đang lưu…":"Lưu ghi chú"})]})]})]})]})]})}function ht({label:t,children:n,sectionKey:r,expanded:s,onToggle:d}){const w=!!d,v=s??!0;return e.jsxs("div",{style:{borderTop:`1px solid ${c.line}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px 6px",fontSize:10,fontWeight:700,letterSpacing:1,color:c.muted,textTransform:"uppercase",cursor:w?"pointer":"default"},onClick:d,children:[e.jsx("span",{children:t}),w&&(v?e.jsx(ut,{size:12,strokeWidth:2}):e.jsx(en,{size:12,strokeWidth:2}))]}),v&&n]})}function Me({label:t,value:n,children:r,valueColor:s,valueMuted:d}){return e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",padding:"5px 16px",fontSize:12,gap:10},children:[e.jsx("span",{style:{color:c.muted,flexShrink:0,lineHeight:1.4},children:t}),e.jsx("span",{style:{color:s??(d?c.muted:c.ink),textAlign:"right",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",flexWrap:"wrap",gap:4,lineHeight:1.4},children:r??n})]})}function Xn({value:t}){const[n,r]=i.useState(!1);return e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:c.muted,padding:2,lineHeight:1},title:"Sao chép",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{r(!0),setTimeout(()=>r(!1),1500)})},"aria-label":"Sao chép ID",children:n?"✓":"⎘"})}function Yn(){return e.jsxs("div",{style:I.empty,children:[e.jsx("div",{style:I.emptyHero,children:e.jsx(Ot,{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 Vt({name:t,color:n,image:r,provider:s}){return e.jsxs("span",{style:I.avatarWrap,children:[e.jsx(Zn,{name:t,color:n,image:r}),s&&e.jsx("span",{style:I.providerBadge,children:e.jsx(nt,{provider:s})})]})}function Zn({name:t,color:n,image:r}){return e.jsx(yt,{src:r,fallback:Qe(t),style:{...I.avatar,background:`${n}18`,color:n}})}function gt(){return e.jsx(st,{size:14,style:I.spinner,"aria-hidden":"true"})}function Qe(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}const Qn={livechat:"web"};function nt({provider:t}){const n=i.useContext(bt),r=14;if(!t)return null;const s=Qn[t]??t;return e.jsx("img",{src:`${n}/static/logos/${s}.avif`,alt:t,width:r,height:r,style:{borderRadius:"50%",objectFit:"cover",display:"block"}})}function ft(t,n=!1){if(!t)return"";const r=new Date(t);return r.toDateString()===new Date().toDateString()?r.toLocaleTimeString("vi-VN",{hour:"2-digit",minute:"2-digit"}):r.toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit"})}const I={frame:{display:"grid",gridTemplateRows:"minmax(0, 1fr)",height:620,maxHeight:"calc(100dvh - 220px)",minHeight:0,overflow:"hidden",border:`1px solid ${c.line}`,background:c.white,color:c.ink,boxShadow:"0 18px 50px rgba(31,45,72,.10)"},sidebar:{display:"flex",flexDirection:"column",minWidth:0,minHeight:0,borderRight:`1px solid ${c.line}`,background:c.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:c.muted},iconButton:{display:"inline-grid",placeItems:"center",width:32,height:32,marginLeft:"auto",border:0,borderRadius:8,background:"transparent",color:c.muted,cursor:"pointer"},search:{display:"flex",alignItems:"center",gap:8,margin:"0 14px 12px",padding:"9px 10px",border:`1px solid ${c.line}`,borderRadius:9,color:c.muted,background:c.surface},clear:{border:0,background:"none",color:c.muted,cursor:"pointer",fontSize:18},listHeader:{display:"flex",alignItems:"center",padding:"10px 18px",borderTop:`1px solid ${c.line}`,borderBottom:`1px solid ${c.line}`,color:c.muted,fontSize:11,fontWeight:700,letterSpacing:.4,textTransform:"uppercase"},conversationList:{overflowY:"auto",flex:1,minHeight:0},row:{display:"flex",width:"100%",gap:11,padding:"16px 14px",border:0,borderBottom:`1px solid ${c.line}`,background:"transparent",textAlign:"left",cursor:"pointer",transition:"background 120ms ease"},avatarWrap:{position:"relative",flex:"0 0 auto",width:44,height:44},avatar:{flex:"0 0 auto",width:44,height:44,display:"grid",placeItems:"center",borderRadius:"50%",objectFit:"cover",fontSize:14,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:14},rowBottom:{display:"flex",marginTop:4,fontSize:12,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:c.muted,fontSize:12,textAlign:"center"},emptyIcon:{display:"grid",placeItems:"center",width:40,height:40,borderRadius:12,background:c.surface},main:{minWidth:0,minHeight:0,overflow:"hidden",background:c.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 ${c.line}`,background:c.white},contact:{display:"grid",gap:3,minWidth:0,flex:1},contactName:{fontSize:14,fontWeight:600,color:c.ink,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},contactMeta:{display:"flex",alignItems:"center",gap:5,fontSize:11,color:c.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 ${c.line}`,borderRadius:20,padding:"6px 12px",background:c.white,color:c.muted,cursor:"pointer",fontSize:11},messageHint:{display:"flex",justifyContent:"center",alignItems:"center",gap:8,padding:40,color:c.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 ${c.line}`,background:c.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:c.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 ${c.line}`,background:c.white,color:c.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 ${c.line}`,background:c.white,minHeight:0,overflow:"hidden"},infoPanelHeader:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 16px 12px",borderBottom:`1px solid ${c.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 ${c.line}`,borderRadius:8,background:"transparent",fontSize:12,cursor:"pointer",textAlign:"center"}};function ei(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}function ti(t){if(!t)return"";const n=new Date(t);return n.toDateString()===new Date().toDateString()?n.toLocaleTimeString("vi-VN",{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit"})}function ni({apiUrl:t,token:n,theme:r,locale:s="vi",icon:d,onConversationSelect:w}){const v=(r==null?void 0:r.primaryColor)??"#2563eb",E=typeof d=="function"?d({size:20,color:"currentColor"}):d??e.jsx(Ct,{size:20,strokeWidth:1.8}),C=i.useRef(new Ze(t,n)),[j,$]=i.useState(!1),[p,O]=i.useState([]),U=i.useRef(null),M=i.useRef(null),G=p.filter(B=>(B.unreadCount??0)>0),N=G.reduce((B,Y)=>B+(Y.unreadCount??0),0),b=i.useCallback(async()=>{try{const B=await C.current.listConversations();O(B.items)}catch{}},[]);i.useEffect(()=>(b(),C.current.connectSSE(Y=>{(Y==="message.new"||Y==="conversation.updated")&&b()})),[b]),i.useEffect(()=>{if(!j)return;const B=Y=>{var T,k;(T=U.current)!=null&&T.contains(Y.target)||(k=M.current)!=null&&k.contains(Y.target)||$(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[j]);const D=async B=>{if($(!1),w==null||w(B.id,B),(B.unreadCount??0)>0)try{await C.current.markRead(B.id),O(Y=>Y.map(T=>T.id===B.id?{...T,unreadCount:0}:T))}catch{}},P=s==="en"?`${N} unread message${N!==1?"s":""}`:`${N} tin nhắn chưa đọc`,ne=s==="en"?"No unread messages":"Không có tin nhắn mới",_=s==="en"?"Messages":"Tin nhắn";return e.jsxs("div",{style:{position:"relative",display:"inline-block",fontFamily:(r==null?void 0:r.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif"},children:[e.jsxs("button",{ref:U,"aria-label":P,"aria-haspopup":"true","aria-expanded":j,onClick:()=>$(B=>!B),style:{position:"relative",display:"inline-grid",placeItems:"center",width:40,height:40,border:0,borderRadius:"50%",background:j?`${v}18`:"transparent",color:j?v:"#6b7280",cursor:"pointer",transition:"background 150ms ease, color 150ms ease"},children:[E,N>0&&e.jsx("span",{"aria-hidden":"true",style:{position:"absolute",top:4,right:4,minWidth:16,height:16,borderRadius:999,background:"#ef4444",color:"#fff",fontSize:10,fontWeight:800,lineHeight:"16px",textAlign:"center",padding:"0 4px",border:"2px solid #fff",boxSizing:"border-box"},children:N>99?"99+":N})]}),j&&e.jsxs("div",{ref:M,role:"dialog","aria-label":_,style:{position:"absolute",top:"calc(100% + 8px)",right:0,zIndex:9999,width:360,maxHeight:480,background:"#fff",border:"1px solid #e7ebf2",borderRadius:14,boxShadow:"0 12px 40px rgba(23,32,51,.14)",overflow:"hidden",display:"flex",flexDirection:"column"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 10px",borderBottom:"1px solid #e7ebf2"},children:[e.jsx("span",{style:{fontSize:16,fontWeight:700,color:"#172033"},children:_}),N>0&&e.jsxs("span",{style:{fontSize:11,fontWeight:600,background:`${v}14`,color:v,borderRadius:999,padding:"2px 8px"},children:[N," ",s==="en"?"unread":"chưa đọc"]})]}),e.jsx("div",{style:{overflowY:"auto",flex:1},children:G.length===0?e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"40px 24px",color:"#9aa5b5"},children:[e.jsx(Ct,{size:28,strokeWidth:1.5}),e.jsx("span",{style:{fontSize:13},children:ne})]}):G.map(B=>e.jsx(ii,{conversation:B,primary:v,apiUrl:t,onSelect:D},B.id))})]})]})}function ii({conversation:t,primary:n,apiUrl:r,onSelect:s}){const[d,w]=i.useState(!1),v=t.contactName??t.providerConversationKey,E=t.unreadCount??0;return e.jsxs("button",{onClick:()=>s(t),onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),style:{display:"flex",width:"100%",gap:12,padding:"10px 16px",border:0,borderBottom:"1px solid #f1f5f9",background:d?"#f7f9fc":E>0?"#f0f4ff":"#fff",textAlign:"left",cursor:"pointer",transition:"background 100ms ease",alignItems:"center"},children:[e.jsxs("span",{style:{position:"relative",flex:"0 0 auto",width:42,height:42},children:[e.jsx(yt,{src:t.contactPictureUrl,fallback:ei(v),style:{width:42,height:42,borderRadius:"50%",objectFit:"cover",display:"grid",placeItems:"center",fontSize:13,fontWeight:800,background:`${n}18`,color:n}}),void 0]}),e.jsxs("span",{style:{flex:1,minWidth:0},children:[e.jsxs("span",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontSize:13,fontWeight:E>0?700:500,color:"#172033",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,flexShrink:0},children:[e.jsx("time",{style:{fontSize:11,color:"#9aa5b5",whiteSpace:"nowrap"},children:ti(t.lastMessageAt)}),E>0&&e.jsx("span",{style:{display:"inline-grid",placeItems:"center",minWidth:18,height:18,borderRadius:999,background:"#ef4444",color:"#fff",fontSize:10,fontWeight:800,padding:"0 4px"},children:E>99?"99+":E})]})]}),e.jsxs("span",{style:{display:"block",marginTop:2,fontSize:12,color:E>0?"#374151":"#9aa5b5",fontWeight:E>0?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.lastMessageDirection==="outbound"&&e.jsx("span",{style:{color:"#9aa5b5"},children:"Bạn: "}),t.lastMessageText||e.jsx("span",{style:{opacity:.5},children:"Chưa có tin nhắn"})]})]})]})}console.log("[ChannelHub] widget v0.1.14 loaded");exports.ChannelHubChannels=Ft;exports.ChannelHubClient=Ze;exports.ChannelHubInbox=Vn;exports.ChannelHubNotificationBell=ni;exports.ChannelHubSettings=Nt;exports.DEFAULT_TENANT_SETTINGS=ze;