@channelhub/widget 0.1.9 → 0.1.10

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
@@ -123,8 +123,8 @@
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 Et=G("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 Ne{constructor(n,i){this.apiUrl=n,this.token=i}async request(n,i,o){const h={authorization:`Bearer ${this.token}`,...o?{}:{"content-type":"application/json"},...i==null?void 0:i.headers},k=await fetch(`${this.apiUrl}${n}`,{...i,headers:h}),y=await k.json().catch(()=>null);if(!k.ok)throw new Error((y==null?void 0:y.message)??`Request failed (${k.status})`);return y}getSessionMe(){return this.request("/v1/auth/session/me")}assignConversation(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/assignee`,{method:"PATCH",body:JSON.stringify({agent:i})})}listConnections(){return this.request("/v1/connections")}listConversations(n){return this.request(`/v1/conversations${n?`?cursor=${encodeURIComponent(n)}`:""}`)}listMessages(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages${i?`?cursor=${encodeURIComponent(i)}`:""}`)}getMessage(n){return this.request(`/v1/messages/${encodeURIComponent(n)}`)}sendMessage(n,i,o){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages`,{method:"POST",headers:{"idempotency-key":crypto.randomUUID()},body:JSON.stringify({text:i,attachments:o})})}async markRead(n){const i=await fetch(`${this.apiUrl}/v1/conversations/${encodeURIComponent(n)}/mark-read`,{method:"POST",headers:{authorization:`Bearer ${this.token}`}});if(!i.ok&&i.status!==204)throw new Error(`markRead failed (${i.status})`)}listCannedResponses(n){const i=n!=null&&n.trim()?`?search=${encodeURIComponent(n)}`:"";return this.request(`/v1/canned-responses${i}`)}getNote(n){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`)}patchContact(n,i){return this.request(`/v1/contacts/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify({externalId:i})})}upsertNote(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`,{method:"PUT",body:JSON.stringify({content:i})})}async uploadAttachment(n){const i=new FormData;return i.append("file",n),this.request("/v1/attachments",{method:"POST",body:i},!0)}connectSSE(n){const i=`${this.apiUrl}/v1/events?token=${encodeURIComponent(this.token)}`;let o,h,k=!1;const y=()=>{o=new EventSource(i),o.addEventListener("message.new",B=>{n("message.new",JSON.parse(B.data))}),o.addEventListener("conversation.updated",B=>{n("conversation.updated",JSON.parse(B.data))}),o.onerror=()=>{o.close(),k||(h=setTimeout(y,5e3))}};return y(),()=>{k=!0,clearTimeout(h),o==null||o.close()}}}function Qe({src:t,alt:n="",fallback:i,style:o}){return t?e.jsx("img",{src:t,alt:n,style:{width:38,height:38,borderRadius:"50%",objectFit:"cover",...o}}):e.jsx("span",{style:{display:"grid",placeItems:"center",width:38,height:38,borderRadius:"50%",...o},children:i})}function Ht({variant:t="ghost",style:n,...i}){return e.jsx("button",{...i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",border:t==="outline"?"1px solid #e7ebf2":0,borderRadius:8,cursor:"pointer",font:"inherit",background:t==="default"?"#2563eb":"transparent",...n}})}function At({style:t,...n}){return e.jsx("input",{...n,style:{width:"100%",minWidth:0,border:0,outline:0,background:"transparent",font:"inherit",...t}})}const yt=r.forwardRef(({children:t,style:n},i)=>e.jsx("div",{ref:i,style:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain",...n},children:t})),Ot=r.forwardRef(function({style:n,...i},o){return e.jsx("textarea",{ref:o,...i,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",border:0,outline:0,background:"transparent",font:"inherit",...n}})});function Ut(t){return{id:t.contactId??t.providerConversationKey,name:t.contactName,pictureUrl:t.contactPictureUrl,providerUserId:t.contactProviderUserId??t.providerConversationKey,...t.contactExternalId?{externalId:t.contactExternalId}:{}}}function Ke(t,n){return{conversation:t,contact:Ut(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 Dt extends r.Component{constructor(){super(...arguments),this.state={caught:!1}}static getDerivedStateFromError(){return{caught:!0}}render(){return this.state.caught?null:this.props.children}}const l={ink:"#172033",muted:"#718096",line:"#e7ebf2",surface:"#f7f9fc",white:"#fff"},st=[{icon:"😊",emojis:["😀","😁","😂","🤣","😊","😇","🙂","😉","😍","🥰","😘","😋","😎","🤩","😏","😒","😔","😢","😭","😤","😠","🤯","😱","🥳","😴","🤔","🤗","🫡","😮","🤧","🥺","😶","🫠","🤭","🤫"]},{icon:"👋",emojis:["👍","👎","👏","🙏","🤝","✌️","🤞","🫡","💪","🤜","👊","✊","🖐","👌","🤌","🤏","☝️","👆","👇","👉","👈","🤙","💅","🫶","❤️","🧡","💛","💚","💙","💜","🖤","💔","❣️","💕","💯"]},{icon:"🐱",emojis:["🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🙈","🐔","🐧","🐦","🦆","🦅","🦉","🦋","🐝","🐛","🐢","🦎","🐬","🦈","🐳","🐙","🦑"]},{icon:"🍕",emojis:["🍎","🍊","🍋","🍇","🍓","🍒","🥝","🥑","🍔","🍕","🌮","🍜","🍣","🍦","🎂","🍰","🧁","☕","🧋","🥤","🍺","🥂","🍾","🧃","🧊"]},{icon:"⚽",emojis:["⚽","🏀","🏈","⚾","🎾","🏐","🏓","🎮","🎲","🎯","🎳","🏆","🥇","🎖","🎁","🎉","🎊","🎈","🎭","🎨","🎬","🎵","🎸","🎹","🎺","🪗","🎻"]},{icon:"🌍",emojis:["🌍","🌈","⭐","🌙","☀️","⛅","🌊","🔥","💧","🌿","🌸","🌺","🌻","🍀","🌴","🏔","🏖","🏕","🌃","🏙","🌅","🌄","🌠","🌌","🌋","🏝"]}],et=r.createContext(""),bt=r.createContext("");function Ft(){try{const t=new AudioContext,n=t.createOscillator(),i=t.createGain();n.connect(i),i.connect(t.destination),n.type="sine",n.frequency.setValueAtTime(880,t.currentTime),n.frequency.exponentialRampToValueAtTime(660,t.currentTime+.12),i.gain.setValueAtTime(.25,t.currentTime),i.gain.exponentialRampToValueAtTime(.001,t.currentTime+.35),n.start(t.currentTime),n.stop(t.currentTime+.35)}catch{}}function Pt(t){if(!(t!=null&&t.metadata))return;const n=t.metadata,i=n.pageName??n.displayName??n.username??n.name;return typeof i=="string"&&i?i:void 0}function mt(t){return t==="facebook"?"Facebook Messenger":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo OA":t==="livechat"?"Live Chat":"Channel"}function at(t){return t==="facebook"?"Facebook":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo":t==="livechat"?"Live Chat":String(t??"")}const Nt=t=>{var i;const n={"application/pdf":"PDF","video/mp4":"Video MP4","audio/mpeg":"Audio MP3","audio/ogg":"Audio OGG","application/octet-stream":"Tệp đính kèm"};return t?n[t]??((i=t.split("/")[1])==null?void 0:i.toUpperCase())??"Tệp":"Tệp đính kèm"};function lt({status:t}){return t==="read"?e.jsx(nt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):t==="delivered"?e.jsx(nt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle",opacity:.5}}):t==="sent"?e.jsx(_e,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):null}function Ye(t){const n=t.trim().split(/\s+/).filter(Boolean);return n.length<=2?t.trim():n.slice(-2).join(" ")}const Kt=r.forwardRef(function({apiUrl:n,token:i,theme:o,height:h,defaultConversationId:k,disableAttachments:y,disableNotificationSound:B,hideKeyboardHint:v,locale:m="vi",extensions:R,currentAgent:z,teamAgents:E,onNewMessage:T,onConversationSelect:w},U){var j,L,N,O,ee;const S=r.useRef(new Ne(n,i)),[$,D]=r.useState([]),[K,_]=r.useState([]),[J,W]=r.useState(),[b,x]=r.useState(),H=r.useRef(void 0),[q,Q]=r.useState(""),[re,C]=r.useState("all"),[te,X]=r.useState(null),[A,Z]=r.useState({provider:"all",unreadOnly:!1}),[oe,c]=r.useState(!1),M=r.useRef(null),F=r.useRef(null),[ne,se]=r.useState(null),[ue,P]=r.useState(!0),[ae,be]=r.useState(""),[ze,Re]=r.useState(()=>!!(R!=null&&R.length)),[Te,me]=r.useState(280),[xe,je]=r.useState(!1),[Ee,fe]=r.useState(0),Y=(o==null?void 0:o.primaryColor)??"#2563eb",de=r.useMemo(()=>new Map(K.map(a=>[a.id,a])),[K]),ve=r.useRef(null),[He,We]=r.useState(0),V=z??te??null;r.useEffect(()=>{S.current=new Ne(n,i),z||S.current.getSessionMe().then(a=>{a!=null&&a.agent&&X(a.agent)}).catch(()=>{})},[n,i,z]);const Ae=r.useMemo(()=>{var u;const a=new Map;V!=null&&V.id&&a.set(V.id,V);for(const p of E??[])p!=null&&p.id&&!a.has(p.id)&&a.set(p.id,p);for(const p of $)(u=p.assignedAgent)!=null&&u.id&&!a.has(p.assignedAgent.id)&&a.set(p.assignedAgent.id,p.assignedAgent);return[...a.values()]},[V,E,$]),Oe=r.useCallback(async(a,u)=>{D(p=>p.map(I=>I.id===a.id?{...I,assignedAgent:u}:I)),x(p=>p&&p.id===a.id?{...p,assignedAgent:u}:p),fe(p=>p+1);try{const p=await S.current.assignConversation(a.id,u);D(I=>I.map(ie=>ie.id===a.id?{...ie,...p,assignedAgent:p.assignedAgent??u}:ie)),x(I=>I&&I.id===a.id?{...I,...p,assignedAgent:p.assignedAgent??u}:I),fe(I=>I+1)}catch{}},[]),ye=r.useCallback(async(a,u)=>{a.contactId&&await S.current.patchContact(a.contactId,u),D(p=>p.map(I=>I.id===a.id?{...I,contactExternalId:u??void 0}:I)),x(p=>p&&p.id===a.id?{...p,contactExternalId:u??void 0}:p),fe(p=>p+1)},[]),ce=r.useCallback(()=>{fe(a=>a+1)},[]),Ue=r.useMemo(()=>{const a=new Set(K.map(u=>u.provider));return["facebook","instagram","telegram","zalo","livechat"].filter(u=>a.has(u))},[K]),De=r.useMemo(()=>{var u;const a={};for(const p of $){const I=((u=de.get(p.connectionId))==null?void 0:u.provider)??"unknown";a[I]=(a[I]??0)+1}return a},[$,de]);function qe(a){const u=a.clientX,p=Te;je(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none";function I(Se){const $e=Math.max(200,Math.min(480,p+(u-Se.clientX)));me($e)}function ie(){je(!1),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",ie)}document.addEventListener("mousemove",I),document.addEventListener("mouseup",ie)}const le=r.useCallback(async a=>{try{const u=await S.current.listConversations(a);D(p=>a?[...p,...u.items]:u.items),W(u.nextCursor),!a&&u.items.length&&x(p=>p??(k?u.items.find(I=>I.id===k)??u.items[0]:u.items[0])),be("")}catch(u){be(u instanceof Error?u.message:"Không tải được hội thoại")}finally{P(!1)}},[k]);r.useEffect(()=>(S.current.listConnections().then(_).catch(()=>{}),le(),S.current.connectSSE((u,p)=>{if(u==="message.new"||u==="conversation.updated"){if(le(),u==="message.new"){const I=typeof p=="object"&&p?p:{},ie=I.conversationId?String(I.conversationId):"",Se=I.messageId?String(I.messageId):"";if((I.direction?String(I.direction):"")==="inbound"&&!B&&Ft(),ie&&ie===H.current&&Se&&ve.current){const Fe=ve.current;S.current.getMessage(Se).then(Pe=>{Fe(Pe)}).catch(()=>{})}T==null||T(ie||H.current||"")}}else u==="message.status_updated"&&We(I=>I+1)})),[le,T]),r.useEffect(()=>{H.current=b==null?void 0:b.id},[b]),r.useEffect(()=>{b!=null&&b.unreadCount&&S.current.markRead(b.id).then(()=>le()).catch(()=>{})},[b==null?void 0:b.id]),r.useEffect(()=>{if(!oe)return;function a(u){var p,I;(p=M.current)!=null&&p.contains(u.target)||(I=F.current)!=null&&I.contains(u.target)||c(!1)}return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[oe]);const pe=r.useMemo(()=>{const a=V?$.filter(p=>{var I;return((I=p.assignedAgent)==null?void 0:I.id)===V.id}).length:0,u=$.filter(p=>!p.assignedAgent).length;return{all:$.length,mine:a,unassigned:u}},[$,V]),ke=r.useMemo(()=>{const a=q.toLowerCase().trim();return $.filter(u=>{var $e,Fe,Pe;if(re==="mine"){if(!V||(($e=u.assignedAgent)==null?void 0:$e.id)!==V.id)return!1}else if(re==="unassigned"&&u.assignedAgent)return!1;const p=`${u.contactName??""} ${u.subject??""} ${u.providerConversationKey} ${((Fe=u.assignedAgent)==null?void 0:Fe.name)??""}`.toLowerCase(),I=((Pe=de.get(u.connectionId))==null?void 0:Pe.provider)??"unknown",ie=A.provider==="all"||I===A.provider,Se=!A.unreadOnly||(u.unreadCount??0)>0;return ie&&Se&&(!a||p.includes(a))})},[$,de,A,q,re,V]),we=A.provider!=="all"||A.unreadOnly,s=m==="en"?{today:"TODAY",loadOlder:"↑ Load older messages",loading:"Loading messages…",noMessages:"No messages in this conversation.",searchPlaceholder:"Search conversations…",unreadOnly:"Unread only",sendPlaceholder:"Write a message…",send:"Send",all:"All"}:{today:"HÔM NAY",loadOlder:"↑ Tải tin cũ hơn",loading:"Đang tải tin nhắn…",noMessages:"Chưa có tin nhắn trong hội thoại này.",searchPlaceholder:"Tìm kiếm hội thoại…",unreadOnly:"Chưa đọc",sendPlaceholder:"Viết tin nhắn…",send:"Gửi",all:"Tất cả"};r.useImperativeHandle(U,()=>({openConversation:a=>{const u=$.find(p=>p.id===a);u&&x(u)},refresh:()=>void le()}),[$,le]);const g={...f.frame,height:h??620,...h?{maxHeight:"none"}:{},fontFamily:(o==null?void 0:o.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",borderRadius:(o==null?void 0:o.borderRadius)??"16px",gridTemplateColumns:ze?`minmax(260px, 300px) minmax(0, 1fr) ${Te}px`:"minmax(260px, 300px) minmax(0, 1fr)",transition:xe?"none":"grid-template-columns 220ms ease"};return ue?e.jsxs("div",{style:{...f.state,borderRadius:(o==null?void 0:o.borderRadius)??"16px"},children:[e.jsx(Je,{})," Đang tải hộp thư…"]}):ae&&!$.length?e.jsxs("div",{style:{...f.state,color:"#b42318",borderRadius:(o==null?void 0:o.borderRadius)??"16px"},children:[e.jsx(Ct,{size:16,strokeWidth:2})," ",ae,e.jsx("button",{style:f.retry,onClick:()=>{P(!0),le()},children:"Thử lại"})]}):e.jsx(et.Provider,{value:n,children:e.jsx(bt.Provider,{value:i,children:e.jsxs("div",{style:g,onFocusCapture:()=>{const a=window.scrollY;requestAnimationFrame(()=>{window.scrollY!==a&&window.scrollTo({top:a,behavior:"instant"})})},children:[e.jsxs("aside",{style:f.sidebar,children:[e.jsxs("div",{style:f.brand,children:[e.jsx("div",{style:{...f.brandMark,background:Y,overflow:"hidden",padding:0},children:(j=o==null?void 0:o.branding)!=null&&j.logoUrl?e.jsx("img",{src:o.branding.logoUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):((L=o==null?void 0:o.branding)==null?void 0:L.mark)??"C"}),e.jsxs("div",{children:[e.jsx("strong",{children:((N=o==null?void 0:o.branding)==null?void 0:N.name)??"Hộp thư"}),!((O=o==null?void 0:o.branding)!=null&&O.name)&&e.jsx("span",{style:f.eyebrow,children:"CHANNELHUB"})]}),e.jsx(Ht,{"aria-label":"Tùy chọn",style:f.iconButton,children:e.jsx(gt,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:f.search,children:[e.jsx(rt,{size:16,strokeWidth:2}),e.jsx(At,{"aria-label":s.searchPlaceholder,value:q,onChange:a=>Q(a.target.value),placeholder:s.searchPlaceholder}),q&&e.jsx("button",{style:f.clear,onClick:()=>Q(""),"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 ${l.line}`,background:l.surface},children:[{key:"all",label:m==="en"?"All":"Tất cả",count:pe.all},{key:"mine",label:m==="en"?"Mine":"Của tôi",count:pe.mine},{key:"unassigned",label:m==="en"?"Unassigned":"Chưa nhận",count:pe.unassigned}].map(a=>{const u=re===a.key;return e.jsxs("button",{type:"button",role:"tab","aria-selected":u,onClick:()=>C(a.key),style:{border:0,borderRadius:6,padding:"5px 4px",fontSize:11,fontWeight:u?700:500,background:u?l.white:"transparent",color:u?Y:l.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:[a.label," ",e.jsxs("span",{style:{opacity:.75},children:["(",a.count,")"]})]},a.key)})}),we&&e.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",padding:"0 14px 8px"},children:[A.provider!=="all"&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:Y,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[e.jsx(Le,{provider:A.provider}),at(A.provider),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:Y,padding:0,lineHeight:1,display:"flex"},onClick:()=>Z(a=>({...a,provider:"all"})),"aria-label":"Xóa filter kênh",children:e.jsx(Me,{size:10})})]}),A.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:[s.unreadOnly,e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:Y,padding:0,lineHeight:1,display:"flex"},onClick:()=>Z(a=>({...a,unreadOnly:!1})),"aria-label":"Xóa filter chưa đọc",children:e.jsx(Me,{size:10})})]}),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:l.muted,fontSize:11,padding:"2px 4px"},onClick:()=>Z({provider:"all",unreadOnly:!1}),children:"Xóa tất cả"})]}),e.jsxs("div",{style:f.listHeader,children:[e.jsxs("span",{children:[ke.length," hội thoại"]}),e.jsx("button",{ref:M,style:{...f.iconButton,background:we?`${Y}14`:"transparent",color:we?Y:l.muted},"aria-label":"Bộ lọc",onClick:()=>{var a;if(!oe){const u=(a=M.current)==null?void 0:a.getBoundingClientRect();u&&se({top:u.bottom+6,left:u.left})}c(u=>!u)},children:e.jsx(Bt,{size:15,strokeWidth:2})})]}),oe&&ne&&pt.createPortal(e.jsxs("div",{ref:F,style:{position:"fixed",top:ne.top,left:ne.left,zIndex:9999,background:l.white,border:`1px solid ${l.line}`,borderRadius:10,padding:"12px 14px",boxShadow:"0 8px 24px rgba(23,32,51,.14)",minWidth:210,fontFamily:(o==null?void 0:o.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",fontSize:13},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:l.muted,letterSpacing:1,textTransform:"uppercase",marginBottom:8},children:"Kênh"}),["all",...Ue].map(a=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:A.provider===a?`${Y}0f`:"transparent"},children:[e.jsx("input",{type:"radio",name:"provider-filter",checked:A.provider===a,onChange:()=>Z(u=>({...u,provider:a})),style:{accentColor:Y}}),a==="all"?e.jsxs("span",{style:{color:l.ink},children:[s.all," (",$.length,")"]}):e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,color:l.ink},children:[e.jsx(Le,{provider:a}),at(a)," ",e.jsxs("span",{style:{color:l.muted},children:["(",De[a]??0,")"]})]})]},a)),e.jsx("div",{style:{borderTop:`1px solid ${l.line}`,margin:"8px 0 6px"}}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:A.unreadOnly?`${Y}0f`:"transparent"},children:[e.jsx("input",{type:"checkbox",checked:A.unreadOnly,onChange:a=>Z(u=>({...u,unreadOnly:a.target.checked})),style:{accentColor:Y}}),e.jsx("span",{style:{color:l.ink},children:s.unreadOnly})]})]}),document.body),e.jsxs(yt,{style:f.conversationList,children:[ke.map(a=>{var u;return e.jsx(qt,{conversation:a,provider:(u=de.get(a.connectionId))==null?void 0:u.provider,selected:(b==null?void 0:b.id)===a.id,primary:Y,currentAgent:V,onSelect:()=>{x(a),w==null||w(a.id),S.current.markRead(a.id).then(()=>le()).catch(()=>{})}},a.id)}),!ke.length&&e.jsxs("div",{style:f.emptySmall,children:[e.jsx("div",{style:f.emptyIcon,children:e.jsx(rt,{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."})]}),J&&e.jsx("button",{style:f.loadMore,onClick:()=>void le(J),children:"Xem thêm hội thoại"})]})]}),e.jsx("main",{style:f.main,children:b?e.jsx(Vt,{conversation:b,provider:(ee=de.get(b.connectionId))==null?void 0:ee.provider,connection:de.get(b.connectionId),client:S.current,primary:Y,error:ae,onRegisterAppend:a=>{ve.current=a},refreshKey:He,infoOpen:ze,onToggleInfo:()=>Re(a=>!a),t:s,disableAttachments:y,hideKeyboardHint:v,extensions:R,currentAgent:V,teamAgents:Ae,onAssignAgent:a=>Oe(b,a),onLinkContact:a=>ye(b,a),onRefreshContactInfo:ce},b.id):e.jsx(Jt,{})}),ze&&b&&e.jsx(Xt,{conversation:b,connection:de.get(b.connectionId),primary:Y,onClose:()=>Re(!1),client:S.current,onStartResize:qe,extensions:R,extRefreshKey:Ee,onLinkContact:a=>ye(b,a),onRefreshContactInfo:ce})]})})})});function qt({conversation:t,provider:n,selected:i,primary:o,currentAgent:h,onSelect:k}){const[y,B]=r.useState(!1),v=t.contactName??t.subject??t.providerConversationKey,m=t.unreadCount??0,R=t.lastMessageText??"",z=t.lastMessageDirection==="outbound"?"Bạn: ":"",E=R.length>60?R.slice(0,60)+"…":R,T=R?z+E:"",w=t.assignedAgent??null,U=!!(w&&h&&w.id===h.id);let S="transparent";i?S="#eef2ff":y?S="#f7f9fc":m>0&&(S="#f0f4ff");const $={...f.row,background:S,...i?{boxShadow:`inset 3px 0 0 ${o}`}:m>0&&!y?{boxShadow:`inset 3px 0 0 ${o}`}:{}};return e.jsxs("button",{onClick:k,style:$,onMouseEnter:()=>B(!0),onMouseLeave:()=>B(!1),children:[e.jsx(jt,{name:v,color:o,image:t.contactPictureUrl,provider:n}),e.jsxs("span",{style:f.rowBody,children:[e.jsxs("span",{style:f.rowTop,children:[e.jsx("strong",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:m>0?700:500},children:v}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:[e.jsx("time",{style:{color:l.muted,fontSize:11,whiteSpace:"nowrap"},children:Ze(t.lastMessageAt)}),m>0&&e.jsx("span",{"aria-label":`${m} tin nhắn chưa đọc`,style:f.unreadBadge,children:m>99?"99+":m})]})]}),e.jsxs("span",{style:{...f.rowBottom,justifyContent:"space-between",alignItems:"center",gap:6,color:m>0&&!i?"#4a5568":l.muted},children:[e.jsx("span",{style:{flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:T||e.jsx("span",{style:{opacity:.5},children:"Chưa có tin nhắn"})}),w?e.jsxs("span",{title:`Phụ trách: ${w.name}${w.title?` (${w.title})`:""}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 6px 1px 2px",borderRadius:999,fontSize:10,fontWeight:600,flexShrink:0,background:U?`${o}18`:"#f1f5f9",color:U?o:"#475569",border:U?`1px solid ${o}33`:"1px solid #e2e8f0"},children:[e.jsx("span",{style:{width:14,height:14,borderRadius:"50%",background:U?o:"#64748b",color:"#fff",fontSize:8,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:w.avatarUrl?e.jsx("img",{src:w.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Ie(w.name)}),e.jsx("span",{style:{maxWidth:68,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ye(w.name)})]}):m>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 Vt({conversation:t,provider:n,connection:i,client:o,primary:h,error:k,onRegisterAppend:y,refreshKey:B,infoOpen:v,onToggleInfo:m,t:R,disableAttachments:z,hideKeyboardHint:E,extensions:T,currentAgent:w,teamAgents:U,onAssignAgent:S,onLinkContact:$,onRefreshContactInfo:D}){var ke,we;const[K,_]=r.useState([]),[J,W]=r.useState(),[b,x]=r.useState(""),[H,q]=r.useState(!0),[Q,re]=r.useState(!1),[C,te]=r.useState(""),X=r.useRef(null),A=t.contactName??t.subject??t.providerConversationKey,Z=r.useRef(null),oe=r.useRef(null),[c,M]=r.useState(null),[F,ne]=r.useState(!1),[se,ue]=r.useState(!1),[P,ae]=r.useState(!1),[be,ze]=r.useState(0),Re=r.useRef(null),Te=r.useRef(null),me=r.useRef(null),[xe,je]=r.useState(!1),[Ee,fe]=r.useState(""),[Y,de]=r.useState([]),ve=r.useRef(null),He=r.useRef(null),[We,V]=r.useState(!1),Ae=r.useRef(null),Oe=r.useRef(null);r.useEffect(()=>{if(!We)return;function s(g){var j,L;(j=Ae.current)!=null&&j.contains(g.target)||(L=Oe.current)!=null&&L.contains(g.target)||V(!1)}return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[We]),r.useEffect(()=>()=>{c!=null&&c.objectUrl&&URL.revokeObjectURL(c.objectUrl)},[c==null?void 0:c.objectUrl]),r.useEffect(()=>{if(!P)return;function s(g){var j,L;(j=Te.current)!=null&&j.contains(g.target)||(L=Re.current)!=null&&L.contains(g.target)||ae(!1)}return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[P]),r.useEffect(()=>{o.listCannedResponses().then(de).catch(()=>{})},[o]),r.useEffect(()=>{if(!xe)return;function s(g){var j,L;(j=He.current)!=null&&j.contains(g.target)||(L=ve.current)!=null&&L.contains(g.target)||je(!1)}return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[xe]);const ye=r.useRef(!0),ce=r.useCallback(async(s,g)=>{g||(ye.current=!s);try{const j=await o.listMessages(t.id,s);_(L=>s?[...j.items,...L]:j.items),W(j.nextCursor)}catch(j){te(j instanceof Error?j.message:"Không tải được tin nhắn")}finally{g||q(!1)}},[o,t.id]);r.useEffect(()=>{q(!0),ce()},[ce]),r.useEffect(()=>{B&&ce(void 0,!0)},[B]),r.useEffect(()=>{ye.current&&requestAnimationFrame(()=>{const s=X.current;s&&(s.scrollTop=s.scrollHeight)})},[K]),r.useEffect(()=>(y==null||y(s=>{ye.current=!0,_(g=>g.some(j=>j.id===s.id)?g:[...g,s])}),()=>{y==null||y(null)}),[y]);async function Ue(s){var L;const g=(L=s.target.files)==null?void 0:L[0];if(!g)return;s.target.value="";const j=URL.createObjectURL(g);M({file:g,uploading:!0,objectUrl:j});try{const N=await o.uploadAttachment(g);M({file:g,uploading:!1,url:N.url,mimeType:N.mimeType,attachmentType:N.attachmentType,objectUrl:j})}catch{URL.revokeObjectURL(j),M(null),te("Không tải lên được tệp đính kèm")}}async function De(s){s.preventDefault();const g=b.trim(),j=c!=null&&c.url?[{url:c.url,mimeType:c.mimeType??"application/octet-stream",type:c.attachmentType}]:[];if(!g&&!j.length||Q)return;re(!0),te(""),!t.assignedAgent&&w&&S(w);const L=`optimistic-${Date.now()}`;w&&(ye.current=!0,_(N=>[...N,{id:L,direction:"outbound",status:"sending",text:g||void 0,attachments:j.length?j:void 0,occurredAt:new Date().toISOString(),senderAgent:w}]));try{await o.sendMessage(t.id,g||void 0,j.length?j:void 0),c!=null&&c.objectUrl&&URL.revokeObjectURL(c.objectUrl),x(""),M(null),await ce(),w&&_(N=>{var a,u;const O=N.filter(p=>p.id!==L),ee=O.length-1;return ee>=0&&((a=O[ee])==null?void 0:a.direction)==="outbound"&&!((u=O[ee])!=null&&u.senderAgent)?O.map((p,I)=>I===ee?{...p,senderAgent:w}:p):O})}catch(N){_(O=>O.filter(ee=>ee.id!==L)),te(N instanceof Error?N.message:"Không gửi được tin nhắn")}finally{re(!1)}}function qe(s){const g=me.current;if(!g){x(O=>O+s),ae(!1);return}const j=g.selectionStart??b.length,L=g.selectionEnd??b.length,N=b.slice(0,j)+s+b.slice(L);x(N),ae(!1),requestAnimationFrame(()=>{g.focus(),g.selectionStart=g.selectionEnd=j+s.length})}function le(s){x(s),je(!1),fe(""),requestAnimationFrame(()=>{const g=me.current;g&&(g.focus(),g.selectionStart=g.selectionEnd=s.length)})}const pe=!Q&&(b.trim().length>0||(c==null?void 0:c.url)!=null&&!c.uploading);return e.jsxs("section",{style:f.chat,children:[e.jsxs("header",{style:f.chatHeader,children:[e.jsx(jt,{name:A,color:h,image:t.contactPictureUrl,provider:n}),e.jsxs("div",{style:f.contact,children:[e.jsx("strong",{style:f.contactName,children:A}),e.jsx("span",{style:f.contactMeta,children:Pt(i)??mt(n)})]}),e.jsxs("div",{style:{...f.headerActions,alignItems:"center",gap:6},children:[e.jsxs("div",{ref:Ae,style:{position:"relative",display:"inline-flex",alignItems:"center",gap:4},children:[!t.assignedAgent&&w?e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",borderRadius:999,border:`1px solid ${h}40`,background:`${h}0d`,overflow:"hidden"},children:[e.jsxs("button",{type:"button",onClick:()=>void S(w),style:{border:0,background:"transparent",color:h,padding:"4px 9px",fontSize:11.5,fontWeight:600,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:[e.jsx(ot,{size:12,strokeWidth:2.2}),e.jsx("span",{children:"+ Nhận phụ trách"})]}),((U==null?void 0:U.length)??0)>1&&e.jsx("button",{type:"button","aria-label":"Chọn nhân viên phụ trách",onClick:()=>V(s=>!s),style:{border:0,borderLeft:`1px solid ${h}30`,background:"transparent",color:h,padding:"4px 6px",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:e.jsx(Xe,{size:12,strokeWidth:2.2})})]}):e.jsxs("button",{type:"button",onClick:()=>V(s=>!s),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 9px 3px 4px",borderRadius:999,border:`1px solid ${l.line}`,background:l.surface,color:l.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:h,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"}}):Ie(t.assignedAgent.name)}),e.jsx("span",{style:{color:l.muted,fontWeight:500},children:"Phụ trách:"}),e.jsx("span",{style:{maxWidth:110,overflow:"hidden",textOverflow:"ellipsis"},children:Ye(t.assignedAgent.name)})]}):e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:13,color:l.muted}),e.jsx("span",{style:{color:l.muted},children:"Chưa phân công"})]}),e.jsx(Xe,{size:12,color:l.muted})]}),We&&e.jsxs("div",{ref:Oe,style:{position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:200,minWidth:230,background:l.white,border:`1px solid ${l.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:l.muted,letterSpacing:.8,textTransform:"uppercase"},children:"Người phụ trách hội thoại"}),w&&((ke=t.assignedAgent)==null?void 0:ke.id)!==w.id&&e.jsxs("button",{type:"button",onClick:()=>{V(!1),S(w)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",border:0,borderRadius:7,background:`${h}10`,color:h,padding:"6px 8px",marginBottom:4,fontWeight:600,fontSize:12,cursor:"pointer",textAlign:"left"},children:[e.jsx(ot,{size:13}),e.jsxs("span",{children:["Nhận phụ trách cho tôi (",Ye(w.name),")"]})]}),e.jsx("div",{style:{maxHeight:200,overflowY:"auto"},children:(U??[]).map(s=>{var j;const g=((j=t.assignedAgent)==null?void 0:j.id)===s.id;return e.jsxs("button",{type:"button",onClick:()=>{V(!1),S(s)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,width:"100%",border:0,borderRadius:7,background:g?"#f1f5f9":"transparent",color:l.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:`${h}18`,color:h,fontSize:10,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"}}):Ie(s.name)}),e.jsxs("span",{style:{minWidth:0},children:[e.jsx("span",{style:{display:"block",fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:s.name}),s.title&&e.jsx("span",{style:{display:"block",fontSize:10.5,color:l.muted},children:s.title})]})]}),g&&e.jsx(_e,{size:13,color:h,strokeWidth:2.5})]},s.id)})}),t.assignedAgent&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{borderTop:`1px solid ${l.line}`,margin:"5px 0"}}),e.jsxs("button",{type:"button",onClick:()=>{V(!1),S(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(Me,{size:13}),e.jsx("span",{children:"Bỏ phân công (Chưa có người nhận)"})]})]})]})]}),e.jsx("button",{style:f.iconButton,"aria-label":"Thêm tùy chọn",children:e.jsx(gt,{size:16,strokeWidth:2})}),e.jsx("button",{style:{...f.iconButton,background:v?`${h}14`:"transparent",color:v?h:l.muted},"aria-label":"Thông tin liên hệ",onClick:m,children:e.jsx(Rt,{size:16,strokeWidth:2})})]})]}),e.jsxs(yt,{ref:X,style:f.messageArea,children:[e.jsx("div",{style:f.day,children:R.today}),J&&e.jsx("button",{onClick:()=>void ce(J),style:f.historyButton,children:R.loadOlder}),H&&e.jsxs("div",{style:f.messageHint,children:[e.jsx(Je,{})," ",R.loading]}),!H&&!K.length&&e.jsx("div",{style:f.messageHint,children:R.noMessages}),K.map((s,g)=>{const j=(T==null?void 0:T.flatMap(ee=>ee.messageEnrichments??[]))??[],L=s.direction==="inbound"&&j.length>0&&g>=K.length-15,N=L?Ke(t,{provider:n,recentMessages:K.slice(-10),linkContact:$,refreshContactInfo:D,sendMessage:async(ee,a)=>{await o.sendMessage(t.id,ee,a),await ce(void 0,!0)}}):null,O=L&&N?j.map((ee,a)=>{var p;const u=(p=s.text)==null?void 0:p.match(ee.pattern);return u?e.jsx(Dt,{children:ee.render(u,N,s)},`${s.id}-${a}`):null}).filter(Boolean):[];return e.jsxs("div",{children:[e.jsx(Gt,{message:s,primary:h}),O.length>0&&e.jsx("div",{style:{maxWidth:"min(70%, 480px)",marginTop:-4,marginBottom:10,display:"flex",flexDirection:"column",gap:6},children:O})]},s.id)})]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",padding:"6px 14px 2px",borderTop:`1px solid ${l.line}`},children:["Cảm ơn bạn đã liên hệ 🙏","Mình sẽ kiểm tra ngay","Vui lòng chờ 1-2 phút"].map(s=>e.jsx("button",{type:"button",onClick:()=>x(s),style:{fontSize:11,padding:"3px 10px",borderRadius:999,background:`${h}0f`,color:h,border:`1px solid ${h}33`,cursor:"pointer",whiteSpace:"nowrap"},children:s},s))}),e.jsxs("form",{onSubmit:De,style:{flex:"0 0 auto",padding:"8px 14px 12px",borderTop:`1px solid ${l.line}`,background:l.white,position:"relative"},children:[P&&e.jsxs("div",{ref:Re,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:l.white,border:`1px solid ${l.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:280,overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${l.line}`,background:"#f9fafb"},children:st.map((s,g)=>e.jsx("button",{type:"button",onClick:()=>ze(g),style:{flex:1,border:0,background:"transparent",padding:"7px 2px",fontSize:16,cursor:"pointer",lineHeight:1,borderBottom:be===g?`2px solid ${h}`:"2px solid transparent",opacity:be===g?1:.5,transition:"opacity 100ms ease"},children:s.icon},g))}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:2,padding:8,maxHeight:180,overflowY:"auto"},children:(we=st[be])==null?void 0:we.emojis.map((s,g)=>e.jsx("button",{type:"button",onClick:()=>qe(s),style:{border:0,background:"transparent",padding:"5px 2px",fontSize:18,cursor:"pointer",borderRadius:6,lineHeight:1,transition:"background 80ms ease"},onMouseEnter:j=>{j.target.style.background="#f3f4f6"},onMouseLeave:j=>{j.target.style.background="transparent"},children:s},g))})]}),xe&&e.jsxs("div",{ref:ve,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:l.white,border:`1px solid ${l.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:300,overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{padding:"8px 10px",borderBottom:`1px solid ${l.line}`},children:e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Tìm template…",value:Ee,onChange:s=>fe(s.target.value),style:{width:"100%",boxSizing:"border-box",border:`1px solid ${l.line}`,borderRadius:7,padding:"5px 8px",fontSize:12,outline:"none",fontFamily:"inherit",color:l.ink}})}),e.jsx("div",{style:{maxHeight:220,overflowY:"auto"},children:(()=>{const s=Ee.trim().toLowerCase(),g=s?Y.filter(j=>j.title.toLowerCase().includes(s)||j.content.toLowerCase().includes(s)||(j.shortcut??"").toLowerCase().includes(s)):Y;return g.length?g.map(j=>e.jsxs("button",{type:"button",onClick:()=>le(j.content),style:{display:"block",width:"100%",textAlign:"left",border:0,borderBottom:`1px solid ${l.line}`,background:"transparent",padding:"9px 12px",cursor:"pointer",fontFamily:"inherit"},onMouseEnter:L=>{L.currentTarget.style.background="#f7f9fc"},onMouseLeave:L=>{L.currentTarget.style.background="transparent"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:2},children:[e.jsx("span",{style:{fontSize:12,fontWeight:600,color:l.ink},children:j.title}),j.shortcut&&e.jsx("span",{style:{fontSize:10,color:h,background:`${h}18`,borderRadius:4,padding:"1px 5px"},children:j.shortcut})]}),e.jsx("div",{style:{fontSize:11,color:l.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.content})]},j.id)):e.jsx("div",{style:{padding:"24px 16px",textAlign:"center",color:l.muted,fontSize:12},children:Y.length===0?"Chưa có template nào":"Không tìm thấy"})})()})]}),e.jsxs("div",{style:{border:`1.5px solid ${l.line}`,borderRadius:12,background:l.white,overflow:"hidden"},children:[c&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:`1px solid ${l.line}`,fontSize:12},children:[c.uploading?e.jsxs(e.Fragment,{children:[e.jsx(Je,{}),e.jsx("span",{style:{color:l.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:l.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),M(null)},style:{marginLeft:"auto",border:0,background:"none",color:l.muted,cursor:"pointer",fontSize:16},"aria-label":"Xóa tệp đính kèm",children:"✕"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 8px",borderBottom:"1px solid #f3f4f6"},children:[e.jsx("button",{ref:Te,type:"button",title:"Chèn emoji",onClick:()=>ae(s=>!s),style:{...f.toolbarBtn,background:P?`${h}18`:"transparent",color:P?h:"#9ca3af"},children:e.jsx(Mt,{size:13,strokeWidth:2})}),!z&&e.jsx("button",{type:"button",title:"Gửi ảnh / video","aria-label":"Gửi ảnh hoặc video",style:f.toolbarBtn,onClick:()=>{var s;return(s=Z.current)==null?void 0:s.click()},children:e.jsx(It,{size:13,strokeWidth:2})}),!z&&e.jsx("button",{type:"button",title:"Gửi tệp đính kèm","aria-label":"Gửi tệp đính kèm",style:f.toolbarBtn,onClick:()=>{var s;return(s=oe.current)==null?void 0:s.click()},children:e.jsx(Tt,{size:13,strokeWidth:2})}),!z&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Z,type:"file",style:{display:"none"},onChange:Ue,accept:"image/*,video/mp4"}),e.jsx("input",{ref:oe,type:"file",style:{display:"none"},onChange:Ue,accept:".pdf,audio/mpeg,audio/ogg,application/octet-stream,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"})]}),e.jsx("button",{ref:He,type:"button",title:"Template nhanh",onClick:()=>{je(s=>!s),fe("")},style:{...f.toolbarBtn,background:xe?`${h}18`:"transparent",color:xe?h:"#9ca3af"},children:e.jsx(Et,{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:()=>ne(s=>!s),style:{...f.toolbarBtn,fontWeight:700,fontSize:12,background:F?`${h}18`:"transparent",color:F?h:"#9ca3af",border:F?`1px solid ${h}33`:"1px solid transparent"},children:"B"}),e.jsx("button",{type:"button",title:"Nghiêng",onClick:()=>ue(s=>!s),style:{...f.toolbarBtn,fontStyle:"italic",fontSize:12,background:se?`${h}18`:"transparent",color:se?h:"#9ca3af",border:se?`1px solid ${h}33`:"1px solid transparent"},children:"I"}),!!(T!=null&&T.some(s=>{var g;return(((g=s.toolbarActions)==null?void 0:g.length)??0)>0}))&&e.jsx("span",{style:{width:1,height:14,background:"#e5e7eb",margin:"0 4px"}}),T==null?void 0:T.flatMap(s=>s.toolbarActions??[]).map((s,g)=>e.jsxs("button",{type:"button",title:s.tooltip,style:s.label?{display:"inline-flex",alignItems:"center",gap:5,padding:"3px 9px",borderRadius:999,border:`1px solid ${h}33`,background:`${h}0f`,color:h,fontSize:11.5,fontWeight:600,cursor:"pointer",lineHeight:1.2,whiteSpace:"nowrap"}:f.toolbarBtn,onClick:()=>{const j=N=>{x(O=>O&&!O.endsWith(" ")&&!O.endsWith(`
126
+ */const Et=G("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 Ne{constructor(n,i){this.apiUrl=n,this.token=i}async request(n,i,o){const h={authorization:`Bearer ${this.token}`,...o?{}:{"content-type":"application/json"},...i==null?void 0:i.headers},k=await fetch(`${this.apiUrl}${n}`,{...i,headers:h}),y=await k.json().catch(()=>null);if(!k.ok)throw new Error((y==null?void 0:y.message)??`Request failed (${k.status})`);return y}getSessionMe(){return this.request("/v1/auth/session/me")}assignConversation(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/assignee`,{method:"PUT",body:JSON.stringify({agent:i})})}listConnections(){return this.request("/v1/connections")}listConversations(n){return this.request(`/v1/conversations${n?`?cursor=${encodeURIComponent(n)}`:""}`)}listMessages(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages${i?`?cursor=${encodeURIComponent(i)}`:""}`)}getMessage(n){return this.request(`/v1/messages/${encodeURIComponent(n)}`)}sendMessage(n,i,o){return this.request(`/v1/conversations/${encodeURIComponent(n)}/messages`,{method:"POST",headers:{"idempotency-key":crypto.randomUUID()},body:JSON.stringify({text:i,attachments:o})})}async markRead(n){const i=await fetch(`${this.apiUrl}/v1/conversations/${encodeURIComponent(n)}/mark-read`,{method:"POST",headers:{authorization:`Bearer ${this.token}`}});if(!i.ok&&i.status!==204)throw new Error(`markRead failed (${i.status})`)}listCannedResponses(n){const i=n!=null&&n.trim()?`?search=${encodeURIComponent(n)}`:"";return this.request(`/v1/canned-responses${i}`)}getNote(n){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`)}patchContact(n,i){return this.request(`/v1/contacts/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify({externalId:i})})}upsertNote(n,i){return this.request(`/v1/conversations/${encodeURIComponent(n)}/note`,{method:"PUT",body:JSON.stringify({content:i})})}async uploadAttachment(n){const i=new FormData;return i.append("file",n),this.request("/v1/attachments",{method:"POST",body:i},!0)}connectSSE(n){const i=`${this.apiUrl}/v1/events?token=${encodeURIComponent(this.token)}`;let o,h,k=!1;const y=()=>{o=new EventSource(i),o.addEventListener("message.new",B=>{n("message.new",JSON.parse(B.data))}),o.addEventListener("conversation.updated",B=>{n("conversation.updated",JSON.parse(B.data))}),o.onerror=()=>{o.close(),k||(h=setTimeout(y,5e3))}};return y(),()=>{k=!0,clearTimeout(h),o==null||o.close()}}}function Qe({src:t,alt:n="",fallback:i,style:o}){return t?e.jsx("img",{src:t,alt:n,style:{width:38,height:38,borderRadius:"50%",objectFit:"cover",...o}}):e.jsx("span",{style:{display:"grid",placeItems:"center",width:38,height:38,borderRadius:"50%",...o},children:i})}function Ht({variant:t="ghost",style:n,...i}){return e.jsx("button",{...i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",border:t==="outline"?"1px solid #e7ebf2":0,borderRadius:8,cursor:"pointer",font:"inherit",background:t==="default"?"#2563eb":"transparent",...n}})}function At({style:t,...n}){return e.jsx("input",{...n,style:{width:"100%",minWidth:0,border:0,outline:0,background:"transparent",font:"inherit",...t}})}const yt=r.forwardRef(({children:t,style:n},i)=>e.jsx("div",{ref:i,style:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain",...n},children:t})),Ot=r.forwardRef(function({style:n,...i},o){return e.jsx("textarea",{ref:o,...i,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",border:0,outline:0,background:"transparent",font:"inherit",...n}})});function Ut(t){return{id:t.contactId??t.providerConversationKey,name:t.contactName,pictureUrl:t.contactPictureUrl,providerUserId:t.contactProviderUserId??t.providerConversationKey,...t.contactExternalId?{externalId:t.contactExternalId}:{}}}function Ke(t,n){return{conversation:t,contact:Ut(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 Dt extends r.Component{constructor(){super(...arguments),this.state={caught:!1}}static getDerivedStateFromError(){return{caught:!0}}render(){return this.state.caught?null:this.props.children}}const l={ink:"#172033",muted:"#718096",line:"#e7ebf2",surface:"#f7f9fc",white:"#fff"},st=[{icon:"😊",emojis:["😀","😁","😂","🤣","😊","😇","🙂","😉","😍","🥰","😘","😋","😎","🤩","😏","😒","😔","😢","😭","😤","😠","🤯","😱","🥳","😴","🤔","🤗","🫡","😮","🤧","🥺","😶","🫠","🤭","🤫"]},{icon:"👋",emojis:["👍","👎","👏","🙏","🤝","✌️","🤞","🫡","💪","🤜","👊","✊","🖐","👌","🤌","🤏","☝️","👆","👇","👉","👈","🤙","💅","🫶","❤️","🧡","💛","💚","💙","💜","🖤","💔","❣️","💕","💯"]},{icon:"🐱",emojis:["🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🙈","🐔","🐧","🐦","🦆","🦅","🦉","🦋","🐝","🐛","🐢","🦎","🐬","🦈","🐳","🐙","🦑"]},{icon:"🍕",emojis:["🍎","🍊","🍋","🍇","🍓","🍒","🥝","🥑","🍔","🍕","🌮","🍜","🍣","🍦","🎂","🍰","🧁","☕","🧋","🥤","🍺","🥂","🍾","🧃","🧊"]},{icon:"⚽",emojis:["⚽","🏀","🏈","⚾","🎾","🏐","🏓","🎮","🎲","🎯","🎳","🏆","🥇","🎖","🎁","🎉","🎊","🎈","🎭","🎨","🎬","🎵","🎸","🎹","🎺","🪗","🎻"]},{icon:"🌍",emojis:["🌍","🌈","⭐","🌙","☀️","⛅","🌊","🔥","💧","🌿","🌸","🌺","🌻","🍀","🌴","🏔","🏖","🏕","🌃","🏙","🌅","🌄","🌠","🌌","🌋","🏝"]}],et=r.createContext(""),bt=r.createContext("");function Ft(){try{const t=new AudioContext,n=t.createOscillator(),i=t.createGain();n.connect(i),i.connect(t.destination),n.type="sine",n.frequency.setValueAtTime(880,t.currentTime),n.frequency.exponentialRampToValueAtTime(660,t.currentTime+.12),i.gain.setValueAtTime(.25,t.currentTime),i.gain.exponentialRampToValueAtTime(.001,t.currentTime+.35),n.start(t.currentTime),n.stop(t.currentTime+.35)}catch{}}function Pt(t){if(!(t!=null&&t.metadata))return;const n=t.metadata,i=n.pageName??n.displayName??n.username??n.name;return typeof i=="string"&&i?i:void 0}function mt(t){return t==="facebook"?"Facebook Messenger":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo OA":t==="livechat"?"Live Chat":"Channel"}function at(t){return t==="facebook"?"Facebook":t==="instagram"?"Instagram":t==="telegram"?"Telegram":t==="zalo"?"Zalo":t==="livechat"?"Live Chat":String(t??"")}const Nt=t=>{var i;const n={"application/pdf":"PDF","video/mp4":"Video MP4","audio/mpeg":"Audio MP3","audio/ogg":"Audio OGG","application/octet-stream":"Tệp đính kèm"};return t?n[t]??((i=t.split("/")[1])==null?void 0:i.toUpperCase())??"Tệp":"Tệp đính kèm"};function lt({status:t}){return t==="read"?e.jsx(nt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):t==="delivered"?e.jsx(nt,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle",opacity:.5}}):t==="sent"?e.jsx(_e,{size:11,strokeWidth:2,style:{display:"inline",verticalAlign:"middle"}}):null}function Ye(t){const n=t.trim().split(/\s+/).filter(Boolean);return n.length<=2?t.trim():n.slice(-2).join(" ")}const Kt=r.forwardRef(function({apiUrl:n,token:i,theme:o,height:h,defaultConversationId:k,disableAttachments:y,disableNotificationSound:B,hideKeyboardHint:v,locale:m="vi",extensions:R,currentAgent:z,teamAgents:E,onNewMessage:T,onConversationSelect:w},U){var j,L,N,O,ee;const S=r.useRef(new Ne(n,i)),[$,D]=r.useState([]),[K,_]=r.useState([]),[J,W]=r.useState(),[b,x]=r.useState(),H=r.useRef(void 0),[q,Q]=r.useState(""),[re,C]=r.useState("all"),[te,X]=r.useState(null),[A,Z]=r.useState({provider:"all",unreadOnly:!1}),[oe,c]=r.useState(!1),M=r.useRef(null),F=r.useRef(null),[ne,se]=r.useState(null),[ue,P]=r.useState(!0),[ae,be]=r.useState(""),[ze,Re]=r.useState(()=>!!(R!=null&&R.length)),[Te,me]=r.useState(280),[xe,je]=r.useState(!1),[Ee,fe]=r.useState(0),Y=(o==null?void 0:o.primaryColor)??"#2563eb",de=r.useMemo(()=>new Map(K.map(a=>[a.id,a])),[K]),ve=r.useRef(null),[He,We]=r.useState(0),V=z??te??null;r.useEffect(()=>{S.current=new Ne(n,i),z||S.current.getSessionMe().then(a=>{a!=null&&a.agent&&X(a.agent)}).catch(()=>{})},[n,i,z]);const Ae=r.useMemo(()=>{var u;const a=new Map;V!=null&&V.id&&a.set(V.id,V);for(const p of E??[])p!=null&&p.id&&!a.has(p.id)&&a.set(p.id,p);for(const p of $)(u=p.assignedAgent)!=null&&u.id&&!a.has(p.assignedAgent.id)&&a.set(p.assignedAgent.id,p.assignedAgent);return[...a.values()]},[V,E,$]),Oe=r.useCallback(async(a,u)=>{D(p=>p.map(I=>I.id===a.id?{...I,assignedAgent:u}:I)),x(p=>p&&p.id===a.id?{...p,assignedAgent:u}:p),fe(p=>p+1);try{const p=await S.current.assignConversation(a.id,u);D(I=>I.map(ie=>ie.id===a.id?{...ie,...p,assignedAgent:p.assignedAgent??u}:ie)),x(I=>I&&I.id===a.id?{...I,...p,assignedAgent:p.assignedAgent??u}:I),fe(I=>I+1)}catch{}},[]),ye=r.useCallback(async(a,u)=>{a.contactId&&await S.current.patchContact(a.contactId,u),D(p=>p.map(I=>I.id===a.id?{...I,contactExternalId:u??void 0}:I)),x(p=>p&&p.id===a.id?{...p,contactExternalId:u??void 0}:p),fe(p=>p+1)},[]),ce=r.useCallback(()=>{fe(a=>a+1)},[]),Ue=r.useMemo(()=>{const a=new Set(K.map(u=>u.provider));return["facebook","instagram","telegram","zalo","livechat"].filter(u=>a.has(u))},[K]),De=r.useMemo(()=>{var u;const a={};for(const p of $){const I=((u=de.get(p.connectionId))==null?void 0:u.provider)??"unknown";a[I]=(a[I]??0)+1}return a},[$,de]);function qe(a){const u=a.clientX,p=Te;je(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none";function I(Se){const $e=Math.max(200,Math.min(480,p+(u-Se.clientX)));me($e)}function ie(){je(!1),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",ie)}document.addEventListener("mousemove",I),document.addEventListener("mouseup",ie)}const le=r.useCallback(async a=>{try{const u=await S.current.listConversations(a);D(p=>a?[...p,...u.items]:u.items),W(u.nextCursor),!a&&u.items.length&&x(p=>p??(k?u.items.find(I=>I.id===k)??u.items[0]:u.items[0])),be("")}catch(u){be(u instanceof Error?u.message:"Không tải được hội thoại")}finally{P(!1)}},[k]);r.useEffect(()=>(S.current.listConnections().then(_).catch(()=>{}),le(),S.current.connectSSE((u,p)=>{if(u==="message.new"||u==="conversation.updated"){if(le(),u==="message.new"){const I=typeof p=="object"&&p?p:{},ie=I.conversationId?String(I.conversationId):"",Se=I.messageId?String(I.messageId):"";if((I.direction?String(I.direction):"")==="inbound"&&!B&&Ft(),ie&&ie===H.current&&Se&&ve.current){const Fe=ve.current;S.current.getMessage(Se).then(Pe=>{Fe(Pe)}).catch(()=>{})}T==null||T(ie||H.current||"")}}else u==="message.status_updated"&&We(I=>I+1)})),[le,T]),r.useEffect(()=>{H.current=b==null?void 0:b.id},[b]),r.useEffect(()=>{b!=null&&b.unreadCount&&S.current.markRead(b.id).then(()=>le()).catch(()=>{})},[b==null?void 0:b.id]),r.useEffect(()=>{if(!oe)return;function a(u){var p,I;(p=M.current)!=null&&p.contains(u.target)||(I=F.current)!=null&&I.contains(u.target)||c(!1)}return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[oe]);const pe=r.useMemo(()=>{const a=V?$.filter(p=>{var I;return((I=p.assignedAgent)==null?void 0:I.id)===V.id}).length:0,u=$.filter(p=>!p.assignedAgent).length;return{all:$.length,mine:a,unassigned:u}},[$,V]),ke=r.useMemo(()=>{const a=q.toLowerCase().trim();return $.filter(u=>{var $e,Fe,Pe;if(re==="mine"){if(!V||(($e=u.assignedAgent)==null?void 0:$e.id)!==V.id)return!1}else if(re==="unassigned"&&u.assignedAgent)return!1;const p=`${u.contactName??""} ${u.subject??""} ${u.providerConversationKey} ${((Fe=u.assignedAgent)==null?void 0:Fe.name)??""}`.toLowerCase(),I=((Pe=de.get(u.connectionId))==null?void 0:Pe.provider)??"unknown",ie=A.provider==="all"||I===A.provider,Se=!A.unreadOnly||(u.unreadCount??0)>0;return ie&&Se&&(!a||p.includes(a))})},[$,de,A,q,re,V]),we=A.provider!=="all"||A.unreadOnly,s=m==="en"?{today:"TODAY",loadOlder:"↑ Load older messages",loading:"Loading messages…",noMessages:"No messages in this conversation.",searchPlaceholder:"Search conversations…",unreadOnly:"Unread only",sendPlaceholder:"Write a message…",send:"Send",all:"All"}:{today:"HÔM NAY",loadOlder:"↑ Tải tin cũ hơn",loading:"Đang tải tin nhắn…",noMessages:"Chưa có tin nhắn trong hội thoại này.",searchPlaceholder:"Tìm kiếm hội thoại…",unreadOnly:"Chưa đọc",sendPlaceholder:"Viết tin nhắn…",send:"Gửi",all:"Tất cả"};r.useImperativeHandle(U,()=>({openConversation:a=>{const u=$.find(p=>p.id===a);u&&x(u)},refresh:()=>void le()}),[$,le]);const g={...f.frame,height:h??620,...h?{maxHeight:"none"}:{},fontFamily:(o==null?void 0:o.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",borderRadius:(o==null?void 0:o.borderRadius)??"16px",gridTemplateColumns:ze?`minmax(260px, 300px) minmax(0, 1fr) ${Te}px`:"minmax(260px, 300px) minmax(0, 1fr)",transition:xe?"none":"grid-template-columns 220ms ease"};return ue?e.jsxs("div",{style:{...f.state,borderRadius:(o==null?void 0:o.borderRadius)??"16px"},children:[e.jsx(Je,{})," Đang tải hộp thư…"]}):ae&&!$.length?e.jsxs("div",{style:{...f.state,color:"#b42318",borderRadius:(o==null?void 0:o.borderRadius)??"16px"},children:[e.jsx(Ct,{size:16,strokeWidth:2})," ",ae,e.jsx("button",{style:f.retry,onClick:()=>{P(!0),le()},children:"Thử lại"})]}):e.jsx(et.Provider,{value:n,children:e.jsx(bt.Provider,{value:i,children:e.jsxs("div",{style:g,onFocusCapture:()=>{const a=window.scrollY;requestAnimationFrame(()=>{window.scrollY!==a&&window.scrollTo({top:a,behavior:"instant"})})},children:[e.jsxs("aside",{style:f.sidebar,children:[e.jsxs("div",{style:f.brand,children:[e.jsx("div",{style:{...f.brandMark,background:Y,overflow:"hidden",padding:0},children:(j=o==null?void 0:o.branding)!=null&&j.logoUrl?e.jsx("img",{src:o.branding.logoUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):((L=o==null?void 0:o.branding)==null?void 0:L.mark)??"C"}),e.jsxs("div",{children:[e.jsx("strong",{children:((N=o==null?void 0:o.branding)==null?void 0:N.name)??"Hộp thư"}),!((O=o==null?void 0:o.branding)!=null&&O.name)&&e.jsx("span",{style:f.eyebrow,children:"CHANNELHUB"})]}),e.jsx(Ht,{"aria-label":"Tùy chọn",style:f.iconButton,children:e.jsx(gt,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:f.search,children:[e.jsx(rt,{size:16,strokeWidth:2}),e.jsx(At,{"aria-label":s.searchPlaceholder,value:q,onChange:a=>Q(a.target.value),placeholder:s.searchPlaceholder}),q&&e.jsx("button",{style:f.clear,onClick:()=>Q(""),"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 ${l.line}`,background:l.surface},children:[{key:"all",label:m==="en"?"All":"Tất cả",count:pe.all},{key:"mine",label:m==="en"?"Mine":"Của tôi",count:pe.mine},{key:"unassigned",label:m==="en"?"Unassigned":"Chưa nhận",count:pe.unassigned}].map(a=>{const u=re===a.key;return e.jsxs("button",{type:"button",role:"tab","aria-selected":u,onClick:()=>C(a.key),style:{border:0,borderRadius:6,padding:"5px 4px",fontSize:11,fontWeight:u?700:500,background:u?l.white:"transparent",color:u?Y:l.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:[a.label," ",e.jsxs("span",{style:{opacity:.75},children:["(",a.count,")"]})]},a.key)})}),we&&e.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",padding:"0 14px 8px"},children:[A.provider!=="all"&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,background:"#eef2ff",color:Y,borderRadius:6,fontSize:11,padding:"2px 8px",fontWeight:500},children:[e.jsx(Le,{provider:A.provider}),at(A.provider),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:Y,padding:0,lineHeight:1,display:"flex"},onClick:()=>Z(a=>({...a,provider:"all"})),"aria-label":"Xóa filter kênh",children:e.jsx(Me,{size:10})})]}),A.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:[s.unreadOnly,e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:Y,padding:0,lineHeight:1,display:"flex"},onClick:()=>Z(a=>({...a,unreadOnly:!1})),"aria-label":"Xóa filter chưa đọc",children:e.jsx(Me,{size:10})})]}),e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:l.muted,fontSize:11,padding:"2px 4px"},onClick:()=>Z({provider:"all",unreadOnly:!1}),children:"Xóa tất cả"})]}),e.jsxs("div",{style:f.listHeader,children:[e.jsxs("span",{children:[ke.length," hội thoại"]}),e.jsx("button",{ref:M,style:{...f.iconButton,background:we?`${Y}14`:"transparent",color:we?Y:l.muted},"aria-label":"Bộ lọc",onClick:()=>{var a;if(!oe){const u=(a=M.current)==null?void 0:a.getBoundingClientRect();u&&se({top:u.bottom+6,left:u.left})}c(u=>!u)},children:e.jsx(Bt,{size:15,strokeWidth:2})})]}),oe&&ne&&pt.createPortal(e.jsxs("div",{ref:F,style:{position:"fixed",top:ne.top,left:ne.left,zIndex:9999,background:l.white,border:`1px solid ${l.line}`,borderRadius:10,padding:"12px 14px",boxShadow:"0 8px 24px rgba(23,32,51,.14)",minWidth:210,fontFamily:(o==null?void 0:o.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif",fontSize:13},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:l.muted,letterSpacing:1,textTransform:"uppercase",marginBottom:8},children:"Kênh"}),["all",...Ue].map(a=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:A.provider===a?`${Y}0f`:"transparent"},children:[e.jsx("input",{type:"radio",name:"provider-filter",checked:A.provider===a,onChange:()=>Z(u=>({...u,provider:a})),style:{accentColor:Y}}),a==="all"?e.jsxs("span",{style:{color:l.ink},children:[s.all," (",$.length,")"]}):e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,color:l.ink},children:[e.jsx(Le,{provider:a}),at(a)," ",e.jsxs("span",{style:{color:l.muted},children:["(",De[a]??0,")"]})]})]},a)),e.jsx("div",{style:{borderTop:`1px solid ${l.line}`,margin:"8px 0 6px"}}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 6px",cursor:"pointer",borderRadius:6,background:A.unreadOnly?`${Y}0f`:"transparent"},children:[e.jsx("input",{type:"checkbox",checked:A.unreadOnly,onChange:a=>Z(u=>({...u,unreadOnly:a.target.checked})),style:{accentColor:Y}}),e.jsx("span",{style:{color:l.ink},children:s.unreadOnly})]})]}),document.body),e.jsxs(yt,{style:f.conversationList,children:[ke.map(a=>{var u;return e.jsx(qt,{conversation:a,provider:(u=de.get(a.connectionId))==null?void 0:u.provider,selected:(b==null?void 0:b.id)===a.id,primary:Y,currentAgent:V,onSelect:()=>{x(a),w==null||w(a.id),S.current.markRead(a.id).then(()=>le()).catch(()=>{})}},a.id)}),!ke.length&&e.jsxs("div",{style:f.emptySmall,children:[e.jsx("div",{style:f.emptyIcon,children:e.jsx(rt,{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."})]}),J&&e.jsx("button",{style:f.loadMore,onClick:()=>void le(J),children:"Xem thêm hội thoại"})]})]}),e.jsx("main",{style:f.main,children:b?e.jsx(Vt,{conversation:b,provider:(ee=de.get(b.connectionId))==null?void 0:ee.provider,connection:de.get(b.connectionId),client:S.current,primary:Y,error:ae,onRegisterAppend:a=>{ve.current=a},refreshKey:He,infoOpen:ze,onToggleInfo:()=>Re(a=>!a),t:s,disableAttachments:y,hideKeyboardHint:v,extensions:R,currentAgent:V,teamAgents:Ae,onAssignAgent:a=>Oe(b,a),onLinkContact:a=>ye(b,a),onRefreshContactInfo:ce},b.id):e.jsx(Jt,{})}),ze&&b&&e.jsx(Xt,{conversation:b,connection:de.get(b.connectionId),primary:Y,onClose:()=>Re(!1),client:S.current,onStartResize:qe,extensions:R,extRefreshKey:Ee,onLinkContact:a=>ye(b,a),onRefreshContactInfo:ce})]})})})});function qt({conversation:t,provider:n,selected:i,primary:o,currentAgent:h,onSelect:k}){const[y,B]=r.useState(!1),v=t.contactName??t.subject??t.providerConversationKey,m=t.unreadCount??0,R=t.lastMessageText??"",z=t.lastMessageDirection==="outbound"?"Bạn: ":"",E=R.length>60?R.slice(0,60)+"…":R,T=R?z+E:"",w=t.assignedAgent??null,U=!!(w&&h&&w.id===h.id);let S="transparent";i?S="#eef2ff":y?S="#f7f9fc":m>0&&(S="#f0f4ff");const $={...f.row,background:S,...i?{boxShadow:`inset 3px 0 0 ${o}`}:m>0&&!y?{boxShadow:`inset 3px 0 0 ${o}`}:{}};return e.jsxs("button",{onClick:k,style:$,onMouseEnter:()=>B(!0),onMouseLeave:()=>B(!1),children:[e.jsx(jt,{name:v,color:o,image:t.contactPictureUrl,provider:n}),e.jsxs("span",{style:f.rowBody,children:[e.jsxs("span",{style:f.rowTop,children:[e.jsx("strong",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:m>0?700:500},children:v}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:[e.jsx("time",{style:{color:l.muted,fontSize:11,whiteSpace:"nowrap"},children:Ze(t.lastMessageAt)}),m>0&&e.jsx("span",{"aria-label":`${m} tin nhắn chưa đọc`,style:f.unreadBadge,children:m>99?"99+":m})]})]}),e.jsxs("span",{style:{...f.rowBottom,justifyContent:"space-between",alignItems:"center",gap:6,color:m>0&&!i?"#4a5568":l.muted},children:[e.jsx("span",{style:{flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:T||e.jsx("span",{style:{opacity:.5},children:"Chưa có tin nhắn"})}),w?e.jsxs("span",{title:`Phụ trách: ${w.name}${w.title?` (${w.title})`:""}`,style:{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 6px 1px 2px",borderRadius:999,fontSize:10,fontWeight:600,flexShrink:0,background:U?`${o}18`:"#f1f5f9",color:U?o:"#475569",border:U?`1px solid ${o}33`:"1px solid #e2e8f0"},children:[e.jsx("span",{style:{width:14,height:14,borderRadius:"50%",background:U?o:"#64748b",color:"#fff",fontSize:8,fontWeight:700,display:"inline-grid",placeItems:"center",overflow:"hidden",flexShrink:0},children:w.avatarUrl?e.jsx("img",{src:w.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Ie(w.name)}),e.jsx("span",{style:{maxWidth:68,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ye(w.name)})]}):m>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 Vt({conversation:t,provider:n,connection:i,client:o,primary:h,error:k,onRegisterAppend:y,refreshKey:B,infoOpen:v,onToggleInfo:m,t:R,disableAttachments:z,hideKeyboardHint:E,extensions:T,currentAgent:w,teamAgents:U,onAssignAgent:S,onLinkContact:$,onRefreshContactInfo:D}){var ke,we;const[K,_]=r.useState([]),[J,W]=r.useState(),[b,x]=r.useState(""),[H,q]=r.useState(!0),[Q,re]=r.useState(!1),[C,te]=r.useState(""),X=r.useRef(null),A=t.contactName??t.subject??t.providerConversationKey,Z=r.useRef(null),oe=r.useRef(null),[c,M]=r.useState(null),[F,ne]=r.useState(!1),[se,ue]=r.useState(!1),[P,ae]=r.useState(!1),[be,ze]=r.useState(0),Re=r.useRef(null),Te=r.useRef(null),me=r.useRef(null),[xe,je]=r.useState(!1),[Ee,fe]=r.useState(""),[Y,de]=r.useState([]),ve=r.useRef(null),He=r.useRef(null),[We,V]=r.useState(!1),Ae=r.useRef(null),Oe=r.useRef(null);r.useEffect(()=>{if(!We)return;function s(g){var j,L;(j=Ae.current)!=null&&j.contains(g.target)||(L=Oe.current)!=null&&L.contains(g.target)||V(!1)}return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[We]),r.useEffect(()=>()=>{c!=null&&c.objectUrl&&URL.revokeObjectURL(c.objectUrl)},[c==null?void 0:c.objectUrl]),r.useEffect(()=>{if(!P)return;function s(g){var j,L;(j=Te.current)!=null&&j.contains(g.target)||(L=Re.current)!=null&&L.contains(g.target)||ae(!1)}return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[P]),r.useEffect(()=>{o.listCannedResponses().then(de).catch(()=>{})},[o]),r.useEffect(()=>{if(!xe)return;function s(g){var j,L;(j=He.current)!=null&&j.contains(g.target)||(L=ve.current)!=null&&L.contains(g.target)||je(!1)}return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[xe]);const ye=r.useRef(!0),ce=r.useCallback(async(s,g)=>{g||(ye.current=!s);try{const j=await o.listMessages(t.id,s);_(L=>s?[...j.items,...L]:j.items),W(j.nextCursor)}catch(j){te(j instanceof Error?j.message:"Không tải được tin nhắn")}finally{g||q(!1)}},[o,t.id]);r.useEffect(()=>{q(!0),ce()},[ce]),r.useEffect(()=>{B&&ce(void 0,!0)},[B]),r.useEffect(()=>{ye.current&&requestAnimationFrame(()=>{const s=X.current;s&&(s.scrollTop=s.scrollHeight)})},[K]),r.useEffect(()=>(y==null||y(s=>{ye.current=!0,_(g=>g.some(j=>j.id===s.id)?g:[...g,s])}),()=>{y==null||y(null)}),[y]);async function Ue(s){var L;const g=(L=s.target.files)==null?void 0:L[0];if(!g)return;s.target.value="";const j=URL.createObjectURL(g);M({file:g,uploading:!0,objectUrl:j});try{const N=await o.uploadAttachment(g);M({file:g,uploading:!1,url:N.url,mimeType:N.mimeType,attachmentType:N.attachmentType,objectUrl:j})}catch{URL.revokeObjectURL(j),M(null),te("Không tải lên được tệp đính kèm")}}async function De(s){s.preventDefault();const g=b.trim(),j=c!=null&&c.url?[{url:c.url,mimeType:c.mimeType??"application/octet-stream",type:c.attachmentType}]:[];if(!g&&!j.length||Q)return;re(!0),te(""),!t.assignedAgent&&w&&S(w);const L=`optimistic-${Date.now()}`;w&&(ye.current=!0,_(N=>[...N,{id:L,direction:"outbound",status:"sending",text:g||void 0,attachments:j.length?j:void 0,occurredAt:new Date().toISOString(),senderAgent:w}]));try{await o.sendMessage(t.id,g||void 0,j.length?j:void 0),c!=null&&c.objectUrl&&URL.revokeObjectURL(c.objectUrl),x(""),M(null),await ce(),w&&_(N=>{var a,u;const O=N.filter(p=>p.id!==L),ee=O.length-1;return ee>=0&&((a=O[ee])==null?void 0:a.direction)==="outbound"&&!((u=O[ee])!=null&&u.senderAgent)?O.map((p,I)=>I===ee?{...p,senderAgent:w}:p):O})}catch(N){_(O=>O.filter(ee=>ee.id!==L)),te(N instanceof Error?N.message:"Không gửi được tin nhắn")}finally{re(!1)}}function qe(s){const g=me.current;if(!g){x(O=>O+s),ae(!1);return}const j=g.selectionStart??b.length,L=g.selectionEnd??b.length,N=b.slice(0,j)+s+b.slice(L);x(N),ae(!1),requestAnimationFrame(()=>{g.focus(),g.selectionStart=g.selectionEnd=j+s.length})}function le(s){x(s),je(!1),fe(""),requestAnimationFrame(()=>{const g=me.current;g&&(g.focus(),g.selectionStart=g.selectionEnd=s.length)})}const pe=!Q&&(b.trim().length>0||(c==null?void 0:c.url)!=null&&!c.uploading);return e.jsxs("section",{style:f.chat,children:[e.jsxs("header",{style:f.chatHeader,children:[e.jsx(jt,{name:A,color:h,image:t.contactPictureUrl,provider:n}),e.jsxs("div",{style:f.contact,children:[e.jsx("strong",{style:f.contactName,children:A}),e.jsx("span",{style:f.contactMeta,children:Pt(i)??mt(n)})]}),e.jsxs("div",{style:{...f.headerActions,alignItems:"center",gap:6},children:[e.jsxs("div",{ref:Ae,style:{position:"relative",display:"inline-flex",alignItems:"center",gap:4},children:[!t.assignedAgent&&w?e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",borderRadius:999,border:`1px solid ${h}40`,background:`${h}0d`,overflow:"hidden"},children:[e.jsxs("button",{type:"button",onClick:()=>void S(w),style:{border:0,background:"transparent",color:h,padding:"4px 9px",fontSize:11.5,fontWeight:600,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:[e.jsx(ot,{size:12,strokeWidth:2.2}),e.jsx("span",{children:"+ Nhận phụ trách"})]}),((U==null?void 0:U.length)??0)>1&&e.jsx("button",{type:"button","aria-label":"Chọn nhân viên phụ trách",onClick:()=>V(s=>!s),style:{border:0,borderLeft:`1px solid ${h}30`,background:"transparent",color:h,padding:"4px 6px",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:e.jsx(Xe,{size:12,strokeWidth:2.2})})]}):e.jsxs("button",{type:"button",onClick:()=>V(s=>!s),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 9px 3px 4px",borderRadius:999,border:`1px solid ${l.line}`,background:l.surface,color:l.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:h,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"}}):Ie(t.assignedAgent.name)}),e.jsx("span",{style:{color:l.muted,fontWeight:500},children:"Phụ trách:"}),e.jsx("span",{style:{maxWidth:110,overflow:"hidden",textOverflow:"ellipsis"},children:Ye(t.assignedAgent.name)})]}):e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:13,color:l.muted}),e.jsx("span",{style:{color:l.muted},children:"Chưa phân công"})]}),e.jsx(Xe,{size:12,color:l.muted})]}),We&&e.jsxs("div",{ref:Oe,style:{position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:200,minWidth:230,background:l.white,border:`1px solid ${l.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:l.muted,letterSpacing:.8,textTransform:"uppercase"},children:"Người phụ trách hội thoại"}),w&&((ke=t.assignedAgent)==null?void 0:ke.id)!==w.id&&e.jsxs("button",{type:"button",onClick:()=>{V(!1),S(w)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",border:0,borderRadius:7,background:`${h}10`,color:h,padding:"6px 8px",marginBottom:4,fontWeight:600,fontSize:12,cursor:"pointer",textAlign:"left"},children:[e.jsx(ot,{size:13}),e.jsxs("span",{children:["Nhận phụ trách cho tôi (",Ye(w.name),")"]})]}),e.jsx("div",{style:{maxHeight:200,overflowY:"auto"},children:(U??[]).map(s=>{var j;const g=((j=t.assignedAgent)==null?void 0:j.id)===s.id;return e.jsxs("button",{type:"button",onClick:()=>{V(!1),S(s)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,width:"100%",border:0,borderRadius:7,background:g?"#f1f5f9":"transparent",color:l.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:`${h}18`,color:h,fontSize:10,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"}}):Ie(s.name)}),e.jsxs("span",{style:{minWidth:0},children:[e.jsx("span",{style:{display:"block",fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:s.name}),s.title&&e.jsx("span",{style:{display:"block",fontSize:10.5,color:l.muted},children:s.title})]})]}),g&&e.jsx(_e,{size:13,color:h,strokeWidth:2.5})]},s.id)})}),t.assignedAgent&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{borderTop:`1px solid ${l.line}`,margin:"5px 0"}}),e.jsxs("button",{type:"button",onClick:()=>{V(!1),S(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(Me,{size:13}),e.jsx("span",{children:"Bỏ phân công (Chưa có người nhận)"})]})]})]})]}),e.jsx("button",{style:f.iconButton,"aria-label":"Thêm tùy chọn",children:e.jsx(gt,{size:16,strokeWidth:2})}),e.jsx("button",{style:{...f.iconButton,background:v?`${h}14`:"transparent",color:v?h:l.muted},"aria-label":"Thông tin liên hệ",onClick:m,children:e.jsx(Rt,{size:16,strokeWidth:2})})]})]}),e.jsxs(yt,{ref:X,style:f.messageArea,children:[e.jsx("div",{style:f.day,children:R.today}),J&&e.jsx("button",{onClick:()=>void ce(J),style:f.historyButton,children:R.loadOlder}),H&&e.jsxs("div",{style:f.messageHint,children:[e.jsx(Je,{})," ",R.loading]}),!H&&!K.length&&e.jsx("div",{style:f.messageHint,children:R.noMessages}),K.map((s,g)=>{const j=(T==null?void 0:T.flatMap(ee=>ee.messageEnrichments??[]))??[],L=s.direction==="inbound"&&j.length>0&&g>=K.length-15,N=L?Ke(t,{provider:n,recentMessages:K.slice(-10),linkContact:$,refreshContactInfo:D,sendMessage:async(ee,a)=>{await o.sendMessage(t.id,ee,a),await ce(void 0,!0)}}):null,O=L&&N?j.map((ee,a)=>{var p;const u=(p=s.text)==null?void 0:p.match(ee.pattern);return u?e.jsx(Dt,{children:ee.render(u,N,s)},`${s.id}-${a}`):null}).filter(Boolean):[];return e.jsxs("div",{children:[e.jsx(Gt,{message:s,primary:h}),O.length>0&&e.jsx("div",{style:{maxWidth:"min(70%, 480px)",marginTop:-4,marginBottom:10,display:"flex",flexDirection:"column",gap:6},children:O})]},s.id)})]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",padding:"6px 14px 2px",borderTop:`1px solid ${l.line}`},children:["Cảm ơn bạn đã liên hệ 🙏","Mình sẽ kiểm tra ngay","Vui lòng chờ 1-2 phút"].map(s=>e.jsx("button",{type:"button",onClick:()=>x(s),style:{fontSize:11,padding:"3px 10px",borderRadius:999,background:`${h}0f`,color:h,border:`1px solid ${h}33`,cursor:"pointer",whiteSpace:"nowrap"},children:s},s))}),e.jsxs("form",{onSubmit:De,style:{flex:"0 0 auto",padding:"8px 14px 12px",borderTop:`1px solid ${l.line}`,background:l.white,position:"relative"},children:[P&&e.jsxs("div",{ref:Re,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:l.white,border:`1px solid ${l.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:280,overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${l.line}`,background:"#f9fafb"},children:st.map((s,g)=>e.jsx("button",{type:"button",onClick:()=>ze(g),style:{flex:1,border:0,background:"transparent",padding:"7px 2px",fontSize:16,cursor:"pointer",lineHeight:1,borderBottom:be===g?`2px solid ${h}`:"2px solid transparent",opacity:be===g?1:.5,transition:"opacity 100ms ease"},children:s.icon},g))}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:2,padding:8,maxHeight:180,overflowY:"auto"},children:(we=st[be])==null?void 0:we.emojis.map((s,g)=>e.jsx("button",{type:"button",onClick:()=>qe(s),style:{border:0,background:"transparent",padding:"5px 2px",fontSize:18,cursor:"pointer",borderRadius:6,lineHeight:1,transition:"background 80ms ease"},onMouseEnter:j=>{j.target.style.background="#f3f4f6"},onMouseLeave:j=>{j.target.style.background="transparent"},children:s},g))})]}),xe&&e.jsxs("div",{ref:ve,style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:l.white,border:`1px solid ${l.line}`,borderRadius:12,boxShadow:"0 8px 24px rgba(23,32,51,.14)",width:300,overflow:"hidden",fontFamily:"inherit"},children:[e.jsx("div",{style:{padding:"8px 10px",borderBottom:`1px solid ${l.line}`},children:e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Tìm template…",value:Ee,onChange:s=>fe(s.target.value),style:{width:"100%",boxSizing:"border-box",border:`1px solid ${l.line}`,borderRadius:7,padding:"5px 8px",fontSize:12,outline:"none",fontFamily:"inherit",color:l.ink}})}),e.jsx("div",{style:{maxHeight:220,overflowY:"auto"},children:(()=>{const s=Ee.trim().toLowerCase(),g=s?Y.filter(j=>j.title.toLowerCase().includes(s)||j.content.toLowerCase().includes(s)||(j.shortcut??"").toLowerCase().includes(s)):Y;return g.length?g.map(j=>e.jsxs("button",{type:"button",onClick:()=>le(j.content),style:{display:"block",width:"100%",textAlign:"left",border:0,borderBottom:`1px solid ${l.line}`,background:"transparent",padding:"9px 12px",cursor:"pointer",fontFamily:"inherit"},onMouseEnter:L=>{L.currentTarget.style.background="#f7f9fc"},onMouseLeave:L=>{L.currentTarget.style.background="transparent"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:2},children:[e.jsx("span",{style:{fontSize:12,fontWeight:600,color:l.ink},children:j.title}),j.shortcut&&e.jsx("span",{style:{fontSize:10,color:h,background:`${h}18`,borderRadius:4,padding:"1px 5px"},children:j.shortcut})]}),e.jsx("div",{style:{fontSize:11,color:l.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.content})]},j.id)):e.jsx("div",{style:{padding:"24px 16px",textAlign:"center",color:l.muted,fontSize:12},children:Y.length===0?"Chưa có template nào":"Không tìm thấy"})})()})]}),e.jsxs("div",{style:{border:`1.5px solid ${l.line}`,borderRadius:12,background:l.white,overflow:"hidden"},children:[c&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:`1px solid ${l.line}`,fontSize:12},children:[c.uploading?e.jsxs(e.Fragment,{children:[e.jsx(Je,{}),e.jsx("span",{style:{color:l.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:l.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),M(null)},style:{marginLeft:"auto",border:0,background:"none",color:l.muted,cursor:"pointer",fontSize:16},"aria-label":"Xóa tệp đính kèm",children:"✕"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 8px",borderBottom:"1px solid #f3f4f6"},children:[e.jsx("button",{ref:Te,type:"button",title:"Chèn emoji",onClick:()=>ae(s=>!s),style:{...f.toolbarBtn,background:P?`${h}18`:"transparent",color:P?h:"#9ca3af"},children:e.jsx(Mt,{size:13,strokeWidth:2})}),!z&&e.jsx("button",{type:"button",title:"Gửi ảnh / video","aria-label":"Gửi ảnh hoặc video",style:f.toolbarBtn,onClick:()=>{var s;return(s=Z.current)==null?void 0:s.click()},children:e.jsx(It,{size:13,strokeWidth:2})}),!z&&e.jsx("button",{type:"button",title:"Gửi tệp đính kèm","aria-label":"Gửi tệp đính kèm",style:f.toolbarBtn,onClick:()=>{var s;return(s=oe.current)==null?void 0:s.click()},children:e.jsx(Tt,{size:13,strokeWidth:2})}),!z&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Z,type:"file",style:{display:"none"},onChange:Ue,accept:"image/*,video/mp4"}),e.jsx("input",{ref:oe,type:"file",style:{display:"none"},onChange:Ue,accept:".pdf,audio/mpeg,audio/ogg,application/octet-stream,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"})]}),e.jsx("button",{ref:He,type:"button",title:"Template nhanh",onClick:()=>{je(s=>!s),fe("")},style:{...f.toolbarBtn,background:xe?`${h}18`:"transparent",color:xe?h:"#9ca3af"},children:e.jsx(Et,{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:()=>ne(s=>!s),style:{...f.toolbarBtn,fontWeight:700,fontSize:12,background:F?`${h}18`:"transparent",color:F?h:"#9ca3af",border:F?`1px solid ${h}33`:"1px solid transparent"},children:"B"}),e.jsx("button",{type:"button",title:"Nghiêng",onClick:()=>ue(s=>!s),style:{...f.toolbarBtn,fontStyle:"italic",fontSize:12,background:se?`${h}18`:"transparent",color:se?h:"#9ca3af",border:se?`1px solid ${h}33`:"1px solid transparent"},children:"I"}),!!(T!=null&&T.some(s=>{var g;return(((g=s.toolbarActions)==null?void 0:g.length)??0)>0}))&&e.jsx("span",{style:{width:1,height:14,background:"#e5e7eb",margin:"0 4px"}}),T==null?void 0:T.flatMap(s=>s.toolbarActions??[]).map((s,g)=>e.jsxs("button",{type:"button",title:s.tooltip,style:s.label?{display:"inline-flex",alignItems:"center",gap:5,padding:"3px 9px",borderRadius:999,border:`1px solid ${h}33`,background:`${h}0f`,color:h,fontSize:11.5,fontWeight:600,cursor:"pointer",lineHeight:1.2,whiteSpace:"nowrap"}:f.toolbarBtn,onClick:()=>{const j=N=>{x(O=>O&&!O.endsWith(" ")&&!O.endsWith(`
127
127
  `)?`${O} ${N}`:`${O}${N}`),requestAnimationFrame(()=>{var O;return(O=me.current)==null?void 0:O.focus()})},L=Ke(t,{provider:n,recentMessages:K.slice(-10),linkContact:$,refreshContactInfo:D,sendMessage:async(N,O)=>{await o.sendMessage(t.id,N,O),await ce(void 0,!0)}});s.onClick({...L,insertText:j})},children:[s.icon,s.label&&e.jsx("span",{children:s.label})]},g))]}),e.jsx(Ot,{ref:me,"aria-label":"Soạn tin nhắn",rows:2,value:b,onChange:s=>x(s.target.value),onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),De(s))},placeholder:R.sendPlaceholder,style:{display:"block",width:"100%",minWidth:0,boxSizing:"border-box",minHeight:52,maxHeight:120,resize:"none",border:0,outline:0,background:"transparent",color:l.ink,padding:"8px 12px 4px",font:"inherit",fontSize:13,lineHeight:1.45,fontStyle:se?"italic":"normal",fontWeight:F?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:b.length>1e3?"#ef4444":b.length>900?"#f59e0b":"#9ca3af",fontWeight:b.length>1e3?600:400},children:[b.length,"/1000"]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[!E&&e.jsx("span",{style:{fontSize:10,color:"#9ca3af"},children:"↵ Gửi · ⇧↵ Xuống dòng"}),e.jsxs("button",{disabled:!pe,"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:pe?`linear-gradient(135deg,${h},#0ea5e9)`:"#e5e7eb",color:pe?"#fff":"#9ca3af",cursor:pe?"pointer":"not-allowed",boxShadow:pe?"0 2px 8px rgba(37,99,235,0.25)":"none",transition:"all 150ms ease"},children:[Q?e.jsx(xt,{size:12,style:{animation:"channelhub-spin .7s linear infinite"}}):e.jsx($t,{size:12,strokeWidth:2}),R.send]})]})]})]})]}),(C||k)&&e.jsx("div",{role:"alert",style:f.error,children:C||k})]})}function Gt({message:t,primary:n}){var K,_,J,W,b;const i=r.useContext(et),o=r.useContext(bt),h=x=>x.startsWith("/v1/media/proxy")?`${i}${x}&tok=${encodeURIComponent(o)}`:x,k=t.direction==="outbound",y=((K=t.attachments)==null?void 0:K.filter(x=>x.type==="image"))??[],B=((_=t.attachments)==null?void 0:_.filter(x=>x.type==="sticker"))??[],v=((J=t.attachments)==null?void 0:J.filter(x=>x.type==="video"))??[],m=((W=t.attachments)==null?void 0:W.filter(x=>x.type==="audio"))??[],R=((b=t.attachments)==null?void 0:b.filter(x=>x.type==="file"))??[],[z,E]=r.useState(null),T=k?"flex-end":"flex-start",w=k?t.senderAgent??null:null,U=e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:k?"flex-end":"flex-start",gap:5,marginTop:4,fontSize:10,opacity:.78,letterSpacing:.2,userSelect:"none"},children:[w&&e.jsxs("span",{title:w.title?`${w.name} (${w.title})`:w.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:w.avatarUrl?e.jsx("img",{src:w.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):Ie(w.name)}),e.jsx("span",{children:w.name}),e.jsx("span",{style:{opacity:.6},children:"•"})]}),e.jsxs("time",{children:[Ze(t.occurredAt,!0),k&&e.jsxs(e.Fragment,{children:[" ",e.jsx(lt,{status:t.status})]})]})]}),S=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:[Ze(t.occurredAt,!0),k&&e.jsxs(e.Fragment,{children:[" ",e.jsx(lt,{status:t.status})]})]})}),$=k?{...f.bubbleOut,background:n,color:"#fff",border:"1px solid transparent"}:f.bubbleIn,D=!t.text&&m.length===0&&R.length===0;return e.jsxs("div",{style:{...f.messageLine,justifyContent:T,flexDirection:"column",alignItems:T},children:[B.map((x,H)=>e.jsxs("div",{style:{position:"relative",marginBottom:2},children:[e.jsx("img",{src:h(x.url),alt:"sticker",style:{display:"block",maxWidth:128,maxHeight:128,objectFit:"contain"}}),D&&y.length===0&&v.length===0&&H===B.length-1&&S]},`s${H}`)),y.map((x,H)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"zoom-in"},onClick:()=>E({url:h(x.url),kind:"image"}),children:[e.jsx("img",{src:h(x.url),alt:"",style:{display:"block",maxWidth:260,maxHeight:260,borderRadius:12,objectFit:"cover"}}),D&&H===y.length-1&&v.length===0&&S]},H)),v.map((x,H)=>e.jsxs("div",{style:{position:"relative",marginBottom:2,cursor:"pointer"},onClick:()=>E({url:h(x.url),kind:"video"}),children:[e.jsx("video",{src:h(x.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(Wt,{size:16,fill:"#172033",color:"#172033",style:{marginLeft:2}})})}),D&&H===v.length-1&&S]},H)),(m.length>0||R.length>0||t.text||!y.length&&!v.length&&!B.length&&!t.text)&&e.jsxs("div",{style:$,children:[m.map((x,H)=>e.jsx("audio",{src:h(x.url),controls:!0,style:{display:"block",width:"100%",marginBottom:4}},H)),R.map((x,H)=>e.jsxs("a",{href:h(x.url),target:"_blank",rel:"noreferrer",style:{display:"block",fontSize:12,color:k?"#fff":"#2563eb",textDecoration:"underline",marginBottom:4},children:["📎 ",Nt(x.mimeType)]},H)),t.text&&e.jsx("p",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t.text}),!m.length&&!R.length&&!t.text&&e.jsx("p",{style:{margin:0,opacity:.5},children:"[attachment]"}),U]}),z&&pt.createPortal(e.jsxs("div",{onClick:()=>E(null),style:{position:"fixed",inset:0,zIndex:1e4,background:"rgba(0,0,0,.88)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"zoom-out"},children:[z.kind==="image"?e.jsx("img",{src:z.url,alt:"",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,objectFit:"contain",boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:x=>x.stopPropagation()}):e.jsx("video",{src:z.url,controls:!0,autoPlay:!0,style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:8,boxShadow:"0 8px 40px rgba(0,0,0,.5)"},onClick:x=>x.stopPropagation()}),e.jsx("button",{onClick:()=>E(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(Me,{size:18})})]}),document.body)]})}function Xt({conversation:t,connection:n,primary:i,onClose:o,client:h,onStartResize:k,extensions:y,extRefreshKey:B,onLinkContact:v,onRefreshContactInfo:m}){const R=t.contactName??t.subject??t.providerConversationKey,z=n==null?void 0:n.provider,E=!!(y!=null&&y.some(C=>C.contactInfoRows)),[T,w]=r.useState({channel:!0,stats:!1,extra:!0}),U=C=>w(te=>({...te,[C]:!te[C]})),[S,$]=r.useState(""),[D,K]=r.useState(!1),[_,J]=r.useState(!1),[W,b]=r.useState(""),[x,H]=r.useState([]),[q,Q]=r.useState(!1);r.useEffect(()=>{$(""),J(!1),b(""),h.getNote(t.id).then(C=>{C&&$(C.content)}).catch(()=>{})},[t.id,h]),r.useEffect(()=>{if(!E||!y)return;let C=!1;const te=Ke(t,{provider:z,linkContact:v,refreshContactInfo:m,sendMessage:async(X,A)=>{await h.sendMessage(t.id,X,A)}});return Q(!0),Promise.allSettled(y.filter(X=>X.contactInfoRows).map(X=>X.contactInfoRows(te))).then(X=>{if(C)return;const A=X.filter(Z=>Z.status==="fulfilled").flatMap(Z=>Z.value);H(A),Q(!1)}),()=>{C=!0}},[t.id,t.contactExternalId,y,B,E,z,v,m,h]);async function re(){if(!(!S.trim()||D)){K(!0),b("");try{await h.upsertNote(t.id,S.trim()),J(!0),setTimeout(()=>J(!1),2e3)}catch{b("Lưu thất bại")}finally{K(!1)}}}return e.jsxs("aside",{style:{...f.infoPanel,position:"relative"},children:[e.jsx("div",{onMouseDown:k,style:{position:"absolute",left:0,top:0,bottom:0,width:4,cursor:"col-resize",zIndex:1},onMouseEnter:C=>{C.currentTarget.style.background="rgba(0,0,0,0.07)"},onMouseLeave:C=>{C.currentTarget.style.background=""}}),e.jsxs("div",{style:f.infoPanelHeader,children:[e.jsx("span",{style:{fontWeight:600,fontSize:13,color:l.ink},children:"Thông tin liên hệ"}),e.jsx("button",{style:f.iconButton,onClick:o,"aria-label":"Đóng",children:e.jsx(Me,{size:16,strokeWidth:2})})]}),e.jsxs("div",{style:{overflowY:"auto",flex:1},children:[e.jsxs("div",{style:f.infoPanelIdentity,children:[e.jsxs("span",{style:{...f.avatarWrap,width:48,height:48},children:[e.jsx(Qe,{src:t.contactPictureUrl,fallback:Ie(R),style:{...f.avatar,width:48,height:48,fontSize:16}}),e.jsx("span",{style:{...f.providerBadge,width:20,height:20},children:e.jsx(Le,{provider:z})})]}),e.jsx("strong",{style:{marginTop:10,fontSize:15,color:l.ink,textAlign:"center"},children:R}),e.jsx("span",{style:{fontSize:11,color:l.muted,fontFamily:"monospace",textAlign:"center"},children:t.providerConversationKey})]}),e.jsxs(Ve,{label:"KÊNH",sectionKey:"channel",expanded:T.channel,onToggle:()=>U("channel"),children:[e.jsx(he,{label:"Nền tảng",children:e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5},children:[e.jsx(Le,{provider:z}),e.jsx("span",{children:mt(z)})]})}),e.jsxs(he,{label:"ID hội thoại",children:[e.jsxs("span",{style:{fontFamily:"monospace",fontSize:11},children:[t.id.slice(0,8),"…"]}),e.jsx(Yt,{value:t.id})]})]}),e.jsxs(Ve,{label:"THỐNG KÊ",sectionKey:"stats",expanded:T.stats,onToggle:()=>U("stats"),children:[e.jsx(he,{label:"Tin nhắn",value:String(t.messageCount??0)}),(t.unreadCount??0)>0&&e.jsx(he,{label:"Chưa đọc",value:String(t.unreadCount),valueColor:"#ef4444"}),e.jsx(he,{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(he,{label:"Lần đầu",value:"—"})]}),e.jsxs(Ve,{label:"THÔNG TIN BỔ SUNG",sectionKey:"extra",expanded:T.extra,onToggle:()=>U("extra"),children:[!E&&e.jsxs(e.Fragment,{children:[e.jsx(he,{label:"Điện thoại",value:"— chưa có",valueMuted:!0}),e.jsx(he,{label:"Email",value:"— chưa có",valueMuted:!0}),e.jsx(he,{label:"Nhãn",value:"— chưa có",valueMuted:!0})]}),q&&x.length===0&&e.jsx("div",{style:{fontSize:12,color:l.muted,padding:"6px 0"},children:"Đang tải hồ sơ CRM…"}),x.map(C=>e.jsx(he,{label:C.label,children:e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,flexWrap:"wrap",justifyContent:"flex-end"},children:[C.onClick?e.jsx("button",{type:"button",onClick:C.onClick,style:{border:0,background:"none",padding:0,color:i,fontSize:12,fontWeight:600,cursor:"pointer",textDecoration:"underline"},children:C.value}):C.href?e.jsx("a",{href:C.href,target:"_blank",rel:"noopener noreferrer",style:{color:i,fontSize:12,fontWeight:600},children:C.value}):e.jsx("span",{style:{fontSize:12,fontWeight:500,color:l.ink},children:C.value}),C.badge&&e.jsx("span",{style:{fontSize:10.5,fontWeight:700,padding:"1px 7px",borderRadius:999,color:C.badge.color??i,background:C.badge.bg??`${i}14`},children:C.badge.text})]})},C.label))]}),e.jsxs("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:8},children:[!(y!=null&&y.length)&&e.jsx("button",{style:{...f.ghostButton,color:i,borderColor:`${i}33`},children:"Xem lịch sử"}),y==null?void 0:y.flatMap(C=>C.sidebarActions??[]).map((C,te)=>{const X=C.variant==="primary";return e.jsxs("button",{style:{...f.ghostButton,background:X?i:"#fff",color:X?"#fff":l.ink,borderColor:X?i:l.line,fontWeight:X?700:600,display:"flex",alignItems:"center",justifyContent:"center",gap:6},onClick:()=>{const A=Ke(t,{provider:z,linkContact:v,refreshContactInfo:m,sendMessage:async(Z,oe)=>{await h.sendMessage(t.id,Z,oe)}});C.onClick(A)},children:[C.icon,C.label]},te)}),e.jsxs("div",{style:{border:`1px solid ${l.line}`,borderRadius:10,background:"#fff",overflow:"hidden"},children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid #fde68a",background:"#fffbeb",fontSize:11,fontWeight:600,color:"#92400e"},children:"Ghi chú nội bộ"}),e.jsx("textarea",{value:S,onChange:C=>$(C.target.value),placeholder:"Nhập ghi chú...",rows:3,style:{display:"block",width:"100%",boxSizing:"border-box",border:0,outline:0,background:"transparent",resize:"none",padding:"8px 10px",font:"inherit",fontSize:12,color:l.ink,lineHeight:1.5}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 10px 6px"},children:[_?e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,fontSize:11,color:"#16a34a"},children:[e.jsx(_e,{size:11,strokeWidth:2.5})," Đã lưu"]}):W?e.jsx("span",{style:{fontSize:11,color:"#ef4444"},children:W}):e.jsx("span",{}),e.jsx("button",{type:"button",onClick:()=>{re()},disabled:!S.trim()||D,style:{padding:"4px 12px",border:0,borderRadius:7,fontSize:12,fontWeight:600,background:S.trim()&&!D?"linear-gradient(135deg,#f59e0b,#fbbf24)":"#e5e7eb",color:S.trim()&&!D?"#fff":"#9ca3af",cursor:S.trim()&&!D?"pointer":"not-allowed"},children:D?"Đang lưu…":"Lưu ghi chú"})]})]})]})]})]})}function Ve({label:t,children:n,sectionKey:i,expanded:o,onToggle:h}){const k=!!h,y=o??!0;return e.jsxs("div",{style:{borderTop:`1px solid ${l.line}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px 6px",fontSize:10,fontWeight:700,letterSpacing:1,color:l.muted,textTransform:"uppercase",cursor:k?"pointer":"default"},onClick:h,children:[e.jsx("span",{children:t}),k&&(y?e.jsx(Xe,{size:12,strokeWidth:2}):e.jsx(St,{size:12,strokeWidth:2}))]}),y&&n]})}function he({label:t,value:n,children:i,valueColor:o,valueMuted:h}){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:l.muted,flexShrink:0,lineHeight:1.4},children:t}),e.jsx("span",{style:{color:o??(h?l.muted:l.ink),textAlign:"right",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",flexWrap:"wrap",gap:4,lineHeight:1.4},children:i??n})]})}function Yt({value:t}){const[n,i]=r.useState(!1);return e.jsx("button",{style:{border:0,background:"none",cursor:"pointer",color:l.muted,padding:2,lineHeight:1},title:"Sao chép",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{i(!0),setTimeout(()=>i(!1),1500)})},"aria-label":"Sao chép ID",children:n?"✓":"⎘"})}function Jt(){return e.jsxs("div",{style:f.empty,children:[e.jsx("div",{style:f.emptyHero,children:e.jsx(zt,{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 jt({name:t,color:n,image:i,provider:o}){return e.jsxs("span",{style:f.avatarWrap,children:[e.jsx(Zt,{name:t,color:n,image:i}),o&&e.jsx("span",{style:f.providerBadge,children:e.jsx(Le,{provider:o})})]})}function Zt({name:t,color:n,image:i}){return e.jsx(Qe,{src:i,fallback:Ie(t),style:{...f.avatar,background:`${n}18`,color:n}})}function Je(){return e.jsx(xt,{size:14,style:f.spinner,"aria-hidden":"true"})}function Ie(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}const _t={livechat:"web"};function Le({provider:t}){const n=r.useContext(et),i=14;if(!t)return null;const o=_t[t]??t;return e.jsx("img",{src:`${n}/static/logos/${o}.avif`,alt:t,width:i,height:i,style:{borderRadius:"50%",objectFit:"cover",display:"block"}})}function Ze(t,n=!1){if(!t)return"";const i=new Date(t);return i.toDateString()===new Date().toDateString()?i.toLocaleTimeString("vi-VN",{hour:"2-digit",minute:"2-digit"}):i.toLocaleDateString("vi-VN",{day:"2-digit",month:"2-digit"})}const f={frame:{display:"grid",gridTemplateRows:"minmax(0, 1fr)",height:620,maxHeight:"calc(100dvh - 220px)",minHeight:0,overflow:"hidden",border:`1px solid ${l.line}`,background:l.white,color:l.ink,boxShadow:"0 18px 50px rgba(31,45,72,.10)"},sidebar:{display:"flex",flexDirection:"column",minWidth:0,minHeight:0,borderRight:`1px solid ${l.line}`,background:l.white},brand:{display:"flex",alignItems:"center",gap:10,padding:"20px 18px 16px"},brandMark:{display:"grid",placeItems:"center",width:32,height:32,borderRadius:10,color:"#fff",fontWeight:800},eyebrow:{display:"block",marginTop:2,fontSize:9,letterSpacing:1.3,color:l.muted},iconButton:{display:"inline-grid",placeItems:"center",width:32,height:32,marginLeft:"auto",border:0,borderRadius:8,background:"transparent",color:l.muted,cursor:"pointer"},search:{display:"flex",alignItems:"center",gap:8,margin:"0 14px 12px",padding:"9px 10px",border:`1px solid ${l.line}`,borderRadius:9,color:l.muted,background:l.surface},clear:{border:0,background:"none",color:l.muted,cursor:"pointer",fontSize:18},listHeader:{display:"flex",alignItems:"center",padding:"10px 18px",borderTop:`1px solid ${l.line}`,borderBottom:`1px solid ${l.line}`,color:l.muted,fontSize:11,fontWeight:700,letterSpacing:.4,textTransform:"uppercase"},conversationList:{overflowY:"auto",flex:1,minHeight:0},row:{display:"flex",width:"100%",gap:11,padding:"16px 14px",border:0,borderBottom:`1px solid ${l.line}`,background:"transparent",textAlign:"left",cursor:"pointer",transition:"background 120ms ease"},avatarWrap:{position:"relative",flex:"0 0 auto",width: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:l.muted,fontSize:12,textAlign:"center"},emptyIcon:{display:"grid",placeItems:"center",width:40,height:40,borderRadius:12,background:l.surface},main:{minWidth:0,minHeight:0,overflow:"hidden",background:l.surface},chat:{display:"flex",flexDirection:"column",height:"100%",minWidth:0,minHeight:0},chatHeader:{flex:"0 0 auto",display:"flex",alignItems:"center",gap:10,padding:"0 16px 0 18px",height:56,borderBottom:`1px solid ${l.line}`,background:l.white},contact:{display:"grid",gap:3,minWidth:0,flex:1},contactName:{fontSize:14,fontWeight:600,color:l.ink,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},contactMeta:{display:"flex",alignItems:"center",gap:5,fontSize:11,color:l.muted},headerActions:{display:"flex",gap:2,marginLeft:"auto"},messageArea:{flex:1,minHeight:0,overflowY:"auto",overscrollBehavior:"contain",padding:"20px clamp(16px,5vw,56px)",background:"linear-gradient(180deg,#f9fbfe 0%,#f4f7fb 100%)"},day:{margin:"0 auto 18px",color:"#a1acbb",fontSize:10,letterSpacing:1.2,fontWeight:700,textAlign:"center"},historyButton:{display:"block",margin:"0 auto 18px",border:`1px solid ${l.line}`,borderRadius:20,padding:"6px 12px",background:l.white,color:l.muted,cursor:"pointer",fontSize:11},messageHint:{display:"flex",justifyContent:"center",alignItems:"center",gap:8,padding:40,color:l.muted,fontSize:12},messageLine:{display:"flex",marginBottom:10},bubbleOut:{maxWidth:"min(70%,480px)",padding:"9px 13px",borderRadius:"14px 14px 3px 14px",boxShadow:"0 2px 5px rgba(30,43,65,.03)",fontSize:14,lineHeight:1.55},bubbleIn:{maxWidth:"min(70%,480px)",padding:"9px 13px",borderRadius:"14px 14px 14px 3px",border:`1px solid ${l.line}`,background:l.surface,boxShadow:"0 2px 5px rgba(30,43,65,.03)",fontSize:14,lineHeight:1.55},error:{padding:"8px 18px",background:"#fff2f0",color:"#b42318",fontSize:12},empty:{display:"grid",placeItems:"center",alignContent:"center",height:"100%",padding:30,textAlign:"center",color:l.muted},emptyHero:{display:"grid",placeItems:"center",width:64,height:64,marginBottom:16,borderRadius:20,background:"#eaf0ff",color:"#5277d7"},state:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,minHeight:180,border:`1px solid ${l.line}`,background:l.white,color:l.muted,fontSize:13},retry:{border:0,borderRadius:7,padding:"7px 10px",background:"#eff4ff",color:"#315dbb",cursor:"pointer"},spinner:{display:"inline-block",width:14,height:14,border:"2px solid #dbe3f3",borderTopColor:"#5277d7",borderRadius:"50%",animation:"channelhub-spin .7s linear infinite"},toolbarBtn:{display:"inline-grid",placeItems:"center",width:26,height:26,border:"1px solid transparent",borderRadius:6,background:"transparent",color:"#9ca3af",cursor:"pointer",padding:0,lineHeight:1},infoPanel:{display:"flex",flexDirection:"column",borderLeft:`1px solid ${l.line}`,background:l.white,minHeight:0,overflow:"hidden"},infoPanelHeader:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 16px 12px",borderBottom:`1px solid ${l.line}`,flex:"0 0 auto"},infoPanelIdentity:{display:"flex",flexDirection:"column",alignItems:"center",padding:"20px 16px 16px",gap:4},ghostButton:{width:"100%",padding:"8px 12px",border:`1px solid ${l.line}`,borderRadius:8,background:"transparent",fontSize:12,cursor:"pointer",textAlign:"center"}},Qt={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"},en={facebook:"facebook",instagram:"instagram",telegram:"telegram",zalo:"zalo",livechat:"web",whatsapp:"web"};function ge({provider:t,apiUrl:n,size:i=40}){const o=Qt[t]??"#f1f5f9",h=en[t],k=n.replace(/\/$/,"");return e.jsx("div",{style:{width:i,height:i,borderRadius:Math.round(i*.28),background:o,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,overflow:"hidden"},children:h?e.jsx("img",{src:`${k}/static/logos/${h}.avif`,alt:t,width:Math.round(i*.65),height:Math.round(i*.65),style:{objectFit:"contain",display:"block"}}):e.jsx("span",{style:{fontSize:Math.round(i*.45),fontWeight:700,color:"#64748b",textTransform:"uppercase"},children:t.slice(0,1)})})}const Be={facebook:"Facebook",zalo:"Zalo OA",instagram:"Instagram",telegram:"Telegram",livechat:"Live Chat",whatsapp:"WhatsApp"},tn={facebook:"#dbeafe",zalo:"#e0f2fe",instagram:"#fce7f3",telegram:"#cffafe",livechat:"#ede9fe",whatsapp:"#dcfce7"};function tt(t){const n=t.metadata;return String(n.displayName??n.pageName??n.username??n.name??t.externalAccountId)}function nn(t){const n=Be[t.provider]??t.provider,i=String(t.metadata.username??t.metadata.pageName??"");return i?`${n} · ${i}`:n}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 dt(){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 Ce(){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 ct(){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 ht(){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 rn(){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 on(){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 ut=!1;function sn(){if(ut||typeof document>"u")return;ut=!0;const t=document.createElement("style");t.textContent="@keyframes ch-spin{to{transform:rotate(360deg)}}",document.head.appendChild(t)}function an({apiUrl:t,token:n,onConnectionChange:i}){const o=t.replace(/\/$/,""),[h,k]=r.useState([]),[y,B]=r.useState(!0),[v,m]=r.useState({name:"list"}),[R,z]=r.useState(null),[E,T]=r.useState(!1),[w,U]=r.useState(""),[S,$]=r.useState(""),[D,K]=r.useState(""),[_,J]=r.useState(""),[W,b]=r.useState(!1),[x,H]=r.useState(!1),q=r.useRef(null);sn();const Q=r.useCallback(async()=>{try{const c=await fetch(`${o}/v1/connections`,{headers:{authorization:`Bearer ${n}`}});if(!c.ok)throw new Error("Không tải được kênh");const M=await c.json();k(M),i==null||i(M)}catch(c){z(c instanceof Error?c.message:"Lỗi tải dữ liệu")}finally{B(!1)}},[o,n,i]);r.useEffect(()=>{Q()},[Q]),r.useEffect(()=>{if(!R)return;const c=setTimeout(()=>z(null),5e3);return()=>clearTimeout(c)},[R]),r.useEffect(()=>()=>{q.current&&window.removeEventListener("message",q.current)},[]);async function re(c,M){if(confirm(`Bạn chắc chắn muốn ngắt kết nối "${M}"?
128
128
 
129
129
  Hành động này không thể hoàn tác.`))try{if(!(await fetch(`${o}/v1/connections/${c}`,{method:"DELETE",headers:{authorization:`Bearer ${n}`}})).ok)throw new Error("Không thể ngắt kết nối");await Q()}catch(F){z(F instanceof Error?F.message:"Lỗi ngắt kết nối")}}async function C(){if(!w.trim()){z("Vui lòng nhập Bot Token");return}if(!/^\d+:[A-Za-z0-9_-]+$/.test(w.trim())){z("Token không đúng định dạng");return}T(!0),z(null);try{const c=await fetch(`${o}/v1/connect/telegram/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({botToken:w.trim(),displayName:S.trim()||void 0})}),M=await c.json();if(!c.ok||!M.connectionId)throw new Error(M.message??"Không thể kết nối Telegram");U(""),$(""),await Q(),m({name:"list"})}catch(c){z(c instanceof Error?c.message:"Lỗi kết nối")}finally{T(!1)}}async function te(){if(!D.trim()){z("Vui lòng nhập tên widget");return}T(!0),z(null);try{const c=_.split(/[\n,]+/).map(ne=>ne.trim()).filter(Boolean),M=await fetch(`${o}/v1/connect/livechat/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({displayName:D.trim(),allowedDomains:c.length?c:void 0})}),F=await M.json();if(!M.ok||!F.connectionId||!F.embedScript)throw new Error(F.message??"Không thể tạo widget");K(""),J(""),await Q(),m({name:"livechat-result",connectionId:F.connectionId,embedScript:F.embedScript,identitySecret:F.identitySecret??"",allowedDomains:F.allowedDomains??[]})}catch(c){z(c instanceof Error?c.message:"Lỗi tạo widget")}finally{T(!1)}}async function X(c){z(null);try{const M=`${o}/static/oauth-popup.html`,F=await fetch(`${o}/v1/connect/${c}/start`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({callbackUrl:M})}),ne=await F.json();if(!F.ok||!ne.authorizationUrl)throw new Error(ne.message??"Không thể bắt đầu kết nối");const se=window.open(ne.authorizationUrl,"channelhub-oauth","width=600,height=700,scrollbars=yes,resizable=yes");m({name:"oauth-waiting",provider:c,popup:se}),q.current&&window.removeEventListener("message",q.current);const ue=P=>{if(P.data){if(P.data.type==="channelhub:oauth-select"){m({name:"oauth-select",provider:P.data.provider,sessionId:String(P.data.sessionId??""),pages:P.data.pages??[],popup:se});return}P.data.type==="channelhub:oauth"&&(window.removeEventListener("message",ue),q.current=null,P.data.status==="active"?(Q(),m({name:"list"})):(z("Kết nối thất bại: "+String(P.data.error??"Không xác định")),m({name:"list"})))}};q.current=ue,window.addEventListener("message",ue)}catch(M){z(M instanceof Error?M.message:"Lỗi kết nối"),m({name:"list"})}}function A(c,M){navigator.clipboard.writeText(c).then(()=>{M==="script"?(b(!0),setTimeout(()=>b(!1),2e3)):(H(!0),setTimeout(()=>H(!1),2e3))})}function Z(){const c=v.name==="oauth-waiting"||v.name==="oauth-select"?v.popup:null;if(c)try{c.close()}catch{}q.current&&(window.removeEventListener("message",q.current),q.current=null),m({name:"add"})}async function oe(c){if(v.name!=="oauth-select")return;const{provider:M,sessionId:F,popup:ne}=v;T(!0),z(null);const se={facebook:`${o}/v1/connect/facebook/select-page`,instagram:`${o}/v1/connect/instagram/select-account`,zalo:`${o}/v1/connect/zalo/select-oa`},ue={facebook:"pageId",instagram:"accountId",zalo:"oaId"};try{const P=await fetch(se[M]??`${o}/v1/connect/${M}/select-page`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({sessionId:F,[ue[M]??"pageId"]:c})}),ae=await P.json();if(!P.ok||!ae.connectionId)throw new Error(ae.message??"Không thể kết nối");if(ne)try{ne.postMessage({type:"channelhub:close-popup"},"*")}catch{}q.current&&(window.removeEventListener("message",q.current),q.current=null),await Q(),m({name:"list"})}catch(P){z(P instanceof Error?P.message:"Lỗi kết nối")}finally{T(!1)}}return e.jsxs("div",{style:d.root,children:[R&&e.jsx("div",{style:d.errorBanner,children:R}),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:y?"Đang tải…":`${h.filter(c=>c.status==="active").length} kênh đang hoạt động`})]})}),e.jsxs("button",{style:d.addBtn,onClick:()=>m({name:"add"}),children:[e.jsx(dt,{}),e.jsx("span",{children:"Thêm kênh"})]})]}),e.jsx("div",{style:d.divider}),e.jsx("div",{style:d.body,children:!y&&h.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(ge,{provider:"livechat",apiUrl:o,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:()=>m({name:"add"}),children:[e.jsx(dt,{}),"Kết nối kênh đầu tiên"]})]}):e.jsx("div",{children:h.map(c=>e.jsx(cn,{conn:c,apiUrl:o,onDisconnect:()=>void re(c.id,tt(c))},c.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:()=>m({name:"list"}),children:e.jsx(Ce,{})}),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:hn.map(c=>e.jsx(un,{provider:c,apiUrl:o,onClick:()=>{c.type==="oauth"?X(c.id):c.id==="telegram"?m({name:"connect-telegram"}):m({name:"connect-livechat"})}},c.id))})})]}),v.name==="connect-telegram"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:d.connectHeader,children:[e.jsx("button",{style:d.backBtn,onClick:()=>m({name:"add"}),children:e.jsx(Ce,{})}),e.jsx(ge,{provider:"telegram",apiUrl:o,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(on,{}),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:w,onChange:c=>U(c.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:S,onChange:c=>$(c.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:()=>m({name:"add"}),children:"Hủy"}),e.jsx("button",{style:d.btnPrimary,disabled:E,onClick:()=>void C(),children:E?"Đ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:()=>m({name:"add"}),children:e.jsx(Ce,{})}),e.jsx(ge,{provider:"livechat",apiUrl:o,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:D,onChange:c=>K(c.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:_,onChange:c=>J(c.target.value),placeholder:`https://myshop.com
130
- 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:()=>m({name:"add"}),children:"Hủy"}),e.jsx("button",{style:d.btnPrimary,disabled:E,onClick:()=>void te(),children:E?"Đ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:()=>m({name:"list"}),children:e.jsx(Ce,{})}),e.jsx(ge,{provider:"livechat",apiUrl:o,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,...W?{background:"#166534",borderColor:"#166534",color:"#bbf7d0"}:{}},onClick:()=>A(v.embedScript,"script"),children:W?e.jsxs(e.Fragment,{children:[e.jsx(ht,{})," Đã sao chép"]}):e.jsxs(e.Fragment,{children:[e.jsx(ct,{})," 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(rn,{}),e.jsx("span",{style:d.secretLabel,children:"Secret:"}),e.jsx("span",{style:d.secretValue,children:v.identitySecret}),e.jsx("button",{onClick:()=>A(v.identitySecret,"secret"),style:{border:"none",background:"transparent",cursor:"pointer",color:x?"#059669":"#ca8a04",padding:2,display:"flex",alignItems:"center"},children:x?e.jsx(ht,{}):e.jsx(ct,{})})]}),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:()=>m({name:"list"}),children:"Về danh sách"}),e.jsx("button",{style:d.btnPrimary,onClick:()=>m({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:Z,children:e.jsx(Ce,{})}),e.jsxs("div",{children:[e.jsxs("div",{style:d.title,children:["Đang xác thực ",Be[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:tn[v.provider]??"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(ge,{provider:v.provider,apiUrl:o,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 ",Be[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(Ge,{done:!0,label:`Đã mở cửa sổ ${Be[v.provider]}`}),e.jsx(Ge,{active:!0,label:"Đang chờ bạn đăng nhập & cấp quyền"}),e.jsx(Ge,{label:"Lưu kết nối & quay về"})]}),e.jsx("button",{style:d.oauthCancel,onClick:Z,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:Z,children:e.jsx(Ce,{})}),e.jsx(ge,{provider:v.provider,apiUrl:o,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 ",Be[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(c=>e.jsxs("button",{disabled:E,onClick:()=>void oe(c.id),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderRadius:12,border:"1.5px solid #e2e8f0",background:"#fff",cursor:E?"not-allowed":"pointer",opacity:E?.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:c.name}),e.jsx("div",{style:{fontSize:11,color:"#94a3b8",fontFamily:"monospace",marginTop:2},children:c.id})]}),e.jsx("span",{style:{fontSize:13,color:"#2563eb",fontWeight:500},children:E?"Đang kết nối…":"Chọn →"})]},c.id))})})]})]})}function ln(t){const n=t.metadata;if(typeof n.pictureUrl=="string")return n.pictureUrl;if(t.provider==="facebook")return`https://graph.facebook.com/${t.externalAccountId}/picture?type=square`;if(t.provider==="instagram"){const i=typeof n.pageId=="string"?n.pageId:null;if(i)return`https://graph.facebook.com/${i}/picture?type=square`}return null}function dn({conn:t,apiUrl:n,size:i=40}){const[o,h]=r.useState(!1),k=ln(t),y=Math.round(i*.28);return k&&!o?e.jsx("img",{src:k,alt:tt(t),referrerPolicy:"no-referrer",onError:()=>h(!0),style:{width:i,height:i,borderRadius:y,objectFit:"cover",flexShrink:0,display:"block"}}):e.jsx(ge,{provider:t.provider,apiUrl:n,size:i})}function cn({conn:t,apiUrl:n,onDisconnect:i}){const[o,h]=r.useState(!1);return e.jsxs("div",{style:d.channelItem,children:[e.jsx(dn,{conn:t,apiUrl:n,size:40}),e.jsxs("div",{style:d.channelInfo,children:[e.jsx("div",{style:d.channelName,children:tt(t)}),e.jsx("div",{style:d.channelMeta,children:nn(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}),e.jsx("button",{style:{...d.disconnectBtn,...o?{background:"#fef2f2",borderColor:"#fca5a5",color:"#dc2626"}:{}},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),onClick:i,children:"Ngắt kết nối"})]})]})}const hn=[{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 un({provider:t,apiUrl:n,onClick:i}){const[o,h]=r.useState(!1);return e.jsxs("div",{style:{...d.providerCard,...o?{background:"#fff",borderColor:"#e2e8f0",boxShadow:"0 2px 8px rgba(0,0,0,.07)",transform:"translateY(-1px)"}:{}},onClick:i,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[e.jsx(ge,{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 Ge({done:t,active:n,label:i}){const o=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:o,flexShrink:0,...n?{boxShadow:"0 0 0 3px rgba(37,99,235,.2)"}:{}}}),i]})}function pn(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}function fn(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 gn({apiUrl:t,token:n,theme:i,locale:o="vi",icon:h,onConversationSelect:k}){const y=(i==null?void 0:i.primaryColor)??"#2563eb",B=typeof h=="function"?h({size:20,color:"currentColor"}):h??e.jsx(it,{size:20,strokeWidth:1.8}),v=r.useRef(new Ne(t,n)),[m,R]=r.useState(!1),[z,E]=r.useState([]),T=r.useRef(null),w=r.useRef(null),U=z.filter(W=>(W.unreadCount??0)>0),S=U.reduce((W,b)=>W+(b.unreadCount??0),0),$=r.useCallback(async()=>{try{const W=await v.current.listConversations();E(W.items)}catch{}},[]);r.useEffect(()=>($(),v.current.connectSSE(b=>{(b==="message.new"||b==="conversation.updated")&&$()})),[$]),r.useEffect(()=>{if(!m)return;const W=b=>{var x,H;(x=T.current)!=null&&x.contains(b.target)||(H=w.current)!=null&&H.contains(b.target)||R(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[m]);const D=async W=>{if(R(!1),k==null||k(W.id,W),(W.unreadCount??0)>0)try{await v.current.markRead(W.id),E(b=>b.map(x=>x.id===W.id?{...x,unreadCount:0}:x))}catch{}},K=o==="en"?`${S} unread message${S!==1?"s":""}`:`${S} tin nhắn chưa đọc`,_=o==="en"?"No unread messages":"Không có tin nhắn mới",J=o==="en"?"Messages":"Tin nhắn";return e.jsxs("div",{style:{position:"relative",display:"inline-block",fontFamily:(i==null?void 0:i.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif"},children:[e.jsxs("button",{ref:T,"aria-label":K,"aria-haspopup":"true","aria-expanded":m,onClick:()=>R(W=>!W),style:{position:"relative",display:"inline-grid",placeItems:"center",width:40,height:40,border:0,borderRadius:"50%",background:m?`${y}18`:"transparent",color:m?y:"#6b7280",cursor:"pointer",transition:"background 150ms ease, color 150ms ease"},children:[B,S>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:S>99?"99+":S})]}),m&&e.jsxs("div",{ref:w,role:"dialog","aria-label":J,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:J}),S>0&&e.jsxs("span",{style:{fontSize:11,fontWeight:600,background:`${y}14`,color:y,borderRadius:999,padding:"2px 8px"},children:[S," ",o==="en"?"unread":"chưa đọc"]})]}),e.jsx("div",{style:{overflowY:"auto",flex:1},children:U.length===0?e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"40px 24px",color:"#9aa5b5"},children:[e.jsx(it,{size:28,strokeWidth:1.5}),e.jsx("span",{style:{fontSize:13},children:_})]}):U.map(W=>e.jsx(xn,{conversation:W,primary:y,apiUrl:t,onSelect:D},W.id))})]})]})}function xn({conversation:t,primary:n,apiUrl:i,onSelect:o}){const[h,k]=r.useState(!1),y=t.contactName??t.providerConversationKey,B=t.unreadCount??0;return e.jsxs("button",{onClick:()=>o(t),onMouseEnter:()=>k(!0),onMouseLeave:()=>k(!1),style:{display:"flex",width:"100%",gap:12,padding:"10px 16px",border:0,borderBottom:"1px solid #f1f5f9",background:h?"#f7f9fc":B>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(Qe,{src:t.contactPictureUrl,fallback:pn(y),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:B>0?700:500,color:"#172033",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,flexShrink:0},children:[e.jsx("time",{style:{fontSize:11,color:"#9aa5b5",whiteSpace:"nowrap"},children:fn(t.lastMessageAt)}),B>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:B>99?"99+":B})]})]}),e.jsxs("span",{style:{display:"block",marginTop:2,fontSize:12,color:B>0?"#374151":"#9aa5b5",fontWeight:B>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.9 loaded");exports.ChannelHubChannels=an;exports.ChannelHubClient=Ne;exports.ChannelHubInbox=Kt;exports.ChannelHubNotificationBell=gn;
130
+ 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:()=>m({name:"add"}),children:"Hủy"}),e.jsx("button",{style:d.btnPrimary,disabled:E,onClick:()=>void te(),children:E?"Đ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:()=>m({name:"list"}),children:e.jsx(Ce,{})}),e.jsx(ge,{provider:"livechat",apiUrl:o,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,...W?{background:"#166534",borderColor:"#166534",color:"#bbf7d0"}:{}},onClick:()=>A(v.embedScript,"script"),children:W?e.jsxs(e.Fragment,{children:[e.jsx(ht,{})," Đã sao chép"]}):e.jsxs(e.Fragment,{children:[e.jsx(ct,{})," 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(rn,{}),e.jsx("span",{style:d.secretLabel,children:"Secret:"}),e.jsx("span",{style:d.secretValue,children:v.identitySecret}),e.jsx("button",{onClick:()=>A(v.identitySecret,"secret"),style:{border:"none",background:"transparent",cursor:"pointer",color:x?"#059669":"#ca8a04",padding:2,display:"flex",alignItems:"center"},children:x?e.jsx(ht,{}):e.jsx(ct,{})})]}),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:()=>m({name:"list"}),children:"Về danh sách"}),e.jsx("button",{style:d.btnPrimary,onClick:()=>m({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:Z,children:e.jsx(Ce,{})}),e.jsxs("div",{children:[e.jsxs("div",{style:d.title,children:["Đang xác thực ",Be[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:tn[v.provider]??"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(ge,{provider:v.provider,apiUrl:o,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 ",Be[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(Ge,{done:!0,label:`Đã mở cửa sổ ${Be[v.provider]}`}),e.jsx(Ge,{active:!0,label:"Đang chờ bạn đăng nhập & cấp quyền"}),e.jsx(Ge,{label:"Lưu kết nối & quay về"})]}),e.jsx("button",{style:d.oauthCancel,onClick:Z,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:Z,children:e.jsx(Ce,{})}),e.jsx(ge,{provider:v.provider,apiUrl:o,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 ",Be[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(c=>e.jsxs("button",{disabled:E,onClick:()=>void oe(c.id),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderRadius:12,border:"1.5px solid #e2e8f0",background:"#fff",cursor:E?"not-allowed":"pointer",opacity:E?.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:c.name}),e.jsx("div",{style:{fontSize:11,color:"#94a3b8",fontFamily:"monospace",marginTop:2},children:c.id})]}),e.jsx("span",{style:{fontSize:13,color:"#2563eb",fontWeight:500},children:E?"Đang kết nối…":"Chọn →"})]},c.id))})})]})]})}function ln(t){const n=t.metadata;if(typeof n.pictureUrl=="string")return n.pictureUrl;if(t.provider==="facebook")return`https://graph.facebook.com/${t.externalAccountId}/picture?type=square`;if(t.provider==="instagram"){const i=typeof n.pageId=="string"?n.pageId:null;if(i)return`https://graph.facebook.com/${i}/picture?type=square`}return null}function dn({conn:t,apiUrl:n,size:i=40}){const[o,h]=r.useState(!1),k=ln(t),y=Math.round(i*.28);return k&&!o?e.jsx("img",{src:k,alt:tt(t),referrerPolicy:"no-referrer",onError:()=>h(!0),style:{width:i,height:i,borderRadius:y,objectFit:"cover",flexShrink:0,display:"block"}}):e.jsx(ge,{provider:t.provider,apiUrl:n,size:i})}function cn({conn:t,apiUrl:n,onDisconnect:i}){const[o,h]=r.useState(!1);return e.jsxs("div",{style:d.channelItem,children:[e.jsx(dn,{conn:t,apiUrl:n,size:40}),e.jsxs("div",{style:d.channelInfo,children:[e.jsx("div",{style:d.channelName,children:tt(t)}),e.jsx("div",{style:d.channelMeta,children:nn(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}),e.jsx("button",{style:{...d.disconnectBtn,...o?{background:"#fef2f2",borderColor:"#fca5a5",color:"#dc2626"}:{}},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),onClick:i,children:"Ngắt kết nối"})]})]})}const hn=[{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 un({provider:t,apiUrl:n,onClick:i}){const[o,h]=r.useState(!1);return e.jsxs("div",{style:{...d.providerCard,...o?{background:"#fff",borderColor:"#e2e8f0",boxShadow:"0 2px 8px rgba(0,0,0,.07)",transform:"translateY(-1px)"}:{}},onClick:i,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[e.jsx(ge,{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 Ge({done:t,active:n,label:i}){const o=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:o,flexShrink:0,...n?{boxShadow:"0 0 0 3px rgba(37,99,235,.2)"}:{}}}),i]})}function pn(t){return t.split(/\s+/).filter(Boolean).slice(-2).map(n=>n[0]).join("").toUpperCase()||"?"}function fn(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 gn({apiUrl:t,token:n,theme:i,locale:o="vi",icon:h,onConversationSelect:k}){const y=(i==null?void 0:i.primaryColor)??"#2563eb",B=typeof h=="function"?h({size:20,color:"currentColor"}):h??e.jsx(it,{size:20,strokeWidth:1.8}),v=r.useRef(new Ne(t,n)),[m,R]=r.useState(!1),[z,E]=r.useState([]),T=r.useRef(null),w=r.useRef(null),U=z.filter(W=>(W.unreadCount??0)>0),S=U.reduce((W,b)=>W+(b.unreadCount??0),0),$=r.useCallback(async()=>{try{const W=await v.current.listConversations();E(W.items)}catch{}},[]);r.useEffect(()=>($(),v.current.connectSSE(b=>{(b==="message.new"||b==="conversation.updated")&&$()})),[$]),r.useEffect(()=>{if(!m)return;const W=b=>{var x,H;(x=T.current)!=null&&x.contains(b.target)||(H=w.current)!=null&&H.contains(b.target)||R(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[m]);const D=async W=>{if(R(!1),k==null||k(W.id,W),(W.unreadCount??0)>0)try{await v.current.markRead(W.id),E(b=>b.map(x=>x.id===W.id?{...x,unreadCount:0}:x))}catch{}},K=o==="en"?`${S} unread message${S!==1?"s":""}`:`${S} tin nhắn chưa đọc`,_=o==="en"?"No unread messages":"Không có tin nhắn mới",J=o==="en"?"Messages":"Tin nhắn";return e.jsxs("div",{style:{position:"relative",display:"inline-block",fontFamily:(i==null?void 0:i.fontFamily)??"Inter, ui-sans-serif, system-ui, sans-serif"},children:[e.jsxs("button",{ref:T,"aria-label":K,"aria-haspopup":"true","aria-expanded":m,onClick:()=>R(W=>!W),style:{position:"relative",display:"inline-grid",placeItems:"center",width:40,height:40,border:0,borderRadius:"50%",background:m?`${y}18`:"transparent",color:m?y:"#6b7280",cursor:"pointer",transition:"background 150ms ease, color 150ms ease"},children:[B,S>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:S>99?"99+":S})]}),m&&e.jsxs("div",{ref:w,role:"dialog","aria-label":J,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:J}),S>0&&e.jsxs("span",{style:{fontSize:11,fontWeight:600,background:`${y}14`,color:y,borderRadius:999,padding:"2px 8px"},children:[S," ",o==="en"?"unread":"chưa đọc"]})]}),e.jsx("div",{style:{overflowY:"auto",flex:1},children:U.length===0?e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"40px 24px",color:"#9aa5b5"},children:[e.jsx(it,{size:28,strokeWidth:1.5}),e.jsx("span",{style:{fontSize:13},children:_})]}):U.map(W=>e.jsx(xn,{conversation:W,primary:y,apiUrl:t,onSelect:D},W.id))})]})]})}function xn({conversation:t,primary:n,apiUrl:i,onSelect:o}){const[h,k]=r.useState(!1),y=t.contactName??t.providerConversationKey,B=t.unreadCount??0;return e.jsxs("button",{onClick:()=>o(t),onMouseEnter:()=>k(!0),onMouseLeave:()=>k(!1),style:{display:"flex",width:"100%",gap:12,padding:"10px 16px",border:0,borderBottom:"1px solid #f1f5f9",background:h?"#f7f9fc":B>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(Qe,{src:t.contactPictureUrl,fallback:pn(y),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:B>0?700:500,color:"#172033",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:5,flexShrink:0},children:[e.jsx("time",{style:{fontSize:11,color:"#9aa5b5",whiteSpace:"nowrap"},children:fn(t.lastMessageAt)}),B>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:B>99?"99+":B})]})]}),e.jsxs("span",{style:{display:"block",marginTop:2,fontSize:12,color:B>0?"#374151":"#9aa5b5",fontWeight:B>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.10 loaded");exports.ChannelHubChannels=an;exports.ChannelHubClient=Ne;exports.ChannelHubInbox=Kt;exports.ChannelHubNotificationBell=gn;
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ var Ht = {
31
31
  * This source code is licensed under the ISC license.
32
32
  * See the LICENSE file in the root directory of this source tree.
33
33
  */
34
- const At = Pe(
34
+ const jt = Pe(
35
35
  ({
36
36
  color: t = "currentColor",
37
37
  size: i = 24,
@@ -67,7 +67,7 @@ const At = Pe(
67
67
  */
68
68
  const Y = (t, i) => {
69
69
  const r = Pe(
70
- ({ className: o, ...h }, S) => et(At, {
70
+ ({ className: o, ...h }, S) => et(jt, {
71
71
  ref: S,
72
72
  iconNode: i,
73
73
  className: Ct(`lucide-${Mt(t)}`, o),
@@ -108,7 +108,7 @@ const nt = Y("ChevronDown", [
108
108
  * This source code is licensed under the ISC license.
109
109
  * See the LICENSE file in the root directory of this source tree.
110
110
  */
111
- const jt = Y("ChevronRight", [
111
+ const At = Y("ChevronRight", [
112
112
  ["path", { d: "m9 18 6-6-6-6", key: "mthhwq" }]
113
113
  ]);
114
114
  /**
@@ -139,7 +139,7 @@ const It = Y("Ellipsis", [
139
139
  * This source code is licensed under the ISC license.
140
140
  * See the LICENSE file in the root directory of this source tree.
141
141
  */
142
- const Ot = Y("Image", [
142
+ const Ut = Y("Image", [
143
143
  ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2", key: "1m3agn" }],
144
144
  ["circle", { cx: "9", cy: "9", r: "2", key: "af1f0g" }],
145
145
  ["path", { d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21", key: "1xmnt7" }]
@@ -150,7 +150,7 @@ const Ot = Y("Image", [
150
150
  * This source code is licensed under the ISC license.
151
151
  * See the LICENSE file in the root directory of this source tree.
152
152
  */
153
- const Ut = Y("Inbox", [
153
+ const Ot = Y("Inbox", [
154
154
  ["polyline", { points: "22 12 16 12 14 15 10 15 8 12 2 12", key: "o97t9d" }],
155
155
  [
156
156
  "path",
@@ -298,7 +298,7 @@ const ft = Y("UserPlus", [
298
298
  * This source code is licensed under the ISC license.
299
299
  * See the LICENSE file in the root directory of this source tree.
300
300
  */
301
- const Ue = Y("X", [
301
+ const Oe = Y("X", [
302
302
  ["path", { d: "M18 6 6 18", key: "1bl5f8" }],
303
303
  ["path", { d: "m6 6 12 12", key: "d8bk6v" }]
304
304
  ]);
@@ -338,7 +338,7 @@ class it {
338
338
  }
339
339
  assignConversation(i, r) {
340
340
  return this.request(`/v1/conversations/${encodeURIComponent(i)}/assignee`, {
341
- method: "PATCH",
341
+ method: "PUT",
342
342
  body: JSON.stringify({ agent: r })
343
343
  });
344
344
  }
@@ -506,9 +506,9 @@ function rt(t) {
506
506
  const i = t.trim().split(/\s+/).filter(Boolean);
507
507
  return i.length <= 2 ? t.trim() : i.slice(-2).join(" ");
508
508
  }
509
- const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConversationId: S, disableAttachments: m, disableNotificationSound: M, hideKeyboardHint: w, locale: v = "vi", extensions: W, currentAgent: T, teamAgents: j, onNewMessage: $, onConversationSelect: C }, D) {
510
- var k, A, K, U, re;
511
- const I = J(new it(i, r)), [L, P] = y([]), [q, te] = y([]), [Q, B] = y(), [x, b] = y(), E = J(void 0), [V, ne] = y(""), [de, z] = y("all"), [oe, Z] = y(null), [O, ee] = y({ provider: "all", unreadOnly: !1 }), [se, c] = y(!1), H = J(null), N = J(null), [ae, ce] = y(null), [ye, F] = y(!0), [he, Se] = y(""), [Me, He] = y(() => !!(W != null && W.length)), [Ae, Ce] = y(280), [ve, Ie] = y(!1), [Ne, me] = y(0), _ = (o == null ? void 0 : o.primaryColor) ?? "#2563eb", ue = $e(() => new Map(q.map((l) => [l.id, l])), [q]), ze = J(null), [Fe, je] = y(0), G = T ?? oe ?? null;
509
+ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConversationId: S, disableAttachments: m, disableNotificationSound: M, hideKeyboardHint: w, locale: v = "vi", extensions: W, currentAgent: T, teamAgents: A, onNewMessage: $, onConversationSelect: C }, D) {
510
+ var k, j, K, O, re;
511
+ const I = J(new it(i, r)), [L, P] = y([]), [q, te] = y([]), [Q, B] = y(), [x, b] = y(), E = J(void 0), [V, ne] = y(""), [de, z] = y("all"), [oe, Z] = y(null), [U, ee] = y({ provider: "all", unreadOnly: !1 }), [se, c] = y(!1), H = J(null), N = J(null), [ae, ce] = y(null), [ye, F] = y(!0), [he, Se] = y(""), [Me, He] = y(() => !!(W != null && W.length)), [je, Ce] = y(280), [ve, Ie] = y(!1), [Ne, me] = y(0), _ = (o == null ? void 0 : o.primaryColor) ?? "#2563eb", ue = $e(() => new Map(q.map((l) => [l.id, l])), [q]), ze = J(null), [Fe, Ae] = y(0), G = T ?? oe ?? null;
512
512
  X(() => {
513
513
  I.current = new it(i, r), T || I.current.getSessionMe().then((l) => {
514
514
  l != null && l.agent && Z(l.agent);
@@ -519,12 +519,12 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
519
519
  var p;
520
520
  const l = /* @__PURE__ */ new Map();
521
521
  G != null && G.id && l.set(G.id, G);
522
- for (const u of j ?? [])
522
+ for (const u of A ?? [])
523
523
  u != null && u.id && !l.has(u.id) && l.set(u.id, u);
524
524
  for (const u of L)
525
525
  (p = u.assignedAgent) != null && p.id && !l.has(u.assignedAgent.id) && l.set(u.assignedAgent.id, u.assignedAgent);
526
526
  return [...l.values()];
527
- }, [G, j, L]), qe = we(async (l, p) => {
527
+ }, [G, A, L]), qe = we(async (l, p) => {
528
528
  P((u) => u.map((R) => R.id === l.id ? { ...R, assignedAgent: p } : R)), b((u) => u && u.id === l.id ? { ...u, assignedAgent: p } : u), me((u) => u + 1);
529
529
  try {
530
530
  const u = await I.current.assignConversation(l.id, p);
@@ -548,7 +548,7 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
548
548
  return l;
549
549
  }, [L, ue]);
550
550
  function Ze(l) {
551
- const p = l.clientX, u = Ae;
551
+ const p = l.clientX, u = je;
552
552
  Ie(!0), document.body.style.cursor = "col-resize", document.body.style.userSelect = "none";
553
553
  function R(We) {
554
554
  const Ee = Math.max(200, Math.min(480, u + (p - We.clientX)));
@@ -583,7 +583,7 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
583
583
  }
584
584
  $ == null || $(le || E.current || "");
585
585
  }
586
- } else p === "message.status_updated" && je((R) => R + 1);
586
+ } else p === "message.status_updated" && Ae((R) => R + 1);
587
587
  })), [pe, $]), X(() => {
588
588
  E.current = x == null ? void 0 : x.id;
589
589
  }, [x]), X(() => {
@@ -611,10 +611,10 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
611
611
  if (!G || ((Ee = p.assignedAgent) == null ? void 0 : Ee.id) !== G.id) return !1;
612
612
  } else if (de === "unassigned" && p.assignedAgent)
613
613
  return !1;
614
- const u = `${p.contactName ?? ""} ${p.subject ?? ""} ${p.providerConversationKey} ${((Xe = p.assignedAgent) == null ? void 0 : Xe.name) ?? ""}`.toLowerCase(), R = ((Ye = ue.get(p.connectionId)) == null ? void 0 : Ye.provider) ?? "unknown", le = O.provider === "all" || R === O.provider, We = !O.unreadOnly || (p.unreadCount ?? 0) > 0;
614
+ const u = `${p.contactName ?? ""} ${p.subject ?? ""} ${p.providerConversationKey} ${((Xe = p.assignedAgent) == null ? void 0 : Xe.name) ?? ""}`.toLowerCase(), R = ((Ye = ue.get(p.connectionId)) == null ? void 0 : Ye.provider) ?? "unknown", le = U.provider === "all" || R === U.provider, We = !U.unreadOnly || (p.unreadCount ?? 0) > 0;
615
615
  return le && We && (!l || u.includes(l));
616
616
  });
617
- }, [L, ue, O, V, de, G]), Te = O.provider !== "all" || O.unreadOnly, a = v === "en" ? {
617
+ }, [L, ue, U, V, de, G]), Te = U.provider !== "all" || U.unreadOnly, a = v === "en" ? {
618
618
  today: "TODAY",
619
619
  loadOlder: "↑ Load older messages",
620
620
  loading: "Loading messages…",
@@ -648,7 +648,7 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
648
648
  ...h ? { maxHeight: "none" } : {},
649
649
  fontFamily: (o == null ? void 0 : o.fontFamily) ?? "Inter, ui-sans-serif, system-ui, sans-serif",
650
650
  borderRadius: (o == null ? void 0 : o.borderRadius) ?? "16px",
651
- gridTemplateColumns: Me ? `minmax(260px, 300px) minmax(0, 1fr) ${Ae}px` : "minmax(260px, 300px) minmax(0, 1fr)",
651
+ gridTemplateColumns: Me ? `minmax(260px, 300px) minmax(0, 1fr) ${je}px` : "minmax(260px, 300px) minmax(0, 1fr)",
652
652
  transition: ve ? "none" : "grid-template-columns 220ms ease"
653
653
  };
654
654
  return ye ? /* @__PURE__ */ n("div", { style: { ...f.state, borderRadius: (o == null ? void 0 : o.borderRadius) ?? "16px" }, children: [
@@ -669,10 +669,10 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
669
669
  }, children: [
670
670
  /* @__PURE__ */ n("aside", { style: f.sidebar, children: [
671
671
  /* @__PURE__ */ n("div", { style: f.brand, children: [
672
- /* @__PURE__ */ e("div", { style: { ...f.brandMark, background: _, overflow: "hidden", padding: 0 }, children: (k = o == null ? void 0 : o.branding) != null && k.logoUrl ? /* @__PURE__ */ e("img", { src: o.branding.logoUrl, alt: "", style: { width: "100%", height: "100%", objectFit: "cover" } }) : ((A = o == null ? void 0 : o.branding) == null ? void 0 : A.mark) ?? "C" }),
672
+ /* @__PURE__ */ e("div", { style: { ...f.brandMark, background: _, overflow: "hidden", padding: 0 }, children: (k = o == null ? void 0 : o.branding) != null && k.logoUrl ? /* @__PURE__ */ e("img", { src: o.branding.logoUrl, alt: "", style: { width: "100%", height: "100%", objectFit: "cover" } }) : ((j = o == null ? void 0 : o.branding) == null ? void 0 : j.mark) ?? "C" }),
673
673
  /* @__PURE__ */ n("div", { children: [
674
674
  /* @__PURE__ */ e("strong", { children: ((K = o == null ? void 0 : o.branding) == null ? void 0 : K.name) ?? "Hộp thư" }),
675
- !((U = o == null ? void 0 : o.branding) != null && U.name) && /* @__PURE__ */ e("span", { style: f.eyebrow, children: "CHANNELHUB" })
675
+ !((O = o == null ? void 0 : o.branding) != null && O.name) && /* @__PURE__ */ e("span", { style: f.eyebrow, children: "CHANNELHUB" })
676
676
  ] }),
677
677
  /* @__PURE__ */ e(Xt, { "aria-label": "Tùy chọn", style: f.iconButton, children: /* @__PURE__ */ e(It, { size: 16, strokeWidth: 2 }) })
678
678
  ] }),
@@ -740,14 +740,14 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
740
740
  }
741
741
  ),
742
742
  Te && /* @__PURE__ */ n("div", { style: { display: "flex", gap: 4, flexWrap: "wrap", padding: "0 14px 8px" }, children: [
743
- O.provider !== "all" && /* @__PURE__ */ n("span", { style: { display: "inline-flex", alignItems: "center", gap: 4, background: "#eef2ff", color: _, borderRadius: 6, fontSize: 11, padding: "2px 8px", fontWeight: 500 }, children: [
744
- /* @__PURE__ */ e(De, { provider: O.provider }),
745
- yt(O.provider),
746
- /* @__PURE__ */ e("button", { style: { border: 0, background: "none", cursor: "pointer", color: _, padding: 0, lineHeight: 1, display: "flex" }, onClick: () => ee((l) => ({ ...l, provider: "all" })), "aria-label": "Xóa filter kênh", children: /* @__PURE__ */ e(Ue, { size: 10 }) })
743
+ U.provider !== "all" && /* @__PURE__ */ n("span", { style: { display: "inline-flex", alignItems: "center", gap: 4, background: "#eef2ff", color: _, borderRadius: 6, fontSize: 11, padding: "2px 8px", fontWeight: 500 }, children: [
744
+ /* @__PURE__ */ e(De, { provider: U.provider }),
745
+ yt(U.provider),
746
+ /* @__PURE__ */ e("button", { style: { border: 0, background: "none", cursor: "pointer", color: _, padding: 0, lineHeight: 1, display: "flex" }, onClick: () => ee((l) => ({ ...l, provider: "all" })), "aria-label": "Xóa filter kênh", children: /* @__PURE__ */ e(Oe, { size: 10 }) })
747
747
  ] }),
748
- O.unreadOnly && /* @__PURE__ */ n("span", { style: { display: "inline-flex", alignItems: "center", gap: 4, background: "#eef2ff", color: _, borderRadius: 6, fontSize: 11, padding: "2px 8px", fontWeight: 500 }, children: [
748
+ U.unreadOnly && /* @__PURE__ */ n("span", { style: { display: "inline-flex", alignItems: "center", gap: 4, background: "#eef2ff", color: _, borderRadius: 6, fontSize: 11, padding: "2px 8px", fontWeight: 500 }, children: [
749
749
  a.unreadOnly,
750
- /* @__PURE__ */ e("button", { style: { border: 0, background: "none", cursor: "pointer", color: _, padding: 0, lineHeight: 1, display: "flex" }, onClick: () => ee((l) => ({ ...l, unreadOnly: !1 })), "aria-label": "Xóa filter chưa đọc", children: /* @__PURE__ */ e(Ue, { size: 10 }) })
750
+ /* @__PURE__ */ e("button", { style: { border: 0, background: "none", cursor: "pointer", color: _, padding: 0, lineHeight: 1, display: "flex" }, onClick: () => ee((l) => ({ ...l, unreadOnly: !1 })), "aria-label": "Xóa filter chưa đọc", children: /* @__PURE__ */ e(Oe, { size: 10 }) })
751
751
  ] }),
752
752
  /* @__PURE__ */ e("button", { style: { border: 0, background: "none", cursor: "pointer", color: d.muted, fontSize: 11, padding: "2px 4px" }, onClick: () => ee({ provider: "all", unreadOnly: !1 }), children: "Xóa tất cả" })
753
753
  ] }),
@@ -782,8 +782,8 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
782
782
  style: { position: "fixed", top: ae.top, left: ae.left, zIndex: 9999, background: d.white, border: `1px solid ${d.line}`, borderRadius: 10, padding: "12px 14px", boxShadow: "0 8px 24px rgba(23,32,51,.14)", minWidth: 210, fontFamily: (o == null ? void 0 : o.fontFamily) ?? "Inter, ui-sans-serif, system-ui, sans-serif", fontSize: 13 },
783
783
  children: [
784
784
  /* @__PURE__ */ e("div", { style: { fontSize: 10, fontWeight: 700, color: d.muted, letterSpacing: 1, textTransform: "uppercase", marginBottom: 8 }, children: "Kênh" }),
785
- ["all", ...Ve].map((l) => /* @__PURE__ */ n("label", { style: { display: "flex", alignItems: "center", gap: 8, padding: "5px 6px", cursor: "pointer", borderRadius: 6, background: O.provider === l ? `${_}0f` : "transparent" }, children: [
786
- /* @__PURE__ */ e("input", { type: "radio", name: "provider-filter", checked: O.provider === l, onChange: () => ee((p) => ({ ...p, provider: l })), style: { accentColor: _ } }),
785
+ ["all", ...Ve].map((l) => /* @__PURE__ */ n("label", { style: { display: "flex", alignItems: "center", gap: 8, padding: "5px 6px", cursor: "pointer", borderRadius: 6, background: U.provider === l ? `${_}0f` : "transparent" }, children: [
786
+ /* @__PURE__ */ e("input", { type: "radio", name: "provider-filter", checked: U.provider === l, onChange: () => ee((p) => ({ ...p, provider: l })), style: { accentColor: _ } }),
787
787
  l === "all" ? /* @__PURE__ */ n("span", { style: { color: d.ink }, children: [
788
788
  a.all,
789
789
  " (",
@@ -801,8 +801,8 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
801
801
  ] })
802
802
  ] }, l)),
803
803
  /* @__PURE__ */ e("div", { style: { borderTop: `1px solid ${d.line}`, margin: "8px 0 6px" } }),
804
- /* @__PURE__ */ n("label", { style: { display: "flex", alignItems: "center", gap: 8, padding: "5px 6px", cursor: "pointer", borderRadius: 6, background: O.unreadOnly ? `${_}0f` : "transparent" }, children: [
805
- /* @__PURE__ */ e("input", { type: "checkbox", checked: O.unreadOnly, onChange: (l) => ee((p) => ({ ...p, unreadOnly: l.target.checked })), style: { accentColor: _ } }),
804
+ /* @__PURE__ */ n("label", { style: { display: "flex", alignItems: "center", gap: 8, padding: "5px 6px", cursor: "pointer", borderRadius: 6, background: U.unreadOnly ? `${_}0f` : "transparent" }, children: [
805
+ /* @__PURE__ */ e("input", { type: "checkbox", checked: U.unreadOnly, onChange: (l) => ee((p) => ({ ...p, unreadOnly: l.target.checked })), style: { accentColor: _ } }),
806
806
  /* @__PURE__ */ e("span", { style: { color: d.ink }, children: a.unreadOnly })
807
807
  ] })
808
808
  ]
@@ -871,7 +871,7 @@ const Wn = Pe(function({ apiUrl: i, token: r, theme: o, height: h, defaultConver
871
871
  ] }) }) });
872
872
  });
873
873
  function nn({ conversation: t, provider: i, selected: r, primary: o, currentAgent: h, onSelect: S }) {
874
- const [m, M] = y(!1), w = t.contactName ?? t.subject ?? t.providerConversationKey, v = t.unreadCount ?? 0, W = t.lastMessageText ?? "", T = t.lastMessageDirection === "outbound" ? "Bạn: " : "", j = W.length > 60 ? W.slice(0, 60) + "…" : W, $ = W ? T + j : "", C = t.assignedAgent ?? null, D = !!(C && h && C.id === h.id);
874
+ const [m, M] = y(!1), w = t.contactName ?? t.subject ?? t.providerConversationKey, v = t.unreadCount ?? 0, W = t.lastMessageText ?? "", T = t.lastMessageDirection === "outbound" ? "Bạn: " : "", A = W.length > 60 ? W.slice(0, 60) + "…" : W, $ = W ? T + A : "", C = t.assignedAgent ?? null, D = !!(C && h && C.id === h.id);
875
875
  let I = "transparent";
876
876
  r ? I = "#eef2ff" : m ? I = "#f7f9fc" : v > 0 && (I = "#f0f4ff");
877
877
  const L = {
@@ -961,23 +961,23 @@ function nn({ conversation: t, provider: i, selected: r, primary: o, currentAgen
961
961
  }
962
962
  );
963
963
  }
964
- function rn({ conversation: t, provider: i, connection: r, client: o, primary: h, error: S, onRegisterAppend: m, refreshKey: M, infoOpen: w, onToggleInfo: v, t: W, disableAttachments: T, hideKeyboardHint: j, extensions: $, currentAgent: C, teamAgents: D, onAssignAgent: I, onLinkContact: L, onRefreshContactInfo: P }) {
964
+ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h, error: S, onRegisterAppend: m, refreshKey: M, infoOpen: w, onToggleInfo: v, t: W, disableAttachments: T, hideKeyboardHint: A, extensions: $, currentAgent: C, teamAgents: D, onAssignAgent: I, onLinkContact: L, onRefreshContactInfo: P }) {
965
965
  var Re, Te;
966
- const [q, te] = y([]), [Q, B] = y(), [x, b] = y(""), [E, V] = y(!0), [ne, de] = y(!1), [z, oe] = y(""), Z = J(null), O = t.contactName ?? t.subject ?? t.providerConversationKey, ee = J(null), se = J(null), [c, H] = y(null), [N, ae] = y(!1), [ce, ye] = y(!1), [F, he] = y(!1), [Se, Me] = y(0), He = J(null), Ae = J(null), Ce = J(null), [ve, Ie] = y(!1), [Ne, me] = y(""), [_, ue] = y([]), ze = J(null), Fe = J(null), [je, G] = y(!1), Ke = J(null), qe = J(null);
966
+ const [q, te] = y([]), [Q, B] = y(), [x, b] = y(""), [E, V] = y(!0), [ne, de] = y(!1), [z, oe] = y(""), Z = J(null), U = t.contactName ?? t.subject ?? t.providerConversationKey, ee = J(null), se = J(null), [c, H] = y(null), [N, ae] = y(!1), [ce, ye] = y(!1), [F, he] = y(!1), [Se, Me] = y(0), He = J(null), je = J(null), Ce = J(null), [ve, Ie] = y(!1), [Ne, me] = y(""), [_, ue] = y([]), ze = J(null), Fe = J(null), [Ae, G] = y(!1), Ke = J(null), qe = J(null);
967
967
  X(() => {
968
- if (!je) return;
968
+ if (!Ae) return;
969
969
  function a(g) {
970
- var k, A;
971
- (k = Ke.current) != null && k.contains(g.target) || (A = qe.current) != null && A.contains(g.target) || G(!1);
970
+ var k, j;
971
+ (k = Ke.current) != null && k.contains(g.target) || (j = qe.current) != null && j.contains(g.target) || G(!1);
972
972
  }
973
973
  return document.addEventListener("mousedown", a), () => document.removeEventListener("mousedown", a);
974
- }, [je]), X(() => () => {
974
+ }, [Ae]), X(() => () => {
975
975
  c != null && c.objectUrl && URL.revokeObjectURL(c.objectUrl);
976
976
  }, [c == null ? void 0 : c.objectUrl]), X(() => {
977
977
  if (!F) return;
978
978
  function a(g) {
979
- var k, A;
980
- (k = Ae.current) != null && k.contains(g.target) || (A = He.current) != null && A.contains(g.target) || he(!1);
979
+ var k, j;
980
+ (k = je.current) != null && k.contains(g.target) || (j = He.current) != null && j.contains(g.target) || he(!1);
981
981
  }
982
982
  return document.addEventListener("mousedown", a), () => document.removeEventListener("mousedown", a);
983
983
  }, [F]), X(() => {
@@ -986,8 +986,8 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
986
986
  }, [o]), X(() => {
987
987
  if (!ve) return;
988
988
  function a(g) {
989
- var k, A;
990
- (k = Fe.current) != null && k.contains(g.target) || (A = ze.current) != null && A.contains(g.target) || Ie(!1);
989
+ var k, j;
990
+ (k = Fe.current) != null && k.contains(g.target) || (j = ze.current) != null && j.contains(g.target) || Ie(!1);
991
991
  }
992
992
  return document.addEventListener("mousedown", a), () => document.removeEventListener("mousedown", a);
993
993
  }, [ve]);
@@ -995,7 +995,7 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
995
995
  g || (ke.current = !a);
996
996
  try {
997
997
  const k = await o.listMessages(t.id, a);
998
- te((A) => a ? [...k.items, ...A] : k.items), B(k.nextCursor);
998
+ te((j) => a ? [...k.items, ...j] : k.items), B(k.nextCursor);
999
999
  } catch (k) {
1000
1000
  oe(k instanceof Error ? k.message : "Không tải được tin nhắn");
1001
1001
  } finally {
@@ -1017,8 +1017,8 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1017
1017
  m == null || m(null);
1018
1018
  }), [m]);
1019
1019
  async function Ve(a) {
1020
- var A;
1021
- const g = (A = a.target.files) == null ? void 0 : A[0];
1020
+ var j;
1021
+ const g = (j = a.target.files) == null ? void 0 : j[0];
1022
1022
  if (!g) return;
1023
1023
  a.target.value = "";
1024
1024
  const k = URL.createObjectURL(g);
@@ -1035,11 +1035,11 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1035
1035
  const g = x.trim(), k = c != null && c.url ? [{ url: c.url, mimeType: c.mimeType ?? "application/octet-stream", type: c.attachmentType }] : [];
1036
1036
  if (!g && !k.length || ne) return;
1037
1037
  de(!0), oe(""), !t.assignedAgent && C && I(C);
1038
- const A = `optimistic-${Date.now()}`;
1038
+ const j = `optimistic-${Date.now()}`;
1039
1039
  C && (ke.current = !0, te((K) => [
1040
1040
  ...K,
1041
1041
  {
1042
- id: A,
1042
+ id: j,
1043
1043
  direction: "outbound",
1044
1044
  status: "sending",
1045
1045
  text: g || void 0,
@@ -1051,11 +1051,11 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1051
1051
  try {
1052
1052
  await o.sendMessage(t.id, g || void 0, k.length ? k : void 0), c != null && c.objectUrl && URL.revokeObjectURL(c.objectUrl), b(""), H(null), await fe(), C && te((K) => {
1053
1053
  var l, p;
1054
- const U = K.filter((u) => u.id !== A), re = U.length - 1;
1055
- return re >= 0 && ((l = U[re]) == null ? void 0 : l.direction) === "outbound" && !((p = U[re]) != null && p.senderAgent) ? U.map((u, R) => R === re ? { ...u, senderAgent: C } : u) : U;
1054
+ const O = K.filter((u) => u.id !== j), re = O.length - 1;
1055
+ return re >= 0 && ((l = O[re]) == null ? void 0 : l.direction) === "outbound" && !((p = O[re]) != null && p.senderAgent) ? O.map((u, R) => R === re ? { ...u, senderAgent: C } : u) : O;
1056
1056
  });
1057
1057
  } catch (K) {
1058
- te((U) => U.filter((re) => re.id !== A)), oe(K instanceof Error ? K.message : "Không gửi được tin nhắn");
1058
+ te((O) => O.filter((re) => re.id !== j)), oe(K instanceof Error ? K.message : "Không gửi được tin nhắn");
1059
1059
  } finally {
1060
1060
  de(!1);
1061
1061
  }
@@ -1063,10 +1063,10 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1063
1063
  function Ze(a) {
1064
1064
  const g = Ce.current;
1065
1065
  if (!g) {
1066
- b((U) => U + a), he(!1);
1066
+ b((O) => O + a), he(!1);
1067
1067
  return;
1068
1068
  }
1069
- const k = g.selectionStart ?? x.length, A = g.selectionEnd ?? x.length, K = x.slice(0, k) + a + x.slice(A);
1069
+ const k = g.selectionStart ?? x.length, j = g.selectionEnd ?? x.length, K = x.slice(0, k) + a + x.slice(j);
1070
1070
  b(K), he(!1), requestAnimationFrame(() => {
1071
1071
  g.focus(), g.selectionStart = g.selectionEnd = k + a.length;
1072
1072
  });
@@ -1080,9 +1080,9 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1080
1080
  const be = !ne && (x.trim().length > 0 || (c == null ? void 0 : c.url) != null && !c.uploading);
1081
1081
  return /* @__PURE__ */ n("section", { style: f.chat, children: [
1082
1082
  /* @__PURE__ */ n("header", { style: f.chatHeader, children: [
1083
- /* @__PURE__ */ e($t, { name: O, color: h, image: t.contactPictureUrl, provider: i }),
1083
+ /* @__PURE__ */ e($t, { name: U, color: h, image: t.contactPictureUrl, provider: i }),
1084
1084
  /* @__PURE__ */ n("div", { style: f.contact, children: [
1085
- /* @__PURE__ */ e("strong", { style: f.contactName, children: O }),
1085
+ /* @__PURE__ */ e("strong", { style: f.contactName, children: U }),
1086
1086
  /* @__PURE__ */ e("span", { style: f.contactMeta, children: en(r) ?? Wt(i) })
1087
1087
  ] }),
1088
1088
  /* @__PURE__ */ n("div", { style: { ...f.headerActions, alignItems: "center", gap: 6 }, children: [
@@ -1181,7 +1181,7 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1181
1181
  ]
1182
1182
  }
1183
1183
  ),
1184
- je && /* @__PURE__ */ n(
1184
+ Ae && /* @__PURE__ */ n(
1185
1185
  "div",
1186
1186
  {
1187
1187
  ref: qe,
@@ -1314,7 +1314,7 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1314
1314
  textAlign: "left"
1315
1315
  },
1316
1316
  children: [
1317
- /* @__PURE__ */ e(Ue, { size: 13 }),
1317
+ /* @__PURE__ */ e(Oe, { size: 13 }),
1318
1318
  /* @__PURE__ */ e("span", { children: "Bỏ phân công (Chưa có người nhận)" })
1319
1319
  ]
1320
1320
  }
@@ -1350,7 +1350,7 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1350
1350
  ] }),
1351
1351
  !E && !q.length && /* @__PURE__ */ e("div", { style: f.messageHint, children: W.noMessages }),
1352
1352
  q.map((a, g) => {
1353
- const k = ($ == null ? void 0 : $.flatMap((re) => re.messageEnrichments ?? [])) ?? [], A = a.direction === "inbound" && k.length > 0 && g >= q.length - 15, K = A ? Je(t, {
1353
+ const k = ($ == null ? void 0 : $.flatMap((re) => re.messageEnrichments ?? [])) ?? [], j = a.direction === "inbound" && k.length > 0 && g >= q.length - 15, K = j ? Je(t, {
1354
1354
  provider: i,
1355
1355
  recentMessages: q.slice(-10),
1356
1356
  linkContact: L,
@@ -1358,14 +1358,14 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1358
1358
  sendMessage: async (re, l) => {
1359
1359
  await o.sendMessage(t.id, re, l), await fe(void 0, !0);
1360
1360
  }
1361
- }) : null, U = A && K ? k.map((re, l) => {
1361
+ }) : null, O = j && K ? k.map((re, l) => {
1362
1362
  var u;
1363
1363
  const p = (u = a.text) == null ? void 0 : u.match(re.pattern);
1364
1364
  return p ? /* @__PURE__ */ e(_t, { children: re.render(p, K, a) }, `${a.id}-${l}`) : null;
1365
1365
  }).filter(Boolean) : [];
1366
1366
  return /* @__PURE__ */ n("div", { children: [
1367
1367
  /* @__PURE__ */ e(on, { message: a, primary: h }),
1368
- U.length > 0 && /* @__PURE__ */ e("div", { style: { maxWidth: "min(70%, 480px)", marginTop: -4, marginBottom: 10, display: "flex", flexDirection: "column", gap: 6 }, children: U })
1368
+ O.length > 0 && /* @__PURE__ */ e("div", { style: { maxWidth: "min(70%, 480px)", marginTop: -4, marginBottom: 10, display: "flex", flexDirection: "column", gap: 6 }, children: O })
1369
1369
  ] }, a.id);
1370
1370
  })
1371
1371
  ] }),
@@ -1493,11 +1493,11 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1493
1493
  type: "button",
1494
1494
  onClick: () => pe(k.content),
1495
1495
  style: { display: "block", width: "100%", textAlign: "left", border: 0, borderBottom: `1px solid ${d.line}`, background: "transparent", padding: "9px 12px", cursor: "pointer", fontFamily: "inherit" },
1496
- onMouseEnter: (A) => {
1497
- A.currentTarget.style.background = "#f7f9fc";
1496
+ onMouseEnter: (j) => {
1497
+ j.currentTarget.style.background = "#f7f9fc";
1498
1498
  },
1499
- onMouseLeave: (A) => {
1500
- A.currentTarget.style.background = "transparent";
1499
+ onMouseLeave: (j) => {
1500
+ j.currentTarget.style.background = "transparent";
1501
1501
  },
1502
1502
  children: [
1503
1503
  /* @__PURE__ */ n("div", { style: { display: "flex", alignItems: "center", gap: 6, marginBottom: 2 }, children: [
@@ -1533,7 +1533,7 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1533
1533
  /* @__PURE__ */ e(
1534
1534
  "button",
1535
1535
  {
1536
- ref: Ae,
1536
+ ref: je,
1537
1537
  type: "button",
1538
1538
  title: "Chèn emoji",
1539
1539
  onClick: () => he((a) => !a),
@@ -1544,7 +1544,7 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1544
1544
  !T && /* @__PURE__ */ e("button", { type: "button", title: "Gửi ảnh / video", "aria-label": "Gửi ảnh hoặc video", style: f.toolbarBtn, onClick: () => {
1545
1545
  var a;
1546
1546
  return (a = ee.current) == null ? void 0 : a.click();
1547
- }, children: /* @__PURE__ */ e(Ot, { size: 13, strokeWidth: 2 }) }),
1547
+ }, children: /* @__PURE__ */ e(Ut, { size: 13, strokeWidth: 2 }) }),
1548
1548
  !T && /* @__PURE__ */ e("button", { type: "button", title: "Gửi tệp đính kèm", "aria-label": "Gửi tệp đính kèm", style: f.toolbarBtn, onClick: () => {
1549
1549
  var a;
1550
1550
  return (a = se.current) == null ? void 0 : a.click();
@@ -1613,21 +1613,21 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1613
1613
  } : f.toolbarBtn,
1614
1614
  onClick: () => {
1615
1615
  const k = (K) => {
1616
- b((U) => U && !U.endsWith(" ") && !U.endsWith(`
1617
- `) ? `${U} ${K}` : `${U}${K}`), requestAnimationFrame(() => {
1618
- var U;
1619
- return (U = Ce.current) == null ? void 0 : U.focus();
1616
+ b((O) => O && !O.endsWith(" ") && !O.endsWith(`
1617
+ `) ? `${O} ${K}` : `${O}${K}`), requestAnimationFrame(() => {
1618
+ var O;
1619
+ return (O = Ce.current) == null ? void 0 : O.focus();
1620
1620
  });
1621
- }, A = Je(t, {
1621
+ }, j = Je(t, {
1622
1622
  provider: i,
1623
1623
  recentMessages: q.slice(-10),
1624
1624
  linkContact: L,
1625
1625
  refreshContactInfo: P,
1626
- sendMessage: async (K, U) => {
1627
- await o.sendMessage(t.id, K, U), await fe(void 0, !0);
1626
+ sendMessage: async (K, O) => {
1627
+ await o.sendMessage(t.id, K, O), await fe(void 0, !0);
1628
1628
  }
1629
1629
  });
1630
- a.onClick({ ...A, insertText: k });
1630
+ a.onClick({ ...j, insertText: k });
1631
1631
  },
1632
1632
  children: [
1633
1633
  a.icon,
@@ -1680,7 +1680,7 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1680
1680
  "/1000"
1681
1681
  ] }),
1682
1682
  /* @__PURE__ */ n("div", { style: { display: "flex", alignItems: "center", gap: 6 }, children: [
1683
- !j && /* @__PURE__ */ e("span", { style: { fontSize: 10, color: "#9ca3af" }, children: "↵ Gửi · ⇧↵ Xuống dòng" }),
1683
+ !A && /* @__PURE__ */ e("span", { style: { fontSize: 10, color: "#9ca3af" }, children: "↵ Gửi · ⇧↵ Xuống dòng" }),
1684
1684
  /* @__PURE__ */ n(
1685
1685
  "button",
1686
1686
  {
@@ -1716,7 +1716,7 @@ function rn({ conversation: t, provider: i, connection: r, client: o, primary: h
1716
1716
  }
1717
1717
  function on({ message: t, primary: i }) {
1718
1718
  var q, te, Q, B, x;
1719
- const r = tt(st), o = tt(Tt), h = (b) => b.startsWith("/v1/media/proxy") ? `${r}${b}&tok=${encodeURIComponent(o)}` : b, S = t.direction === "outbound", m = ((q = t.attachments) == null ? void 0 : q.filter((b) => b.type === "image")) ?? [], M = ((te = t.attachments) == null ? void 0 : te.filter((b) => b.type === "sticker")) ?? [], w = ((Q = t.attachments) == null ? void 0 : Q.filter((b) => b.type === "video")) ?? [], v = ((B = t.attachments) == null ? void 0 : B.filter((b) => b.type === "audio")) ?? [], W = ((x = t.attachments) == null ? void 0 : x.filter((b) => b.type === "file")) ?? [], [T, j] = y(null), $ = S ? "flex-end" : "flex-start", C = S ? t.senderAgent ?? null : null, D = /* @__PURE__ */ n("div", { style: { display: "flex", alignItems: "center", justifyContent: S ? "flex-end" : "flex-start", gap: 5, marginTop: 4, fontSize: 10, opacity: 0.78, letterSpacing: 0.2, userSelect: "none" }, children: [
1719
+ const r = tt(st), o = tt(Tt), h = (b) => b.startsWith("/v1/media/proxy") ? `${r}${b}&tok=${encodeURIComponent(o)}` : b, S = t.direction === "outbound", m = ((q = t.attachments) == null ? void 0 : q.filter((b) => b.type === "image")) ?? [], M = ((te = t.attachments) == null ? void 0 : te.filter((b) => b.type === "sticker")) ?? [], w = ((Q = t.attachments) == null ? void 0 : Q.filter((b) => b.type === "video")) ?? [], v = ((B = t.attachments) == null ? void 0 : B.filter((b) => b.type === "audio")) ?? [], W = ((x = t.attachments) == null ? void 0 : x.filter((b) => b.type === "file")) ?? [], [T, A] = y(null), $ = S ? "flex-end" : "flex-start", C = S ? t.senderAgent ?? null : null, D = /* @__PURE__ */ n("div", { style: { display: "flex", alignItems: "center", justifyContent: S ? "flex-end" : "flex-start", gap: 5, marginTop: 4, fontSize: 10, opacity: 0.78, letterSpacing: 0.2, userSelect: "none" }, children: [
1720
1720
  C && /* @__PURE__ */ n(
1721
1721
  "span",
1722
1722
  {
@@ -1766,11 +1766,11 @@ function on({ message: t, primary: i }) {
1766
1766
  /* @__PURE__ */ e("img", { src: h(b.url), alt: "sticker", style: { display: "block", maxWidth: 128, maxHeight: 128, objectFit: "contain" } }),
1767
1767
  P && m.length === 0 && w.length === 0 && E === M.length - 1 && I
1768
1768
  ] }, `s${E}`)),
1769
- m.map((b, E) => /* @__PURE__ */ n("div", { style: { position: "relative", marginBottom: 2, cursor: "zoom-in" }, onClick: () => j({ url: h(b.url), kind: "image" }), children: [
1769
+ m.map((b, E) => /* @__PURE__ */ n("div", { style: { position: "relative", marginBottom: 2, cursor: "zoom-in" }, onClick: () => A({ url: h(b.url), kind: "image" }), children: [
1770
1770
  /* @__PURE__ */ e("img", { src: h(b.url), alt: "", style: { display: "block", maxWidth: 260, maxHeight: 260, borderRadius: 12, objectFit: "cover" } }),
1771
1771
  P && E === m.length - 1 && w.length === 0 && I
1772
1772
  ] }, E)),
1773
- w.map((b, E) => /* @__PURE__ */ n("div", { style: { position: "relative", marginBottom: 2, cursor: "pointer" }, onClick: () => j({ url: h(b.url), kind: "video" }), children: [
1773
+ w.map((b, E) => /* @__PURE__ */ n("div", { style: { position: "relative", marginBottom: 2, cursor: "pointer" }, onClick: () => A({ url: h(b.url), kind: "video" }), children: [
1774
1774
  /* @__PURE__ */ e("video", { src: h(b.url), style: { display: "block", maxWidth: 260, maxHeight: 200, borderRadius: 12, objectFit: "cover" } }),
1775
1775
  /* @__PURE__ */ e("div", { style: { position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: 12, background: "rgba(0,0,0,.25)" }, children: /* @__PURE__ */ e("div", { style: { width: 40, height: 40, borderRadius: "50%", background: "rgba(255,255,255,.9)", display: "flex", alignItems: "center", justifyContent: "center" }, children: /* @__PURE__ */ e(Nt, { size: 16, fill: "#172033", color: "#172033", style: { marginLeft: 2 } }) }) }),
1776
1776
  P && E === w.length - 1 && I
@@ -1786,9 +1786,9 @@ function on({ message: t, primary: i }) {
1786
1786
  D
1787
1787
  ] }),
1788
1788
  T && St(
1789
- /* @__PURE__ */ n("div", { onClick: () => j(null), style: { position: "fixed", inset: 0, zIndex: 1e4, background: "rgba(0,0,0,.88)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "zoom-out" }, children: [
1789
+ /* @__PURE__ */ n("div", { onClick: () => A(null), style: { position: "fixed", inset: 0, zIndex: 1e4, background: "rgba(0,0,0,.88)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "zoom-out" }, children: [
1790
1790
  T.kind === "image" ? /* @__PURE__ */ e("img", { src: T.url, alt: "", style: { maxWidth: "90vw", maxHeight: "90vh", borderRadius: 8, objectFit: "contain", boxShadow: "0 8px 40px rgba(0,0,0,.5)" }, onClick: (b) => b.stopPropagation() }) : /* @__PURE__ */ e("video", { src: T.url, controls: !0, autoPlay: !0, style: { maxWidth: "90vw", maxHeight: "90vh", borderRadius: 8, boxShadow: "0 8px 40px rgba(0,0,0,.5)" }, onClick: (b) => b.stopPropagation() }),
1791
- /* @__PURE__ */ e("button", { onClick: () => j(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: /* @__PURE__ */ e(Ue, { size: 18 }) })
1791
+ /* @__PURE__ */ e("button", { onClick: () => A(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: /* @__PURE__ */ e(Oe, { size: 18 }) })
1792
1792
  ] }),
1793
1793
  document.body
1794
1794
  )
@@ -1806,33 +1806,33 @@ function an({
1806
1806
  onLinkContact: w,
1807
1807
  onRefreshContactInfo: v
1808
1808
  }) {
1809
- const W = t.contactName ?? t.subject ?? t.providerConversationKey, T = i == null ? void 0 : i.provider, j = !!(m != null && m.some((z) => z.contactInfoRows)), [$, C] = y({ channel: !0, stats: !1, extra: !0 }), D = (z) => C((oe) => ({ ...oe, [z]: !oe[z] })), [I, L] = y(""), [P, q] = y(!1), [te, Q] = y(!1), [B, x] = y(""), [b, E] = y([]), [V, ne] = y(!1);
1809
+ const W = t.contactName ?? t.subject ?? t.providerConversationKey, T = i == null ? void 0 : i.provider, A = !!(m != null && m.some((z) => z.contactInfoRows)), [$, C] = y({ channel: !0, stats: !1, extra: !0 }), D = (z) => C((oe) => ({ ...oe, [z]: !oe[z] })), [I, L] = y(""), [P, q] = y(!1), [te, Q] = y(!1), [B, x] = y(""), [b, E] = y([]), [V, ne] = y(!1);
1810
1810
  X(() => {
1811
1811
  L(""), Q(!1), x(""), h.getNote(t.id).then((z) => {
1812
1812
  z && L(z.content);
1813
1813
  }).catch(() => {
1814
1814
  });
1815
1815
  }, [t.id, h]), X(() => {
1816
- if (!j || !m) return;
1816
+ if (!A || !m) return;
1817
1817
  let z = !1;
1818
1818
  const oe = Je(t, {
1819
1819
  provider: T,
1820
1820
  linkContact: w,
1821
1821
  refreshContactInfo: v,
1822
- sendMessage: async (Z, O) => {
1823
- await h.sendMessage(t.id, Z, O);
1822
+ sendMessage: async (Z, U) => {
1823
+ await h.sendMessage(t.id, Z, U);
1824
1824
  }
1825
1825
  });
1826
1826
  return ne(!0), Promise.allSettled(
1827
1827
  m.filter((Z) => Z.contactInfoRows).map((Z) => Z.contactInfoRows(oe))
1828
1828
  ).then((Z) => {
1829
1829
  if (z) return;
1830
- const O = Z.filter((ee) => ee.status === "fulfilled").flatMap((ee) => ee.value);
1831
- E(O), ne(!1);
1830
+ const U = Z.filter((ee) => ee.status === "fulfilled").flatMap((ee) => ee.value);
1831
+ E(U), ne(!1);
1832
1832
  }), () => {
1833
1833
  z = !0;
1834
1834
  };
1835
- }, [t.id, t.contactExternalId, m, M, j, T, w, v, h]);
1835
+ }, [t.id, t.contactExternalId, m, M, A, T, w, v, h]);
1836
1836
  async function de() {
1837
1837
  if (!(!I.trim() || P)) {
1838
1838
  q(!0), x("");
@@ -1861,7 +1861,7 @@ function an({
1861
1861
  ),
1862
1862
  /* @__PURE__ */ n("div", { style: f.infoPanelHeader, children: [
1863
1863
  /* @__PURE__ */ e("span", { style: { fontWeight: 600, fontSize: 13, color: d.ink }, children: "Thông tin liên hệ" }),
1864
- /* @__PURE__ */ e("button", { style: f.iconButton, onClick: o, "aria-label": "Đóng", children: /* @__PURE__ */ e(Ue, { size: 16, strokeWidth: 2 }) })
1864
+ /* @__PURE__ */ e("button", { style: f.iconButton, onClick: o, "aria-label": "Đóng", children: /* @__PURE__ */ e(Oe, { size: 16, strokeWidth: 2 }) })
1865
1865
  ] }),
1866
1866
  /* @__PURE__ */ n("div", { style: { overflowY: "auto", flex: 1 }, children: [
1867
1867
  /* @__PURE__ */ n("div", { style: f.infoPanelIdentity, children: [
@@ -1905,7 +1905,7 @@ function an({
1905
1905
  /* @__PURE__ */ e(ge, { label: "Lần đầu", value: "—" })
1906
1906
  ] }),
1907
1907
  /* @__PURE__ */ n(_e, { label: "THÔNG TIN BỔ SUNG", sectionKey: "extra", expanded: $.extra, onToggle: () => D("extra"), children: [
1908
- !j && /* @__PURE__ */ n(ie, { children: [
1908
+ !A && /* @__PURE__ */ n(ie, { children: [
1909
1909
  /* @__PURE__ */ e(ge, { label: "Điện thoại", value: "— chưa có", valueMuted: !0 }),
1910
1910
  /* @__PURE__ */ e(ge, { label: "Email", value: "— chưa có", valueMuted: !0 }),
1911
1911
  /* @__PURE__ */ e(ge, { label: "Nhãn", value: "— chưa có", valueMuted: !0 })
@@ -1956,7 +1956,7 @@ function an({
1956
1956
  gap: 6
1957
1957
  },
1958
1958
  onClick: () => {
1959
- const O = Je(t, {
1959
+ const U = Je(t, {
1960
1960
  provider: T,
1961
1961
  linkContact: w,
1962
1962
  refreshContactInfo: v,
@@ -1964,7 +1964,7 @@ function an({
1964
1964
  await h.sendMessage(t.id, ee, se);
1965
1965
  }
1966
1966
  });
1967
- z.onClick(O);
1967
+ z.onClick(U);
1968
1968
  },
1969
1969
  children: [
1970
1970
  z.icon,
@@ -2019,7 +2019,7 @@ function _e({ label: t, children: i, sectionKey: r, expanded: o, onToggle: h })
2019
2019
  onClick: h,
2020
2020
  children: [
2021
2021
  /* @__PURE__ */ e("span", { children: t }),
2022
- S && (m ? /* @__PURE__ */ e(nt, { size: 12, strokeWidth: 2 }) : /* @__PURE__ */ e(jt, { size: 12, strokeWidth: 2 }))
2022
+ S && (m ? /* @__PURE__ */ e(nt, { size: 12, strokeWidth: 2 }) : /* @__PURE__ */ e(At, { size: 12, strokeWidth: 2 }))
2023
2023
  ]
2024
2024
  }
2025
2025
  ),
@@ -2051,7 +2051,7 @@ function ln({ value: t }) {
2051
2051
  }
2052
2052
  function dn() {
2053
2053
  return /* @__PURE__ */ n("div", { style: f.empty, children: [
2054
- /* @__PURE__ */ e("div", { style: f.emptyHero, children: /* @__PURE__ */ e(Ut, { size: 16, strokeWidth: 2 }) }),
2054
+ /* @__PURE__ */ e("div", { style: f.emptyHero, children: /* @__PURE__ */ e(Ot, { size: 16, strokeWidth: 2 }) }),
2055
2055
  /* @__PURE__ */ e("h2", { children: "Chọn một hội thoại" }),
2056
2056
  /* @__PURE__ */ e("p", { children: "Chọn hội thoại bên trái để xem và trả lời tin nhắn." })
2057
2057
  ] });
@@ -2174,7 +2174,7 @@ function xe({ provider: t, apiUrl: i, size: r = 40 }) {
2174
2174
  }
2175
2175
  );
2176
2176
  }
2177
- const Oe = {
2177
+ const Ue = {
2178
2178
  facebook: "Facebook",
2179
2179
  zalo: "Zalo OA",
2180
2180
  instagram: "Instagram",
@@ -2194,7 +2194,7 @@ function ct(t) {
2194
2194
  return String(i.displayName ?? i.pageName ?? i.username ?? i.name ?? t.externalAccountId);
2195
2195
  }
2196
2196
  function fn(t) {
2197
- const i = Oe[t.provider] ?? t.provider, r = String(t.metadata.username ?? t.metadata.pageName ?? "");
2197
+ const i = Ue[t.provider] ?? t.provider, r = String(t.metadata.username ?? t.metadata.pageName ?? "");
2198
2198
  return r ? `${i} · ${r}` : i;
2199
2199
  }
2200
2200
  const s = {
@@ -2507,7 +2507,7 @@ function bn() {
2507
2507
  t.textContent = "@keyframes ch-spin{to{transform:rotate(360deg)}}", document.head.appendChild(t);
2508
2508
  }
2509
2509
  function $n({ apiUrl: t, token: i, onConnectionChange: r }) {
2510
- const o = t.replace(/\/$/, ""), [h, S] = y([]), [m, M] = y(!0), [w, v] = y({ name: "list" }), [W, T] = y(null), [j, $] = y(!1), [C, D] = y(""), [I, L] = y(""), [P, q] = y(""), [te, Q] = y(""), [B, x] = y(!1), [b, E] = y(!1), V = J(null);
2510
+ const o = t.replace(/\/$/, ""), [h, S] = y([]), [m, M] = y(!0), [w, v] = y({ name: "list" }), [W, T] = y(null), [A, $] = y(!1), [C, D] = y(""), [I, L] = y(""), [P, q] = y(""), [te, Q] = y(""), [B, x] = y(!1), [b, E] = y(!1), V = J(null);
2511
2511
  bn();
2512
2512
  const ne = we(async () => {
2513
2513
  try {
@@ -2627,7 +2627,7 @@ Hành động này không thể hoàn tác.`))
2627
2627
  T(H instanceof Error ? H.message : "Lỗi kết nối"), v({ name: "list" });
2628
2628
  }
2629
2629
  }
2630
- function O(c, H) {
2630
+ function U(c, H) {
2631
2631
  navigator.clipboard.writeText(c).then(() => {
2632
2632
  H === "script" ? (x(!0), setTimeout(() => x(!1), 2e3)) : (E(!0), setTimeout(() => E(!1), 2e3));
2633
2633
  });
@@ -2788,7 +2788,7 @@ Hành động này không thể hoàn tác.`))
2788
2788
  ] }),
2789
2789
  /* @__PURE__ */ n("div", { style: s.formActions, children: [
2790
2790
  /* @__PURE__ */ e("button", { style: s.btnSecondary, onClick: () => v({ name: "add" }), children: "Hủy" }),
2791
- /* @__PURE__ */ e("button", { style: s.btnPrimary, disabled: j, onClick: () => void z(), children: j ? "Đang kết nối…" : "Kết nối Telegram" })
2791
+ /* @__PURE__ */ e("button", { style: s.btnPrimary, disabled: A, onClick: () => void z(), children: A ? "Đang kết nối…" : "Kết nối Telegram" })
2792
2792
  ] })
2793
2793
  ] })
2794
2794
  ] }),
@@ -2838,7 +2838,7 @@ https://www.myshop.com`,
2838
2838
  ] }),
2839
2839
  /* @__PURE__ */ n("div", { style: s.formActions, children: [
2840
2840
  /* @__PURE__ */ e("button", { style: s.btnSecondary, onClick: () => v({ name: "add" }), children: "Hủy" }),
2841
- /* @__PURE__ */ e("button", { style: s.btnPrimary, disabled: j, onClick: () => void oe(), children: j ? "Đang tạo…" : "Tạo widget" })
2841
+ /* @__PURE__ */ e("button", { style: s.btnPrimary, disabled: A, onClick: () => void oe(), children: A ? "Đang tạo…" : "Tạo widget" })
2842
2842
  ] })
2843
2843
  ] })
2844
2844
  ] }),
@@ -2865,7 +2865,7 @@ https://www.myshop.com`,
2865
2865
  /* @__PURE__ */ e("div", { style: s.codeLabel, children: "Mã nhúng" }),
2866
2866
  /* @__PURE__ */ n("div", { style: s.codeBlock, children: [
2867
2867
  /* @__PURE__ */ e("pre", { style: s.codePre, children: w.embedScript }),
2868
- /* @__PURE__ */ e("button", { style: { ...s.copyBtn, ...B ? { background: "#166534", borderColor: "#166534", color: "#bbf7d0" } : {} }, onClick: () => O(w.embedScript, "script"), children: B ? /* @__PURE__ */ n(ie, { children: [
2868
+ /* @__PURE__ */ e("button", { style: { ...s.copyBtn, ...B ? { background: "#166534", borderColor: "#166534", color: "#bbf7d0" } : {} }, onClick: () => U(w.embedScript, "script"), children: B ? /* @__PURE__ */ n(ie, { children: [
2869
2869
  /* @__PURE__ */ e(vt, {}),
2870
2870
  " Đã sao chép"
2871
2871
  ] }) : /* @__PURE__ */ n(ie, { children: [
@@ -2886,7 +2886,7 @@ https://www.myshop.com`,
2886
2886
  /* @__PURE__ */ e(
2887
2887
  "button",
2888
2888
  {
2889
- onClick: () => O(w.identitySecret, "secret"),
2889
+ onClick: () => U(w.identitySecret, "secret"),
2890
2890
  style: { border: "none", background: "transparent", cursor: "pointer", color: b ? "#059669" : "#ca8a04", padding: 2, display: "flex", alignItems: "center" },
2891
2891
  children: b ? /* @__PURE__ */ e(vt, {}) : /* @__PURE__ */ e(xt, {})
2892
2892
  }
@@ -2906,7 +2906,7 @@ https://www.myshop.com`,
2906
2906
  /* @__PURE__ */ n("div", { children: [
2907
2907
  /* @__PURE__ */ n("div", { style: s.title, children: [
2908
2908
  "Đang xác thực ",
2909
- Oe[w.provider]
2909
+ Ue[w.provider]
2910
2910
  ] }),
2911
2911
  /* @__PURE__ */ e("div", { style: s.subtitle, children: "Vui lòng hoàn thành trong cửa sổ bật lên" })
2912
2912
  ] })
@@ -2942,11 +2942,11 @@ https://www.myshop.com`,
2942
2942
  ] }),
2943
2943
  /* @__PURE__ */ n("div", { style: s.oauthTitle, children: [
2944
2944
  "Đang chờ xác thực với ",
2945
- Oe[w.provider]
2945
+ Ue[w.provider]
2946
2946
  ] }),
2947
2947
  /* @__PURE__ */ e("div", { style: s.oauthDesc, children: "Một cửa sổ đăng nhập đã được mở. Vui lòng đăng nhập và cấp quyền truy cập để hoàn tất kết nối." }),
2948
2948
  /* @__PURE__ */ n("div", { style: { display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-start", width: "100%", maxWidth: 280 }, children: [
2949
- /* @__PURE__ */ e(Qe, { done: !0, label: `Đã mở cửa sổ ${Oe[w.provider]}` }),
2949
+ /* @__PURE__ */ e(Qe, { done: !0, label: `Đã mở cửa sổ ${Ue[w.provider]}` }),
2950
2950
  /* @__PURE__ */ e(Qe, { active: !0, label: "Đang chờ bạn đăng nhập & cấp quyền" }),
2951
2951
  /* @__PURE__ */ e(Qe, { label: "Lưu kết nối & quay về" })
2952
2952
  ] }),
@@ -2964,7 +2964,7 @@ https://www.myshop.com`,
2964
2964
  ] }),
2965
2965
  /* @__PURE__ */ n("div", { style: s.connectDesc, children: [
2966
2966
  "Chọn ",
2967
- Oe[w.provider],
2967
+ Ue[w.provider],
2968
2968
  " bạn muốn kết nối với ChannelHub"
2969
2969
  ] })
2970
2970
  ] })
@@ -2972,7 +2972,7 @@ https://www.myshop.com`,
2972
2972
  /* @__PURE__ */ e("div", { style: s.body, children: w.pages.length === 0 ? /* @__PURE__ */ e("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." }) : /* @__PURE__ */ e("div", { style: { display: "flex", flexDirection: "column", gap: 8 }, children: w.pages.map((c) => /* @__PURE__ */ n(
2973
2973
  "button",
2974
2974
  {
2975
- disabled: j,
2975
+ disabled: A,
2976
2976
  onClick: () => void se(c.id),
2977
2977
  style: {
2978
2978
  display: "flex",
@@ -2982,8 +2982,8 @@ https://www.myshop.com`,
2982
2982
  borderRadius: 12,
2983
2983
  border: "1.5px solid #e2e8f0",
2984
2984
  background: "#fff",
2985
- cursor: j ? "not-allowed" : "pointer",
2986
- opacity: j ? 0.6 : 1,
2985
+ cursor: A ? "not-allowed" : "pointer",
2986
+ opacity: A ? 0.6 : 1,
2987
2987
  textAlign: "left",
2988
2988
  fontFamily: "inherit",
2989
2989
  transition: "border-color .15s, background .15s"
@@ -2993,7 +2993,7 @@ https://www.myshop.com`,
2993
2993
  /* @__PURE__ */ e("div", { style: { fontSize: 14, fontWeight: 600, color: "#0f172a" }, children: c.name }),
2994
2994
  /* @__PURE__ */ e("div", { style: { fontSize: 11, color: "#94a3b8", fontFamily: "monospace", marginTop: 2 }, children: c.id })
2995
2995
  ] }),
2996
- /* @__PURE__ */ e("span", { style: { fontSize: 13, color: "#2563eb", fontWeight: 500 }, children: j ? "Đang kết nối…" : "Chọn →" })
2996
+ /* @__PURE__ */ e("span", { style: { fontSize: 13, color: "#2563eb", fontWeight: 500 }, children: A ? "Đang kết nối…" : "Chọn →" })
2997
2997
  ]
2998
2998
  },
2999
2999
  c.id
@@ -3109,10 +3109,10 @@ function Bn({
3109
3109
  icon: h,
3110
3110
  onConversationSelect: S
3111
3111
  }) {
3112
- const m = (r == null ? void 0 : r.primaryColor) ?? "#2563eb", M = typeof h == "function" ? h({ size: 20, color: "currentColor" }) : h ?? /* @__PURE__ */ e(pt, { size: 20, strokeWidth: 1.8 }), w = J(new it(t, i)), [v, W] = y(!1), [T, j] = y([]), $ = J(null), C = J(null), D = T.filter((B) => (B.unreadCount ?? 0) > 0), I = D.reduce((B, x) => B + (x.unreadCount ?? 0), 0), L = we(async () => {
3112
+ const m = (r == null ? void 0 : r.primaryColor) ?? "#2563eb", M = typeof h == "function" ? h({ size: 20, color: "currentColor" }) : h ?? /* @__PURE__ */ e(pt, { size: 20, strokeWidth: 1.8 }), w = J(new it(t, i)), [v, W] = y(!1), [T, A] = y([]), $ = J(null), C = J(null), D = T.filter((B) => (B.unreadCount ?? 0) > 0), I = D.reduce((B, x) => B + (x.unreadCount ?? 0), 0), L = we(async () => {
3113
3113
  try {
3114
3114
  const B = await w.current.listConversations();
3115
- j(B.items);
3115
+ A(B.items);
3116
3116
  } catch {
3117
3117
  }
3118
3118
  }, []);
@@ -3129,7 +3129,7 @@ function Bn({
3129
3129
  const P = async (B) => {
3130
3130
  if (W(!1), S == null || S(B.id, B), (B.unreadCount ?? 0) > 0)
3131
3131
  try {
3132
- await w.current.markRead(B.id), j(
3132
+ await w.current.markRead(B.id), A(
3133
3133
  (x) => x.map((b) => b.id === B.id ? { ...b, unreadCount: 0 } : b)
3134
3134
  );
3135
3135
  } catch {
@@ -3347,7 +3347,7 @@ function In({
3347
3347
  }
3348
3348
  );
3349
3349
  }
3350
- console.log("[ChannelHub] widget v0.1.9 loaded");
3350
+ console.log("[ChannelHub] widget v0.1.10 loaded");
3351
3351
  export {
3352
3352
  $n as ChannelHubChannels,
3353
3353
  it as ChannelHubClient,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@channelhub/widget",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "Embeddable chat inbox widget for ChannelHub",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/src/api.ts CHANGED
@@ -24,7 +24,7 @@ export class ChannelHubClient {
24
24
 
25
25
  assignConversation(conversationId: string, agent: ChannelHubAgent | null): Promise<Conversation> {
26
26
  return this.request(`/v1/conversations/${encodeURIComponent(conversationId)}/assignee`, {
27
- method: 'PATCH',
27
+ method: 'PUT',
28
28
  body: JSON.stringify({ agent }),
29
29
  });
30
30
  }