@channelhub/widget 0.1.6 → 0.1.7

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