@sendbird/ai-agent-messenger-react 1.34.0 → 1.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var ac=Object.defineProperty;var cc=(e,t,n)=>t in e?ac(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var y=(e,t,n)=>cc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const le=require("@sendbird/chat"),l=require("react"),U=require("styled-components"),at=require("date-fns"),lc=require("date-fns/locale/en-US"),$e=require("@sendbird/chat/message"),uc=require("react-dom"),fe=require("@sendbird/chat/aiAgent"),We=require("@sendbird/chat/groupChannel"),dc=require("date-fns/isSameDay"),mc=require("dompurify"),Tr=e=>e&&e.__esModule?e:{default:e};function hc(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const fc=Tr(le),a=hc(l),C=Tr(U),Ko=Tr(mc),Yo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},gc=e=>{const t=Yo(e);return typeof t=="object"&&t!==null?t:{}},Wo=e=>typeof e=="string"?gc(e):e??{},pc=e=>!!Wo(e).stream,hs=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},jo=e=>{const t=Wo(e),n=hs(t.user_message_id)??hs(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},bt="sb-agent",Xo="KEY_IMG_ASPECT_RATIO",lr="*/*",ee={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var bn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(bn||{}),Pt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Pt||{});const _c=e=>!!(e!=null&&e.cta_button),Ec=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Zo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,Cc=e=>{var t;return Zo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},bc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Ve=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},kn=e=>Object.defineProperties({},{hasMessageTemplate:Ve(()=>!!(e!=null&&e.message_template)),hasCTAButton:Ve(()=>_c(e)),hasChallenge:Ve(()=>!!(e!=null&&e.challenge)),isThinking:Ve(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Ve(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Ve(()=>bc(e)),hasCustomMessageTemplates:Ve(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Ve(()=>Zo(e)),hasActiveForm:Ve(()=>Cc(e)),hasSteward:Ve(()=>!!(e!=null&&e.steward)),hasCitations:Ve(()=>Ec(e))}),vc=e=>{const t=kn(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Jo=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},yc=e=>e===Pt.COMPLETED||e===Pt.CANCELED?e:Pt.IN_PROGRESS,Kn=e=>Qe(e)&&!Jo(e),Qe=e=>!!e&&"sender"in e,Sc=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Ac=(e,t,n,r=!0)=>{if(!r||!Kn(e))return"single";const s=()=>{if(!Kn(t))return!1;const u=t.sender.userId===e.sender.userId,d=at.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Kn(n))return!1;const u=n.sender.userId===e.sender.userId,d=at.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},st=(e,t)=>(()=>{var r;return Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Le={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Jo(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===$e.SendingStatus.PENDING)},Ye=e=>e.startsWith("image/"),zt=e=>e.startsWith("video/"),Tc=e=>e.startsWith("audio/"),Qo=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Ir=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},ei=e=>{var t;return e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.messageType==="multipleFiles"?e.message.length>0&&((t=e.files[0])==null?void 0:t.name)!==e.message:e.message.length>0},Ic=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return vc(t)},Ln=e=>{switch(e){case"top":case"middle":return ee.GAP_GROUPED;default:return ee.GAP_UNGROUPED}},xc=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...i)=>{const[c,u,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:u.trim(),language:c?c.trim():"plaintext"}),s=d+o.length,o}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(o=>o.type!=="text"?o:{...o,value:t(o.value)}):r},Rc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Mc=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),wc=e=>e.replace(/~~/g,"\\~\\~"),kc=e=>{let t=e;return t=Rc(t),t=Mc(t),t=wc(t),t},Lc=typeof navigator<"u"&&navigator.product==="ReactNative",fs=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return Lc?e.find(n):e.findLast(n)};function ce(){}function Oc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Nc(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const Re={isStreaming(e){return pc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(Re.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!st(e,t))return!1;const n=jo(e.data);return!n.isStreaming&&!n.hasResponseMetadata},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},Yn=`@${bt}`,Dc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Yn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Nc(`${e}/${t}/${s}`);return`${Yn}-udata/${o}`},anonUserSession:()=>`${Yn}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},ti=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},$c=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class Fc{constructor(t){y(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??fe.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[fe.ConversationStatus.OPEN,fe.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??fe.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===fe.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==fe.DeskChannelFilter.EXCLUDE:!1}}class ni extends We.BaseChannelCollection{constructor(n,r){const s=new Fc(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=We.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,f,g)=>i.getMyGroupChannels(m,h.params,g),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:_,copilotConversationOnly:b,copilotSupportChannelUrl:v}=s.params,p={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:_,copilotConversationOnly:b,copilotSupportChannelUrl:v};return i.getMyGroupChannelChangeLogs(m,p,We.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});y(this,"_params");y(this,"_sdk");y(this,"_throttledOnChannelChanged");y(this,"_key");y(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${$c()}`,this._throttledOnChannelChanged=ti(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:_,context:b}of m)h.delete(_.url),h.set(_.url,{channel:_,context:b});const f=new Map;for(const{channel:_,context:b}of h.values())f.has(b)||f.set(b,new Map),f.get(b).set(_.url,_);for(const[_,b]of f){const v=Array.from(b.values()),p=(g=this._sdk.currentUser)==null?void 0:g.userId,S=v.filter(T=>this.filter.match(T,p)),A=v.filter(T=>!this.filter.match(T,p)).map(T=>T.url);S.length>0&&this._base._addChannelsToView(S,_,!1),A.length>0&&this._removeChannels(A,_)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const f of m)this._pendingChannels.push({channel:f,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class ri{constructor(t){y(this,"subscribers",{});this.logger=t}async send(t){const n=Pc(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Pc=()=>{let e=ce,t=ce;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Ke=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e))(Ke||{});class Vt{constructor(t={}){y(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const ct={CloseConversation:e=>new Uc(e),MessengerSettingsUpdated:e=>new Bc(e),ActiveChannelUpdated:e=>new Hc(e),AnonymousSessionTokenExpired:()=>new Gc,AuthTokenRefreshed:()=>new zc};class Uc extends Vt{constructor(){super(...arguments);y(this,"type","conv.close")}}class Bc extends Vt{constructor(){super(...arguments);y(this,"type","messenger.settings.updated")}}class Hc extends Vt{constructor(){super(...arguments);y(this,"type","active.channel.updated")}}class Gc extends Vt{constructor(){super(...arguments);y(this,"type","anon.token.expired")}}class zc extends Vt{constructor(){super(...arguments);y(this,"type","auth.token.refreshed")}}const qt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class Kt{constructor(t){y(this,"category","connection");this.userId=t}get data(){return qt({user_id:this.userId})}}class Vc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_connected")}}class qc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_reconnect_started")}}class Kc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_reconnect_succeeded")}}class Yc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_reconnect_failed")}}class Wc extends Kt{constructor(){super(...arguments);y(this,"metricKey","connection_disconnected")}}class jc{constructor(t){y(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new Vc(n):t==="reconnectStarted"?new qc(n):t==="reconnectSucceeded"?new Kc(n):t==="reconnectFailed"?new Yc(n):new Wc(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class xr{constructor(t,n){y(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Xc extends xr{constructor(){super(...arguments);y(this,"metricKey","conversation_initialized")}}class Zc extends xr{constructor(){super(...arguments);y(this,"metricKey","conversation_open")}}class Jc extends xr{constructor(){super(...arguments);y(this,"metricKey","conversation_closed")}}class Qc{constructor(t){y(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===fe.ConversationStatus.INITIALIZED?new Xc(t.url,n.id):s===fe.ConversationStatus.OPEN?new Zc(t.url,n.id):new Jc(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===fe.ConversationStatus.INITIALIZED?t===void 0:n===fe.ConversationStatus.OPEN?t===fe.ConversationStatus.INITIALIZED:t===fe.ConversationStatus.OPEN}}const si=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Fe=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===fe.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Rr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===fe.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function rt(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function el(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!rt(e):!1}function tl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function oi(e){return!!e&&e<=Date.now()}function nl(e){return!e.title}function rl(e,t){var n;if(e)return nl(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question,always_visible:!1}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}class Mr{constructor(t,n){y(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class sl extends Mr{constructor(){super(...arguments);y(this,"metricKey","handoff_started")}}class ol extends Mr{constructor(){super(...arguments);y(this,"metricKey","handoff_succeeded")}}class il extends Mr{constructor(){super(...arguments);y(this,"metricKey","handoff_failed")}}class al{constructor(t){y(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new sl(t.url,r.id):o==="succeeded"?new ol(t.url,r.id):new il(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(Fe(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class cl{constructor(t){y(this,"category","message");y(this,"metricKey","incoming_message_received");y(this,"channelUrl");y(this,"messageId");y(this,"senderType");y(this,"createdAt");y(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return qt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const ll=(e,t)=>{const n=Qe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class ul{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new cl({channelUrl:t.url,messageId:n.messageId,senderType:ll(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!st(t,this.getCurrentUserId())&&n!==null}}class dl{constructor(t){y(this,"category","message");y(this,"metricKey");y(this,"channelUrl");y(this,"requestId");y(this,"messageId");y(this,"target");y(this,"sendingStatus");y(this,"createdAt");y(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return qt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const ml=e=>{switch(e){case $e.SendingStatus.PENDING:return"pending";case $e.SendingStatus.SUCCEEDED:return"succeeded";case $e.SendingStatus.FAILED:return"failed";case $e.SendingStatus.SCHEDULED:return"scheduled";default:return}};class hl{constructor(t,n){y(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!st(n,this.getCurrentUserId()))return;const r=ml(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new dl({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:rt(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class fl{constructor(t){y(this,"id","aiagent_livemetric");y(this,"dispatch");y(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});y(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new jc(this.emit),conversation:new Qc(this.emit),handoff:new al(this.emit),incomingMessage:new ul(this.emit,n),outgoingMessage:new hl(this.emit,n)}}start(){const t=new le.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new We.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var wr=(e=>(e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(wr||{});class ii{constructor(t){y(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${bt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${bt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${bt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${bt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${bt}/error]`,...t)}}class ai{constructor({userId:t,authToken:n,sessionHandler:r}){y(this,"userId");y(this,"authToken");y(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class ur{constructor(){y(this,"userId");y(this,"authToken");y(this,"sessionHandler")}}const gl=e=>({onSessionTokenRequired:t=>{t(null),e.send(ct.AnonymousSessionTokenExpired())}}),ci="ai_agent:stats",pl="conversation_initial_render",gs="conversation_not_interactive_timeout",_l="recovery_not_interactive_timeout",El="conversation_list_initial_render",Cl="message_pending_stuck",ps="aiev_auth_expired_unhandled",bl="user_perceived_response_time",vl="stream_stalled",yl="ai_typing_indicator_absent_timeout",Sl="rendered_content_unusable",li=800220;var he=(e=>(e.AUTH="auth_duration_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.TOTAL_DURATION="total_duration_ms",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache_ms",e))(he||{});const vn={now:()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()},ui=(e,t,n)=>{const r={key:e,value:String(t)};return(n==null?void 0:n.conversationId)!==void 0&&(r.conversation_id=n.conversationId),n!=null&&n.error&&(r.error_code=n.error.code??li,r.error_description=n.error.message??""),n!=null&&n.extra&&Object.keys(n.extra).length>0&&(r.extra=n.extra),r},It=e=>(e==null?void 0:e.clock)??vn,Al=((e,t)=>setTimeout(e,t)),Tl=(e=>clearTimeout(e)),Yt=e=>(e==null?void 0:e.setTimeout)??Al,Wt=e=>(e==null?void 0:e.clearTimeout)??Tl,et=(e,t,n,r)=>e(ci,ui(t,n,r)),Se=(e,t)=>{e!==null&&t(e)},On=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)},mt=(e,t)=>!(e.channelUrl&&t&&e.channelUrl!==t),di=(e,t)=>{for(const n of e)if(n.userMessageId===void 0&&mt(n,t))return!0;return!1};class Il{constructor(t){y(this,"callback");this.callback=t}onPayloadParseFailed(t){et(this.callback,ps,"payload_parse_failed",{extra:{agent_id:t.aiAgentId}})}onCallbackNotFound(t){et(this.callback,ps,"callback_not_found",{extra:{agent_id:t.aiAgentId}})}clear(){}}class xl{constructor(){y(this,"timers",new Map);y(this,"committed",!1);y(this,"commitCallback",null);y(this,"conversationId",null);y(this,"channelUrl",null);y(this,"errorCode",null);y(this,"errorDescription",null);y(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??li,this.errorDescription=n,this}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:vn.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:vn.now()}),this)}getDuration(t){const n=this.timers.get(t);return!n||n.startTime===null||n.endTime===null?null:n.endTime-n.startTime}isCommitted(){return this.committed}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(ci,t)):!1}}class Rl extends xl{constructor(){super(...arguments);y(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return pl}buildPayload(){const n=this.getDuration(he.AUTH),r=this.getDuration(he.GET_CHANNEL),s=this.getDuration(he.GET_MESSAGES),o=this.getDuration(he.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(he.TOTAL_DURATION),c={...this.extraData,present_method:this.presentMethod,...n!==null&&{[he.AUTH]:n},...r!==null&&{[he.GET_CHANNEL]:r},...s!==null&&{[he.GET_MESSAGES]:s},...o!==null&&{[he.TOTAL_DURATION_FROM_CACHE]:o}};return ui(this.getMetricKey(),i??0,{conversationId:this.conversationId??void 0,error:this.errorCode!==null?{code:this.errorCode,message:this.errorDescription??""}:void 0,extra:c})}}class Ml{constructor(t){y(this,"commitCallback");y(this,"apiResultReceived",!1);y(this,"channelUrl");y(this,"consumed",!1);y(this,"consumedByAuthError",!1);y(this,"presentMethod","direct_present");y(this,"renderedAfterApiResult",!1);y(this,"stats",null);this.commitCallback=t}getOrCreateStats(){var t;return this.consumed?null:(t=this.stats)!=null&&t.isCommitted()?(this.consumed=!0,null):(this.stats||(this.stats=new Rl().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod),this.apiResultReceived=!1,this.renderedAfterApiResult=!1),this.stats)}getActiveStats(){return this.consumed||!this.stats||this.stats.isCommitted()?null:this.stats}matchesChannelUrl(t){return t===void 0||this.channelUrl===void 0||t===this.channelUrl}pinChannelUrl(t){var n;return t===void 0?!0:this.matchesChannelUrl(t)?(this.channelUrl=t,(n=this.stats)==null||n.setChannelUrl(t),!0):!1}consume(t){return t&&(this.consumed=!0),t}commitIfReady(t){return this.consumed||!this.stats||this.stats.isCommitted()?!0:!this.matchesChannelUrl(t)||!this.apiResultReceived||!this.renderedAfterApiResult?!1:this.consume(this.stats.stopTimer(he.TOTAL_DURATION).commit())}start(t){const n=this.getOrCreateStats();!n||!this.pinChannelUrl(t)||n.startTimer(he.TOTAL_DURATION).startTimer(he.TOTAL_DURATION_FROM_CACHE)}onAuthStart(){var t;this.consumedByAuthError&&this.clear(),(t=this.getOrCreateStats())==null||t.startTimer(he.AUTH)}onAuthComplete(){var t;(t=this.getActiveStats())==null||t.stopTimer(he.AUTH)}onAuthError(t){const n=this.getActiveStats();n&&this.consume(n.stopTimer(he.AUTH).setError(t instanceof le.SendbirdError?t.code:void 0,t.message).stopTimer(he.TOTAL_DURATION).commit())&&(this.consumedByAuthError=!0)}onGetChannelStart(t){const n=this.getActiveStats();!n||!this.pinChannelUrl(t)||n.startTimer(he.GET_CHANNEL)}onGetChannelComplete(t){const n=typeof t=="object"?t.channelUrl:void 0,r=typeof t=="object"?t.conversationId:t,s=this.getActiveStats();!s||!this.pinChannelUrl(n)||(s.stopTimer(he.GET_CHANNEL),r!==void 0&&s.setConversationId(r),s.startTimer(he.GET_MESSAGES))}onGetChannelError(t){const n=t instanceof Error?void 0:t.channelUrl,r=t instanceof Error?t:t.error,s=this.getActiveStats();s&&this.pinChannelUrl(n)&&this.consume(s.stopTimer(he.GET_CHANNEL).setError(r instanceof le.SendbirdError?r.code:void 0,r.message).stopTimer(he.TOTAL_DURATION).commit())}onCacheResult(t){const n=this.getActiveStats();n&&(t&&n.setError(t instanceof le.SendbirdError?t.code:void 0,t.message),n.stopTimer(he.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){const n=this.getActiveStats();if(n){if(t){this.consume(n.setError(t instanceof le.SendbirdError?t.code:void 0,t.message).stopTimer(he.TOTAL_DURATION).stopTimer(he.GET_MESSAGES).commit());return}this.apiResultReceived=!0,this.renderedAfterApiResult=!1,n.stopTimer(he.GET_MESSAGES),this.commitIfReady()}}setChannelUrl(t){this.pinChannelUrl(t)}commitPending(){const t=this.getActiveStats();return t?this.consume(t.stopTimer(he.TOTAL_DURATION).commit()):!0}markRendered(t){return this.matchesChannelUrl(t)?(this.renderedAfterApiResult=!0,this.commitIfReady(t)):!1}setPresentMethod(t){var n;this.presentMethod=t,(n=this.getActiveStats())==null||n.setPresentMethod(t)}clear(){this.stats=null,this.apiResultReceived=!1,this.channelUrl=void 0,this.consumed=!1,this.consumedByAuthError=!1,this.renderedAfterApiResult=!1}}const _s=()=>({initialized:!1,listStarted:!1,listCompleted:!1,rendered:!1});class wl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"measurement",_s());y(this,"renderedCommitted",!1);y(this,"startedAt",null);y(this,"listStartedAt",null);y(this,"authStartedAt",null);y(this,"authDuration",null);y(this,"listDuration",null);y(this,"presentMethod","direct_present");y(this,"committed",!1);this.callback=t,this.clock=It(n)}onInitializeStart(){this.measurement.rendered||(this.measurement.initialized&&this.clearMeasurementState(),this.renderedCommitted=!1,this.startMeasurement())}onListRequestStart(){this.measurement.listStarted&&!this.measurement.listCompleted&&!this.measurement.rendered&&this.clearMeasurementState(),this.markListRequestStartOnce()}onListRequestComplete(){this.markListRequestCompleteOnce()}onRendered(){this.markRenderedOnce()}setPresentMethod(t){this.presentMethod=t}start(t){this.committed||(this.startedAt=this.clock.now(),t&&(this.presentMethod=t))}onAuthStart(){this.committed&&(this.clearMeasurementState(),this.renderedCommitted=!1),this.authDuration=null,this.authStartedAt=this.clock.now()}onAuthComplete(){if(!(this.committed||this.authDuration!==null)){if(this.authStartedAt===null){this.authDuration=0;return}this.authDuration=this.clock.now()-this.authStartedAt,this.authStartedAt=null}}markListRequestStart(){this.committed||(this.startedAt===null&&this.start(),this.listStartedAt=this.clock.now())}markListRequestComplete(){this.committed||this.listStartedAt===null||(this.listDuration=this.clock.now()-this.listStartedAt)}markRendered(){this.committed||this.startedAt===null||(this.committed=!0,et(this.callback,El,this.clock.now()-this.startedAt,{extra:{...this.authDuration!==null&&{auth_duration_ms:this.authDuration},...this.listDuration!==null&&{get_list_duration_ms:this.listDuration},present_method:this.presentMethod}}))}clear(){this.clearMeasurementState(),this.clearAuthState(),this.renderedCommitted=!1}clearMeasurementState(){this.startedAt=null,this.listStartedAt=null,this.listDuration=null,this.committed=!1,this.measurement=_s()}clearAuthState(){this.authStartedAt=null,this.authDuration=null}startMeasurement(){this.measurement.initialized||(this.clearMeasurementState(),this.start(),this.measurement.initialized=!0)}markListRequestStartOnce(){this.startMeasurement(),!this.measurement.listStarted&&(this.markListRequestStart(),this.measurement.listStarted=!0)}markListRequestCompleteOnce(){this.markListRequestStartOnce(),!this.measurement.listCompleted&&(this.markListRequestComplete(),this.measurement.listCompleted=!0)}markRenderedOnce(){this.renderedCommitted||(this.startMeasurement(),!this.measurement.rendered&&(this.markRendered(),this.measurement.rendered=!0,this.renderedCommitted=!0))}}class kl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={startedAt:this.clock.now(),channelUrl:t==null?void 0:t.channelUrl,conversationId:t==null?void 0:t.conversationId,committed:!1,inputEnabled:!1,phaseReached:"auth",historyLoadResult:"pending",timer:null};r.timer=this.setTimeoutFn(()=>this.commitTimeout(n),1e4),this.measurements.set(n,r)}markChannelJoined(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="channel_join",t!==void 0&&(r.conversationId=t))}markHistoryLoaded(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="history_load",r.historyLoadResult=t,this.cancelIfReady(n))}markInputEnabled(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="input_enable",n.inputEnabled=!0,this.cancelIfReady(t))}markRendered(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="render")}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}cancelIfReady(t){const n=this.getMeasurement(t);!n||!n.inputEnabled||n.historyLoadResult==="pending"||this.clearKey(this.getKey(n.channelUrl))}commitTimeout(t){const n=this.measurements.get(t);!n||n.committed||(n.committed=!0,n.timer=null,et(this.callback,gs,this.clock.now()-n.startedAt,{conversationId:n.conversationId,error:{message:gs},extra:{outcome:"timeout",phase_reached:n.phaseReached,history_load_result:n.historyLoadResult}}),this.measurements.delete(t))}getMeasurement(t){return t!==void 0?this.measurements.get(this.getKey(t)):this.measurements.size===1?Array.from(this.measurements.values())[0]:this.measurements.get(this.getKey())}getKey(t){return t??"__default__"}}const Ll=5e3,Es=1e4;class Ol{constructor(t,n){y(this,"callback");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"measurements",new Map);this.callback=t,this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t){if(!t.requestId||this.measurements.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,r={channelUrl:t.channelUrl,messageType:t.messageType,stuckReason:n?"upload_no_progress":"pending_too_long",timer:null},s=n?Es:Ll;r.timer=this.setTimeoutFn(()=>this.detect(t.requestId),s),this.measurements.set(t.requestId,r)}resolve(t){const n=this.measurements.get(t.requestId);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}disappear(t){const n=this.measurements.get(t.requestId);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}markUploadProgress(t){const n=this.measurements.get(t);n&&n.stuckReason==="upload_no_progress"&&(Se(n.timer,this.clearTimeoutFn),n.timer=this.setTimeoutFn(()=>this.detect(t),Es))}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t&&this.measurements.forEach((n,r)=>{n.channelUrl===t&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(r))})}detect(t){const n=this.measurements.get(t);n&&(this.measurements.delete(t),this.commit(t,n))}commit(t,n){et(this.callback,Cl,n.stuckReason,{extra:{message_type:n.messageType,request_id:t}})}}class Nl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}start(t,n){const r=this.getKey(n);let s=this.measurements.get(r);s&&s.startedAt!==null||s!=null&&s.inputEnabled||(s={startedAt:this.clock.now(),triggerType:t,inputEnabled:(s==null?void 0:s.inputEnabled)??!1,timer:this.setTimeoutFn(()=>this.commitTimeout(r),1e4)},this.measurements.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.measurements.get(r);if(!s){if(!t)return;s={startedAt:null,triggerType:null,inputEnabled:t,timer:null},this.measurements.set(r,s)}s.inputEnabled=t,t&&this.cancelMeasurement(s)}cancelPending(t){const n=this.getKey(t),r=this.measurements.get(n);r&&(this.cancelMeasurement(r),r.inputEnabled||this.measurements.delete(n))}clear(){this.measurements.forEach(t=>Se(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}commitTimeout(t){const n=this.measurements.get(t);if(!n||n.startedAt===null||n.triggerType===null)return;if(n.inputEnabled){this.cancelMeasurement(n);return}const r=this.clock.now()-n.startedAt,s=n.triggerType;this.measurements.delete(t),et(this.callback,_l,r,{extra:{trigger_type:s}})}cancelMeasurement(t){Se(t.timer,this.clearTimeoutFn),t.timer=null,t.startedAt=null,t.triggerType=null}getKey(t){return t??"__default__"}}const Dl=500;class $l{constructor(t){y(this,"callback");y(this,"committed",new Set);this.callback=t}commit(t){const n=`${t.messageId}:${t.contentKind}:${t.errorDomain}`;this.committed.has(n)||(On(this.committed,Dl),this.committed.add(n),et(this.callback,Sl,t.errorDomain,{error:t.error?{code:t.error.code,message:t.errorDomain}:void 0,extra:{content_kind:t.contentKind,message_id:String(t.messageId)}}))}clear(){this.committed.clear()}}const Cs=1e4,Ct=5e3,Fl=500;class Pl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"streams",new Map);y(this,"emittedMessageChannels",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}markRawProgress(t){if(!t.aiResponse.isStreaming){this.completeDelivery(t.messageId,t.textLength);return}if(this.emittedMessageChannels.has(t.messageId))return;const n=this.getOrCreate(t.messageId,t.channelUrl);t.textLength>n.lastRawLength?(n.chunksReceived+=1,n.lastRawLength=t.textLength,n.lastRawAt=this.clock.now(),Se(n.deliveryTimer,this.clearTimeoutFn),n.deliveryTimer=null,this.scheduleDeliveryStallCheck(t.messageId,n)):this.scheduleDeliveryStallCheck(t.messageId,n),n.lastRenderedLength<n.lastRawLength&&n.renderTimer===null&&(n.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t.messageId,n,Ct))}markRenderedProgress(t){const n=this.streams.get(t.messageId);if(!(!n||t.displayedLength<=n.lastRenderedLength)){if(n.lastRenderedLength=t.displayedLength,n.lastRenderAt=this.clock.now(),n.lastRenderedLength>=n.lastRawLength){if(n.deliveryTimer===null){this.clearStream(t.messageId,n);return}Se(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null;return}this.scheduleRenderStallCheck(t.messageId,n,Ct)}}hasPendingStream(t){return this.streams.has(t)}complete(t){const n=this.streams.get(t);n&&this.clearStream(t,n)}completeDelivery(t,n){const r=this.streams.get(t);if(r){if(n>r.lastRawLength&&(r.lastRawLength=n,r.lastRawAt=this.clock.now()),Se(r.deliveryTimer,this.clearTimeoutFn),r.deliveryTimer=null,r.lastRenderedLength>=r.lastRawLength){this.clearStream(t,r);return}r.renderTimer===null&&(r.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t,r,Ct))}}clearMessage(t){const n=this.streams.get(t);n&&this.clearStream(t,n),this.emittedMessageChannels.delete(t)}clear(){this.streams.forEach(t=>{Se(t.deliveryTimer,this.clearTimeoutFn),Se(t.renderTimer,this.clearTimeoutFn)}),this.streams.clear(),this.emittedMessageChannels.clear()}clearChannel(t){t&&(this.streams.forEach((n,r)=>{n.channelUrl!==t&&n.channelUrl!==void 0||this.clearStream(r,n)}),this.emittedMessageChannels.forEach((n,r)=>{(n===t||n===void 0)&&this.emittedMessageChannels.delete(r)}))}detectDelivery(t){const n=this.streams.get(t);n&&(n.deliveryTimer=null,Se(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null,this.emit(t,n,"delivery"))}detectRender(t){const n=this.streams.get(t);if(!n||(n.renderTimer=null,n.lastRenderedLength>=n.lastRawLength))return;const r=this.clock.now()-n.lastRenderAt;if(r<Ct){this.scheduleRenderStallCheck(t,n,Ct-r);return}const s=this.clock.now()-n.lastRawAt;if(s>=Ct&&n.deliveryTimer!==null){const o=Cs-s;if(o>0){this.scheduleRenderStallCheck(t,n,o);return}}this.emit(t,n,"render")}scheduleRenderStallCheck(t,n,r){n.renderTimer===null&&(n.renderTimer=this.setTimeoutFn(()=>this.detectRender(t),r))}scheduleDeliveryStallCheck(t,n){n.deliveryTimer===null&&(n.deliveryTimer=this.setTimeoutFn(()=>this.detectDelivery(t),Cs))}emit(t,n,r){if(this.emittedMessageChannels.has(t))return;const s=r==="delivery"?n.lastRawAt:n.lastRenderAt;et(this.callback,vl,this.clock.now()-s,{extra:{message_id:String(t),stall_kind:r}}),this.rememberEmitted(t,n.channelUrl),this.clearStream(t,n)}getOrCreate(t,n){const r=this.streams.get(t);if(r)return r;const s=this.clock.now(),o={channelUrl:n,chunksReceived:0,lastRawAt:s,lastRenderAt:s,lastRawLength:0,lastRenderedLength:0,deliveryTimer:null,renderTimer:null};return this.streams.set(t,o),o}rememberEmitted(t,n){this.emittedMessageChannels.has(t)||On(this.emittedMessageChannels,Fl),this.emittedMessageChannels.set(t,n)}clearStream(t,n){Se(n.deliveryTimer,this.clearTimeoutFn),Se(n.renderTimer,this.clearTimeoutFn),this.streams.delete(t)}}const bs=3e3,Ul=3e4;class Bl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"setTimeoutFn");y(this,"clearTimeoutFn");y(this,"turns",new Map);y(this,"pendingAIResponseStartsByUserMessageId",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Yt(n),this.clearTimeoutFn=Wt(n)}startTurn(t){this.cancelTurn(t.requestId);const n={requestId:t.requestId,channelUrl:t.channelUrl,beforeTpstStartedAt:this.clock.now(),afterTpenStartedAt:null,timer:null};n.timer=this.setTimeoutFn(()=>this.commitTimeout(n.requestId),Ul),this.turns.set(t.requestId,n)}markUserMessageAck(t){const n=this.turns.get(t.requestId);if(!n)return;n.userMessageId=t.messageId;const r=this.pendingAIResponseStartsByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseStartsByUserMessageId.delete(t.messageId),this.applyAIResponseStarted({channelUrl:r.channelUrl,matchesUserMessage:!0,userMessageId:t.messageId},r.startedAt))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.turns.get(t);r&&(this.turns.delete(t),r.requestId=n,this.turns.set(n,r))}cancelTurn(t){this.cleanupTurn(t)}markTypingStarted(t){const n=this.clock.now();this.turns.forEach(r=>{mt(r,t)&&(this.recordAfterTpen(r,n),this.recordBeforeTpst(r,n))})}markTypingEnded(t){const n=this.clock.now();this.turns.forEach(r=>{mt(r,t)&&(this.recordBeforeTpst(r,n),r.afterTpenStartedAt=n)})}markAIResponseStarted(t={}){const n=t.channelUrl,r=t.userMessageId,s=r!==void 0,o=this.clock.now();this.applyAIResponseStarted({channelUrl:n,matchesUserMessage:s,userMessageId:r},o)||!s||r===void 0||!this.hasUnackedTurn(n)||this.pendingAIResponseStartsByUserMessageId.has(r)||(On(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(r,{channelUrl:n,startedAt:o}))}applyAIResponseStarted(t,n){if(!t.matchesUserMessage){const s=this.findSingleTurn(t.channelUrl);return s?(this.completeTurn(s.requestId,s.turn,n),!0):!1}let r=!1;return this.turns.forEach((s,o)=>{mt(s,t.channelUrl)&&(t.matchesUserMessage&&s.userMessageId!==t.userMessageId||(r=!0,this.completeTurn(o,s,n)))}),r}findSingleTurn(t){let n,r=0;return this.turns.forEach((s,o)=>{mt(s,t)&&(r+=1,!(r>1)&&(n={requestId:o,turn:s}))}),r===1?n:void 0}completeTurn(t,n,r){this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}hasUnackedTurn(t){return di(this.turns.values(),t)}clear(){this.turns.forEach(t=>{Se(t.timer,this.clearTimeoutFn)}),this.turns.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(t){t&&(this.turns.forEach((n,r)=>{n.channelUrl===t&&this.cleanupTurn(r)}),this.pendingAIResponseStartsByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseStartsByUserMessageId.delete(r)}))}commitTimeout(t){const n=this.turns.get(t);if(!n)return;const r=this.clock.now();this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}recordBeforeTpst(t,n){if(t.beforeTpstStartedAt===null)return;const r=n-t.beforeTpstStartedAt;r>=bs&&(t.beforeTpstAbsentMs=r),t.beforeTpstStartedAt=null}recordAfterTpen(t,n){if(t.afterTpenStartedAt===null)return;const r=n-t.afterTpenStartedAt;r>=bs&&(t.afterTpenAbsentMs=r),t.afterTpenStartedAt=null}commitIfAbsent(t,n){const r=n.beforeTpstAbsentMs,s=n.afterTpenAbsentMs;if(r===void 0&&s===void 0){this.cleanupTurn(t);return}et(this.callback,yl,(r??0)+(s??0),{extra:{...r!==void 0&&{before_tpst_absent_ms:r},...s!==void 0&&{after_tpen_absent_ms:s}}}),this.cleanupTurn(t)}cleanupTurn(t){const n=this.turns.get(t);n&&(Se(n.timer,this.clearTimeoutFn),this.turns.delete(t))}}class Hl{constructor(t,n){y(this,"callback");y(this,"clock");y(this,"random");y(this,"sampledByRequestId",new Map);y(this,"sampledByAIMessageId",new Map);y(this,"pendingAIResponseByUserMessageId",new Map);y(this,"collectedCount",0);this.callback=t,this.clock=It(n),this.random=(n==null?void 0:n.random)??Math.random}startTurn(t){this.collectedCount>=10||this.random()>=.15||(this.collectedCount+=1,this.sampledByRequestId.set(t.requestId,{requestId:t.requestId,channelUrl:t.channelUrl,startedAt:this.clock.now()}))}markUserMessageAck(t){const n=this.sampledByRequestId.get(t.requestId);if(!n)return;n.ackAt=this.clock.now(),n.userMessageId=t.messageId;const r=this.pendingAIResponseByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseByUserMessageId.delete(t.messageId),this.applyAIResponseRaw(n,r))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.sampledByRequestId.get(t);r&&(this.sampledByRequestId.delete(t),r.requestId=n,this.sampledByRequestId.set(n,r))}cancelTurn(t){const n=this.sampledByRequestId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(t){const n=this.clock.now(),r=t.aiResponse.userMessageId;if(r===void 0&&this.hasUnackedTurn(t.channelUrl))return;const s=this.findPendingTurn(t.channelUrl,r);if(s){this.applyAIResponseRaw(s,{...t,firstChunkAt:n});return}r===void 0||!this.hasUnackedTurn(t.channelUrl)||this.bufferAIResponseRaw({messageId:t.messageId,...t.channelUrl!==void 0&&{channelUrl:t.channelUrl},aiResponse:t.aiResponse,firstChunkAt:n},r)}markAIResponseVisible(t){const n=this.sampledByAIMessageId.get(t);if(!n||n.ackAt===void 0||n.firstChunkAt===void 0||n.userMessageId===void 0)return!1;const r=this.clock.now();return et(this.callback,bl,r-n.startedAt,{extra:{ack_to_first_chunk_ms:n.firstChunkAt-n.ackAt,first_chunk_to_render_ms:r-n.firstChunkAt,is_streaming:!!n.isStreaming,send_to_ack_ms:n.ackAt-n.startedAt}}),this.deleteTurn(n),!0}hasPendingAIResponse(t){return this.sampledByAIMessageId.has(t)}clearMessage(t){this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.messageId===t&&this.pendingAIResponseByUserMessageId.delete(s)});const n=this.sampledByAIMessageId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(t){t&&(this.sampledByRequestId.forEach(n=>{n.channelUrl===t&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseByUserMessageId.delete(r)}))}clear(){this.sampledByRequestId.clear(),this.sampledByAIMessageId.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findPendingTurn(t,n){if(n!==void 0){for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&mt(s,t)&&s.userMessageId===n)return s;return}let r;for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&mt(s,t)){if(r)return;r=s}return r}applyAIResponseRaw(t,n){t.firstChunkAt===void 0&&(t.firstChunkAt=t.ackAt===void 0?n.firstChunkAt:Math.max(n.firstChunkAt,t.ackAt),t.aiMessageId=n.messageId,t.channelUrl=t.channelUrl??n.channelUrl,t.isStreaming=n.aiResponse.isStreaming,this.sampledByAIMessageId.set(n.messageId,t))}bufferAIResponseRaw(t,n){this.pendingAIResponseByUserMessageId.has(n)||(On(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(n,t))}hasUnackedTurn(t){return di(this.sampledByRequestId.values(),t)}deleteTurn(t){this.sampledByRequestId.delete(t.requestId),t.aiMessageId!==void 0&&this.sampledByAIMessageId.delete(t.aiMessageId),t.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(t.userMessageId)}}function Gl(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const mi=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),vs={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},kr={conversation:{...vs,messageAlertSoundEnabled:!1,list:{...vs,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},ys=e=>e?{conversation:ql(e.conversation),launcher:zl(e.launcher)}:kr,zl=e=>vt(kr.launcher,e),Vl=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},ql=e=>{const t=kr.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...vt(t.list,c,n),deferredMarkdownElements:Vl(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:vt(t.header,r),input:{camera:vt(t.input.camera,u),gallery:vt(t.input.gallery,d),fileEnabled:m},fileViewer:vt(t.fileViewer,o)}},vt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,mi(r));return n},Kl=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),Yl=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),dr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Wl{constructor(){y(this,"_channelHandlerId",null);y(this,"_connectionHandlerId",null);y(this,"_handleActiveChannelChangedThrottled",null);y(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ti(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:Fe(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new We.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new le.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});y(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});y(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:Fe(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});y(this,"_initConversationIfNeeded",async t=>{if(t.isAIAgent&&!t.conversation)try{await t.initConversation({aiAgentId:this.aiAgentId})}catch(n){this._logger.warn("AIAgentEventManager: initConversation failed",n)}});y(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Ke.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Ke.MessengerSettingsUpdated,t)}));y(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Ke.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Ke.ActiveChannelUpdated,t)}));y(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Ke.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Ke.AuthTokenRefreshed,t)}))}}class jl{constructor(t){y(this,"_sdkUser");y(this,"_userSession");y(this,"_dispatcher");y(this,"_activeChannel");y(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(ct.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});y(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(ct.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const hi=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},fi=e=>JSON.parse(e),Xl=e=>JSON.parse(e);function Zl(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Jl(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function Ql({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,hi(c))},e)}async function eu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,hi(c)),e)}var Lr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Lr||{});const gi=e=>typeof e=="object"&&e!==null,Ss=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",tu=e=>!gi(e)||!Ss(e,"channel_url")||!Ss(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},nu={1:tu};function ru(e){if(!gi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=nu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function su(e,t,n,r){const s=fc.default.init({appId:e,modules:[new We.GroupChannelModule,new fe.AIAgentModule],localCacheEnabled:!0,options:new le.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:le.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function ou(e){const t=n=>{throw new Error(`Please initialize chat sdk with ${n}`)};typeof e.groupChannel!="object"&&t("GroupChannelModule"),typeof e.aiAgent!="object"&&t("AIAgentModule")}const iu=[400300,400301,400302,400310],au=Lr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),cu=e=>`${au}:${e}`;class Or{constructor(t,n,r,s,o){y(this,"chatSDK");y(this,"_aiAgentId");y(this,"_externalAuthTokenExpiredEventHandlerKey");y(this,"_logger");y(this,"_cache");y(this,"_statsTrackers");y(this,"_sessionHandler");y(this,"_aiEventHandlerRegistered",!1);y(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const o=new le.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(o)}this._registerAIEventHandler();try{return await this.chatSDK.connect(t.userId,t.authToken),await this._syncTemplatesIfNeeded(),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(o){const i=o;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(c=>this._logger.warn("ChatClient.connect","clear cached-data failure",c));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",i.message,i.code),this.dispose(),i}});y(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});y(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=ru(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Lr.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});y(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});y(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});y(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));y(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));y(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));y(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});y(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});y(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});y(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});y(this,"_isCacheRestrictedError",t=>iu.some(n=>t.code===n));y(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=fi(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=cu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(ou(t.chatSDK),n=t.chatSDK):n=su(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Or(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const rn=new Map,pi={set:(e,t)=>{rn.set(e,t)},get:e=>{if(rn.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=rn.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=rn.entries().next().value;return{platform:t[0],...t[1]}}};class As extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);y(this,"status");y(this,"code");y(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var Nr=(e=>(e.INITIALIZED="INITIALIZED",e.PROACTIVE="PROACTIVE",e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.CLOSED="CLOSED",e.WORK_IN_PROGRESS="WORK_IN_PROGRESS",e.IDLE="IDLE",e))(Nr||{}),Dr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Dr||{}),_i=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(_i||{});const lu=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class uu{constructor(t){y(this,"_appId");y(this,"_apiHost");y(this,"_logger");y(this,"_credential",null);y(this,"_authRefreshPromise",null);y(this,"_onDeskTokenRefreshRequired",async()=>!1);y(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});y(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});y(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});y(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!lu(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});y(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});y(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));y(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));y(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));y(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));y(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new As(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new As(t.status,{})}});y(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class yn{constructor(t,n){y(this,"id");y(this,"title");y(this,"status");y(this,"agent");y(this,"priority");y(this,"group");y(this,"firstResponseTime");y(this,"issuedAt");y(this,"customFields");y(this,"_client");y(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new yn({id:t.id,title:t.channelName??null,status:t.status2??Nr.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??Dr.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class $r{constructor(t){y(this,"_logger");y(this,"_apiClient");y(this,"_onDeskTokenRefreshRequired");y(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);y(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});y(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});y(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});y(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return yn._fromResponse(n,this)});y(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:mi({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return yn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new uu(t)}static init(t){return new $r(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Fr{constructor(){y(this,"authenticate",async t=>!1);y(this,"deauthenticate",()=>{});y(this,"refreshDeskAuthToken",async()=>!1);y(this,"setCustomerLanguage",async()=>{});y(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Fr}}function du(e){return{get:t=>e.getString(t)??null,set:(t,n)=>{e.set(t,n)},delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}const mu=1440*60*1e3,hu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function nt(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function fu(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const gu=e=>{const t={conversationInitialRender:new Ml(e),conversationNotInteractiveTimeout:new kl(e),recoveryNotInteractiveTimeout:new Nl(e),conversationListInitialRender:new wl(e),aievAuthExpiredUnhandled:new Il(e),messagePendingStuck:new Ol(e),userPerceivedResponseTime:new Hl(e),streamStalled:new Pl(e),typingIndicatorAbsentTimeout:new Bl(e),renderedContentUnusable:new $l(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class Sn extends Wl{constructor(n){super();y(this,"appId");y(this,"aiAgentId");y(this,"_chatClient");y(this,"_deskClient");y(this,"_cache");y(this,"_logger");y(this,"_dispatcher");y(this,"_session",null);y(this,"language");y(this,"countryCode");y(this,"context");y(this,"queryParams");y(this,"_config");y(this,"_networkStateAdapter");y(this,"_scheduleForegroundTask");y(this,"_forceCreateChannel");y(this,"_agentVersion");y(this,"_statsTrackers");y(this,"_liveMetricManager");y(this,"_operationQueue",Gl());y(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});y(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));y(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(ct.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:b,session_token:v,expire_at:p}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:b,authToken:v,expireAt:p}),f={userId:b,authToken:v},this._logger.debug("AIAgent.authenticate: anonymous user created",b)}else f={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(f.userId,h),this._dispatcher.send(ct.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var b;return s.type==="anonymous"?gl(this._dispatcher):(b=s.userSessionCandidate)==null?void 0:b.sessionHandler})(),_=await this._chatClient.connect(f,g,b=>{var v;this._logger.debug("AIAgent: session token refreshed"),(v=this._session)==null||v._updateAuthToken(b),this._deskClient.refreshDeskAuthToken(b)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:b})=>{var v;if(b===_i.ERR_SESSION_KEY_EXPIRED){await new Promise(S=>setTimeout(S,2e3));const p=(v=this._session)==null?void 0:v.userSession.authToken;return p?await this._deskClient.refreshDeskAuthToken(p):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new jl({sdkUser:_,userSession:f,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:f.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),h}})});y(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));y(this,"createConversation",async n=>{nt(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});y(this,"searchConversation",async n=>{if(nt(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:fe.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)fu(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});y(this,"closeConversation",async n=>{var s;nt(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===fe.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:fe.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});y(this,"createConversationListCollection",n=>new ni(this.chatSDK,n??{}));y(this,"patchContext",async(n,r)=>{nt(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});y(this,"updateContext",async(n,r)=>{nt(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});y(this,"getContextObject",async n=>{nt(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});y(this,"clearUserMemories",async(n={})=>{nt(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});y(this,"setUserMemoryState",async n=>{nt(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),dr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(ct.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),dr(i)});y(this,"refreshActiveChannel",async n=>{var c,u,d;nt(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});y(this,"_getSessionCandidate",n=>n instanceof ai?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof ur?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});y(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-mu<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});y(this,"_getManualSessionInfo",n=>{if(!n||n instanceof ur)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=ys(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=n.scheduleForegroundTask,this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new fl(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=pi.get(n.platform),s=n.logger??new ii(n.logLevel??wr.WARN),o=n.dispatcher??new ri(s),i=n.useMMKVStorage?du(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=Dc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=gu((_,b)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(_,b)});d=Or.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const f=hu?$r.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Fr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Sn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,scheduleForegroundTask:r.scheduleForegroundTask??(_=>_()),forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:f,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=ys(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}}const be=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function je(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m={Template:i,updateTemplate:h=>c(()=>h),components:u,updateComponent:(h,f)=>d(g=>({...g,[h]:f}))};return a.createElement(t.Provider,{value:m},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function pu(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function _u(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Ei(e,t)}function Ei(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function Eu(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=at.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):at.isToday(s)?n.hoursAgo(at.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Cu=e=>{const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},sn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ts=(e,t)=>{const n=sn(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=Cu(e);return r?`#${sn(r[0])}${sn(r[1])}${sn(r[2])}${n}`:e},bu=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},vu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",yu=e=>e.length>0,Su=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ye(s.type)),r=e.some(s=>!Ye(s.type));return n&&r?Ye(t.type)?e.filter(s=>Ye(s.type)):[t]:r?[t]:e},Is=e=>e.length===0?"empty":e.every(t=>Ye(t.type))?"images":"non_images",Au=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Su(t),s=Is(e),o=Is(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},At=3,Ci=6,Tu=e=>e%At===0?At:Ci,Iu=({index:e,itemCount:t})=>{const n=t%At,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:At,c=o?e-s:e%At,u=!r&&e>=t-At;return{columnSpan:r?Ci/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},bi=be("AIAgent"),xu=bi.Provider,we=bi.useContext;function Ru(e){const t=Mu(e);return a.createElement(xu,{value:{_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}},e.children)}function Mu(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=Sn.init(e);else{const o=wu(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=Sn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function wu(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}const xs=Symbol("conversationMessageEventBridge"),wt=Symbol("conversationMessageEventPublisher"),ku=(e,t)=>{const n=e;if(n[wt]=t,n[xs])return e;n[xs]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=o=>{r({...o,onMessagesAdded:(i,c,u)=>{var d,m;(d=o.onMessagesAdded)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesAdded",source:i.source,messages:u})},onMessagesUpdated:(i,c,u)=>{var d,m;(d=o.onMessagesUpdated)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesUpdated",source:i.source,messages:u})}})};const s=e.initialize.bind(e);return e.initialize=o=>{const i=s(o),c=i.onCacheResult.bind(i),u=i.onApiResult.bind(i);return i.onCacheResult=d=>c((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),i.onApiResult=d=>u((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"api",messages:h??[]})}),i},e},Nn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let Lu=0;function Ou(){return l.useState(()=>`${Lu++}`)[0]}const ht=(e,t,n)=>{const r=l.useRef(t),o=Ou();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var _;const g=r.current;(_=g[h])==null||_.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new We.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Nu(e,t){return!e||!t?!0:e.url!==t.url}function ze(e){return e!=null&&"sendingStatus"in e}function Du(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return ze(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function $u(e,t){return Du(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Rs(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const An={collection:{groupChannel:{defaultOrder:We.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Ms(e){return!e||!Array.isArray(e)?!1:e.length!==0}function ws(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Fu=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=Pu(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=ze(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];Uu(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{ze(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{ze(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>$u(s,n));return t.value.clearBeforeAction?e.newMessageMap=ws(r,Rs):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...ws(r,Rs)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Pu=e=>e.reduce((t,n)=>(ze(n)?(t[n.reqId]=n,n.sendingStatus===$e.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Uu=(e,t,n=!1)=>{var r,s;if(!ze(e)||!ze(t))return!0;if(n&&e&&Re.isStreaming(e)&&Re.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===$e.SendingStatus.SUCCEEDED?t.sendingStatus===$e.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Bu=(e=Hu)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Fu,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(v,p,S,A)=>{i({type:"update_messages",value:{messages:v,clearBeforeAction:p,currentUserId:S,strictStreamingOrder:A}})},u=(v,p)=>{i({type:"delete_messages",value:{messageIds:v,reqIds:p}})},d=(v,p,S)=>{i({type:"update_new_messages",value:{messages:v,clearBeforeAction:p,currentUserId:S}})},m=(v,p)=>{i({type:"delete_new_messages",value:{messageIds:v,reqIds:p}})},h=v=>{i({type:"update_initialized",value:{status:v}})},f=v=>{i({type:"update_loading",value:{status:v}})},g=v=>{i({type:"update_refreshing",value:{status:v}})},_=Object.values(o),b=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:g,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:b,newMessages:_,updateNewMessages:d,deleteNewMessages:m}},ks=Math.floor(Number.MAX_SAFE_INTEGER/10);function Hu(e,t){let n=0,r=0;return ze(e)&&e.sendingStatus!=="succeeded"&&(n=ks),ze(t)&&t.sendingStatus!=="succeeded"&&(r=ks),e.createdAt+n-(t.createdAt+r)}function Ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Gu=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new We.MessageFilter(r)})};function Ls(e){return e<Date.now()?An.collection.message.searchLimit:An.collection.message.defaultLimit}const zu=(e,t,n={})=>{var He,$;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=Ls(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Nn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:_,messages:b,newMessages:v,updateMessages:p,updateNewMessages:S,deleteNewMessages:A,deleteMessages:T,updateInitialized:M,updateLoading:k,updateRefreshing:N}=Bu(n==null?void 0:n.sortComparator),x=Ce(R=>{var O,F,j,X;if(!s.current||!s.current.url)return(O=o==null?void 0:o.error)==null?void 0:O.call(o,"[useGroupChannelMessages] channel is required");try{switch(R){case le.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case le.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case le.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(j=(F=r.current).markAsRead)==null||j.call(F,[s.current]);break}}catch(ne){(X=o==null?void 0:o.warn)==null||X.call(o,"[useGroupChannelMessages/markAsReadBySource]",ne)}}),L=Ce((R,O)=>{var F,j,X,ne,Z;if(O.length>0)switch(R){case le.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case le.CollectionEventSource.SYNC_MESSAGE_FILL:{(j=(F=r.current).shouldCountNewMessages)!=null&&j.call(F)&&S(O,!1,(X=e.currentUser)==null?void 0:X.userId),(Z=(ne=r.current).onMessagesReceived)==null||Z.call(ne,O);break}}}),z=Ce(R=>{var O,F;(F=(O=r.current).onCollectionEvent)==null||F.call(O,R)}),D=Ce(async(R,O,F)=>new Promise((j,X)=>{var Xe;h.current.instance&&h.current.instance.dispose(),x(),S([],!0,(Xe=e.currentUser)==null?void 0:Xe.userId);const ne=()=>{var pe,_e;const{pendingMessages:ie,failedMessages:de}=h.current.instance??{};Ms(ie)&&p(ie,!1,(pe=e.currentUser)==null?void 0:pe.userId),Ms(de)&&p(de,!1,(_e=e.currentUser)==null?void 0:_e.userId)},Z=Gu(R,F,{...r.current,startingPoint:O});h.current={apiInitialized:!1,initialized:!1,instance:Z},Z.setMessageCollectionHandler({onMessagesAdded:(ie,de,pe)=>{var _e;x(ie.source),L(ie.source,pe),p(pe,!1,(_e=e.currentUser)==null?void 0:_e.userId,u),z({kind:"messagesAdded",source:ie.source,channelUrl:R.url,messages:pe})},onMessagesUpdated:(ie,de,pe)=>{var _e,Ee,Ie;x(ie.source),L(ie.source,pe),p(pe,!1,(_e=e.currentUser)==null?void 0:_e.userId,u),ie.source===le.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Ie=(Ee=r.current).onMessagesUpdated)==null||Ie.call(Ee,pe)),z({kind:"messagesUpdated",source:ie.source,channelUrl:R.url,messages:pe})},onMessagesDeleted:(ie,de,pe,_e)=>{const Ee=_e.map(ve=>ve.messageId),Ie=_e.filter(ze).map(ve=>ve.reqId);T(Ee,Ie),A(Ee,Ie),z({kind:"messagesDeleted",source:ie.source,channelUrl:R.url,messages:_e})},onChannelDeleted:(ie,de)=>{var pe,_e;(_e=(pe=r.current).onChannelDeleted)==null||_e.call(pe,de)},onChannelUpdated:(ie,de)=>{var pe,_e;m(),(_e=(pe=r.current).onChannelUpdated)==null||_e.call(pe,de,ie)},onHugeGapDetected:()=>{D(R,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit)}});let ge=!1;Z.initialize(We.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ie,de)=>{var pe,_e,Ee,Ie,ve;(_e=(pe=r.current).onCacheResult)==null||_e.call(pe,ie,de??[],R.url),ie?(e.isCacheEnabled&&((Ee=o==null?void 0:o.error)==null||Ee.call(o,"[useGroupChannelMessages/onCacheResult]",ie)),ge=!0):de&&((Ie=o==null?void 0:o.debug)==null||Ie.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",de.length),p(Z.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),ne(),de.length>0&&(h.current.initialized=!0,j())),z({kind:"initialized",source:"cache",channelUrl:R.url,messages:de??[]})}).onApiResult((ie,de)=>{var pe,_e,Ee,Ie,ve,De,Pe;(_e=(pe=r.current).onApiResult)==null||_e.call(pe,ie,de??[],R.url),h.current.initialized=!0,h.current.apiInitialized=!0,ie?((Ee=o==null?void 0:o.warn)==null||Ee.call(o,"[useGroupChannelMessages/onApiResult]",ie),ge?X(ie):j()):de&&((Ie=o==null?void 0:o.debug)==null||Ie.call(o,"[useGroupChannelMessages/onApiResult]","message length:",de.length),p(Z.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),r.current.startingPoint||(Pe=(De=r.current).onMessagesReceived)==null||Pe.call(De,de),e.isCacheEnabled&&ne(),j()),z({kind:"initialized",source:"api",channelUrl:R.url,messages:de??[]})})}));ht(e,{onUserBanned(R,O){var F,j,X;R.isGroupChannel()&&!Nu(R,s.current)&&(O.userId===((F=e.currentUser)==null?void 0:F.userId)?(X=(j=r.current).onCurrentUserBanned)==null||X.call(j):m())}}),l.useLayoutEffect(()=>{const R=setTimeout(async()=>{e.currentUser&&s.current&&(M(!1),k(!0),await D(s.current,i,c),k(!1),M(!0))});return()=>clearTimeout(R)},[e,(He=e.currentUser)==null?void 0:He.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const W=Ce(async()=>{e.currentUser&&s.current&&(N(!0),await D(s.current,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit),N(!1))}),K=Ce(async()=>{var O;const R=h.current.instance;if(R!=null&&R.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const F=await R.loadPrevious();p(F,!1,(O=e.currentUser)==null?void 0:O.userId)}catch{}finally{d.current.prev=!1}}),w=Ce(()=>{const{initialized:R,instance:O}=h.current;return R&&O?O.hasPrevious:!1}),V=Ce(async()=>{var O;const R=h.current.instance;if(R!=null&&R.hasNext&&!d.current.next)try{d.current.next=!0;const F=await R.loadNext();p(F,!1,(O=e.currentUser)==null?void 0:O.userId)}catch{}finally{d.current.next=!1}}),P=Ce(()=>{const{initialized:R,apiInitialized:O,instance:F}=h.current;return O&&R&&F?F.hasNext:!1}),q=R=>{var O,F,j,X;!R||R.channelUrl!==((O=s.current)==null?void 0:O.url)||(p([R],!1,(F=e.currentUser)==null?void 0:F.userId),(X=(j=r.current).onOutgoingMessageStatusChanged)==null||X.call(j,R))},ue=Ce((R,O)=>{var F;if(!s.current||!s.current.url)throw(F=o==null?void 0:o.error)==null||F.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,X)=>{s.current.sendUserMessage(R).onPending(ne=>{q(ne),O==null||O(ne)}).onSucceeded(ne=>{q(ne),j(ne)}).onFailed((ne,Z)=>{q(Z),X(ne)})})}),Te=Ce((R,O)=>{var F;if(!s.current||!s.current.url)throw(F=o==null?void 0:o.error)==null||F.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,X)=>{s.current.sendFileMessage(R).onPending(ne=>{q(ne),O==null||O(ne)}).onSucceeded(ne=>{q(ne),j(ne)}).onFailed((ne,Z)=>{q(Z),X(ne)})})}),B=Ce((R,O,F)=>{var j;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((X,ne)=>{s.current.sendMultipleFilesMessage(R).onPending(Z=>{q(Z),O==null||O(Z)}).onFileUploaded(Z=>{F==null||F(Z),m()}).onSucceeded(Z=>{q(Z),X(Z)}).onFailed((Z,ge)=>{q(ge),ne(Z)})})}),G=Ce(async(R,O)=>{var j,X;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const F=await s.current.updateUserMessage(R,O);return F.channelUrl===s.current.url&&p([F],!1,(X=e.currentUser)==null?void 0:X.userId),F}),I=Ce(async(R,O)=>{var j,X;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const F=await s.current.updateFileMessage(R,O);return F.channelUrl===s.current.url&&p([F],!1,(X=e.currentUser)==null?void 0:X.userId),F}),Y=Ce(async(R,O,F)=>{var j;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((X,ne)=>{let Z;R.isUserMessage()&&(Z=s.current.resendMessage(R)),R.isFileMessage()&&(Z=s.current.resendMessage(R)),R.isMultipleFilesMessage()&&(Z=s.current.resendMessage(R)),Z&&("onPending"in Z&&Z.onPending(ge=>{q(ge),O==null||O(ge)}),"onFileUploaded"in Z&&Z.onFileUploaded(ge=>{F==null||F(ge),m()}),"onSucceeded"in Z&&Z.onSucceeded(ge=>{q(ge),X(ge)}),"onFailed"in Z&&Z.onFailed((ge,Xe)=>{q(Xe),ne(ge)}))})}),te=Ce(async R=>{var O,F;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(R.sendingStatus==="succeeded")R.isUserMessage()&&await s.current.deleteMessage(R),R.isFileMessage()&&await s.current.deleteMessage(R),R.isMultipleFilesMessage()&&await s.current.deleteMessage(R);else try{await((F=h.current.instance)==null?void 0:F.removeFailedMessage(R.reqId))}finally{T([],[R.reqId])}}),se=Ce(()=>{var R;S([],!0,(R=e.currentUser)==null?void 0:R.userId)}),Ne=Ce(async R=>{var O;if(e.currentUser&&s.current){const F=Ls(R);k(!0),p([],!0,(O=e.currentUser)==null?void 0:O.userId),await D(s.current,R,F),k(!1)}});return{initialized:f,loading:g,refreshing:_,messages:b,newMessages:v,resetNewMessages:se,refresh:W,loadPrevious:K,hasPrevious:w,loadNext:V,hasNext:P,sendUserMessage:ue,sendFileMessage:Te,sendMultipleFilesMessage:B,updateUserMessage:G,updateFileMessage:I,resendMessage:Y,deleteMessage:te,resetWithStartingPoint:Ne,_dangerous_reducer_updateMessages:p,_dangerous_reducer_deleteMessages:T}},Vu=(e,t,n)=>{const r=l.useRef(0),s=l.useRef(new Set),o=l.useCallback(d=>{const m={id:r.current+=1,...d};s.current.forEach(h=>{h(m)})},[]),i=l.useCallback(d=>{var h;const m=((h=n==null?void 0:n.collectionCreator)==null?void 0:h.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new We.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return ku(m,o)},[t,n==null?void 0:n.collectionCreator,o]),c=zu(e,t,{...n,collectionCreator:i,strictStreamingOrder:!0}),u=l.useCallback(d=>(s.current.add(d),()=>{s.current.delete(d)}),[]);return{...c,subscribeMessageEvents:u}},qu=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(!1),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);s.current=t;const d=l.useCallback(p=>r.current===p,[]),m=l.useCallback(()=>{o.current&&(n.clear(),o.current=!1,i.current=null)},[n]),h=l.useCallback(p=>{if(!s.current)return;const S=!o.current||i.current!==p;n.start(p),S&&n.onGetChannelStart(p),o.current=!0,i.current=p},[n]),f=l.useCallback(p=>{d(p)&&(u.current=p,c.current=null,h(p))},[d,h]),g=l.useCallback(({channelUrl:p,conversationId:S})=>{o.current||h(p),n.onGetChannelComplete({channelUrl:p,conversationId:S})},[h,n]),_=l.useCallback(({channelUrl:p,error:S})=>{o.current||h(p),n.onGetChannelError({channelUrl:p,error:S})},[h,n]),b=l.useCallback(p=>{if(d(p.channelUrl)){if(u.current=null,!s.current){c.current=p;return}c.current=null,g(p)}},[d,g]),v=l.useCallback(p=>{if(d(p.channelUrl)){if(u.current=null,!s.current){c.current=p;return}c.current=null,_(p)}},[d,_]);return l.useEffect(()=>{if(t){const p=c.current;if(p){if(c.current=null,p.channelUrl!==e)return;"error"in p?_(p):g(p);return}const S=u.current;if(S){if(S!==e){u.current=null;return}h(S)}return}m()},[e,m,t,_,g,h]),l.useEffect(()=>(r.current=e,o.current=!1,i.current=null,c.current=null,u.current=null,()=>{m(),o.current=!1,i.current=null,c.current=null,u.current=null}),[e,m]),{onFetchStart:f,onFetchSuccess:b,onFetchError:v}},Ku=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(_=>r.current===_,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(_=>{c(_)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:_,conversationId:b})=>{i.current=!0,n.markChannelJoined(b,_)},[n]),h=l.useCallback(({channelUrl:_})=>{n.clearChannel(_),i.current=!1},[n]),f=l.useCallback(_=>{if(c(_.channelUrl)){if(!s.current){o.current=_;return}o.current=null,m(_)}},[c,m]),g=l.useCallback(_=>{if(c(_.channelUrl)){if(!s.current){o.current=_;return}o.current=null,h(_)}},[c,h]);return l.useEffect(()=>{if(t){const _=o.current;if(!_||(o.current=null,_.channelUrl!==e))return;"error"in _?h(_):m(_);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:f,onFetchError:g}},Yu=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var g;(g=o.current)==null||g.call(o),o.current=null;const f=u.current;h&&(u.current=null),h&&f&&r.clearChannel(f)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const f=c.current,g=()=>{if(!i.current||f!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(g))??null,n||g()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},Bt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function vi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Wu(e){const t=vi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function ju(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Xu(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function Zu(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function on(e,t,n){const[r,s,o]=Wu(e),[i,c,u]=Xu(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=Zu(i,m,d);return ju([Math.round(h),Math.round(f),Math.round(g)])}function Ju(e,t="light"){return{extraDark:on(e,.6,1.2),dark:on(e,.85,1.1),main:e,light:on(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:on(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function mr(e){const t=vi(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?Bt.BLACK:Bt.WHITE}function Qu(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const ed=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),an={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},Wn={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function Os(e){const t=td(e),n=nd(e,t),r=sd(n,e.colors,e.selectedTheme),s=id(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function td({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===an.primary.main?an.primary:Ju(n,e):an.primary;return{...an,primary:r,...t}}function nd({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??mr(o),c=n??Bt.DEFAULT_BOT_MSG_BG,u=r??mr(c);return(e==="light"?Qu:ed)(s,o,i,c,u)}function rd(e,t,n){return typeof e=="string"?e:e[t]??n}function sd(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=rd(m,n,h)}}}return r}function od(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function id({typography:e}){if(!e)return Wn;const t={...Wn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Wn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=od(s,r,o)}}),t}const{Provider:ad,useContext:Pr}=be("AIAgentTheme");function cd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Os({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((m,h)=>{h&&(i.current=h);const f=(s==null?void 0:s.theme)??m,g=i.current?i.current.themes[f]:null,_={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!_.primary&&(g!=null&&g.primary_color)&&(_.primary=g.primary_color,_.primaryContrast=g.primary_contrast_color),!_.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(_.botMessageBackground=g.bot_message_bg_color,_.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const b=Os({selectedTheme:f,palette:t,typography:n,colors:r,..._});u(b),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);return l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),a.createElement(ad,{value:{theme:c,updateTheme:d}},o)}const jn=25*1024*1024,Ns=1,Ds=new Set(["image/png","image/jpeg","image/jpg"]),$s=new Set(["application/pdf"]),ld={off:"off",always:"always",handed_off_only:"handed_off_only"},ud=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:Ns,attachmentMode:"handed_off_only",defaultUploadSizeLimit:jn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Ds,supportedFileMimeTypes:$s})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Ns,attachmentMode:ld[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??jn,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??Ds),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??$s)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=jn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?rt(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return rt(o);default:return!0}},get supportedMimeTypes(){return c()?[lr]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},Fs=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},kt=e=>({...e,context:e.context??{}}),{Provider:dd,useContext:ft}=be("AIAgentMessengerSession"),md=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=we(),{updateTheme:c}=Pr(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[_,b]=l.useState(null),[v,p]=l.useState(null),[S,A]=l.useState(null),[T,M]=l.useState(null),{updateBaseAttachmentRules:k,createAttachmentRules:N}=ud();l.useEffect(()=>{const D=r.onMessengerSettingsUpdated(({settings:w})=>{const{appearance:V,bot:P,launcher:q,memory:ue}=w;c(V.selected_theme,V),p(Kl(P)),A(Yl(q)),M(ue?dr(ue):null),k(w)}),W=r.onActiveChannelUpdated(({channelUrl:w,status:V,conversationStatus:P})=>{h({url:w,status:V,conversationStatus:P})}),K=r.onAuthTokenRefreshed(()=>{var V;const w=(V=r.session)==null?void 0:V.userSession.authToken;w&&b(P=>P?{...P,authToken:w}:null)});return()=>{D(),W(),K()}},[r,c,k]);const x=l.useCallback(async()=>{try{const D=await r.authenticate(e),W=r.session;return g(W.sdkUser),b(W.userSession),h(W.activeChannel),d(void 0),D}catch(D){throw g(null),b(null),h(void 0),d(D),D}},[r,e]),L=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),b(null),p(null),A(null),M(null)},[r]),z=l.useCallback(async()=>{if(!r.session){if(_)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(_==null?void 0:_.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,_]);return l.useImperativeHandle(n,()=>{const D=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:x,deauthenticate:L,updateContext:async(...W)=>{const K=Fs(...W);if(K.type==="active"){const P=await(await D()).updateContext(o,K.context);return kt(P)}const w=await s.aiAgent.updateContext(K.aiAgentId,K.channelUrl,K.context);return kt(w)},patchContext:async(...W)=>{const K=Fs(...W);if(K.type==="active"){const P=await(await D()).patchContext(o,K.context);return kt(P)}const w=await s.aiAgent.patchContext(K.aiAgentId,K.channelUrl,K.context);return kt(w)},getContextObject:async()=>{const K=await(await D()).getContextObject(o);return kt(K)}}},[x,L,m,s,o,i]),a.createElement(dd,{value:{sdkUser:f,userSessionInfo:e,userSession:_,activeChannel:m,setActiveChannel:h,refreshActiveChannel:z,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:u,aiAgentInfo:v,launcherInfo:S,memoryInfo:T,authenticate:x,deauthenticate:L,createAttachmentRules:N}},t)}),hd={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},fd=e=>e.disabled?hd[e.disabledBy]==="ready":!0,gd=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ye(t)?"file_image":t&&zt(t)?"file_video":t&&Tc(t)?"file_audio":"file_document"};let Ps=0;const pd=e=>(Ps+=1,`${e??"unknown"}:${Ps}`),yt=(e,t)=>e===void 0||t===e,yi=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Si=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},_d=(e,t)=>{e.conversationInitialRender.onCacheResult(t.error),yi(e,t)},Ed=(e,t)=>{e.conversationInitialRender.onApiResult(t.error),Si(e,t)},Cd=(e,t,n)=>{var o;if(!st(e,n))return;const{hasResponseMetadata:r,...s}=jo(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},Us=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Qe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},Xn=(e,t)=>{t&&(e.conversationInitialRender.clear(),e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},bd=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=we(),{aiAgentInfo:r}=ft(),s=l.useRef(!1),o=r==null?void 0:r.userId;ht(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},vd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0),s=l.useRef(e);l.useLayoutEffect(()=>{const o=r.current,i=s.current;if(s.current=e,!e){o&&(Xn(n,o),r.current=void 0);return}o&&o!==t&&(Xn(n,o),r.current=void 0),t&&o!==t&&(i||n.conversationInitialRender.start(),n.conversationInitialRender.setChannelUrl(t),n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const o=r.current;o&&(Xn(n,o),r.current=void 0)},[n])},yd=({aiAgentUserId:e,conversationStatsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(g=>i.current&&c.current===g,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const g=d.current;d.current=t,!(g||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const f=l.useCallback(g=>g.lifecycleGeneration===u.current&&yt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(r.conversationInitialRender.onCacheResult(g.error),g.tracked=!0),yi(r,g));const _=o.current;_&&f(_)&&(_.tracked||(r.conversationInitialRender.onApiResult(_.error),_.tracked=!0),Si(r,_))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&yt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(_=>Us(_,r));return}t&&g.messages.forEach(_=>Cd(_,r,e))}},onCacheResult:(g,_,b)=>{if(!h(m)||!yt(n,b))return;const v={error:g,messages:_,channelUrl:b,lifecycleGeneration:u.current,tracked:!1};s.current=v,t&&(_d(r,v),v.tracked=!0)},onApiResult:(g,_,b)=>{if(!h(m)||!yt(n,b))return;const v={error:g,messages:_,channelUrl:b,lifecycleGeneration:u.current,tracked:!1};o.current=v,t&&(Ed(r,v),v.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&yt(n,g.channelUrl)&&Us(g,r)}}),[e,m,t,h,n,r])},Sd=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputEnabled(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationInitialRender.markRendered(t)&&(i.current=!0),o.conversationNotInteractiveTimeout.markRendered(t))});return()=>clearTimeout(d)},[t,e,n,s,o])},Ad=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(b=>u==null?void 0:u(b),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,_=b=>g()&&yt(f,b);try{const b=await c(v=>{if(!_(v.channelUrl)){u==null||u(v);return}m=v.reqId,n.messagePendingStuck.start({requestId:v.reqId,channelUrl:v.channelUrl,messageType:gd(v),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(v)},v=>{!g()||m!==v||n.messagePendingStuck.markUploadProgress(v)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),b}catch(b){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),b}},[n])},Td=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=pd(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const f=await c(g=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,g),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,g),h=g)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:f.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:f.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),f}catch(f){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),f}},[e,n])},Id=({requestedChannelUrl:e,activeChannelUrl:t,conversationStatsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ft();bd({activeChannelUrl:t,statsTrackers:r}),vd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=yd({aiAgentUserId:s==null?void 0:s.userId,conversationStatsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Ad({channelUrl:t,enabled:n,statsTrackers:r}),c=Td({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},jt=()=>we()._aiAgentSDK.statsTrackers,Xt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new le.ConnectionHandler({onDisconnected:o=>{var i,c;return(c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o)},onConnected:o=>{var i,c;return(c=(i=r.current).onConnected)==null?void 0:c.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,c;return(c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},Bs=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function xd(e,t={}){const{chatSDK:n,logger:r,aiAgentId:s,_aiAgentSDK:o}=we(),{sdkUser:i}=ft(),c=Bs(),u=Bs(),d=Nn(),[m,h]=l.useState(void 0),[f,g]=l.useState(void 0),[_,b]=l.useState(!1);function v(S){if(S.isAIAgent&&!S.conversation){const A=u.next();b(!0),o.initConversationIfNeeded(S).finally(()=>{u.isCurrent(A)&&b(!1)})}}async function p(){var A,T,M,k,N,x;const S=c.next();if(!i){r.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(r.debug("useChannel.getChannel: start"),h(void 0),g(void 0),u.invalidate(),b(!1),e){(A=t.onFetchStart)==null||A.call(t,e);try{r.debug("useChannel.getChannel: get channel",e);const L=await n.groupChannel.getChannel(e);if(!c.isCurrent(S))return;v(L),h(L),(M=t.onFetchSuccess)==null||M.call(t,{channelUrl:L.url,conversationId:(T=L.conversation)==null?void 0:T.id}),L.url===((k=o.session)==null?void 0:k.activeChannel.url)&&o.session._updateActiveChannel({url:L.url,status:Fe(L)?"closed":"open",conversationStatus:(N=L.conversation)==null?void 0:N.status}),r.debug("useChannel.getChannel: fetched channel",L)}catch(L){if(!c.isCurrent(S))return;(x=t.onFetchError)==null||x.call(t,{channelUrl:e,error:L}),L instanceof le.SendbirdError&&g(L),r.error("useChannel.getChannel: error",L)}}}return l.useEffect(()=>(p(),()=>{c.invalidate()}),[n,i,e,s]),Xt(n,{async onReconnectSucceeded(){var T;if(!m){f&&await p();return}const S=c.current(),A=await m.refresh();!c.isCurrent(S)||m.url!==e||((T=t.onReconnectSucceeded)==null||T.call(t,m.url),v(A),h(A))}}),ht(n,{onChannelChanged:S=>{S.isGroupChannel()&&S.url===e&&(r.debug("useChannel.onChannelChanged: channel changed",S.url),h(S),d())}}),{channel:m,channelFetchError:f,getChannel:p,isInitializingConversation:_}}const Rd=new Set(["suggested_replies","steward","system"]),Md=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!(!r||!Rd.has(r)))return r},wd=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=kn(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},kd=()=>{const{chatSDK:e,networkStateAdapter:t}=we(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Xt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===le.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Ld=3e4,Od=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&st(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=f=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},f)},m=Date.now()-c,h=Ld-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ai=e=>{const{chatSDK:t}=we(),[n,r]=l.useState([]);return ht(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Nd=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Ai(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=st(t,n)&&(Re.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},Dd=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ft(),i=kd(),c=Nd({channel:e,lastMessage:fs(t,[$e.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Od({shouldApply:!!(e!=null&&e.isAIAgent)&&!rt(e),isBlockedWhileAIResponding:c,lastMessage:fs(t,[$e.SendingStatus.PENDING,$e.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""}),d=h=>h===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:h==="ai_responding"?{disabled:!0,disabledBy:h,focusPolicy:"preserve"}:{disabled:!0,disabledBy:h,focusPolicy:"release"};if(!e||i==="disconnected")return d("unavailable");if(i==="reconnecting")return d("reconnecting");if(Fe(e))return d("conversation_closed");if(el(e))return d("handoff_pending");if(wd(e))return d("form_active");const m=Md(e);return d(m||(c||u||r?"ai_responding":""))},$d=()=>{const[e,t]=l.useState(new Set),n=l.useCallback(s=>{t(o=>{if(o.has(s))return o;const i=new Set(o);return i.add(s),i})},[]),r=l.useCallback(s=>{t(o=>{if(!o.has(s))return o;const i=new Set(o);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Fd}=be("AIAgentConversation"),Pd=({initialRenderStats:e,notInteractiveStats:t,recoveryStats:n})=>({onFetchStart:r=>{e.onFetchStart(r),t.onFetchStart(r)},onFetchSuccess:r=>{e.onFetchSuccess(r),t.onFetchSuccess(r)},onFetchError:r=>{e.onFetchError(r),t.onFetchError(r)},onReconnectSucceeded:n.onReconnectSucceeded});function Ud({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=ce,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldCountNewMessages:h=()=>!1,sortComparator:f}){var Te;const g=()=>d&&(x==null?void 0:x.markAsRead()),{_aiAgentSDK:_,chatSDK:b,logger:v,dispatcher:p}=we(),S=jt(),A={channelUrl:t,enabled:m},T=qu({...A,statsTracker:S.conversationInitialRender}),M=Ku({...A,statsTracker:S.conversationNotInteractiveTimeout}),k=Yu({...A,scheduleForegroundTask:_.scheduleForegroundTask,statsTracker:S.recoveryNotInteractiveTimeout}),N=Pd({initialRenderStats:T,notInteractiveStats:M,recoveryStats:k}),{channel:x,channelFetchError:L,getChannel:z,isInitializingConversation:D}=xd(t,N),W=x==null?void 0:x.url,K=Id({requestedChannelUrl:t,activeChannelUrl:W,conversationStatsEnabled:m,statsTrackers:S}),w=Vu(b,x,{replyType:$e.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:h,onChannelDeleted:n,onMessagesReceived:B=>r==null?void 0:r(B),onMessagesUpdated:B=>s==null?void 0:s(B),...K.messageCallbacks,onOutgoingMessageStatusChanged:B=>{x&&_.liveMetricManager.track({type:"outgoingMessage",channel:x,message:B})},logger:v,markAsRead:g,sortComparator:f}),V=$d(),P=Dd({channel:x,messages:w.messages,isStreamAnimating:V.isAnimating,isInitializingConversation:D});Sd({enabled:m,channelUrl:W,initialized:w.initialized,inputReady:fd(P),renderedSignal:w.messages,statsTrackers:S}),l.useEffect(()=>{g()},[d,x]);const q=Fe(x);l.useEffect(()=>{o==null||o(q)},[q,o]),l.useEffect(()=>{const B=async G=>{const I=typeof(G==null?void 0:G.channelUrl)=="string";x&&I&&G.channelUrl!==x.url||(v.debug("conversation.dispatcher: try to close conversation",x),x!=null&&x.conversation&&x.conversation.status===fe.ConversationStatus.OPEN&&(await x.closeConversation(),i==null||i()))};return p.subscribe(Ke.ConversationClose,B),()=>{p.unsubscribe(Ke.ConversationClose,B)}},[p,x,v,(Te=x==null?void 0:x.conversation)==null?void 0:Te.status,i]);const ue={conversation:(x==null?void 0:x.conversation)??void 0,actions:{setUserMemoryState:_.setUserMemoryState},channelSource:{channel:x,error:L,refetch:()=>z(),closeConversation:async()=>{Fe(x)||await(x==null?void 0:x.closeConversation())}},messageSource:{messages:w.messages,newMessages:w.newMessages,initialized:w.initialized,subscribeMessageEvents:w.subscribeMessageEvents,loadPrevious:()=>w.loadPrevious(),loadNext:()=>w.loadNext(),deleteMessage:async B=>{try{await w.deleteMessage(B)}finally{B.sendingStatus!=="succeeded"&&K.messageCallbacks.onLocalMessageDeleted(B)}},resendMessage:B=>B.isUserMessage()?K.runWithUserTurnStats(G=>K.runWithPendingStuckStats(I=>w.resendMessage(B,Y=>{G(Y.reqId),I(Y)}),void 0)):K.runWithPendingStuckStats((G,I)=>w.resendMessage(B,G,I),void 0,{tracksUploadProgress:B.isMultipleFilesMessage()}),resetNewMessages:()=>w.resetNewMessages(),sendUserMessage:async B=>{var I;if(((I=x==null?void 0:x.conversation)==null?void 0:I.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(B=await c(B));const G=await K.runWithUserTurnStats(Y=>K.runWithPendingStuckStats(te=>w.sendUserMessage(B,se=>{Y(se.reqId),te(se)}),u));return u==null||u(G),G},sendFileMessage:async B=>{var I;if(((I=x==null?void 0:x.conversation)==null?void 0:I.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(B=await c(B));const G=await K.runWithPendingStuckStats(Y=>w.sendFileMessage(B,Y),u);return u==null||u(G),G},sendMultipleFilesMessage:async B=>{var I;if(((I=x==null?void 0:x.conversation)==null?void 0:I.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(B=await c(B));const G=await K.runWithPendingStuckStats((Y,te)=>w.sendMultipleFilesMessage(B,Y,te),u,{tracksUploadProgress:!0});return u==null||u(G),G}},state:{streamAnimation:V,input:P}};return a.createElement(Fd,{value:ue},e)}function Bd(e,t,n){var p,S,A,T,M,k,N,x,L,z;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=Ce(()=>{var D;return(D=n==null?void 0:n.onListRequestStart)==null?void 0:D.call(n)}),g=Ce(()=>{var D;return(D=n==null?void 0:n.onListRequestComplete)==null?void 0:D.call(n)}),_=l.useCallback(async D=>{f(),await D.loadMore(),g()},[f,g]),b=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const D=new ni(e,t);D.setConversationListCollectionHandler({onChannelsAdded:()=>{u(D.channels)},onChannelsUpdated:()=>{u(D.channels)},onChannelsDeleted:()=>{u(D.channels)}}),await _(D),u(D.channels),m(D),i(null)}catch(D){m(null),i(D)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(p=t.filter)==null?void 0:p.aiAgentChannelFilter,(A=(S=t.filter)==null?void 0:S.aiAgentConversationStatusFilter)==null?void 0:A.join(),(M=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:M.join(),(k=t.filter)==null?void 0:k.deskChannelFilter,(x=(N=t.filter)==null?void 0:N.pinnedChannelUrls)==null?void 0:x.join(),(L=t.filter)==null?void 0:L.copilotConversationOnly,(z=t.filter)==null?void 0:z.copilotSupportChannelUrl,t.limit,_]),v=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(D){i(D)}},[d]);return Xt(e,{onConnected:()=>b()}),l.useEffect(()=>{b()},[b]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:v}}const Ti=e=>{var s;const{aiAgentId:t,queryParams:n}=we(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[fe.ConversationStatus.CLOSED,fe.ConversationStatus.OPEN],...r,...e}},Hd=({enabled:e=!0}={})=>{const n=jt().conversationListInitialRender,r=l.useRef(e),s=l.useRef(!1),o=l.useRef(!1),i=l.useRef(!1);r.current=e,l.useEffect(()=>{if(!e){o.current&&(s.current=!0);return}if(o.current&&!s.current)return;const m=s.current&&i.current;n.onInitializeStart(),o.current=!0,s.current=!1,m&&n.onListRequestStart()},[e,n]),l.useEffect(()=>()=>{n.clear(),o.current=!1,s.current=!1,i.current=!1},[n]);const c=l.useCallback(()=>r.current&&o.current&&!s.current,[]),u=l.useMemo(()=>({onListRequestStart:()=>{i.current=!0,c()&&n.onListRequestStart()},onListRequestComplete:()=>{i.current=!1,c()&&n.onListRequestComplete()}}),[c,n]),d=l.useCallback(()=>{c()&&n.onRendered()},[c,n]);return l.useMemo(()=>({collectionCallbacks:u,onRendered:d}),[u,d])},{Provider:Gd}=be("AIAgentConversationList");function zd({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=we(),i=Hd({enabled:n}),c=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),u=Ti(t),d=Bd(s,{limit:c,filter:u},i.collectionCallbacks);l.useEffect(()=>{n&&d.initialized&&(d.error||i.onRendered())},[n,d.error,d.initialized,i]);const m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(Gd,{value:m},r)}function Vd(e){let t="pending",n=e.then(r=>{t="resolved",n=r}).catch(r=>{t="rejected",n=r});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:qd,useContext:Kd}=be("MessageTemplateFetching");function Yd({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const g=m(h);if(g)return g;const _=r.current[h];if(_)return _;f||i(h,{fetching:!0});const b=d(h).catch(v=>{throw f||i(h,{error:!0}),v}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=b,b},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Vd(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(qd,{value:u},e)}const Wd="remove_powered_by",Ur=(e,t)=>{var s,o;const{chatSDK:n}=we(),{aiAgentInfo:r}=ft();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&Rr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(Wd)),[i])}throw new Error("Unsupported feature")},jd={required:"This question is required",minLength:e=>`Minimum ${e} characters required`,maxLength:e=>`Maximum ${e} characters allowed`,min:e=>`Minimum value is ${e}`,max:e=>`Maximum value is ${e}`,minSelect:e=>`Select at least ${e} options`,maxSelect:e=>`Select at most ${e} options`,regex:"Invalid format",invalidSelection:"Invalid selection"},Xd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Zd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Jd={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;return e.required&&!r?{isValid:!1,error:n.required}:r&&!e.options.includes(r)?{isValid:!1,error:n.invalidSelection}:{isValid:!0}}},Qd={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},em={text:Xd,number:Zd,"single-select":Jd,"multi-select":Qd},tm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ii(e){return em[e.type]||tm}function Hs(e){return Ii(e).getValueOrDefault(e)}function nm(e,t,n={}){const r={...jd,...n};return Ii(e).validate(e,t,r)}const rm=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const b={};return e.fields.forEach(v=>{b[v.key]=Hs(v)}),b}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const b={};let v=!1;e.fields.forEach(p=>{const S=Hs(p);JSON.stringify(c[p.key])!==JSON.stringify(S)&&(v=!0),b[p.key]=S}),v&&u(b)}},[d]);const m=(b,v)=>{u(p=>({...p,[b]:v})),i(p=>({...p,[b]:void 0}))},h=e.fields.map(b=>{var S,A,T;const v=c[b.key]??null,p={key:b.key,label:b.label,error:o[b.key],required:b.required};return b.type==="text"?{...p,type:"text",layout:b.layout,value:v,...b.placeholder&&{placeholder:b.placeholder},...((S=b.rules)==null?void 0:S.max_length)&&{maxLength:b.rules.max_length}}:b.type==="number"?{...p,type:"number",layout:b.layout,value:v,...b.placeholder&&{placeholder:b.placeholder},...((A=b.rules)==null?void 0:A.max)&&{max:b.rules.max}}:b.type==="single-select"?{...p,type:"single-select",layout:b.layout,value:v,options:b.options}:b.type==="multi-select"?{...p,type:"multi-select",layout:b.layout,value:v,options:b.options,...((T=b.rules)==null?void 0:T.max_select)&&{maxSelect:b.rules.max_select}}:{...p,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:b=>h.find(v=>v.key===b),updateFieldValue:m,submit:async()=>{const b={};let v=!1;for(const p of e.fields){const S=c[p.key]??null,A=nm(p,S,n);A.isValid||(b[p.key]=A.error,v=!0)}if(i(b),!v&&r){const p={};e.fields.forEach(S=>{p[S.key]=c[S.key]??null}),await r(p)}},cancel:async()=>{await(s==null?void 0:s())}}},sm=e=>{const{chatSDK:t,handlers:n,logger:r}=we(),{aiAgentInfo:s}=ft(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!st(m,s.userId))return;const f=m.messageId;if(Re.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=Yo(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,f)=>{m.url===e&&(c(h,f),u(h))};return ht(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},om=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},xi=e=>{const{aiAgentInfo:t}=ft(),n=Ai(e);if(Fe(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?om(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},im=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},am=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},cm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=am(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},lm=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},Br=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=si(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?rt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Gs=e=>l.useReducer((t,n)=>({...t,...n}),e);var Je=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(Je||{});const um=new Set(["free_text","single_choice"]),dm=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Gs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Gs({followUpItem:!1}),d=l.useMemo(()=>{var v;const g=o.csat,_=typeof g=="number",b=(v=e.follow_up)==null?void 0:v.find(p=>_?p.scores.includes(g):p.always_visible??!1);if(um.has(b==null?void 0:b.response_type))return b},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===Je.AI_AGENT_CSAT_5||t===Je.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Je.AI_AGENT_CSAT_5_WITH_CRE){const _=typeof o.csat=="number",b=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(_&&b)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},mm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!Je[n.type],o=!r&&typeof e!="number"&&oi(t),i=Nn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},Zn=5,Nt=250,hm=50,zs=e=>Math.max(0,e-hm),gn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,fm=e=>e<1e3?{speed:Zn*.5,chunkSize:2}:e<2e3?{speed:Zn*.8,chunkSize:2}:{speed:Zn*.6,chunkSize:3},pn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Vs=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(pn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Ri=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!pn(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!pn(e,s),c=e[s]==="["&&!pn(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=Vs(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=Vs(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},gm=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(S=>{var A;(A=r.current)==null||A.call(r,S)},[]),m=l.useCallback(S=>{const A=e.initialEnabled&&(e.enabled||S<e.textLength),T=A&&e.deferImages,M=A&&e.deferLinks;return!T&&!M?S:Ri(e.text.slice(0,S),{hideImages:T,hideLinks:M}).length},[e]),h=l.useCallback((S,A,T=!1)=>{r.current&&(S<=c.lastLength||!T&&A-c.lastReportedAt<Nt||(c.lastLength=S,c.lastReportedAt=A,d(S)))},[d,c]),f=l.useCallback((S,A,T=!1)=>{if(!r.current)return;const M=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&A-M<Nt||(c.lastCheckedAt=A,h(m(S),A,!0))},[m,h,c]),g=l.useCallback((S,A,T=!1)=>{s.current&&(S<=i.lastLength||!T&&A-i.lastReportedAt<Nt||(i.lastLength=S,i.lastReportedAt=A,s.current(S)))},[i]),_=l.useCallback((S,A,T)=>{const M=S>=A,k=T-i.lastReportedAt>=Nt;if(!M&&!k)return;const N=m(S);g(N,T,M)},[m,i,g]),b=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),v=l.useCallback(S=>{r.current&&(o.current!==null&&S<=o.current||(o.current=S,d(S)))},[d]),p=l.useCallback(({displayedLength:S,streamTextLength:A})=>{const T=u.current;if(u.current={displayedLength:S,streamTextLength:A},!e.initialEnabled||!T||S>T.displayedLength||A<=T.streamTextLength)return;const M=gn();h(A,M,!0),g(A,M,!0)},[u,g,h,e]);return{resetProgress:b,reportVisibleTextProgress:f,reportRenderedTextProgress:_,reportNonStreamingVisibleTextProgress:v,reportMarkdownRevealProgress:p}},pm=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onVisibleTextProgress:u,onRenderedTextProgress:d}=e,m=s.includes("image"),h=s.includes("link"),[f,g]=l.useState(()=>zs(t.length)),_=l.useRef(null),b=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,v=l.useRef({startCalled:!1,completeCalled:!1}).current,p=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:m,deferLinks:h,snapOnDisable:r}).current,S=Ce(()=>o==null?void 0:o()),A=Ce(()=>i==null?void 0:i()),T=Ce(()=>c==null?void 0:c()),{resetProgress:M,reportVisibleTextProgress:k,reportRenderedTextProgress:N,reportNonStreamingVisibleTextProgress:x,reportMarkdownRevealProgress:L}=gm({trackedRef:p,onVisibleTextProgress:u,onRenderedTextProgress:d}),z=n,D=f<t.length,W=p.initialEnabled&&(z||D);l.useLayoutEffect(()=>{p.textLength=t.length,p.enabled=n,p.text=t,p.deferImages=m,p.deferLinks=h,p.snapOnDisable=r}),l.useLayoutEffect(()=>{if(p.initialEnabled){if(v.startCalled||(v.startCalled=!0,S()),!p.enabled&&p.snapOnDisable){g(t.length);const w=gn();k(t.length,w,!0),N(t.length,t.length,w);return}g(w=>t.length<w?t.length:w)}},[S,N,k,t]),l.useEffect(()=>{if(!p.initialEnabled)return;let w=zs(t.length);b.lastUpdate=0,b.startTime=0,b.lastProgressCall=0,M();const V=P=>{b.lastUpdate===0&&(b.lastUpdate=P,b.startTime=P,b.lastProgressCall=P,w>0&&k(w,P,!0));const q=p.textLength;!p.enabled&&p.snapOnDisable&&w<q&&(w=q,g(w),k(w,P,!0),N(w,q,P));const ue=P-b.lastUpdate,Te=P-b.startTime,{speed:B,chunkSize:G}=fm(Te),I=B*G;ue>=I&&w<q&&(w=Math.min(w+G,q),g(w),k(w,P,w>=q),N(w,q,P),b.lastUpdate=P),P-b.lastProgressCall>=Nt&&(b.lastProgressCall=P,A()),(w<q||p.enabled)&&(_.current=requestAnimationFrame(V))};return _.current=requestAnimationFrame(V),()=>{_.current&&cancelAnimationFrame(_.current),v.startCalled&&!v.completeCalled&&(v.completeCalled=!0,T())}},[T,A,N,k,M]),l.useEffect(()=>{p.initialEnabled&&(n||t.length>0)||(x(t.length),N(t.length,t.length,gn()))},[n,d,u,x,N,t.length,p]),l.useEffect(()=>{const w=p.initialEnabled&&v.startCalled,V=!n,P=f>=t.length;w&&V&&P&&!v.completeCalled&&(v.completeCalled=!0,T())},[n,f,T,t.length]);const K=l.useMemo(()=>{const w=p.initialEnabled?t.slice(0,f):t,V=W&&m,P=W&&h;return!V&&!P?w:Ri(w,{hideImages:V,hideLinks:P})},[t,f,m,h,W]);return l.useEffect(()=>{!p.initialEnabled||W||k(f,gn(),!0)},[f,W,k]),l.useEffect(()=>{L({displayedLength:f,streamTextLength:K.length})},[f,L,K.length]),{streamText:K,isAnimating:W}},qs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},_m=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Em=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},Cm=()=>{const{chatSDK:e}=we(),[t,n]=l.useState(qs),r=()=>n(qs);return Xt(e,{onConnectionDelayed:s=>{s>0?n(_m(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Em(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},bm=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},vm=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},ym=({enabled:e=!0}={})=>{const t=jt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=Re.isStreaming(n),c=kn(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!Ic(n)&&!Re.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,_=!1;const b={};return(f||m)&&(b.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!_&&(_=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(b.onRenderedTextProgress=v=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:v})}),u&&(b.onMessageTemplateError=v=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:v})}),d&&(b.onFormRenderError=v=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:v})}),b},[e,t])},Sm=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},Jn=5e3,cn=()=>vn.now(),Am=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=jt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?cn()-Jn:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(cn()-u.current<Jn){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=cn()-Jn):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=cn()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Tm=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=jt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Im=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(f=>{h===i.current&&o(f.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===le.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),Xt(e,{onConnected:c,onReconnectSucceeded:c}),s},Hr=e=>e.replace(/\s+/g," ").trim(),xm="Code block",Mi=e=>`A11Y_INLINE_CODE_${e}`,wi=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},ki=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},Rm=e=>{const{blockquotePrefix:t,content:n}=wi(e),{content:r}=ki(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},Mm=(e,t)=>{const{blockquotePrefix:n,content:r}=wi(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=ki(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},wm=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},km=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},Lm=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},Om=e=>{let t=0,n="";for(;t<e.length;){const r=wm(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=km(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Tn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!Tn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=Lm(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Li=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Nm=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Li(n,r,i)?t:`${n}${r}`}),Dm=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),$m=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Fm=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return Li(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Pm=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Um=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},Ks=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},Ys=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},Bm=e=>{const t=e.split(`
2
- `),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=Ys(s);if(i.length>0&&o&&Ks(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=Ys(c);if(u.length===0||Ks(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
3
- `)},Hm=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Gm=(e,t)=>{const n=e.split(`
4
- `),r=[];let s=0;for(;s<n.length;){const o=n[s],i=Rm(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(Mm(n[u],i)){c=u;break}if(c===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=c+1}return r.join(`
5
- `)},Tn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},zm=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||Tn(e,n)){r+=s,n+=1;continue}let o=n;for(;o<e.length&&e[o]==="`";)o+=1;const i=e.slice(n,o);let c=o,u=!1;for(;c<e.length&&e[c]!==`
6
- `;){if(e[c]==="`"&&!Tn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=Mi(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Oi=(e,{codeBlockPlaceholder:t=xm}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
7
- `);if(!n)return;const r=[];let s=n;s=Gm(s,t),s=Um(s);const o=zm(s);s=o.text,r.push(...o.inlineCodes),s=Om(s),s=Nm(s),s=Dm(s),s=$m(s),s=Fm(s),s=Bm(s),s=Hm(s),s=Pm(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Mi(c),r[c]);return Hr(s)||void 0},Vm=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ye(r)?t.image:zt(r)?t.video:Qo({name:n,mimeType:r})?t.pdf(n):t.document(n)},In=e=>(e==null?void 0:e.trim())||"",qm=e=>(e?Hr(e):void 0)||void 0,Ni=e=>({text:In(e),format:"plain"}),Km=e=>({text:In(e),format:"markdown"}),Qn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=In(e);return r&&r!==In(n)?Km(r):Ni(t)},Dt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Oi(t,{codeBlockPlaceholder:s}):qm(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},Di=(e,t)=>Oi(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Ym=(...e)=>Hr(e.filter(Boolean).join(", "))||void 0,Ws=(e,t,n,r)=>{if(!t||t===n)return e;const s=Di(t,r);return s?Ym(e,s):e},Wm=(e,t)=>{var r,s,o,i;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const c=((s=e.name)==null?void 0:s.trim())||"",u=Vm({name:c,mimeType:e.type},t);return Ws(u,n,c,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const c=e.fileInfoList??[],u=c.length;if(u===0)return;const d=((i=(o=c[0])==null?void 0:o.fileName)==null?void 0:i.trim())||"",h=c.every(f=>{var g;return(g=f.mimeType)==null?void 0:g.startsWith("image")})?t.receivedFilesImageCount(u):t.multipleFilesCount(u);return Ws(h,n,d,t.codeBlockPlaceholder)}return Di(n,t.codeBlockPlaceholder)},jm=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,f=0;const g=(x,L,z)=>({text:x,ignoreSuppression:L,queueOrder:f++,dedupeKey:z}),_=()=>{const x=c[0]??null,L=i;return x&&L?L.queueOrder<x.queueOrder?(i=null,L):c.shift()??null:x?c.shift()??null:L!==null?(i=null,L):null},b=()=>{for(;;){const x=_();if(!x)return null;if(!(!x.ignoreSuppression&&(r!=null&&r())))return x}},v=x=>{u=x.text,d=x.dedupeKey??null,h=!0,e(x.text),m=setTimeout(()=>{m=null,h=!1;const L=b();L&&v(L)},n)},p=x=>{u=x.text,d=x.dedupeKey??null,e(x.text)},S=(x,L,z,D)=>L!=null&&D!=null?L===D:L==null&&D==null?x!=null&&x===z:!1,A=(x,L,z)=>{if(!x||!L&&(r!=null&&r()))return;const D=z==null?void 0:z.dedupeKey;if(!(h&&S(x,D,u,d)))if(h){if(((z==null?void 0:z.mode)??"latestOnly")==="ordered"){const K=c[c.length-1];if(K&&S(x,D,K.text,K.dedupeKey))return;c.push(g(x,L,D)),c.length>o&&c.shift();return}i=g(x,L,D)}else i=null,v(g(x,L,D))};return{announce:(x,L)=>{A(x,!1,L)},announceIgnoringSuppression:(x,L)=>{A(x,!0,L)},flush:()=>{const x=[];let L=_();for(;L!==null;)x.push(L),L=_();if(m!==null&&(clearTimeout(m),m=null),h=!1,x.length!==0)for(const z of x)p(z)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Xm=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Zm=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),Jm=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},Qm=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},eh=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),th=(e,t)=>Le.isAdmin(e)?Le.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,nh=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,rh=e=>e===le.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===le.CollectionEventSource.EVENT_MESSAGE_UPDATED,sh=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",oh=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},ih=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},ah=({intent:e,strings:t})=>({label:oh(e,t),hint:ih(e,t)}),ch="1.34.0",Ge="sb-agent",ye={ENTRY:`${Ge}-entry`,MODAL_ROOT:`${Ge}-modal-root`,WINDOW:`${Ge}-window`,LAUNCHER:`${Ge}-launcher`,WINDOW_TITLE:`${Ge}-window-title`},$i="data-sb-initial-focus",Fi="true",lh=`[${$i}="${Fi}"]`,Pi={[$i]:Fi},Gr="data-sb-focus-trap-sentinel",uh="true",Ui="data-sb-initial-focus-header",Bi="true",dh=`[${Ui}="${Bi}"]`,Hi={[Ui]:Bi},Gi="data-sb-message-input",zi="true",mh=`textarea[${Gi}="${zi}"]:not(:disabled)`,hh={[Gi]:zi},Vi=1e3,ln=2147483647,gt={MODAL:ln-1,TOOLTIP:ln-2,WINDOW:ln-3,LAUNCHER:ln-4},qi=36,fh=100,gh=ch,zr="noopener noreferrer nofollow",hr=()=>typeof document>"u"||document.visibilityState==="visible",js=()=>typeof document<"u"&&document.visibilityState==="hidden",ph=e=>{if(hr()){e();return}if(typeof document>"u")return;const t=()=>{hr()&&(document.removeEventListener("visibilitychange",t),e())};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)};function _h(){return{isOnline:()=>navigator.onLine,subscribe:e=>{const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}const un={};function Eh(){return{get:e=>{try{return localStorage.getItem(e)}catch{return un[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{un[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete un[e]}},getKeys:e=>{try{const t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r&&r.startsWith(e)&&t.push(r)}return t}catch{return Object.keys(un).filter(t=>t.startsWith(e))}}}}const Ch={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry",button_ok:"OK",button_cancel:"Cancel"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`}},fr={language:"en",strings:Ch,dateLocale:lc.enUS},Ki=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),Yi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Zt},Zt="en",Wi=new Set([Zt,"ko","es","pt","fr","hi","it","de","tr","ja"]),bh='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:vh,useContext:Vr}=be("AgentUIElementResolver"),yh=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===ye.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(vh,{value:s},r)};function ut(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Xs=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:Sh,useContext:qr}=be("EscapeDismissStack"),Zs=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Ah=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Xs()),s.current||(s.current=Xs());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??ut(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Zs(m);return}i.dismissTopmost()&&Zs(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(Sh,{value:c},n)},ji=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Th=(e,t)=>{const{register:n}=qr();ji(e,t,n)},Ih=(e,t)=>{const{registerShellDismissHandler:n}=qr();ji(e,t,n)},Xi=()=>{const{subscribe:e,getOpenCount:t}=qr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},xh=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Js=Ki(fr.strings),Rh={...Js,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:Js.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},xn={language:fr.language,dateLocale:fr.dateLocale,stringSet:Rh},Mh=Object.freeze(Object.defineProperty({__proto__:null,default:xn},Symbol.toStringTag,{value:"Module"})),gr=new Map([[Zt,xn]]);async function wh(e){const t=gr.get(e);if(t)return t;try{if(Wi.has(e)){const{default:n}=await xh(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Mh),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/D_km8dcd.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/CLIpC7kY.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/ChrM6HN1.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/CPZf2TWM.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/D7UQ9OK7.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMDJStMQ.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/etCQgYrr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DKQwAy8C.cjs"))}),`./languages/${e}.ts`,3);return gr.set(e,n),n}return xn}catch{return xn}}const{Provider:kh,useContext:oe}=be("Localization"),Lh=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(gr.get(Zt));return l.useEffect(()=>{const c=t??Yi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),wh(c).then(i))},[e,t,n]),a.createElement(kh,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>at.format(c,u,{locale:o.dateLocale,...d})}},s)},Rn="data-sb-agent-theme",Qs=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Rn}='${e}'] & { ${r} }`},Q={light:Qs("light"),dark:Qs("dark")},Oh=U.css(({theme:e})=>{const{palette:t}=e;return`
1
+ "use strict";var lc=Object.defineProperty;var uc=(e,t,n)=>t in e?lc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var v=(e,t,n)=>uc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("@sendbird/chat"),l=require("react"),U=require("styled-components"),at=require("date-fns"),dc=require("date-fns/locale/en-US"),Fe=require("@sendbird/chat/message"),de=require("@sendbird/chat/aiAgent"),mc=require("react-dom"),Ye=require("@sendbird/chat/groupChannel"),hc=require("date-fns/isSameDay"),fc=require("dompurify"),Ir=e=>e&&e.__esModule?e:{default:e};function gc(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const pc=Ir(ie),a=gc(l),C=Ir(U),Wo=Ir(fc),Yo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},_c=e=>{const t=Yo(e);return typeof t=="object"&&t!==null?t:{}},jo=e=>typeof e=="string"?_c(e):e??{},Ec=e=>!!jo(e).stream,fs=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},Xo=e=>{const t=jo(e),n=fs(t.user_message_id)??fs(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},bt="sb-agent",Zo="KEY_IMG_ASPECT_RATIO",ur="*/*",ee={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var Sn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Sn||{}),Pt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Pt||{});const Cc=e=>!!(e!=null&&e.cta_button),bc=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Jo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,vc=e=>{var t;return Jo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},Sc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Ve=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},On=e=>Object.defineProperties({},{hasMessageTemplate:Ve(()=>!!(e!=null&&e.message_template)),hasCTAButton:Ve(()=>Cc(e)),hasChallenge:Ve(()=>!!(e!=null&&e.challenge)),isThinking:Ve(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Ve(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Ve(()=>Sc(e)),hasCustomMessageTemplates:Ve(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Ve(()=>Jo(e)),hasActiveForm:Ve(()=>vc(e)),hasSteward:Ve(()=>!!(e!=null&&e.steward)),hasCitations:Ve(()=>bc(e))}),yc=e=>{const t=On(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Qo=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Ac=e=>e===Pt.COMPLETED||e===Pt.CANCELED?e:Pt.IN_PROGRESS,Wn=e=>Qe(e)&&!Qo(e),Qe=e=>!!e&&"sender"in e,Tc=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Ic=(e,t,n,r=!0)=>{if(!r||!Wn(e))return"single";const s=()=>{if(!Wn(t))return!1;const u=t.sender.userId===e.sender.userId,d=at.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Wn(n))return!1;const u=n.sender.userId===e.sender.userId,d=at.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},st=(e,t)=>(()=>{var r;return Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,De={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Qo(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Fe.SendingStatus.PENDING)},We=e=>e.startsWith("image/"),zt=e=>e.startsWith("video/"),xc=e=>e.startsWith("audio/"),ei=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),xr=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},ti=e=>{var t;return e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.messageType==="multipleFiles"?e.message.length>0&&((t=e.files[0])==null?void 0:t.name)!==e.message:e.message.length>0},Rc=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return yc(t)},Dn=e=>{switch(e){case"top":case"middle":return ee.GAP_GROUPED;default:return ee.GAP_UNGROUPED}},Mc=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...i)=>{const[c,u,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:u.trim(),language:c?c.trim():"plaintext"}),s=d+o.length,o}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(o=>o.type!=="text"?o:{...o,value:t(o.value)}):r},wc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),kc=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Lc=e=>e.replace(/~~/g,"\\~\\~"),Oc=e=>{let t=e;return t=wc(t),t=kc(t),t=Lc(t),t},Dc=typeof navigator<"u"&&navigator.product==="ReactNative",gs=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return Dc?e.find(n):e.findLast(n)};function ue(){}function Nc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function $c(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const Me={isStreaming(e){return Ec(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(Me.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!st(e,t))return!1;const n=Xo(e.data);return!n.isStreaming&&!n.hasResponseMetadata},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},Yn=`@${bt}`,Fc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Yn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=$c(`${e}/${t}/${s}`);return`${Yn}-udata/${o}`},anonUserSession:()=>`${Yn}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},ni=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},Pc=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class Uc{constructor(t){v(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??de.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[de.ConversationStatus.OPEN,de.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??de.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===de.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==de.DeskChannelFilter.EXCLUDE:!1}}class ri extends Ye.BaseChannelCollection{constructor(n,r){const s=new Uc(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=Ye.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,f,g)=>i.getMyGroupChannels(m,h.params,g),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:b,copilotConversationOnly:S,copilotSupportChannelUrl:_}=s.params,p={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:b,copilotConversationOnly:S,copilotSupportChannelUrl:_};return i.getMyGroupChannelChangeLogs(m,p,Ye.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});v(this,"_params");v(this,"_sdk");v(this,"_throttledOnChannelChanged");v(this,"_key");v(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Pc()}`,this._throttledOnChannelChanged=ni(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:b,context:S}of m)h.delete(b.url),h.set(b.url,{channel:b,context:S});const f=new Map;for(const{channel:b,context:S}of h.values())f.has(S)||f.set(S,new Map),f.get(S).set(b.url,b);for(const[b,S]of f){const _=Array.from(S.values()),p=(g=this._sdk.currentUser)==null?void 0:g.userId,y=_.filter(T=>this.filter.match(T,p)),A=_.filter(T=>!this.filter.match(T,p)).map(T=>T.url);y.length>0&&this._base._addChannelsToView(y,b,!1),A.length>0&&this._removeChannels(A,b)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const f of m)this._pendingChannels.push({channel:f,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class si{constructor(t){v(this,"subscribers",{});this.logger=t}async send(t){const n=Bc(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Bc=()=>{let e=ue,t=ue;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Ke=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e))(Ke||{});class Vt{constructor(t={}){v(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const ct={CloseConversation:e=>new Hc(e),MessengerSettingsUpdated:e=>new Gc(e),ActiveChannelUpdated:e=>new zc(e),AnonymousSessionTokenExpired:()=>new Vc,AuthTokenRefreshed:()=>new qc};class Hc extends Vt{constructor(){super(...arguments);v(this,"type","conv.close")}}class Gc extends Vt{constructor(){super(...arguments);v(this,"type","messenger.settings.updated")}}class zc extends Vt{constructor(){super(...arguments);v(this,"type","active.channel.updated")}}class Vc extends Vt{constructor(){super(...arguments);v(this,"type","anon.token.expired")}}class qc extends Vt{constructor(){super(...arguments);v(this,"type","auth.token.refreshed")}}const qt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class Kt{constructor(t){v(this,"category","connection");this.userId=t}get data(){return qt({user_id:this.userId})}}class Kc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_connected")}}class Wc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_started")}}class Yc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_succeeded")}}class jc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_failed")}}class Xc extends Kt{constructor(){super(...arguments);v(this,"metricKey","connection_disconnected")}}class Zc{constructor(t){v(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new Kc(n):t==="reconnectStarted"?new Wc(n):t==="reconnectSucceeded"?new Yc(n):t==="reconnectFailed"?new jc(n):new Xc(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Rr{constructor(t,n){v(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Jc extends Rr{constructor(){super(...arguments);v(this,"metricKey","conversation_initialized")}}class Qc extends Rr{constructor(){super(...arguments);v(this,"metricKey","conversation_open")}}class el extends Rr{constructor(){super(...arguments);v(this,"metricKey","conversation_closed")}}class tl{constructor(t){v(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===de.ConversationStatus.INITIALIZED?new Jc(t.url,n.id):s===de.ConversationStatus.OPEN?new Qc(t.url,n.id):new el(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===de.ConversationStatus.INITIALIZED?t===void 0:n===de.ConversationStatus.OPEN?t===de.ConversationStatus.INITIALIZED:t===de.ConversationStatus.OPEN}}const oi=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},He=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===de.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Mr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===de.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function rt(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function nl(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!rt(e):!1}function rl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function ii(e){return!!e&&e<=Date.now()}function sl(e){return!e.title}function ol(e,t){var n;if(e)return sl(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question,always_visible:!1}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}class wr{constructor(t,n){v(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class il extends wr{constructor(){super(...arguments);v(this,"metricKey","handoff_started")}}class al extends wr{constructor(){super(...arguments);v(this,"metricKey","handoff_succeeded")}}class cl extends wr{constructor(){super(...arguments);v(this,"metricKey","handoff_failed")}}class ll{constructor(t){v(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new il(t.url,r.id):o==="succeeded"?new al(t.url,r.id):new cl(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(He(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class ul{constructor(t){v(this,"category","message");v(this,"metricKey","incoming_message_received");v(this,"channelUrl");v(this,"messageId");v(this,"senderType");v(this,"createdAt");v(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return qt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const dl=(e,t)=>{const n=Qe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class ml{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new ul({channelUrl:t.url,messageId:n.messageId,senderType:dl(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!st(t,this.getCurrentUserId())&&n!==null}}class hl{constructor(t){v(this,"category","message");v(this,"metricKey");v(this,"channelUrl");v(this,"requestId");v(this,"messageId");v(this,"target");v(this,"sendingStatus");v(this,"createdAt");v(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return qt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const fl=e=>{switch(e){case Fe.SendingStatus.PENDING:return"pending";case Fe.SendingStatus.SUCCEEDED:return"succeeded";case Fe.SendingStatus.FAILED:return"failed";case Fe.SendingStatus.SCHEDULED:return"scheduled";default:return}};class gl{constructor(t,n){v(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!st(n,this.getCurrentUserId()))return;const r=fl(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new hl({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:rt(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class pl{constructor(){v(this,"id","aiagent_livemetric");v(this,"dispatch");v(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});v(this,"emitters");v(this,"isStarted",!1);v(this,"registeredChatSDK");const t=()=>{var n,r;return(r=(n=this.registeredChatSDK)==null?void 0:n.currentUser)==null?void 0:r.userId};this.emitters={connection:new Zc(this.emit),conversation:new tl(this.emit),handoff:new ll(this.emit),incomingMessage:new ml(this.emit,t),outgoingMessage:new gl(this.emit,t)}}start(t){if(this.isStarted)return;const n=new ie.ConnectionHandler({onConnected:s=>this.trackConnection("connected",s),onDisconnected:s=>this.trackConnection("disconnected",s),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),r=new Ye.GroupChannelHandler({onMessageReceived:(s,o)=>{s.isGroupChannel()&&this.track({type:"incomingMessage",channel:s,message:o})},onChannelChanged:s=>{s.isGroupChannel()&&(this.track({type:"handoff",channel:s}),this.track({type:"conversation",channel:s}))},onUserJoined:s=>this.track({type:"handoff",channel:s}),onUserLeft:s=>this.track({type:"handoff",channel:s})});t.addConnectionHandler(this.id,n),t.groupChannel.addGroupChannelHandler(this.id,r),this.registeredChatSDK=t,this.isStarted=!0}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){!this.isStarted||!this.registeredChatSDK||(this.registeredChatSDK.removeConnectionHandler(this.id),this.registeredChatSDK.groupChannel.removeGroupChannelHandler(this.id),this.registeredChatSDK=void 0,this.isStarted=!1)}trackConnection(t,n=(s=>(s=(r=>(r=this.registeredChatSDK)==null?void 0:r.currentUser)())==null?void 0:s.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var kr=(e=>(e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(kr||{});class ai{constructor(t){v(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${bt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${bt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${bt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${bt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${bt}/error]`,...t)}}class ci{constructor({userId:t,authToken:n,sessionHandler:r}){v(this,"userId");v(this,"authToken");v(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class dr{constructor(){v(this,"userId");v(this,"authToken");v(this,"sessionHandler")}}const _l=e=>({onSessionTokenRequired:t=>{t(null),e.send(ct.AnonymousSessionTokenExpired())}}),li="ai_agent:stats",El="conversation_initial_render",ps="conversation_not_interactive_timeout",Cl="recovery_not_interactive_timeout",bl="conversation_list_initial_render",vl="message_pending_stuck",_s="aiev_auth_expired_unhandled",Sl="user_perceived_response_time",yl="stream_stalled",Al="ai_typing_indicator_absent_timeout",Tl="rendered_content_unusable",ui=800220;var ge=(e=>(e.AUTH="auth_duration_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.TOTAL_DURATION="total_duration_ms",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache_ms",e))(ge||{});const yn={now:()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()},di=(e,t,n)=>{const r={key:e,value:String(t)};return(n==null?void 0:n.conversationId)!==void 0&&(r.conversation_id=n.conversationId),n!=null&&n.error&&(r.error_code=n.error.code??ui,r.error_description=n.error.message??""),n!=null&&n.extra&&Object.keys(n.extra).length>0&&(r.extra=n.extra),r},It=e=>(e==null?void 0:e.clock)??yn,Il=((e,t)=>setTimeout(e,t)),xl=(e=>clearTimeout(e)),Wt=e=>(e==null?void 0:e.setTimeout)??Il,Yt=e=>(e==null?void 0:e.clearTimeout)??xl,et=(e,t,n,r)=>e(li,di(t,n,r)),ye=(e,t)=>{e!==null&&t(e)},Nn=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)},mt=(e,t)=>!(e.channelUrl&&t&&e.channelUrl!==t),mi=(e,t)=>{for(const n of e)if(n.userMessageId===void 0&&mt(n,t))return!0;return!1};class Rl{constructor(t){v(this,"callback");this.callback=t}onPayloadParseFailed(t){et(this.callback,_s,"payload_parse_failed",{extra:{agent_id:t.aiAgentId}})}onCallbackNotFound(t){et(this.callback,_s,"callback_not_found",{extra:{agent_id:t.aiAgentId}})}clear(){}}class Ml{constructor(){v(this,"timers",new Map);v(this,"committed",!1);v(this,"commitCallback",null);v(this,"conversationId",null);v(this,"channelUrl",null);v(this,"errorCode",null);v(this,"errorDescription",null);v(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??ui,this.errorDescription=n,this}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:yn.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:yn.now()}),this)}getDuration(t){const n=this.timers.get(t);return!n||n.startTime===null||n.endTime===null?null:n.endTime-n.startTime}isCommitted(){return this.committed}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(li,t)):!1}}class wl extends Ml{constructor(){super(...arguments);v(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return El}buildPayload(){const n=this.getDuration(ge.AUTH),r=this.getDuration(ge.GET_CHANNEL),s=this.getDuration(ge.GET_MESSAGES),o=this.getDuration(ge.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(ge.TOTAL_DURATION),c={...this.extraData,present_method:this.presentMethod,...n!==null&&{[ge.AUTH]:n},...r!==null&&{[ge.GET_CHANNEL]:r},...s!==null&&{[ge.GET_MESSAGES]:s},...o!==null&&{[ge.TOTAL_DURATION_FROM_CACHE]:o}};return di(this.getMetricKey(),i??0,{conversationId:this.conversationId??void 0,error:this.errorCode!==null?{code:this.errorCode,message:this.errorDescription??""}:void 0,extra:c})}}class kl{constructor(t){v(this,"commitCallback");v(this,"apiResultReceived",!1);v(this,"channelUrl");v(this,"consumed",!1);v(this,"consumedByAuthError",!1);v(this,"presentMethod","direct_present");v(this,"renderedAfterApiResult",!1);v(this,"stats",null);this.commitCallback=t}getOrCreateStats(){var t;return this.consumed?null:(t=this.stats)!=null&&t.isCommitted()?(this.consumed=!0,null):(this.stats||(this.stats=new wl().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod),this.apiResultReceived=!1,this.renderedAfterApiResult=!1),this.stats)}getActiveStats(){return this.consumed||!this.stats||this.stats.isCommitted()?null:this.stats}matchesChannelUrl(t){return t===void 0||this.channelUrl===void 0||t===this.channelUrl}pinChannelUrl(t){var n;return t===void 0?!0:this.matchesChannelUrl(t)?(this.channelUrl=t,(n=this.stats)==null||n.setChannelUrl(t),!0):!1}consume(t){return t&&(this.consumed=!0),t}commitIfReady(t){return this.consumed||!this.stats||this.stats.isCommitted()?!0:!this.matchesChannelUrl(t)||!this.apiResultReceived||!this.renderedAfterApiResult?!1:this.consume(this.stats.stopTimer(ge.TOTAL_DURATION).commit())}start(t){const n=this.getOrCreateStats();!n||!this.pinChannelUrl(t)||n.startTimer(ge.TOTAL_DURATION).startTimer(ge.TOTAL_DURATION_FROM_CACHE)}onAuthStart(){var t;this.consumedByAuthError&&this.clear(),(t=this.getOrCreateStats())==null||t.startTimer(ge.AUTH)}onAuthComplete(){var t;(t=this.getActiveStats())==null||t.stopTimer(ge.AUTH)}onAuthError(t){const n=this.getActiveStats();n&&this.consume(n.stopTimer(ge.AUTH).setError(t instanceof ie.SendbirdError?t.code:void 0,t.message).stopTimer(ge.TOTAL_DURATION).commit())&&(this.consumedByAuthError=!0)}onGetChannelStart(t){const n=this.getActiveStats();!n||!this.pinChannelUrl(t)||n.startTimer(ge.GET_CHANNEL)}onGetChannelComplete(t){const n=typeof t=="object"?t.channelUrl:void 0,r=typeof t=="object"?t.conversationId:t,s=this.getActiveStats();!s||!this.pinChannelUrl(n)||(s.stopTimer(ge.GET_CHANNEL),r!==void 0&&s.setConversationId(r),s.startTimer(ge.GET_MESSAGES))}onGetChannelError(t){const n=t instanceof Error?void 0:t.channelUrl,r=t instanceof Error?t:t.error,s=this.getActiveStats();s&&this.pinChannelUrl(n)&&this.consume(s.stopTimer(ge.GET_CHANNEL).setError(r instanceof ie.SendbirdError?r.code:void 0,r.message).stopTimer(ge.TOTAL_DURATION).commit())}onCacheResult(t){const n=this.getActiveStats();n&&(t&&n.setError(t instanceof ie.SendbirdError?t.code:void 0,t.message),n.stopTimer(ge.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){const n=this.getActiveStats();if(n){if(t){this.consume(n.setError(t instanceof ie.SendbirdError?t.code:void 0,t.message).stopTimer(ge.TOTAL_DURATION).stopTimer(ge.GET_MESSAGES).commit());return}this.apiResultReceived=!0,this.renderedAfterApiResult=!1,n.stopTimer(ge.GET_MESSAGES),this.commitIfReady()}}setChannelUrl(t){this.pinChannelUrl(t)}commitPending(){const t=this.getActiveStats();return t?this.consume(t.stopTimer(ge.TOTAL_DURATION).commit()):!0}markRendered(t){return this.matchesChannelUrl(t)?(this.renderedAfterApiResult=!0,this.commitIfReady(t)):!1}setPresentMethod(t){var n;this.presentMethod=t,(n=this.getActiveStats())==null||n.setPresentMethod(t)}clear(){this.stats=null,this.apiResultReceived=!1,this.channelUrl=void 0,this.consumed=!1,this.consumedByAuthError=!1,this.renderedAfterApiResult=!1}}const Es=()=>({initialized:!1,listStarted:!1,listCompleted:!1,rendered:!1});class Ll{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"measurement",Es());v(this,"renderedCommitted",!1);v(this,"startedAt",null);v(this,"listStartedAt",null);v(this,"authStartedAt",null);v(this,"authDuration",null);v(this,"listDuration",null);v(this,"presentMethod","direct_present");v(this,"committed",!1);this.callback=t,this.clock=It(n)}onInitializeStart(){this.measurement.rendered||(this.measurement.initialized&&this.clearMeasurementState(),this.renderedCommitted=!1,this.startMeasurement())}onListRequestStart(){this.measurement.listStarted&&!this.measurement.listCompleted&&!this.measurement.rendered&&this.clearMeasurementState(),this.markListRequestStartOnce()}onListRequestComplete(){this.markListRequestCompleteOnce()}onRendered(){this.markRenderedOnce()}setPresentMethod(t){this.presentMethod=t}start(t){this.committed||(this.startedAt=this.clock.now(),t&&(this.presentMethod=t))}onAuthStart(){this.committed&&(this.clearMeasurementState(),this.renderedCommitted=!1),this.authDuration=null,this.authStartedAt=this.clock.now()}onAuthComplete(){if(!(this.committed||this.authDuration!==null)){if(this.authStartedAt===null){this.authDuration=0;return}this.authDuration=this.clock.now()-this.authStartedAt,this.authStartedAt=null}}markListRequestStart(){this.committed||(this.startedAt===null&&this.start(),this.listStartedAt=this.clock.now())}markListRequestComplete(){this.committed||this.listStartedAt===null||(this.listDuration=this.clock.now()-this.listStartedAt)}markRendered(){this.committed||this.startedAt===null||(this.committed=!0,et(this.callback,bl,this.clock.now()-this.startedAt,{extra:{...this.authDuration!==null&&{auth_duration_ms:this.authDuration},...this.listDuration!==null&&{get_list_duration_ms:this.listDuration},present_method:this.presentMethod}}))}clear(){this.clearMeasurementState(),this.clearAuthState(),this.renderedCommitted=!1}clearMeasurementState(){this.startedAt=null,this.listStartedAt=null,this.listDuration=null,this.committed=!1,this.measurement=Es()}clearAuthState(){this.authStartedAt=null,this.authDuration=null}startMeasurement(){this.measurement.initialized||(this.clearMeasurementState(),this.start(),this.measurement.initialized=!0)}markListRequestStartOnce(){this.startMeasurement(),!this.measurement.listStarted&&(this.markListRequestStart(),this.measurement.listStarted=!0)}markListRequestCompleteOnce(){this.markListRequestStartOnce(),!this.measurement.listCompleted&&(this.markListRequestComplete(),this.measurement.listCompleted=!0)}markRenderedOnce(){this.renderedCommitted||(this.startMeasurement(),!this.measurement.rendered&&(this.markRendered(),this.measurement.rendered=!0,this.renderedCommitted=!0))}}class Ol{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Wt(n),this.clearTimeoutFn=Yt(n)}start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={startedAt:this.clock.now(),channelUrl:t==null?void 0:t.channelUrl,conversationId:t==null?void 0:t.conversationId,committed:!1,inputEnabled:!1,phaseReached:"auth",historyLoadResult:"pending",timer:null};r.timer=this.setTimeoutFn(()=>this.commitTimeout(n),1e4),this.measurements.set(n,r)}markChannelJoined(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="channel_join",t!==void 0&&(r.conversationId=t))}markHistoryLoaded(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="history_load",r.historyLoadResult=t,this.cancelIfReady(n))}markInputEnabled(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="input_enable",n.inputEnabled=!0,this.cancelIfReady(t))}markRendered(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="render")}clear(){this.measurements.forEach(t=>ye(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(ye(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}cancelIfReady(t){const n=this.getMeasurement(t);!n||!n.inputEnabled||n.historyLoadResult==="pending"||this.clearKey(this.getKey(n.channelUrl))}commitTimeout(t){const n=this.measurements.get(t);!n||n.committed||(n.committed=!0,n.timer=null,et(this.callback,ps,this.clock.now()-n.startedAt,{conversationId:n.conversationId,error:{message:ps},extra:{outcome:"timeout",phase_reached:n.phaseReached,history_load_result:n.historyLoadResult}}),this.measurements.delete(t))}getMeasurement(t){return t!==void 0?this.measurements.get(this.getKey(t)):this.measurements.size===1?Array.from(this.measurements.values())[0]:this.measurements.get(this.getKey())}getKey(t){return t??"__default__"}}const Dl=5e3,Cs=1e4;class Nl{constructor(t,n){v(this,"callback");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"measurements",new Map);this.callback=t,this.setTimeoutFn=Wt(n),this.clearTimeoutFn=Yt(n)}start(t){if(!t.requestId||this.measurements.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,r={channelUrl:t.channelUrl,messageType:t.messageType,stuckReason:n?"upload_no_progress":"pending_too_long",timer:null},s=n?Cs:Dl;r.timer=this.setTimeoutFn(()=>this.detect(t.requestId),s),this.measurements.set(t.requestId,r)}resolve(t){const n=this.measurements.get(t.requestId);n&&(ye(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}disappear(t){const n=this.measurements.get(t.requestId);n&&(ye(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}markUploadProgress(t){const n=this.measurements.get(t);n&&n.stuckReason==="upload_no_progress"&&(ye(n.timer,this.clearTimeoutFn),n.timer=this.setTimeoutFn(()=>this.detect(t),Cs))}clear(){this.measurements.forEach(t=>ye(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t&&this.measurements.forEach((n,r)=>{n.channelUrl===t&&(ye(n.timer,this.clearTimeoutFn),this.measurements.delete(r))})}detect(t){const n=this.measurements.get(t);n&&(this.measurements.delete(t),this.commit(t,n))}commit(t,n){et(this.callback,vl,n.stuckReason,{extra:{message_type:n.messageType,request_id:t}})}}class $l{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Wt(n),this.clearTimeoutFn=Yt(n)}start(t,n){const r=this.getKey(n);let s=this.measurements.get(r);s&&s.startedAt!==null||s!=null&&s.inputEnabled||(s={startedAt:this.clock.now(),triggerType:t,inputEnabled:(s==null?void 0:s.inputEnabled)??!1,timer:this.setTimeoutFn(()=>this.commitTimeout(r),1e4)},this.measurements.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.measurements.get(r);if(!s){if(!t)return;s={startedAt:null,triggerType:null,inputEnabled:t,timer:null},this.measurements.set(r,s)}s.inputEnabled=t,t&&this.cancelMeasurement(s)}cancelPending(t){const n=this.getKey(t),r=this.measurements.get(n);r&&(this.cancelMeasurement(r),r.inputEnabled||this.measurements.delete(n))}clear(){this.measurements.forEach(t=>ye(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(ye(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}commitTimeout(t){const n=this.measurements.get(t);if(!n||n.startedAt===null||n.triggerType===null)return;if(n.inputEnabled){this.cancelMeasurement(n);return}const r=this.clock.now()-n.startedAt,s=n.triggerType;this.measurements.delete(t),et(this.callback,Cl,r,{extra:{trigger_type:s}})}cancelMeasurement(t){ye(t.timer,this.clearTimeoutFn),t.timer=null,t.startedAt=null,t.triggerType=null}getKey(t){return t??"__default__"}}const Fl=500;class Pl{constructor(t){v(this,"callback");v(this,"committed",new Set);this.callback=t}commit(t){const n=`${t.messageId}:${t.contentKind}:${t.errorDomain}`;this.committed.has(n)||(Nn(this.committed,Fl),this.committed.add(n),et(this.callback,Tl,t.errorDomain,{error:t.error?{code:t.error.code,message:t.errorDomain}:void 0,extra:{content_kind:t.contentKind,message_id:String(t.messageId)}}))}clear(){this.committed.clear()}}const bs=1e4,Ct=5e3,Ul=500;class Bl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"streams",new Map);v(this,"emittedMessageChannels",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Wt(n),this.clearTimeoutFn=Yt(n)}markRawProgress(t){if(!t.aiResponse.isStreaming){this.completeDelivery(t.messageId,t.textLength);return}if(this.emittedMessageChannels.has(t.messageId))return;const n=this.getOrCreate(t.messageId,t.channelUrl);t.textLength>n.lastRawLength?(n.chunksReceived+=1,n.lastRawLength=t.textLength,n.lastRawAt=this.clock.now(),ye(n.deliveryTimer,this.clearTimeoutFn),n.deliveryTimer=null,this.scheduleDeliveryStallCheck(t.messageId,n)):this.scheduleDeliveryStallCheck(t.messageId,n),n.lastRenderedLength<n.lastRawLength&&n.renderTimer===null&&(n.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t.messageId,n,Ct))}markRenderedProgress(t){const n=this.streams.get(t.messageId);if(!(!n||t.displayedLength<=n.lastRenderedLength)){if(n.lastRenderedLength=t.displayedLength,n.lastRenderAt=this.clock.now(),n.lastRenderedLength>=n.lastRawLength){if(n.deliveryTimer===null){this.clearStream(t.messageId,n);return}ye(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null;return}this.scheduleRenderStallCheck(t.messageId,n,Ct)}}hasPendingStream(t){return this.streams.has(t)}complete(t){const n=this.streams.get(t);n&&this.clearStream(t,n)}completeDelivery(t,n){const r=this.streams.get(t);if(r){if(n>r.lastRawLength&&(r.lastRawLength=n,r.lastRawAt=this.clock.now()),ye(r.deliveryTimer,this.clearTimeoutFn),r.deliveryTimer=null,r.lastRenderedLength>=r.lastRawLength){this.clearStream(t,r);return}r.renderTimer===null&&(r.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t,r,Ct))}}clearMessage(t){const n=this.streams.get(t);n&&this.clearStream(t,n),this.emittedMessageChannels.delete(t)}clear(){this.streams.forEach(t=>{ye(t.deliveryTimer,this.clearTimeoutFn),ye(t.renderTimer,this.clearTimeoutFn)}),this.streams.clear(),this.emittedMessageChannels.clear()}clearChannel(t){t&&(this.streams.forEach((n,r)=>{n.channelUrl!==t&&n.channelUrl!==void 0||this.clearStream(r,n)}),this.emittedMessageChannels.forEach((n,r)=>{(n===t||n===void 0)&&this.emittedMessageChannels.delete(r)}))}detectDelivery(t){const n=this.streams.get(t);n&&(n.deliveryTimer=null,ye(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null,this.emit(t,n,"delivery"))}detectRender(t){const n=this.streams.get(t);if(!n||(n.renderTimer=null,n.lastRenderedLength>=n.lastRawLength))return;const r=this.clock.now()-n.lastRenderAt;if(r<Ct){this.scheduleRenderStallCheck(t,n,Ct-r);return}const s=this.clock.now()-n.lastRawAt;if(s>=Ct&&n.deliveryTimer!==null){const o=bs-s;if(o>0){this.scheduleRenderStallCheck(t,n,o);return}}this.emit(t,n,"render")}scheduleRenderStallCheck(t,n,r){n.renderTimer===null&&(n.renderTimer=this.setTimeoutFn(()=>this.detectRender(t),r))}scheduleDeliveryStallCheck(t,n){n.deliveryTimer===null&&(n.deliveryTimer=this.setTimeoutFn(()=>this.detectDelivery(t),bs))}emit(t,n,r){if(this.emittedMessageChannels.has(t))return;const s=r==="delivery"?n.lastRawAt:n.lastRenderAt;et(this.callback,yl,this.clock.now()-s,{extra:{message_id:String(t),stall_kind:r}}),this.rememberEmitted(t,n.channelUrl),this.clearStream(t,n)}getOrCreate(t,n){const r=this.streams.get(t);if(r)return r;const s=this.clock.now(),o={channelUrl:n,chunksReceived:0,lastRawAt:s,lastRenderAt:s,lastRawLength:0,lastRenderedLength:0,deliveryTimer:null,renderTimer:null};return this.streams.set(t,o),o}rememberEmitted(t,n){this.emittedMessageChannels.has(t)||Nn(this.emittedMessageChannels,Ul),this.emittedMessageChannels.set(t,n)}clearStream(t,n){ye(n.deliveryTimer,this.clearTimeoutFn),ye(n.renderTimer,this.clearTimeoutFn),this.streams.delete(t)}}const vs=3e3,Hl=3e4;class Gl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"setTimeoutFn");v(this,"clearTimeoutFn");v(this,"turns",new Map);v(this,"pendingAIResponseStartsByUserMessageId",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=Wt(n),this.clearTimeoutFn=Yt(n)}startTurn(t){this.cancelTurn(t.requestId);const n={requestId:t.requestId,channelUrl:t.channelUrl,beforeTpstStartedAt:this.clock.now(),afterTpenStartedAt:null,timer:null};n.timer=this.setTimeoutFn(()=>this.commitTimeout(n.requestId),Hl),this.turns.set(t.requestId,n)}markUserMessageAck(t){const n=this.turns.get(t.requestId);if(!n)return;n.userMessageId=t.messageId;const r=this.pendingAIResponseStartsByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseStartsByUserMessageId.delete(t.messageId),this.applyAIResponseStarted({channelUrl:r.channelUrl,matchesUserMessage:!0,userMessageId:t.messageId},r.startedAt))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.turns.get(t);r&&(this.turns.delete(t),r.requestId=n,this.turns.set(n,r))}cancelTurn(t){this.cleanupTurn(t)}markTypingStarted(t){const n=this.clock.now();this.turns.forEach(r=>{mt(r,t)&&(this.recordAfterTpen(r,n),this.recordBeforeTpst(r,n))})}markTypingEnded(t){const n=this.clock.now();this.turns.forEach(r=>{mt(r,t)&&(this.recordBeforeTpst(r,n),r.afterTpenStartedAt=n)})}markAIResponseStarted(t={}){const n=t.channelUrl,r=t.userMessageId,s=r!==void 0,o=this.clock.now();this.applyAIResponseStarted({channelUrl:n,matchesUserMessage:s,userMessageId:r},o)||!s||r===void 0||!this.hasUnackedTurn(n)||this.pendingAIResponseStartsByUserMessageId.has(r)||(Nn(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(r,{channelUrl:n,startedAt:o}))}applyAIResponseStarted(t,n){if(!t.matchesUserMessage){const s=this.findSingleTurn(t.channelUrl);return s?(this.completeTurn(s.requestId,s.turn,n),!0):!1}let r=!1;return this.turns.forEach((s,o)=>{mt(s,t.channelUrl)&&(t.matchesUserMessage&&s.userMessageId!==t.userMessageId||(r=!0,this.completeTurn(o,s,n)))}),r}findSingleTurn(t){let n,r=0;return this.turns.forEach((s,o)=>{mt(s,t)&&(r+=1,!(r>1)&&(n={requestId:o,turn:s}))}),r===1?n:void 0}completeTurn(t,n,r){this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}hasUnackedTurn(t){return mi(this.turns.values(),t)}clear(){this.turns.forEach(t=>{ye(t.timer,this.clearTimeoutFn)}),this.turns.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(t){t&&(this.turns.forEach((n,r)=>{n.channelUrl===t&&this.cleanupTurn(r)}),this.pendingAIResponseStartsByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseStartsByUserMessageId.delete(r)}))}commitTimeout(t){const n=this.turns.get(t);if(!n)return;const r=this.clock.now();this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}recordBeforeTpst(t,n){if(t.beforeTpstStartedAt===null)return;const r=n-t.beforeTpstStartedAt;r>=vs&&(t.beforeTpstAbsentMs=r),t.beforeTpstStartedAt=null}recordAfterTpen(t,n){if(t.afterTpenStartedAt===null)return;const r=n-t.afterTpenStartedAt;r>=vs&&(t.afterTpenAbsentMs=r),t.afterTpenStartedAt=null}commitIfAbsent(t,n){const r=n.beforeTpstAbsentMs,s=n.afterTpenAbsentMs;if(r===void 0&&s===void 0){this.cleanupTurn(t);return}et(this.callback,Al,(r??0)+(s??0),{extra:{...r!==void 0&&{before_tpst_absent_ms:r},...s!==void 0&&{after_tpen_absent_ms:s}}}),this.cleanupTurn(t)}cleanupTurn(t){const n=this.turns.get(t);n&&(ye(n.timer,this.clearTimeoutFn),this.turns.delete(t))}}class zl{constructor(t,n){v(this,"callback");v(this,"clock");v(this,"random");v(this,"sampledByRequestId",new Map);v(this,"sampledByAIMessageId",new Map);v(this,"pendingAIResponseByUserMessageId",new Map);v(this,"collectedCount",0);this.callback=t,this.clock=It(n),this.random=(n==null?void 0:n.random)??Math.random}startTurn(t){this.collectedCount>=10||this.random()>=.15||(this.collectedCount+=1,this.sampledByRequestId.set(t.requestId,{requestId:t.requestId,channelUrl:t.channelUrl,startedAt:this.clock.now()}))}markUserMessageAck(t){const n=this.sampledByRequestId.get(t.requestId);if(!n)return;n.ackAt=this.clock.now(),n.userMessageId=t.messageId;const r=this.pendingAIResponseByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseByUserMessageId.delete(t.messageId),this.applyAIResponseRaw(n,r))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.sampledByRequestId.get(t);r&&(this.sampledByRequestId.delete(t),r.requestId=n,this.sampledByRequestId.set(n,r))}cancelTurn(t){const n=this.sampledByRequestId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(t){const n=this.clock.now(),r=t.aiResponse.userMessageId;if(r===void 0&&this.hasUnackedTurn(t.channelUrl))return;const s=this.findPendingTurn(t.channelUrl,r);if(s){this.applyAIResponseRaw(s,{...t,firstChunkAt:n});return}r===void 0||!this.hasUnackedTurn(t.channelUrl)||this.bufferAIResponseRaw({messageId:t.messageId,...t.channelUrl!==void 0&&{channelUrl:t.channelUrl},aiResponse:t.aiResponse,firstChunkAt:n},r)}markAIResponseVisible(t){const n=this.sampledByAIMessageId.get(t);if(!n||n.ackAt===void 0||n.firstChunkAt===void 0||n.userMessageId===void 0)return!1;const r=this.clock.now();return et(this.callback,Sl,r-n.startedAt,{extra:{ack_to_first_chunk_ms:n.firstChunkAt-n.ackAt,first_chunk_to_render_ms:r-n.firstChunkAt,is_streaming:!!n.isStreaming,send_to_ack_ms:n.ackAt-n.startedAt}}),this.deleteTurn(n),!0}hasPendingAIResponse(t){return this.sampledByAIMessageId.has(t)}clearMessage(t){this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.messageId===t&&this.pendingAIResponseByUserMessageId.delete(s)});const n=this.sampledByAIMessageId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(t){t&&(this.sampledByRequestId.forEach(n=>{n.channelUrl===t&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseByUserMessageId.delete(r)}))}clear(){this.sampledByRequestId.clear(),this.sampledByAIMessageId.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findPendingTurn(t,n){if(n!==void 0){for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&mt(s,t)&&s.userMessageId===n)return s;return}let r;for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&mt(s,t)){if(r)return;r=s}return r}applyAIResponseRaw(t,n){t.firstChunkAt===void 0&&(t.firstChunkAt=t.ackAt===void 0?n.firstChunkAt:Math.max(n.firstChunkAt,t.ackAt),t.aiMessageId=n.messageId,t.channelUrl=t.channelUrl??n.channelUrl,t.isStreaming=n.aiResponse.isStreaming,this.sampledByAIMessageId.set(n.messageId,t))}bufferAIResponseRaw(t,n){this.pendingAIResponseByUserMessageId.has(n)||(Nn(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(n,t))}hasUnackedTurn(t){return mi(this.sampledByRequestId.values(),t)}deleteTurn(t){this.sampledByRequestId.delete(t.requestId),t.aiMessageId!==void 0&&this.sampledByAIMessageId.delete(t.aiMessageId),t.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(t.userMessageId)}}function Vl(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const hi=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Ss={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},Lr={conversation:{...Ss,messageAlertSoundEnabled:!1,list:{...Ss,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},ys=e=>e?{conversation:Wl(e.conversation),launcher:ql(e.launcher)}:Lr,ql=e=>vt(Lr.launcher,e),Kl=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},Wl=e=>{const t=Lr.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...vt(t.list,c,n),deferredMarkdownElements:Kl(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:vt(t.header,r),input:{camera:vt(t.input.camera,u),gallery:vt(t.input.gallery,d),fileEnabled:m},fileViewer:vt(t.fileViewer,o)}},vt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,hi(r));return n},Yl=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),jl=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),mr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Xl{constructor(){v(this,"_channelHandlerId",null);v(this,"_connectionHandlerId",null);v(this,"_handlerChatSDK",null);v(this,"_handleActiveChannelChangedThrottled",null);v(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ni(o=>{var i,c;(c=this._session)==null||c._updateActiveChannel({url:o.url,status:He(o)?"closed":"open",conversationStatus:(i=o.conversation)==null?void 0:i.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",o.url)},250,{leading:!0,trailing:!1});const n=new Ye.GroupChannelHandler({onChannelChanged:o=>{var i,c;o.isGroupChannel()&&o.url===((i=this._session)==null?void 0:i.activeChannel.url)&&((c=this._handleActiveChannelChangedThrottled)==null||c.call(this,o))}}),r=new ie.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}}),s=this._chatClient.chatSDK;s.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),s.addConnectionHandler(this._connectionHandlerId,r),this._handlerChatSDK=s,this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});v(this,"_removeChannelHandler",()=>{const t=this._handlerChatSDK??this._chatClient.chatSDK;this._channelHandlerId&&(t.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(t.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handlerChatSDK=null,this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});v(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:He(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});v(this,"_initConversationIfNeeded",async t=>{if(t.isAIAgent&&!t.conversation)try{await t.initConversation({aiAgentId:this.aiAgentId})}catch(n){this._logger.warn("AIAgentEventManager: initConversation failed",n)}});v(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Ke.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Ke.MessengerSettingsUpdated,t)}));v(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Ke.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Ke.ActiveChannelUpdated,t)}));v(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Ke.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Ke.AuthTokenRefreshed,t)}))}}class Zl{constructor(t){v(this,"_sdkUser");v(this,"_userSession");v(this,"_dispatcher");v(this,"_activeChannel");v(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(ct.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});v(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(ct.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const fi=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},gi=e=>JSON.parse(e),Jl=e=>JSON.parse(e);function Ql(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function eu(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function tu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,fi(c))},e)}async function nu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,fi(c)),e)}var Or=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Or||{});const pi=e=>typeof e=="object"&&e!==null,As=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",ru=e=>!pi(e)||!As(e,"channel_url")||!As(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},su={1:ru};function ou(e){if(!pi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=su[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function _i(e,t,n,r){const s=pc.default.init({appId:e,modules:[new Ye.GroupChannelModule,new de.AIAgentModule],localCacheEnabled:!0,options:new ie.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:ie.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function iu(e){const t=n=>{throw new Error(`Please initialize chat sdk with ${n}`)};typeof e.groupChannel!="object"&&t("GroupChannelModule"),typeof e.aiAgent!="object"&&t("AIAgentModule")}const au=e=>!!(e!=null&&e.customApiHost||e!=null&&e.customWebSocketHost),cu=({appId:e,extensions:t,messengerVersion:n,chatParams:r})=>{const s=e.toLowerCase();return _i(e.toUpperCase(),t,n,{...r,customApiHost:`https://api-${s}.app.delight.ai`,customWebSocketHost:`wss://ws-${s}.app.delight.ai`,newInstance:!0})},lu=e=>{if(!(e instanceof ie.SendbirdError))return!1;const t=e.message.toLowerCase();return e.code===ie.SendbirdErrorCode.APPLICATION_NOT_FOUND?t.includes("application")&&t.includes("not found"):e.code===ie.SendbirdErrorCode.NETWORK_ROUTING_ERROR?t===""||t.includes("routing")||t.includes("route"):e.code===ie.SendbirdErrorCode.NETWORK_ERROR?t.includes("network error"):!1},uu=[400300,400301,400302,400310],du=Or.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),mu=e=>`${du}:${e}`;class Dr{constructor(t,n,r,s,o,i){v(this,"_chatSDK");v(this,"_aiAgentId");v(this,"_externalAuthTokenExpiredEventHandlerKey");v(this,"_logger");v(this,"_cache");v(this,"_statsTrackers");v(this,"_sdkInitParams");v(this,"_sessionHandler");v(this,"_aiEventHandlerRegistered",!1);v(this,"_hasConnected",!1);v(this,"_usingDelightAppHostFallback",!1);v(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const o=new ie.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(o)}this._registerAIEventHandler();try{return await this.chatSDK.connect(t.userId,t.authToken),this._hasConnected=!0,await this._syncTemplatesIfNeeded(),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(o){const i=o;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(c=>this._logger.warn("ChatClient.connect","clear cached-data failure",c));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this._hasConnected=!0,this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",i.message,i.code),this.dispose(),i}});v(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});v(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=ou(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Or.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});v(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});v(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._hasConnected=!1,this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});v(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));v(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));v(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));v(this,"requestMessengerSettings",async t=>{if(t.userId===""){const r=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",r),r}const n={...t,shouldSendFirstMessage:!1};try{return await this._requestMessengerSettings(n)}catch(r){if(!this._shouldRetryWithDelightAppHosts(r))throw r;this._logger.debug("ChatClient.requestMessengerSettings","retrying with alternate Chat hosts",r.message,r.code);const s=cu(this._sdkInitParams);try{const o=await this._requestMessengerSettings(n,s);return this._chatSDK=s,this._usingDelightAppHostFallback=!0,o}catch(o){throw this._logger.warn("ChatClient.requestMessengerSettings","alternate Chat host retry failed",o.message,o.code),r}}});v(this,"_requestMessengerSettings",async(t,n=this.chatSDK)=>{var s;this._logger.debug("ChatClient.requestMessengerSettings: requesting",t);const r=await n.aiAgent.requestMessengerSettings(t);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});v(this,"_shouldRetryWithDelightAppHosts",t=>!!(this._sdkInitParams&&!this._hasConnected&&!this.chatSDK.currentUser&&this.chatSDK.connectionState!=="OPEN"&&this.chatSDK.connectionState!=="CONNECTING"&&!this._usingDelightAppHostFallback&&lu(t)));v(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});v(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});v(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});v(this,"_isCacheRestrictedError",t=>uu.some(n=>t.code===n));v(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=gi(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this._chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=mu(n),this._logger=r,this._cache=s,this._statsTrackers=o,this._sdkInitParams=i}get chatSDK(){return this._chatSDK}static init(t){let n;t.chatSDK?(iu(t.chatSDK),n=t.chatSDK):n=_i(t.appId,t.extensions,t.messengerVersion,t.chatParams);const r=t.chatSDK||au(t.chatParams)?void 0:{appId:t.appId,extensions:t.extensions,messengerVersion:t.messengerVersion,chatParams:t.chatParams};return new Dr(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers,r)}}const pn=new WeakMap,hu=(e,t)=>{const n=pn.get(e)??new Set;return n.add(t),pn.set(e,n),()=>{n.delete(t),n.size===0&&pn.delete(e)}},fu=e=>{const t=pn.get(e);t&&t.forEach(n=>n())},sn=new Map,Ei={set:(e,t)=>{sn.set(e,t)},get:e=>{if(sn.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=sn.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=sn.entries().next().value;return{platform:t[0],...t[1]}}};class Ts extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);v(this,"status");v(this,"code");v(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var Nr=(e=>(e.INITIALIZED="INITIALIZED",e.PROACTIVE="PROACTIVE",e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.CLOSED="CLOSED",e.WORK_IN_PROGRESS="WORK_IN_PROGRESS",e.IDLE="IDLE",e))(Nr||{}),$r=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))($r||{}),Ci=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(Ci||{});const gu=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class pu{constructor(t){v(this,"_appId");v(this,"_apiHost");v(this,"_logger");v(this,"_credential",null);v(this,"_authRefreshPromise",null);v(this,"_onDeskTokenRefreshRequired",async()=>!1);v(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});v(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});v(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});v(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!gu(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});v(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});v(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));v(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));v(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));v(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));v(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Ts(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Ts(t.status,{})}});v(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class An{constructor(t,n){v(this,"id");v(this,"title");v(this,"status");v(this,"agent");v(this,"priority");v(this,"group");v(this,"firstResponseTime");v(this,"issuedAt");v(this,"customFields");v(this,"_client");v(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new An({id:t.id,title:t.channelName??null,status:t.status2??Nr.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??$r.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class Fr{constructor(t){v(this,"_logger");v(this,"_apiClient");v(this,"_onDeskTokenRefreshRequired");v(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);v(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});v(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});v(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});v(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return An._fromResponse(n,this)});v(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:hi({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return An._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new pu(t)}static init(t){return new Fr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Pr{constructor(){v(this,"authenticate",async t=>!1);v(this,"deauthenticate",()=>{});v(this,"refreshDeskAuthToken",async()=>!1);v(this,"setCustomerLanguage",async()=>{});v(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Pr}}function _u(e){return{get:t=>e.getString(t)??null,set:(t,n)=>{e.set(t,n)},delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}const Eu=1440*60*1e3,Cu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function nt(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function bu(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const vu=e=>{const t={conversationInitialRender:new kl(e),conversationNotInteractiveTimeout:new Ol(e),recoveryNotInteractiveTimeout:new $l(e),conversationListInitialRender:new Ll(e),aievAuthExpiredUnhandled:new Rl(e),messagePendingStuck:new Nl(e),userPerceivedResponseTime:new zl(e),streamStalled:new Bl(e),typingIndicatorAbsentTimeout:new Gl(e),renderedContentUnusable:new Pl(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class Tn extends Xl{constructor(n){super();v(this,"appId");v(this,"aiAgentId");v(this,"_chatClient");v(this,"_deskClient");v(this,"_cache");v(this,"_logger");v(this,"_dispatcher");v(this,"_session",null);v(this,"language");v(this,"countryCode");v(this,"context");v(this,"queryParams");v(this,"_config");v(this,"_networkStateAdapter");v(this,"_scheduleForegroundTask");v(this,"_forceCreateChannel");v(this,"_agentVersion");v(this,"_statsTrackers");v(this,"_liveMetricManager");v(this,"_operationQueue",Vl());v(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});v(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));v(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(ct.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=this._chatClient.chatSDK,f=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});h!==this._chatClient.chatSDK&&fu(this);let g;if(f.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),g={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:_,session_token:p,expire_at:y}=f.auto_created_user;this._cache.messenger.setAnonUser({userId:_,authToken:p,expireAt:y}),g={userId:_,authToken:p},this._logger.debug("AIAgent.authenticate: anonymous user created",_)}else g={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,f),this._dispatcher.send(ct.MessengerSettingsUpdated({settings:f,source:"server"}));const b=(()=>{var _;return s.type==="anonymous"?_l(this._dispatcher):(_=s.userSessionCandidate)==null?void 0:_.sessionHandler})();this._liveMetricManager.start(this._chatClient.chatSDK);const S=await this._chatClient.connect(g,b,_=>{var p;this._logger.debug("AIAgent: session token refreshed"),(p=this._session)==null||p._updateAuthToken(_),this._deskClient.refreshDeskAuthToken(_)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:g.userId,accessToken:g.authToken,onDeskTokenRefreshRequired:async({reason:_})=>{var p;if(_===Ci.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const y=(p=this._session)==null?void 0:p.userSession.authToken;return y?await this._deskClient.refreshDeskAuthToken(y):!1}return!1}}),(o==null?void 0:o.language)!==f.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new Zl({sdkUser:S,userSession:g,activeChannel:{url:f.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:g.userId}),f}catch(h){throw this._session===null&&this._liveMetricManager.dispose(),this._statsTrackers.conversationInitialRender.onAuthError(h),h}})});v(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._liveMetricManager.dispose(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));v(this,"createConversation",async n=>{nt(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});v(this,"searchConversation",async n=>{if(nt(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:de.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)bu(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});v(this,"closeConversation",async n=>{var s;nt(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===de.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:de.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});v(this,"createConversationListCollection",n=>new ri(this.chatSDK,n??{}));v(this,"patchContext",async(n,r)=>{nt(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});v(this,"updateContext",async(n,r)=>{nt(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});v(this,"getContextObject",async n=>{nt(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});v(this,"clearUserMemories",async(n={})=>{nt(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});v(this,"setUserMemoryState",async n=>{nt(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),mr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(ct.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),mr(i)});v(this,"refreshActiveChannel",async n=>{var c,u,d;nt(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});v(this,"_getSessionCandidate",n=>n instanceof ci?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof dr?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});v(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Eu<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});v(this,"_getManualSessionInfo",n=>{if(!n||n instanceof dr)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=ys(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=n.scheduleForegroundTask,this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new pl}static init(n){var g;const r=Ei.get(n.platform),s=n.logger??new ai(n.logLevel??kr.WARN),o=n.dispatcher??new si(s),i=n.useMMKVStorage?_u(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=Fc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=vu((b,S)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(b,S)});d=Dr.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const f=Cu?Fr.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Pr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Tn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,scheduleForegroundTask:r.scheduleForegroundTask??(b=>b()),forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:f,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=ys(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}}const be=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function je(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m={Template:i,updateTemplate:h=>c(()=>h),components:u,updateComponent:(h,f)=>d(g=>({...g,[h]:f}))};return a.createElement(t.Provider,{value:m},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function Su(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function yu(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":bi(e,t)}function bi(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function Au(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=at.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):at.isToday(s)?n.hoursAgo(at.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Tu=e=>{const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},on=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Is=(e,t)=>{const n=on(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=Tu(e);return r?`#${on(r[0])}${on(r[1])}${on(r[2])}${n}`:e},Iu=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},xu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Ru=e=>e.length>0,Mu=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>We(s.type)),r=e.some(s=>!We(s.type));return n&&r?We(t.type)?e.filter(s=>We(s.type)):[t]:r?[t]:e},xs=e=>e.length===0?"empty":e.every(t=>We(t.type))?"images":"non_images",wu=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Mu(t),s=xs(e),o=xs(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},At=3,vi=6,ku=e=>e%At===0?At:vi,Lu=({index:e,itemCount:t})=>{const n=t%At,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:At,c=o?e-s:e%At,u=!r&&e>=t-At;return{columnSpan:r?vi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},jt=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])},Ou=e=>{const t=jt(),n=l.useRef(e.chatSDK);n.current!==e.chatSDK&&(n.current=e.chatSDK),l.useEffect(()=>{const r=()=>{n.current!==e.chatSDK&&(n.current=e.chatSDK,t())};return r(),hu(e,r)},[e,t])},Si=be("AIAgent"),Du=Si.Provider,ke=Si.useContext;function Nu(e){const t=$u(e);return Ou(t),a.createElement(Du,{value:{_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}},e.children)}function $u(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=Tn.init(e);else{const o=Fu(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=Tn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function Fu(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function ae(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Rs=Symbol("conversationMessageEventBridge"),wt=Symbol("conversationMessageEventPublisher"),Pu=(e,t)=>{const n=e;if(n[wt]=t,n[Rs])return e;n[Rs]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=o=>{r({...o,onMessagesAdded:(i,c,u)=>{var d,m;(d=o.onMessagesAdded)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesAdded",source:i.source,messages:u})},onMessagesUpdated:(i,c,u)=>{var d,m;(d=o.onMessagesUpdated)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesUpdated",source:i.source,messages:u})}})};const s=e.initialize.bind(e);return e.initialize=o=>{const i=s(o),c=i.onCacheResult.bind(i),u=i.onApiResult.bind(i);return i.onCacheResult=d=>c((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),i.onApiResult=d=>u((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"api",messages:h??[]})}),i},e};let Uu=0;function Bu(){return l.useState(()=>`${Uu++}`)[0]}const ht=(e,t,n)=>{const r=l.useRef(t),o=Bu();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var b;const g=r.current;(b=g[h])==null||b.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new Ye.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Hu(e,t){return!e||!t?!0:e.url!==t.url}function ze(e){return e!=null&&"sendingStatus"in e}function Gu(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return ze(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function zu(e,t){return Gu(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Ms(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const In={collection:{groupChannel:{defaultOrder:Ye.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function ws(e){return!e||!Array.isArray(e)?!1:e.length!==0}function ks(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Vu=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=qu(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=ze(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];Ku(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{ze(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{ze(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>zu(s,n));return t.value.clearBeforeAction?e.newMessageMap=ks(r,Ms):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...ks(r,Ms)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},qu=e=>e.reduce((t,n)=>(ze(n)?(t[n.reqId]=n,n.sendingStatus===Fe.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Ku=(e,t,n=!1)=>{var r,s;if(!ze(e)||!ze(t))return!0;if(n&&e&&Me.isStreaming(e)&&Me.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===Fe.SendingStatus.SUCCEEDED?t.sendingStatus===Fe.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Wu=(e=Yu)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Vu,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(_,p,y,A)=>{i({type:"update_messages",value:{messages:_,clearBeforeAction:p,currentUserId:y,strictStreamingOrder:A}})},u=(_,p)=>{i({type:"delete_messages",value:{messageIds:_,reqIds:p}})},d=(_,p,y)=>{i({type:"update_new_messages",value:{messages:_,clearBeforeAction:p,currentUserId:y}})},m=(_,p)=>{i({type:"delete_new_messages",value:{messageIds:_,reqIds:p}})},h=_=>{i({type:"update_initialized",value:{status:_}})},f=_=>{i({type:"update_loading",value:{status:_}})},g=_=>{i({type:"update_refreshing",value:{status:_}})},b=Object.values(o),S=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:g,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:S,newMessages:b,updateNewMessages:d,deleteNewMessages:m}},Ls=Math.floor(Number.MAX_SAFE_INTEGER/10);function Yu(e,t){let n=0,r=0;return ze(e)&&e.sendingStatus!=="succeeded"&&(n=Ls),ze(t)&&t.sendingStatus!=="succeeded"&&(r=Ls),e.createdAt+n-(t.createdAt+r)}const ju=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new Ye.MessageFilter(r)})};function Os(e){return e<Date.now()?In.collection.message.searchLimit:In.collection.message.defaultLimit}const Xu=(e,t,n={})=>{var Le,$;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=Os(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=jt(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:b,messages:S,newMessages:_,updateMessages:p,updateNewMessages:y,deleteNewMessages:A,deleteMessages:T,updateInitialized:M,updateLoading:L,updateRefreshing:N}=Wu(n==null?void 0:n.sortComparator),x=ae(I=>{var w,D,z,W;if(!s.current||!s.current.url)return(w=o==null?void 0:o.error)==null?void 0:w.call(o,"[useGroupChannelMessages] channel is required");try{switch(I){case ie.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ie.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case ie.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(z=(D=r.current).markAsRead)==null||z.call(D,[s.current]);break}}catch(te){(W=o==null?void 0:o.warn)==null||W.call(o,"[useGroupChannelMessages/markAsReadBySource]",te)}}),O=ae((I,w)=>{var D,z,W,te,Z;if(w.length>0)switch(I){case ie.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ie.CollectionEventSource.SYNC_MESSAGE_FILL:{(z=(D=r.current).shouldCountNewMessages)!=null&&z.call(D)&&y(w,!1,(W=e.currentUser)==null?void 0:W.userId),(Z=(te=r.current).onMessagesReceived)==null||Z.call(te,w);break}}}),H=ae(I=>{var w,D;(D=(w=r.current).onCollectionEvent)==null||D.call(w,I)}),F=ae(async(I,w,D)=>new Promise((z,W)=>{var Xe;h.current.instance&&h.current.instance.dispose(),x(),y([],!0,(Xe=e.currentUser)==null?void 0:Xe.userId);const te=()=>{var _e,Ee;const{pendingMessages:ce,failedMessages:he}=h.current.instance??{};ws(ce)&&p(ce,!1,(_e=e.currentUser)==null?void 0:_e.userId),ws(he)&&p(he,!1,(Ee=e.currentUser)==null?void 0:Ee.userId)},Z=ju(I,D,{...r.current,startingPoint:w});h.current={apiInitialized:!1,initialized:!1,instance:Z},Z.setMessageCollectionHandler({onMessagesAdded:(ce,he,_e)=>{var Ee;x(ce.source),O(ce.source,_e),p(_e,!1,(Ee=e.currentUser)==null?void 0:Ee.userId,u),H({kind:"messagesAdded",source:ce.source,channelUrl:I.url,messages:_e})},onMessagesUpdated:(ce,he,_e)=>{var Ee,Ce,Te;x(ce.source),O(ce.source,_e),p(_e,!1,(Ee=e.currentUser)==null?void 0:Ee.userId,u),ce.source===ie.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Te=(Ce=r.current).onMessagesUpdated)==null||Te.call(Ce,_e)),H({kind:"messagesUpdated",source:ce.source,channelUrl:I.url,messages:_e})},onMessagesDeleted:(ce,he,_e,Ee)=>{const Ce=Ee.map(ve=>ve.messageId),Te=Ee.filter(ze).map(ve=>ve.reqId);T(Ce,Te),A(Ce,Te),H({kind:"messagesDeleted",source:ce.source,channelUrl:I.url,messages:Ee})},onChannelDeleted:(ce,he)=>{var _e,Ee;(Ee=(_e=r.current).onChannelDeleted)==null||Ee.call(_e,he)},onChannelUpdated:(ce,he)=>{var _e,Ee;m(),(Ee=(_e=r.current).onChannelUpdated)==null||Ee.call(_e,he,ce)},onHugeGapDetected:()=>{F(I,Number.MAX_SAFE_INTEGER,In.collection.message.defaultLimit)}});let pe=!1;Z.initialize(Ye.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ce,he)=>{var _e,Ee,Ce,Te,ve;(Ee=(_e=r.current).onCacheResult)==null||Ee.call(_e,ce,he??[],I.url),ce?(e.isCacheEnabled&&((Ce=o==null?void 0:o.error)==null||Ce.call(o,"[useGroupChannelMessages/onCacheResult]",ce)),pe=!0):he&&((Te=o==null?void 0:o.debug)==null||Te.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",he.length),p(Z.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),te(),he.length>0&&(h.current.initialized=!0,z())),H({kind:"initialized",source:"cache",channelUrl:I.url,messages:he??[]})}).onApiResult((ce,he)=>{var _e,Ee,Ce,Te,ve,$e,Pe;(Ee=(_e=r.current).onApiResult)==null||Ee.call(_e,ce,he??[],I.url),h.current.initialized=!0,h.current.apiInitialized=!0,ce?((Ce=o==null?void 0:o.warn)==null||Ce.call(o,"[useGroupChannelMessages/onApiResult]",ce),pe?W(ce):z()):he&&((Te=o==null?void 0:o.debug)==null||Te.call(o,"[useGroupChannelMessages/onApiResult]","message length:",he.length),p(Z.succeededMessages,!0,(ve=e.currentUser)==null?void 0:ve.userId),r.current.startingPoint||(Pe=($e=r.current).onMessagesReceived)==null||Pe.call($e,he),e.isCacheEnabled&&te(),z()),H({kind:"initialized",source:"api",channelUrl:I.url,messages:he??[]})})}));ht(e,{onUserBanned(I,w){var D,z,W;I.isGroupChannel()&&!Hu(I,s.current)&&(w.userId===((D=e.currentUser)==null?void 0:D.userId)?(W=(z=r.current).onCurrentUserBanned)==null||W.call(z):m())}}),l.useLayoutEffect(()=>{const I=setTimeout(async()=>{e.currentUser&&s.current&&(M(!1),L(!0),await F(s.current,i,c),L(!1),M(!0))});return()=>clearTimeout(I)},[e,(Le=e.currentUser)==null?void 0:Le.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const Y=ae(async()=>{e.currentUser&&s.current&&(N(!0),await F(s.current,Number.MAX_SAFE_INTEGER,In.collection.message.defaultLimit),N(!1))}),q=ae(async()=>{var w;const I=h.current.instance;if(I!=null&&I.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const D=await I.loadPrevious();p(D,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.prev=!1}}),k=ae(()=>{const{initialized:I,instance:w}=h.current;return I&&w?w.hasPrevious:!1}),G=ae(async()=>{var w;const I=h.current.instance;if(I!=null&&I.hasNext&&!d.current.next)try{d.current.next=!0;const D=await I.loadNext();p(D,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.next=!1}}),P=ae(()=>{const{initialized:I,apiInitialized:w,instance:D}=h.current;return w&&I&&D?D.hasNext:!1}),V=I=>{var w,D,z,W;!I||I.channelUrl!==((w=s.current)==null?void 0:w.url)||(p([I],!1,(D=e.currentUser)==null?void 0:D.userId),(W=(z=r.current).onOutgoingMessageStatusChanged)==null||W.call(z,I))},me=ae((I,w)=>{var D;if(!s.current||!s.current.url)throw(D=o==null?void 0:o.error)==null||D.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((z,W)=>{s.current.sendUserMessage(I).onPending(te=>{V(te),w==null||w(te)}).onSucceeded(te=>{V(te),z(te)}).onFailed((te,Z)=>{V(Z),W(te)})})}),Ie=ae((I,w)=>{var D;if(!s.current||!s.current.url)throw(D=o==null?void 0:o.error)==null||D.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((z,W)=>{s.current.sendFileMessage(I).onPending(te=>{V(te),w==null||w(te)}).onSucceeded(te=>{V(te),z(te)}).onFailed((te,Z)=>{V(Z),W(te)})})}),j=ae((I,w,D)=>{var z;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((W,te)=>{s.current.sendMultipleFilesMessage(I).onPending(Z=>{V(Z),w==null||w(Z)}).onFileUploaded(Z=>{D==null||D(Z),m()}).onSucceeded(Z=>{V(Z),W(Z)}).onFailed((Z,pe)=>{V(pe),te(Z)})})}),K=ae(async(I,w)=>{var z,W;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const D=await s.current.updateUserMessage(I,w);return D.channelUrl===s.current.url&&p([D],!1,(W=e.currentUser)==null?void 0:W.userId),D}),R=ae(async(I,w)=>{var z,W;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const D=await s.current.updateFileMessage(I,w);return D.channelUrl===s.current.url&&p([D],!1,(W=e.currentUser)==null?void 0:W.userId),D}),X=ae(async(I,w,D)=>{var z;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((W,te)=>{let Z;I.isUserMessage()&&(Z=s.current.resendMessage(I)),I.isFileMessage()&&(Z=s.current.resendMessage(I)),I.isMultipleFilesMessage()&&(Z=s.current.resendMessage(I)),Z&&("onPending"in Z&&Z.onPending(pe=>{V(pe),w==null||w(pe)}),"onFileUploaded"in Z&&Z.onFileUploaded(pe=>{D==null||D(pe),m()}),"onSucceeded"in Z&&Z.onSucceeded(pe=>{V(pe),W(pe)}),"onFailed"in Z&&Z.onFailed((pe,Xe)=>{V(Xe),te(pe)}))})}),ne=ae(async I=>{var w,D;if(!s.current||!s.current.url)throw(w=o==null?void 0:o.error)==null||w.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(I.sendingStatus==="succeeded")I.isUserMessage()&&await s.current.deleteMessage(I),I.isFileMessage()&&await s.current.deleteMessage(I),I.isMultipleFilesMessage()&&await s.current.deleteMessage(I);else try{await((D=h.current.instance)==null?void 0:D.removeFailedMessage(I.reqId))}finally{T([],[I.reqId])}}),oe=ae(()=>{var I;y([],!0,(I=e.currentUser)==null?void 0:I.userId)}),Re=ae(async I=>{var w;if(e.currentUser&&s.current){const D=Os(I);L(!0),p([],!0,(w=e.currentUser)==null?void 0:w.userId),await F(s.current,I,D),L(!1)}});return{initialized:f,loading:g,refreshing:b,messages:S,newMessages:_,resetNewMessages:oe,refresh:Y,loadPrevious:q,hasPrevious:k,loadNext:G,hasNext:P,sendUserMessage:me,sendFileMessage:Ie,sendMultipleFilesMessage:j,updateUserMessage:K,updateFileMessage:R,resendMessage:X,deleteMessage:ne,resetWithStartingPoint:Re,_dangerous_reducer_updateMessages:p,_dangerous_reducer_deleteMessages:T}},Zu=(e,t,n)=>{const r=l.useRef(0),s=l.useRef(new Set),o=l.useCallback(d=>{const m={id:r.current+=1,...d};s.current.forEach(h=>{h(m)})},[]),i=l.useCallback(d=>{var h;const m=((h=n==null?void 0:n.collectionCreator)==null?void 0:h.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new Ye.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return Pu(m,o)},[t,n==null?void 0:n.collectionCreator,o]),c=Xu(e,t,{...n,collectionCreator:i,strictStreamingOrder:!0}),u=l.useCallback(d=>(s.current.add(d),()=>{s.current.delete(d)}),[]);return{...c,subscribeMessageEvents:u}},Ju=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(!1),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);s.current=t;const d=l.useCallback(p=>r.current===p,[]),m=l.useCallback(()=>{o.current&&(n.clear(),o.current=!1,i.current=null)},[n]),h=l.useCallback(p=>{if(!s.current)return;const y=!o.current||i.current!==p;n.start(p),y&&n.onGetChannelStart(p),o.current=!0,i.current=p},[n]),f=l.useCallback(p=>{d(p)&&(u.current=p,c.current=null,h(p))},[d,h]),g=l.useCallback(({channelUrl:p,conversationId:y})=>{o.current||h(p),n.onGetChannelComplete({channelUrl:p,conversationId:y})},[h,n]),b=l.useCallback(({channelUrl:p,error:y})=>{o.current||h(p),n.onGetChannelError({channelUrl:p,error:y})},[h,n]),S=l.useCallback(p=>{if(d(p.channelUrl)){if(u.current=null,!s.current){c.current=p;return}c.current=null,g(p)}},[d,g]),_=l.useCallback(p=>{if(d(p.channelUrl)){if(u.current=null,!s.current){c.current=p;return}c.current=null,b(p)}},[d,b]);return l.useEffect(()=>{if(t){const p=c.current;if(p){if(c.current=null,p.channelUrl!==e)return;"error"in p?b(p):g(p);return}const y=u.current;if(y){if(y!==e){u.current=null;return}h(y)}return}m()},[e,m,t,b,g,h]),l.useEffect(()=>(r.current=e,o.current=!1,i.current=null,c.current=null,u.current=null,()=>{m(),o.current=!1,i.current=null,c.current=null,u.current=null}),[e,m]),{onFetchStart:f,onFetchSuccess:S,onFetchError:_}},Qu=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(b=>r.current===b,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(b=>{c(b)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:b,conversationId:S})=>{i.current=!0,n.markChannelJoined(S,b)},[n]),h=l.useCallback(({channelUrl:b})=>{n.clearChannel(b),i.current=!1},[n]),f=l.useCallback(b=>{if(c(b.channelUrl)){if(!s.current){o.current=b;return}o.current=null,m(b)}},[c,m]),g=l.useCallback(b=>{if(c(b.channelUrl)){if(!s.current){o.current=b;return}o.current=null,h(b)}},[c,h]);return l.useEffect(()=>{if(t){const b=o.current;if(!b||(o.current=null,b.channelUrl!==e))return;"error"in b?h(b):m(b);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:f,onFetchError:g}},ed=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var g;(g=o.current)==null||g.call(o),o.current=null;const f=u.current;h&&(u.current=null),h&&f&&r.clearChannel(f)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const f=c.current,g=()=>{if(!i.current||f!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(g))??null,n||g()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},Bt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function yi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function td(e){const t=yi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function nd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function rd(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function sd(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function an(e,t,n){const[r,s,o]=td(e),[i,c,u]=rd(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=sd(i,m,d);return nd([Math.round(h),Math.round(f),Math.round(g)])}function od(e,t="light"){return{extraDark:an(e,.6,1.2),dark:an(e,.85,1.1),main:e,light:an(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:an(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function hr(e){const t=yi(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?Bt.BLACK:Bt.WHITE}function id(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const ad=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),cn={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},jn={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function Ds(e){const t=cd(e),n=ld(e,t),r=dd(n,e.colors,e.selectedTheme),s=hd(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function cd({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===cn.primary.main?cn.primary:od(n,e):cn.primary;return{...cn,primary:r,...t}}function ld({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??hr(o),c=n??Bt.DEFAULT_BOT_MSG_BG,u=r??hr(c);return(e==="light"?id:ad)(s,o,i,c,u)}function ud(e,t,n){return typeof e=="string"?e:e[t]??n}function dd(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=ud(m,n,h)}}}return r}function md(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function hd({typography:e}){if(!e)return jn;const t={...jn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=jn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=md(s,r,o)}}),t}const{Provider:fd,useContext:Ur}=be("AIAgentTheme");function gd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Ds({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((m,h)=>{h&&(i.current=h);const f=(s==null?void 0:s.theme)??m,g=i.current?i.current.themes[f]:null,b={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!b.primary&&(g!=null&&g.primary_color)&&(b.primary=g.primary_color,b.primaryContrast=g.primary_contrast_color),!b.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(b.botMessageBackground=g.bot_message_bg_color,b.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const S=Ds({selectedTheme:f,palette:t,typography:n,colors:r,...b});u(S),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);return l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),a.createElement(fd,{value:{theme:c,updateTheme:d}},o)}const Xn=25*1024*1024,Ns=1,$s=new Set(["image/png","image/jpeg","image/jpg"]),Fs=new Set(["application/pdf"]),pd={off:"off",always:"always",handed_off_only:"handed_off_only"},_d=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:Ns,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Xn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:$s,supportedFileMimeTypes:Fs})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Ns,attachmentMode:pd[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Xn,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??$s),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Fs)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=Xn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?rt(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return rt(o);default:return!0}},get supportedMimeTypes(){return c()?[ur]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},Ps=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},kt=e=>({...e,context:e.context??{}}),{Provider:Ed,useContext:ft}=be("AIAgentMessengerSession"),Cd=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=ke(),{updateTheme:c}=Ur(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[b,S]=l.useState(null),[_,p]=l.useState(null),[y,A]=l.useState(null),[T,M]=l.useState(null),{updateBaseAttachmentRules:L,createAttachmentRules:N}=_d();l.useEffect(()=>{const F=r.onMessengerSettingsUpdated(({settings:k})=>{const{appearance:G,bot:P,launcher:V,memory:me}=k;c(G.selected_theme,G),p(Yl(P)),A(jl(V)),M(me?mr(me):null),L(k)}),Y=r.onActiveChannelUpdated(({channelUrl:k,status:G,conversationStatus:P})=>{h({url:k,status:G,conversationStatus:P})}),q=r.onAuthTokenRefreshed(()=>{var G;const k=(G=r.session)==null?void 0:G.userSession.authToken;k&&S(P=>P?{...P,authToken:k}:null)});return()=>{F(),Y(),q()}},[r,c,L]);const x=l.useCallback(async()=>{try{const F=await r.authenticate(e),Y=r.session;return g(Y.sdkUser),S(Y.userSession),h(Y.activeChannel),d(void 0),F}catch(F){throw g(null),S(null),h(void 0),d(F),F}},[r,e]),O=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),S(null),p(null),A(null),M(null)},[r]),H=l.useCallback(async()=>{if(!r.session){if(b)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(b==null?void 0:b.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,b]);return l.useImperativeHandle(n,()=>{const F=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:x,deauthenticate:O,updateContext:async(...Y)=>{const q=Ps(...Y);if(q.type==="active"){const P=await(await F()).updateContext(o,q.context);return kt(P)}const k=await s.aiAgent.updateContext(q.aiAgentId,q.channelUrl,q.context);return kt(k)},patchContext:async(...Y)=>{const q=Ps(...Y);if(q.type==="active"){const P=await(await F()).patchContext(o,q.context);return kt(P)}const k=await s.aiAgent.patchContext(q.aiAgentId,q.channelUrl,q.context);return kt(k)},getContextObject:async()=>{const q=await(await F()).getContextObject(o);return kt(q)}}},[x,O,m,s,o,i]),a.createElement(Ed,{value:{sdkUser:f,userSessionInfo:e,userSession:b,activeChannel:m,setActiveChannel:h,refreshActiveChannel:H,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:u,aiAgentInfo:_,launcherInfo:y,memoryInfo:T,authenticate:x,deauthenticate:O,createAttachmentRules:N}},t)}),bd={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},vd=e=>e.disabled?bd[e.disabledBy]==="ready":!0,Sd=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&We(t)?"file_image":t&&zt(t)?"file_video":t&&xc(t)?"file_audio":"file_document"};let Us=0;const yd=e=>(Us+=1,`${e??"unknown"}:${Us}`),St=(e,t)=>e===void 0||t===e,Ai=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Ti=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},Ad=(e,t)=>{e.conversationInitialRender.onCacheResult(t.error),Ai(e,t)},Td=(e,t)=>{e.conversationInitialRender.onApiResult(t.error),Ti(e,t)},Id=(e,t,n)=>{var o;if(!st(e,n))return;const{hasResponseMetadata:r,...s}=Xo(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},Bs=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Qe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},Zn=(e,t)=>{t&&(e.conversationInitialRender.clear(),e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},xd=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=ke(),{aiAgentInfo:r}=ft(),s=l.useRef(!1),o=r==null?void 0:r.userId;ht(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},Rd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0),s=l.useRef(e);l.useLayoutEffect(()=>{const o=r.current,i=s.current;if(s.current=e,!e){o&&(Zn(n,o),r.current=void 0);return}o&&o!==t&&(Zn(n,o),r.current=void 0),t&&o!==t&&(i||n.conversationInitialRender.start(),n.conversationInitialRender.setChannelUrl(t),n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const o=r.current;o&&(Zn(n,o),r.current=void 0)},[n])},Md=({aiAgentUserId:e,conversationStatsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(g=>i.current&&c.current===g,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const g=d.current;d.current=t,!(g||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const f=l.useCallback(g=>g.lifecycleGeneration===u.current&&St(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(r.conversationInitialRender.onCacheResult(g.error),g.tracked=!0),Ai(r,g));const b=o.current;b&&f(b)&&(b.tracked||(r.conversationInitialRender.onApiResult(b.error),b.tracked=!0),Ti(r,b))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&St(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(b=>Bs(b,r));return}t&&g.messages.forEach(b=>Id(b,r,e))}},onCacheResult:(g,b,S)=>{if(!h(m)||!St(n,S))return;const _={error:g,messages:b,channelUrl:S,lifecycleGeneration:u.current,tracked:!1};s.current=_,t&&(Ad(r,_),_.tracked=!0)},onApiResult:(g,b,S)=>{if(!h(m)||!St(n,S))return;const _={error:g,messages:b,channelUrl:S,lifecycleGeneration:u.current,tracked:!1};o.current=_,t&&(Td(r,_),_.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&St(n,g.channelUrl)&&Bs(g,r)}}),[e,m,t,h,n,r])},wd=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputEnabled(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationInitialRender.markRendered(t)&&(i.current=!0),o.conversationNotInteractiveTimeout.markRendered(t))});return()=>clearTimeout(d)},[t,e,n,s,o])},kd=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(S=>u==null?void 0:u(S),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,b=S=>g()&&St(f,S);try{const S=await c(_=>{if(!b(_.channelUrl)){u==null||u(_);return}m=_.reqId,n.messagePendingStuck.start({requestId:_.reqId,channelUrl:_.channelUrl,messageType:Sd(_),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(_)},_=>{!g()||m!==_||n.messagePendingStuck.markUploadProgress(_)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),S}catch(S){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),S}},[n])},Ld=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=yd(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const f=await c(g=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,g),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,g),h=g)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:f.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:f.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),f}catch(f){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),f}},[e,n])},Od=({requestedChannelUrl:e,activeChannelUrl:t,conversationStatsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ft();xd({activeChannelUrl:t,statsTrackers:r}),Rd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=Md({aiAgentUserId:s==null?void 0:s.userId,conversationStatsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=kd({channelUrl:t,enabled:n,statsTrackers:r}),c=Ld({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},Xt=()=>ke()._aiAgentSDK.statsTrackers,Zt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new ie.ConnectionHandler({onDisconnected:o=>{var i,c;return(c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o)},onConnected:o=>{var i,c;return(c=(i=r.current).onConnected)==null?void 0:c.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,c;return(c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},Hs=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function Dd(e,t={}){const{chatSDK:n,logger:r,aiAgentId:s,_aiAgentSDK:o}=ke(),{sdkUser:i}=ft(),c=Hs(),u=Hs(),d=jt(),[m,h]=l.useState(void 0),[f,g]=l.useState(void 0),[b,S]=l.useState(!1);function _(y){if(y.isAIAgent&&!y.conversation){const A=u.next();S(!0),o.initConversationIfNeeded(y).finally(()=>{u.isCurrent(A)&&S(!1)})}}async function p(){var A,T,M,L,N,x;const y=c.next();if(!i){r.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(r.debug("useChannel.getChannel: start"),h(void 0),g(void 0),u.invalidate(),S(!1),e){(A=t.onFetchStart)==null||A.call(t,e);try{r.debug("useChannel.getChannel: get channel",e);const O=await n.groupChannel.getChannel(e);if(!c.isCurrent(y))return;_(O),h(O),(M=t.onFetchSuccess)==null||M.call(t,{channelUrl:O.url,conversationId:(T=O.conversation)==null?void 0:T.id}),O.url===((L=o.session)==null?void 0:L.activeChannel.url)&&o.session._updateActiveChannel({url:O.url,status:He(O)?"closed":"open",conversationStatus:(N=O.conversation)==null?void 0:N.status}),r.debug("useChannel.getChannel: fetched channel",O)}catch(O){if(!c.isCurrent(y))return;(x=t.onFetchError)==null||x.call(t,{channelUrl:e,error:O}),O instanceof ie.SendbirdError&&g(O),r.error("useChannel.getChannel: error",O)}}}return l.useEffect(()=>(p(),()=>{c.invalidate()}),[n,i,e,s]),Zt(n,{async onReconnectSucceeded(){var T;if(!m){f&&await p();return}const y=c.current(),A=await m.refresh();!c.isCurrent(y)||m.url!==e||((T=t.onReconnectSucceeded)==null||T.call(t,m.url),_(A),h(A))}}),ht(n,{onChannelChanged:y=>{y.isGroupChannel()&&y.url===e&&(r.debug("useChannel.onChannelChanged: channel changed",y.url),h(y),d())}}),{channel:m,channelFetchError:f,getChannel:p,isInitializingConversation:b}}const Nd=new Set(["suggested_replies","steward","system"]),$d=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!(!r||!Nd.has(r)))return r},Fd=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=On(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},Pd=()=>{const{chatSDK:e,networkStateAdapter:t}=ke(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Zt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===ie.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Ud=3e4,Bd=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&st(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=f=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},f)},m=Date.now()-c,h=Ud-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ii=e=>{const{chatSDK:t}=ke(),[n,r]=l.useState([]);return ht(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Hd=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Ii(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=st(t,n)&&(Me.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},Gd=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ft(),i=Pd(),c=Hd({channel:e,lastMessage:gs(t,[Fe.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Bd({shouldApply:!!(e!=null&&e.isAIAgent)&&!rt(e),isBlockedWhileAIResponding:c,lastMessage:gs(t,[Fe.SendingStatus.PENDING,Fe.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""}),d=h=>h===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:h==="ai_responding"?{disabled:!0,disabledBy:h,focusPolicy:"preserve"}:{disabled:!0,disabledBy:h,focusPolicy:"release"};if(!e||i==="disconnected")return d("unavailable");if(i==="reconnecting")return d("reconnecting");if(He(e))return d("conversation_closed");if(nl(e))return d("handoff_pending");if(Fd(e))return d("form_active");const m=$d(e);return d(m||(c||u||r?"ai_responding":""))},zd=()=>{const[e,t]=l.useState(new Set),n=l.useCallback(s=>{t(o=>{if(o.has(s))return o;const i=new Set(o);return i.add(s),i})},[]),r=l.useCallback(s=>{t(o=>{if(!o.has(s))return o;const i=new Set(o);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Vd}=be("AIAgentConversation"),qd=({initialRenderStats:e,notInteractiveStats:t,recoveryStats:n})=>({onFetchStart:r=>{e.onFetchStart(r),t.onFetchStart(r)},onFetchSuccess:r=>{e.onFetchSuccess(r),t.onFetchSuccess(r)},onFetchError:r=>{e.onFetchError(r),t.onFetchError(r)},onReconnectSucceeded:n.onReconnectSucceeded});function Kd({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=ue,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldCountNewMessages:h=()=>!1,sortComparator:f}){var Le,$;const g=()=>d&&(x==null?void 0:x.markAsRead()),{_aiAgentSDK:b,chatSDK:S,logger:_,dispatcher:p}=ke(),y=Xt(),A={channelUrl:t,enabled:m},T=Ju({...A,statsTracker:y.conversationInitialRender}),M=Qu({...A,statsTracker:y.conversationNotInteractiveTimeout}),L=ed({...A,scheduleForegroundTask:b.scheduleForegroundTask,statsTracker:y.recoveryNotInteractiveTimeout}),N=qd({initialRenderStats:T,notInteractiveStats:M,recoveryStats:L}),{channel:x,channelFetchError:O,getChannel:H,isInitializingConversation:F}=Dd(t,N),Y=x==null?void 0:x.url,q=Od({requestedChannelUrl:t,activeChannelUrl:Y,conversationStatsEnabled:m,statsTrackers:y}),k=Zu(S,x,{replyType:Fe.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:h,onChannelDeleted:n,onMessagesReceived:I=>r==null?void 0:r(I),onMessagesUpdated:I=>s==null?void 0:s(I),...q.messageCallbacks,onOutgoingMessageStatusChanged:I=>{x&&b.liveMetricManager.track({type:"outgoingMessage",channel:x,message:I})},logger:_,markAsRead:g,sortComparator:f}),G=zd(),P=Gd({channel:x,messages:k.messages,isStreamAnimating:G.isAnimating,isInitializingConversation:F});wd({enabled:m,channelUrl:Y,initialized:k.initialized,inputReady:vd(P),renderedSignal:k.messages,statsTrackers:y}),l.useEffect(()=>{g()},[d,x]);const V=(Le=x==null?void 0:x.conversation)==null?void 0:Le.status;l.useEffect(()=>{V&&(o==null||o(V))},[V,o]),l.useEffect(()=>{const I=async w=>{const D=typeof(w==null?void 0:w.channelUrl)=="string";x&&D&&w.channelUrl!==x.url||(_.debug("conversation.dispatcher: try to close conversation",x),x!=null&&x.conversation&&x.conversation.status===de.ConversationStatus.OPEN&&(await x.closeConversation(),i==null||i()))};return p.subscribe(Ke.ConversationClose,I),()=>{p.unsubscribe(Ke.ConversationClose,I)}},[p,x,_,($=x==null?void 0:x.conversation)==null?void 0:$.status,i]);const me=ae(()=>k.loadPrevious()),Ie=ae(()=>k.loadNext()),j=ae(async I=>{try{await k.deleteMessage(I)}finally{I.sendingStatus!=="succeeded"&&q.messageCallbacks.onLocalMessageDeleted(I)}}),K=ae(I=>I.isUserMessage()?q.runWithUserTurnStats(w=>q.runWithPendingStuckStats(D=>k.resendMessage(I,z=>{w(z.reqId),D(z)}),void 0)):q.runWithPendingStuckStats((w,D)=>k.resendMessage(I,w,D),void 0,{tracksUploadProgress:I.isMultipleFilesMessage()})),R=ae(()=>k.resetNewMessages()),X=ae(async I=>{var D;if(((D=x==null?void 0:x.conversation)==null?void 0:D.status)===de.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await q.runWithUserTurnStats(z=>q.runWithPendingStuckStats(W=>k.sendUserMessage(I,te=>{z(te.reqId),W(te)}),u));return u==null||u(w),w}),ne=ae(async I=>{var D;if(((D=x==null?void 0:x.conversation)==null?void 0:D.status)===de.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await q.runWithPendingStuckStats(z=>k.sendFileMessage(I,z),u);return u==null||u(w),w}),oe=ae(async I=>{var D;if(((D=x==null?void 0:x.conversation)==null?void 0:D.status)===de.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await q.runWithPendingStuckStats((z,W)=>k.sendMultipleFilesMessage(I,z,W),u,{tracksUploadProgress:!0});return u==null||u(w),w}),Re={conversation:(x==null?void 0:x.conversation)??void 0,actions:{setUserMemoryState:b.setUserMemoryState},channelSource:{channel:x,error:O,refetch:()=>H(),closeConversation:async()=>{He(x)||await(x==null?void 0:x.closeConversation())}},messageSource:{messages:k.messages,newMessages:k.newMessages,initialized:k.initialized,subscribeMessageEvents:k.subscribeMessageEvents,loadPrevious:me,loadNext:Ie,deleteMessage:j,resendMessage:K,resetNewMessages:R,sendUserMessage:X,sendFileMessage:ne,sendMultipleFilesMessage:oe},state:{streamAnimation:G,input:P}};return a.createElement(Vd,{value:Re},e)}function Wd(e,t,n){var p,y,A,T,M,L,N,x,O,H;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=ae(()=>{var F;return(F=n==null?void 0:n.onListRequestStart)==null?void 0:F.call(n)}),g=ae(()=>{var F;return(F=n==null?void 0:n.onListRequestComplete)==null?void 0:F.call(n)}),b=l.useCallback(async F=>{f(),await F.loadMore(),g()},[f,g]),S=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const F=new ri(e,t);F.setConversationListCollectionHandler({onChannelsAdded:()=>{u(F.channels)},onChannelsUpdated:()=>{u(F.channels)},onChannelsDeleted:()=>{u(F.channels)}}),await b(F),u(F.channels),m(F),i(null)}catch(F){m(null),i(F)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(p=t.filter)==null?void 0:p.aiAgentChannelFilter,(A=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:A.join(),(M=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:M.join(),(L=t.filter)==null?void 0:L.deskChannelFilter,(x=(N=t.filter)==null?void 0:N.pinnedChannelUrls)==null?void 0:x.join(),(O=t.filter)==null?void 0:O.copilotConversationOnly,(H=t.filter)==null?void 0:H.copilotSupportChannelUrl,t.limit,b]),_=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(F){i(F)}},[d]);return Zt(e,{onConnected:()=>S()}),l.useEffect(()=>{S()},[S]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:_}}const xi=e=>{var s;const{aiAgentId:t,queryParams:n}=ke(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[de.ConversationStatus.CLOSED,de.ConversationStatus.OPEN],...r,...e}},Yd=({enabled:e=!0}={})=>{const n=Xt().conversationListInitialRender,r=l.useRef(e),s=l.useRef(!1),o=l.useRef(!1),i=l.useRef(!1);r.current=e,l.useEffect(()=>{if(!e){o.current&&(s.current=!0);return}if(o.current&&!s.current)return;const m=s.current&&i.current;n.onInitializeStart(),o.current=!0,s.current=!1,m&&n.onListRequestStart()},[e,n]),l.useEffect(()=>()=>{n.clear(),o.current=!1,s.current=!1,i.current=!1},[n]);const c=l.useCallback(()=>r.current&&o.current&&!s.current,[]),u=l.useMemo(()=>({onListRequestStart:()=>{i.current=!0,c()&&n.onListRequestStart()},onListRequestComplete:()=>{i.current=!1,c()&&n.onListRequestComplete()}}),[c,n]),d=l.useCallback(()=>{c()&&n.onRendered()},[c,n]);return l.useMemo(()=>({collectionCallbacks:u,onRendered:d}),[u,d])},{Provider:jd}=be("AIAgentConversationList");function Xd({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=ke(),i=Yd({enabled:n}),c=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),u=xi(t),d=Wd(s,{limit:c,filter:u},i.collectionCallbacks);l.useEffect(()=>{n&&d.initialized&&(d.error||i.onRendered())},[n,d.error,d.initialized,i]);const m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(jd,{value:m},r)}function Zd(e){let t="pending",n=e.then(r=>{t="resolved",n=r}).catch(r=>{t="rejected",n=r});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:Jd,useContext:Qd}=be("MessageTemplateFetching");function em({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const g=m(h);if(g)return g;const b=r.current[h];if(b)return b;f||i(h,{fetching:!0});const S=d(h).catch(_=>{throw f||i(h,{error:!0}),_}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=S,S},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Zd(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(Jd,{value:u},e)}const tm="remove_powered_by",Br=(e,t)=>{var s,o;const{chatSDK:n}=ke(),{aiAgentInfo:r}=ft();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&Mr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(tm)),[i])}throw new Error("Unsupported feature")},nm={required:"This question is required",minLength:e=>`Minimum ${e} characters required`,maxLength:e=>`Maximum ${e} characters allowed`,min:e=>`Minimum value is ${e}`,max:e=>`Maximum value is ${e}`,minSelect:e=>`Select at least ${e} options`,maxSelect:e=>`Select at most ${e} options`,regex:"Invalid format",invalidSelection:"Invalid selection"},rm={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},sm={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},om={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;return e.required&&!r?{isValid:!1,error:n.required}:r&&!e.options.includes(r)?{isValid:!1,error:n.invalidSelection}:{isValid:!0}}},im={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},am={text:rm,number:sm,"single-select":om,"multi-select":im},cm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ri(e){return am[e.type]||cm}function Gs(e){return Ri(e).getValueOrDefault(e)}function lm(e,t,n={}){const r={...nm,...n};return Ri(e).validate(e,t,r)}const um=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const S={};return e.fields.forEach(_=>{S[_.key]=Gs(_)}),S}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const S={};let _=!1;e.fields.forEach(p=>{const y=Gs(p);JSON.stringify(c[p.key])!==JSON.stringify(y)&&(_=!0),S[p.key]=y}),_&&u(S)}},[d]);const m=(S,_)=>{u(p=>({...p,[S]:_})),i(p=>({...p,[S]:void 0}))},h=e.fields.map(S=>{var y,A,T;const _=c[S.key]??null,p={key:S.key,label:S.label,error:o[S.key],required:S.required};return S.type==="text"?{...p,type:"text",layout:S.layout,value:_,...S.placeholder&&{placeholder:S.placeholder},...((y=S.rules)==null?void 0:y.max_length)&&{maxLength:S.rules.max_length}}:S.type==="number"?{...p,type:"number",layout:S.layout,value:_,...S.placeholder&&{placeholder:S.placeholder},...((A=S.rules)==null?void 0:A.max)&&{max:S.rules.max}}:S.type==="single-select"?{...p,type:"single-select",layout:S.layout,value:_,options:S.options}:S.type==="multi-select"?{...p,type:"multi-select",layout:S.layout,value:_,options:S.options,...((T=S.rules)==null?void 0:T.max_select)&&{maxSelect:S.rules.max_select}}:{...p,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:S=>h.find(_=>_.key===S),updateFieldValue:m,submit:async()=>{const S={};let _=!1;for(const p of e.fields){const y=c[p.key]??null,A=lm(p,y,n);A.isValid||(S[p.key]=A.error,_=!0)}if(i(S),!_&&r){const p={};e.fields.forEach(y=>{p[y.key]=c[y.key]??null}),await r(p)}},cancel:async()=>{await(s==null?void 0:s())}}},dm=e=>{const{chatSDK:t,handlers:n,logger:r}=ke(),{aiAgentInfo:s}=ft(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!st(m,s.userId))return;const f=m.messageId;if(Me.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=Yo(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,f)=>{m.url===e&&(c(h,f),u(h))};return ht(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},mm=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},Mi=e=>{const{aiAgentInfo:t}=ft(),n=Ii(e);if(He(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?mm(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},hm=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},fm=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},gm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=fm(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},pm=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},Hr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=oi(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?rt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},zs=e=>l.useReducer((t,n)=>({...t,...n}),e);var Je=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(Je||{});const _m=new Set(["free_text","single_choice"]),Em=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=zs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=zs({followUpItem:!1}),d=l.useMemo(()=>{var _;const g=o.csat,b=typeof g=="number",S=(_=e.follow_up)==null?void 0:_.find(p=>b?p.scores.includes(g):p.always_visible??!1);if(_m.has(S==null?void 0:S.response_type))return S},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===Je.AI_AGENT_CSAT_5||t===Je.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Je.AI_AGENT_CSAT_5_WITH_CRE){const b=typeof o.csat=="number",S=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(b&&S)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Cm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!Je[n.type],o=!r&&typeof e!="number"&&ii(t),i=jt();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},Jn=5,Dt=250,bm=50,Vs=e=>Math.max(0,e-bm),_n=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,vm=e=>e<1e3?{speed:Jn*.5,chunkSize:2}:e<2e3?{speed:Jn*.8,chunkSize:2}:{speed:Jn*.6,chunkSize:3},En=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},qs=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(En(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},wi=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!En(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!En(e,s),c=e[s]==="["&&!En(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=qs(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=qs(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},Sm=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(y=>{var A;(A=r.current)==null||A.call(r,y)},[]),m=l.useCallback(y=>{const A=e.initialEnabled&&(e.enabled||y<e.textLength),T=A&&e.deferImages,M=A&&e.deferLinks;return!T&&!M?y:wi(e.text.slice(0,y),{hideImages:T,hideLinks:M}).length},[e]),h=l.useCallback((y,A,T=!1)=>{r.current&&(y<=c.lastLength||!T&&A-c.lastReportedAt<Dt||(c.lastLength=y,c.lastReportedAt=A,d(y)))},[d,c]),f=l.useCallback((y,A,T=!1)=>{if(!r.current)return;const M=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&A-M<Dt||(c.lastCheckedAt=A,h(m(y),A,!0))},[m,h,c]),g=l.useCallback((y,A,T=!1)=>{s.current&&(y<=i.lastLength||!T&&A-i.lastReportedAt<Dt||(i.lastLength=y,i.lastReportedAt=A,s.current(y)))},[i]),b=l.useCallback((y,A,T)=>{const M=y>=A,L=T-i.lastReportedAt>=Dt;if(!M&&!L)return;const N=m(y);g(N,T,M)},[m,i,g]),S=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),_=l.useCallback(y=>{r.current&&(o.current!==null&&y<=o.current||(o.current=y,d(y)))},[d]),p=l.useCallback(({displayedLength:y,streamTextLength:A})=>{const T=u.current;if(u.current={displayedLength:y,streamTextLength:A},!e.initialEnabled||!T||y>T.displayedLength||A<=T.streamTextLength)return;const M=_n();h(A,M,!0),g(A,M,!0)},[u,g,h,e]);return{resetProgress:S,reportVisibleTextProgress:f,reportRenderedTextProgress:b,reportNonStreamingVisibleTextProgress:_,reportMarkdownRevealProgress:p}},ym=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onVisibleTextProgress:u,onRenderedTextProgress:d}=e,m=s.includes("image"),h=s.includes("link"),[f,g]=l.useState(()=>Vs(t.length)),b=l.useRef(null),S=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,_=l.useRef({startCalled:!1,completeCalled:!1}).current,p=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:m,deferLinks:h,snapOnDisable:r}).current,y=ae(()=>o==null?void 0:o()),A=ae(()=>i==null?void 0:i()),T=ae(()=>c==null?void 0:c()),{resetProgress:M,reportVisibleTextProgress:L,reportRenderedTextProgress:N,reportNonStreamingVisibleTextProgress:x,reportMarkdownRevealProgress:O}=Sm({trackedRef:p,onVisibleTextProgress:u,onRenderedTextProgress:d}),H=n,F=f<t.length,Y=p.initialEnabled&&(H||F);l.useLayoutEffect(()=>{p.textLength=t.length,p.enabled=n,p.text=t,p.deferImages=m,p.deferLinks=h,p.snapOnDisable=r}),l.useLayoutEffect(()=>{if(p.initialEnabled){if(_.startCalled||(_.startCalled=!0,y()),!p.enabled&&p.snapOnDisable){g(t.length);const k=_n();L(t.length,k,!0),N(t.length,t.length,k);return}g(k=>t.length<k?t.length:k)}},[y,N,L,t]),l.useEffect(()=>{if(!p.initialEnabled)return;let k=Vs(t.length);S.lastUpdate=0,S.startTime=0,S.lastProgressCall=0,M();const G=P=>{S.lastUpdate===0&&(S.lastUpdate=P,S.startTime=P,S.lastProgressCall=P,k>0&&L(k,P,!0));const V=p.textLength;!p.enabled&&p.snapOnDisable&&k<V&&(k=V,g(k),L(k,P,!0),N(k,V,P));const me=P-S.lastUpdate,Ie=P-S.startTime,{speed:j,chunkSize:K}=vm(Ie),R=j*K;me>=R&&k<V&&(k=Math.min(k+K,V),g(k),L(k,P,k>=V),N(k,V,P),S.lastUpdate=P),P-S.lastProgressCall>=Dt&&(S.lastProgressCall=P,A()),(k<V||p.enabled)&&(b.current=requestAnimationFrame(G))};return b.current=requestAnimationFrame(G),()=>{b.current&&cancelAnimationFrame(b.current),_.startCalled&&!_.completeCalled&&(_.completeCalled=!0,T())}},[T,A,N,L,M]),l.useEffect(()=>{p.initialEnabled&&(n||t.length>0)||(x(t.length),N(t.length,t.length,_n()))},[n,d,u,x,N,t.length,p]),l.useEffect(()=>{const k=p.initialEnabled&&_.startCalled,G=!n,P=f>=t.length;k&&G&&P&&!_.completeCalled&&(_.completeCalled=!0,T())},[n,f,T,t.length]);const q=l.useMemo(()=>{const k=p.initialEnabled?t.slice(0,f):t,G=Y&&m,P=Y&&h;return!G&&!P?k:wi(k,{hideImages:G,hideLinks:P})},[t,f,m,h,Y]);return l.useEffect(()=>{!p.initialEnabled||Y||L(f,_n(),!0)},[f,Y,L]),l.useEffect(()=>{O({displayedLength:f,streamTextLength:q.length})},[f,O,q.length]),{streamText:q,isAnimating:Y}},Ks={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Am=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Tm=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},Im=()=>{const{chatSDK:e}=ke(),[t,n]=l.useState(Ks),r=()=>n(Ks);return Zt(e,{onConnectionDelayed:s=>{s>0?n(Am(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Tm(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},xm=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Rm=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},Mm=({enabled:e=!0}={})=>{const t=Xt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=Me.isStreaming(n),c=On(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!Rc(n)&&!Me.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,b=!1;const S={};return(f||m)&&(S.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!b&&(b=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(S.onRenderedTextProgress=_=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:_})}),u&&(S.onMessageTemplateError=_=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:_})}),d&&(S.onFormRenderError=_=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:_})}),S},[e,t])},wm=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},Qn=5e3,ln=()=>yn.now(),km=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=Xt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?ln()-Qn:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(ln()-u.current<Qn){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=ln()-Qn):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=ln()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Lm=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=Xt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Om=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(f=>{h===i.current&&o(f.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===ie.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),Zt(e,{onConnected:c,onReconnectSucceeded:c}),s},Gr=e=>e.replace(/\s+/g," ").trim(),Dm="Code block",ki=e=>`A11Y_INLINE_CODE_${e}`,Li=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},Oi=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},Nm=e=>{const{blockquotePrefix:t,content:n}=Li(e),{content:r}=Oi(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},$m=(e,t)=>{const{blockquotePrefix:n,content:r}=Li(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=Oi(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},Fm=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},Pm=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},Um=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},Bm=e=>{let t=0,n="";for(;t<e.length;){const r=Fm(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Pm(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&xn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!xn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=Um(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Di=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Hm=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Di(n,r,i)?t:`${n}${r}`}),Gm=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),zm=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Vm=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return Di(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},qm=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Km=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},Ws=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},Ys=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},Wm=e=>{const t=e.split(`
2
+ `),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=Ys(s);if(i.length>0&&o&&Ws(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=Ys(c);if(u.length===0||Ws(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
3
+ `)},Ym=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),jm=(e,t)=>{const n=e.split(`
4
+ `),r=[];let s=0;for(;s<n.length;){const o=n[s],i=Nm(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if($m(n[u],i)){c=u;break}if(c===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=c+1}return r.join(`
5
+ `)},xn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},Xm=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||xn(e,n)){r+=s,n+=1;continue}let o=n;for(;o<e.length&&e[o]==="`";)o+=1;const i=e.slice(n,o);let c=o,u=!1;for(;c<e.length&&e[c]!==`
6
+ `;){if(e[c]==="`"&&!xn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=ki(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Ni=(e,{codeBlockPlaceholder:t=Dm}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
7
+ `);if(!n)return;const r=[];let s=n;s=jm(s,t),s=Km(s);const o=Xm(s);s=o.text,r.push(...o.inlineCodes),s=Bm(s),s=Hm(s),s=Gm(s),s=zm(s),s=Vm(s),s=Wm(s),s=Ym(s),s=qm(s);for(let c=0;c<r.length;c++)s=s.replaceAll(ki(c),r[c]);return Gr(s)||void 0},Zm=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return We(r)?t.image:zt(r)?t.video:ei({name:n,mimeType:r})?t.pdf(n):t.document(n)},Rn=e=>(e==null?void 0:e.trim())||"",Jm=e=>(e?Gr(e):void 0)||void 0,$i=e=>({text:Rn(e),format:"plain"}),Qm=e=>({text:Rn(e),format:"markdown"}),er=({markdownText:e,plainText:t,comparisonText:n})=>{const r=Rn(e);return r&&r!==Rn(n)?Qm(r):$i(t)},Nt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Ni(t,{codeBlockPlaceholder:s}):Jm(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},Fi=(e,t)=>Ni(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),eh=(...e)=>Gr(e.filter(Boolean).join(", "))||void 0,js=(e,t,n,r)=>{if(!t||t===n)return e;const s=Fi(t,r);return s?eh(e,s):e},th=(e,t)=>{var r,s,o,i;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const c=((s=e.name)==null?void 0:s.trim())||"",u=Zm({name:c,mimeType:e.type},t);return js(u,n,c,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const c=e.fileInfoList??[],u=c.length;if(u===0)return;const d=((i=(o=c[0])==null?void 0:o.fileName)==null?void 0:i.trim())||"",h=c.every(f=>{var g;return(g=f.mimeType)==null?void 0:g.startsWith("image")})?t.receivedFilesImageCount(u):t.multipleFilesCount(u);return js(h,n,d,t.codeBlockPlaceholder)}return Fi(n,t.codeBlockPlaceholder)},nh=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,f=0;const g=(x,O,H)=>({text:x,ignoreSuppression:O,queueOrder:f++,dedupeKey:H}),b=()=>{const x=c[0]??null,O=i;return x&&O?O.queueOrder<x.queueOrder?(i=null,O):c.shift()??null:x?c.shift()??null:O!==null?(i=null,O):null},S=()=>{for(;;){const x=b();if(!x)return null;if(!(!x.ignoreSuppression&&(r!=null&&r())))return x}},_=x=>{u=x.text,d=x.dedupeKey??null,h=!0,e(x.text),m=setTimeout(()=>{m=null,h=!1;const O=S();O&&_(O)},n)},p=x=>{u=x.text,d=x.dedupeKey??null,e(x.text)},y=(x,O,H,F)=>O!=null&&F!=null?O===F:O==null&&F==null?x!=null&&x===H:!1,A=(x,O,H)=>{if(!x||!O&&(r!=null&&r()))return;const F=H==null?void 0:H.dedupeKey;if(!(h&&y(x,F,u,d)))if(h){if(((H==null?void 0:H.mode)??"latestOnly")==="ordered"){const q=c[c.length-1];if(q&&y(x,F,q.text,q.dedupeKey))return;c.push(g(x,O,F)),c.length>o&&c.shift();return}i=g(x,O,F)}else i=null,_(g(x,O,F))};return{announce:(x,O)=>{A(x,!1,O)},announceIgnoringSuppression:(x,O)=>{A(x,!0,O)},flush:()=>{const x=[];let O=b();for(;O!==null;)x.push(O),O=b();if(m!==null&&(clearTimeout(m),m=null),h=!1,x.length!==0)for(const H of x)p(H)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},rh=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},sh=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),oh=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},ih=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},ah=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),ch=(e,t)=>De.isAdmin(e)?De.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,lh=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,uh=e=>e===ie.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===ie.CollectionEventSource.EVENT_MESSAGE_UPDATED,dh=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",mh=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},hh=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},fh=({intent:e,strings:t})=>({label:mh(e,t),hint:hh(e,t)}),gh="1.34.2",Ge="sb-agent",Se={ENTRY:`${Ge}-entry`,MODAL_ROOT:`${Ge}-modal-root`,WINDOW:`${Ge}-window`,LAUNCHER:`${Ge}-launcher`,WINDOW_TITLE:`${Ge}-window-title`},Pi="data-sb-initial-focus",Ui="true",ph=`[${Pi}="${Ui}"]`,Bi={[Pi]:Ui},zr="data-sb-focus-trap-sentinel",_h="true",Hi="data-sb-initial-focus-header",Gi="true",Eh=`[${Hi}="${Gi}"]`,zi={[Hi]:Gi},Vi="data-sb-message-input",qi="true",Ch=`textarea[${Vi}="${qi}"]:not(:disabled)`,bh={[Vi]:qi},Ki=1e3,un=2147483647,gt={MODAL:un-1,TOOLTIP:un-2,WINDOW:un-3,LAUNCHER:un-4},Wi=36,vh=100,Sh=gh,Vr="noopener noreferrer nofollow",fr=()=>typeof document>"u"||document.visibilityState==="visible",Xs=()=>typeof document<"u"&&document.visibilityState==="hidden",yh=e=>{if(fr()){e();return}if(typeof document>"u")return;const t=()=>{fr()&&(document.removeEventListener("visibilitychange",t),e())};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)};function Ah(){return{isOnline:()=>navigator.onLine,subscribe:e=>{const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}const dn={};function Th(){return{get:e=>{try{return localStorage.getItem(e)}catch{return dn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{dn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete dn[e]}},getKeys:e=>{try{const t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r&&r.startsWith(e)&&t.push(r)}return t}catch{return Object.keys(dn).filter(t=>t.startsWith(e))}}}}const Ih={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry",button_ok:"OK",button_cancel:"Cancel"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`}},gr={language:"en",strings:Ih,dateLocale:dc.enUS},Yi=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),ji=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Jt},Jt="en",Xi=new Set([Jt,"ko","es","pt","fr","hi","it","de","tr","ja"]),xh='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:Rh,useContext:qr}=be("AgentUIElementResolver"),Mh=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===Se.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(Rh,{value:s},r)};function ut(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Zs=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:wh,useContext:Kr}=be("EscapeDismissStack"),Js=e=>{e.stopPropagation(),e.stopImmediatePropagation()},kh=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Zs()),s.current||(s.current=Zs());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??ut(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Js(m);return}i.dismissTopmost()&&Js(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(wh,{value:c},n)},Zi=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Lh=(e,t)=>{const{register:n}=Kr();Zi(e,t,n)},Oh=(e,t)=>{const{registerShellDismissHandler:n}=Kr();Zi(e,t,n)},Ji=()=>{const{subscribe:e,getOpenCount:t}=Kr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},Dh=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Qs=Yi(gr.strings),Nh={...Qs,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:Qs.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},Mn={language:gr.language,dateLocale:gr.dateLocale,stringSet:Nh},$h=Object.freeze(Object.defineProperty({__proto__:null,default:Mn},Symbol.toStringTag,{value:"Module"})),pr=new Map([[Jt,Mn]]);async function Fh(e){const t=pr.get(e);if(t)return t;try{if(Xi.has(e)){const{default:n}=await Dh(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>$h),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/D_km8dcd.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/CLIpC7kY.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/ChrM6HN1.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/CPZf2TWM.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/D7UQ9OK7.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMDJStMQ.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/etCQgYrr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DKQwAy8C.cjs"))}),`./languages/${e}.ts`,3);return pr.set(e,n),n}return Mn}catch{return Mn}}const{Provider:Ph,useContext:se}=be("Localization"),Uh=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(pr.get(Jt));return l.useEffect(()=>{const c=t??ji(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Fh(c).then(i))},[e,t,n]),a.createElement(Ph,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>at.format(c,u,{locale:o.dateLocale,...d})}},s)},wn="data-sb-agent-theme",eo=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${wn}='${e}'] & { ${r} }`},Q={light:eo("light"),dark:eo("dark")},Bh=U.css(({theme:e})=>{const{palette:t}=e;return`
8
8
  :root,
9
9
  :host {
10
10
  --sendbird-primary-extra-dark: ${t.primary.extraDark};
@@ -53,7 +53,7 @@
53
53
  --sendbird-overlay-dark: ${t.overlay.dark};
54
54
  --sendbird-overlay-light: ${t.overlay.light};
55
55
  }
56
- `}),Nh=U.css`[${Rn}='light'] &{--sb-text-high-emphasis:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled:var(--sendbird-onlight-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-ondark-text-disabled);--sb-bg-50-600:var(--sendbird-background-50);--sb-bg-100-500:var(--sendbird-background-100);--sb-bg-300-500:var(--sendbird-background-300);--sb-bg-200-400:var(--sendbird-background-200);--sb-primary:var(--sendbird-primary-main);--sb-secondary:var(--sendbird-secondary-main);--sb-error:var(--sendbird-error-main);--sb-information:var(--sendbird-information-light);}[${Rn}='dark'] &{--sb-text-high-emphasis:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled:var(--sendbird-ondark-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-onlight-text-disabled);--sb-bg-50-600:var(--sendbird-background-600);--sb-bg-100-500:var(--sendbird-background-500);--sb-bg-300-500:var(--sendbird-background-500);--sb-bg-200-400:var(--sendbird-background-400);--sb-primary:var(--sendbird-primary-light);--sb-secondary:var(--sendbird-secondary-light);--sb-error:var(--sendbird-error-light);--sb-information:var(--sendbird-information-light);}`,E={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},secondary:{dark:"var(--sendbird-secondary-dark)",light:"var(--sendbird-secondary-light)"},error:{dark:"var(--sendbird-error-dark)",light:"var(--sendbird-error-light)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background300:"var(--sendbird-background-300)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)",textDisabled:"var(--sendbird-onlight-text-disabled)"},ondark:{textHighEmphasis:"var(--sendbird-ondark-text-high-emphasis)",textMidEmphasis:"var(--sendbird-ondark-text-mid-emphasis)",textLowEmphasis:"var(--sendbird-ondark-text-low-emphasis)",textDisabled:"var(--sendbird-ondark-text-disabled)"},overlay:{dark:"var(--sendbird-overlay-dark)"}},themedColor:{textHighEmphasis:"var(--sb-text-high-emphasis)",textMidEmphasis:"var(--sb-text-mid-emphasis)",textLowEmphasis:"var(--sb-text-low-emphasis)",textDisabled:"var(--sb-text-disabled)",textHighEmphasisInverse:"var(--sb-text-high-emphasis-inverse)",textLowEmphasisInverse:"var(--sb-text-low-emphasis-inverse)",bg_50_600:"var(--sb-bg-50-600)",bg_100_500:"var(--sb-bg-100-500)",bg_300_500:"var(--sb-bg-300-500)",bg_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}};class Ht extends l.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){var n,r;(r=(n=this.props).onError)==null||r.call(n,t)}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:s}=this.props;return this.state.hasError?n:a.createElement(l.Suspense,{fallback:r},s)}}const Ze=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Dh=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{className:"fill",d:"M52.552 11.448a2.666 2.666 0 0 1 .222 3.52l-.222.251-16.781 16.78 16.781 16.782a2.665 2.665 0 0 1 0 3.771 2.666 2.666 0 0 1-3.52.222l-.251-.222L32 35.771 15.219 52.552a2.665 2.665 0 0 1-3.771 0 2.666 2.666 0 0 1-.222-3.52l.222-.251L28.228 32l-16.78-16.781a2.665 2.665 0 0 1 0-3.771 2.666 2.666 0 0 1 3.52-.222l.251.222 16.78 16.78 16.782-16.78a2.665 2.665 0 0 1 3.771 0z",fill:"#000",fillRule:"evenodd"})),$h=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},a.createElement("path",{className:"fill",d:"M7.33348 7.3335L2.00015 7.3335L2.00015 6.00016H5.05735L1.3335 2.27631L2.27631 1.3335L6.00015 5.05734V2.00016L7.33348 2.00016L7.33348 7.3335ZM8.66683 8.66683H14.0002V10.0002L10.943 10.0002L14.6668 13.724L13.724 14.6668L10.0002 10.943V14.0002H8.66683L8.66683 8.66683Z",fill:"#000",fillRule:"evenodd"})),Fh=e=>a.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},a.createElement("path",{className:"fill",fillRule:"evenodd",clipRule:"evenodd",d:"M2 2H7.33333V3.33333L4.27613 3.33333L7.99999 7.05719L7.05718 8L3.33333 4.27616L3.33333 7.33333H2V2ZM14 14H8.66667V12.6667H11.7239L8.00001 8.94281L8.94282 8L12.6667 11.7238V8.66667H14V14Z",fill:"#000"})),Ph=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},a.createElement("path",{className:"fill",fill:"#0D0D0D",d:"M50.667 18.667H13.333v-5.334h37.334zM50.667 34.667H13.333v-5.334h37.334zM13.333 50.667h37.334v-5.334H13.333z"})),Uh=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{fill:"#000",fillRule:"evenodd",d:"M59.795 29.43 7.329 2.979C4.691 1.802 1.76 4.153 2.932 6.798l6.925 18.609a2 2 0 0 0 1.544 1.275l32.273 5.394L11.4 37.47a1.998 1.998 0 0 0-1.544 1.275L2.932 57.353c-.879 2.645 1.76 4.997 4.397 3.527l52.466-26.453c2.051-.882 2.051-3.82 0-4.996z",className:"fill"})),Bh=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Hh={close:Dh,send:Uh,menu:Ph,expand:Fh,collapse:$h,spinner:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs"))),activity:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DP95uu-Y.cjs")))},Gh=e=>({size:t=24,color:n=E.color.primary.main,flipInRtl:r=!1})=>a.createElement(Vh,{$size:t,$color:n,$rtlFlip:r},a.createElement(Ht,{errorFallback:a.createElement(qh,null)},a.createElement(e,null))),Zi=Object.fromEntries(Object.entries(Hh).map(([e,t])=>[e,Gh(t)])),zh=U.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Vh=C.default.span.attrs({"aria-hidden":"true"})`
56
+ `}),Hh=U.css`[${wn}='light'] &{--sb-text-high-emphasis:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled:var(--sendbird-onlight-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-ondark-text-disabled);--sb-bg-50-600:var(--sendbird-background-50);--sb-bg-100-500:var(--sendbird-background-100);--sb-bg-300-500:var(--sendbird-background-300);--sb-bg-200-400:var(--sendbird-background-200);--sb-primary:var(--sendbird-primary-main);--sb-secondary:var(--sendbird-secondary-main);--sb-error:var(--sendbird-error-main);--sb-information:var(--sendbird-information-light);}[${wn}='dark'] &{--sb-text-high-emphasis:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled:var(--sendbird-ondark-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-onlight-text-disabled);--sb-bg-50-600:var(--sendbird-background-600);--sb-bg-100-500:var(--sendbird-background-500);--sb-bg-300-500:var(--sendbird-background-500);--sb-bg-200-400:var(--sendbird-background-400);--sb-primary:var(--sendbird-primary-light);--sb-secondary:var(--sendbird-secondary-light);--sb-error:var(--sendbird-error-light);--sb-information:var(--sendbird-information-light);}`,E={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},secondary:{dark:"var(--sendbird-secondary-dark)",light:"var(--sendbird-secondary-light)"},error:{dark:"var(--sendbird-error-dark)",light:"var(--sendbird-error-light)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background300:"var(--sendbird-background-300)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)",textDisabled:"var(--sendbird-onlight-text-disabled)"},ondark:{textHighEmphasis:"var(--sendbird-ondark-text-high-emphasis)",textMidEmphasis:"var(--sendbird-ondark-text-mid-emphasis)",textLowEmphasis:"var(--sendbird-ondark-text-low-emphasis)",textDisabled:"var(--sendbird-ondark-text-disabled)"},overlay:{dark:"var(--sendbird-overlay-dark)"}},themedColor:{textHighEmphasis:"var(--sb-text-high-emphasis)",textMidEmphasis:"var(--sb-text-mid-emphasis)",textLowEmphasis:"var(--sb-text-low-emphasis)",textDisabled:"var(--sb-text-disabled)",textHighEmphasisInverse:"var(--sb-text-high-emphasis-inverse)",textLowEmphasisInverse:"var(--sb-text-low-emphasis-inverse)",bg_50_600:"var(--sb-bg-50-600)",bg_100_500:"var(--sb-bg-100-500)",bg_300_500:"var(--sb-bg-300-500)",bg_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}};class Ht extends l.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){var n,r;(r=(n=this.props).onError)==null||r.call(n,t)}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:s}=this.props;return this.state.hasError?n:a.createElement(l.Suspense,{fallback:r},s)}}const Ze=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Gh=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{className:"fill",d:"M52.552 11.448a2.666 2.666 0 0 1 .222 3.52l-.222.251-16.781 16.78 16.781 16.782a2.665 2.665 0 0 1 0 3.771 2.666 2.666 0 0 1-3.52.222l-.251-.222L32 35.771 15.219 52.552a2.665 2.665 0 0 1-3.771 0 2.666 2.666 0 0 1-.222-3.52l.222-.251L28.228 32l-16.78-16.781a2.665 2.665 0 0 1 0-3.771 2.666 2.666 0 0 1 3.52-.222l.251.222 16.78 16.78 16.782-16.78a2.665 2.665 0 0 1 3.771 0z",fill:"#000",fillRule:"evenodd"})),zh=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},a.createElement("path",{className:"fill",d:"M7.33348 7.3335L2.00015 7.3335L2.00015 6.00016H5.05735L1.3335 2.27631L2.27631 1.3335L6.00015 5.05734V2.00016L7.33348 2.00016L7.33348 7.3335ZM8.66683 8.66683H14.0002V10.0002L10.943 10.0002L14.6668 13.724L13.724 14.6668L10.0002 10.943V14.0002H8.66683L8.66683 8.66683Z",fill:"#000",fillRule:"evenodd"})),Vh=e=>a.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},a.createElement("path",{className:"fill",fillRule:"evenodd",clipRule:"evenodd",d:"M2 2H7.33333V3.33333L4.27613 3.33333L7.99999 7.05719L7.05718 8L3.33333 4.27616L3.33333 7.33333H2V2ZM14 14H8.66667V12.6667H11.7239L8.00001 8.94281L8.94282 8L12.6667 11.7238V8.66667H14V14Z",fill:"#000"})),qh=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},a.createElement("path",{className:"fill",fill:"#0D0D0D",d:"M50.667 18.667H13.333v-5.334h37.334zM50.667 34.667H13.333v-5.334h37.334zM13.333 50.667h37.334v-5.334H13.333z"})),Kh=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{fill:"#000",fillRule:"evenodd",d:"M59.795 29.43 7.329 2.979C4.691 1.802 1.76 4.153 2.932 6.798l6.925 18.609a2 2 0 0 0 1.544 1.275l32.273 5.394L11.4 37.47a1.998 1.998 0 0 0-1.544 1.275L2.932 57.353c-.879 2.645 1.76 4.997 4.397 3.527l52.466-26.453c2.051-.882 2.051-3.82 0-4.996z",className:"fill"})),Wh=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Yh={close:Gh,send:Kh,menu:qh,expand:Vh,collapse:zh,spinner:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs"))),activity:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DP95uu-Y.cjs")))},jh=e=>({size:t=24,color:n=E.color.primary.main,flipInRtl:r=!1})=>a.createElement(Zh,{$size:t,$color:n,$rtlFlip:r},a.createElement(Ht,{errorFallback:a.createElement(Jh,null)},a.createElement(e,null))),Qi=Object.fromEntries(Object.entries(Yh).map(([e,t])=>[e,jh(t)])),Xh=U.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Zh=C.default.span.attrs({"aria-hidden":"true"})`
57
57
  width: ${({$size:e})=>Ze(e)};
58
58
  height: ${({$size:e})=>Ze(e)};
59
59
  display: inline-block;
@@ -74,21 +74,21 @@
74
74
  stroke-linejoin: round;
75
75
  }
76
76
 
77
- ${({$rtlFlip:e})=>e&&zh};
78
- `,qh=()=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},a.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),a.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),a.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Kh,useContext:Yh}=be("MessengerIcon",{icons:Zi}),Wh=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:bu(Zi,e)}),[e]);return a.createElement(Kh,{value:n},t)},{Provider:jh,useContext:Ji}=be("MessengerTheme");function Xh(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(cd,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},a.createElement(Zh,{...e}))}function Zh({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Pr();return l.useLayoutEffect(()=>{e.setAttribute(Rn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(U.ThemeProvider,{theme:n},a.createElement(jh,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Jh=(e,t)=>{l.useEffect(()=>{const n=ut(t)instanceof ShadowRoot,r=ut(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const o=r.createElement("link");o.rel="stylesheet",o.href=e,(n?t:r.head).appendChild(o)}},[e,t])},Qh=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=ut(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let i=s.querySelector(`style#${o}`);i?i.textContent!==e&&(i.textContent=e):(i=s.ownerDocument.createElement("style"),i.id=o,i.textContent=e,s.appendChild(i))},[e,t])},ef=80,tf=()=>{const{stringSet:e}=oe(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=l.useRef(t);return n.current=t,n},Qi=be("AriaLiveRegion",{announce:ce,announceScreenEntry:ce,announceStatus:ce,announceError:ce,flush:ce,setSuppressionState:ce}),nf=Qi.Provider,Kr=Qi.useContext,rf={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},sf=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(ce),s=tf(),[o]=l.useState(()=>jm(g=>{r.current(g)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=g=>{const _=t.current;_&&(_.textContent="",requestAnimationFrame(()=>{_.textContent=g}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(g=>{const _=Zm(g,s.current);i(_)},[i]),d=l.useCallback((g,_)=>{const b=Jm(g,s.current),v=(_==null?void 0:_.mode)??Xm(g.event);i(b,{mode:v,dedupeKey:_==null?void 0:_.dedupeKey})},[i]),m=l.useCallback((g,_)=>{const b=Qm(g,s.current);o.announceIgnoringSuppression(b),_&&setTimeout(()=>{_.focus()},ef)},[o]),h=l.useCallback((g,_)=>{if(_){n.current.add(g);return}n.current.delete(g)},[]),f=l.useMemo(()=>({announce:i,announceScreenEntry:u,announceStatus:d,announceError:m,flush:c,setSuppressionState:h}),[i,m,u,d,c,h]);return a.createElement(nf,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:rf}))},ea=be("ConversationAnnouncements",{announcementsEnabled:!0,announce:ce,announceScreenEntry:ce,announceStatus:ce,announceError:ce,setIsSuppressed:ce,setStatusPauseState:ce,flush:ce}),of=ea.Provider,ot=ea.useContext,af=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=Kr(),u=l.useRef([]),d=l.useRef(new Set),m=l.useRef(Symbol("conversation-announcements")),h=l.useCallback(T=>{if(!t||!T){c(m.current,!1);return}c(m.current,!0)},[t,c]),f=l.useCallback(()=>{u.current=[]},[]),g=l.useCallback(()=>{if(u.current.length===0)return;if(!t){f();return}const T=[...u.current];f(),T.forEach(M=>{i(),s(M.params,M.options)})},[s,t,f,i]),_=l.useCallback((T,M)=>{if(M){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),b=l.useCallback(T=>{t&&n(T)},[n,t]),v=l.useCallback(T=>{t&&r(T)},[r,t]),p=l.useCallback((T,M)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:M});return}s(T,M)}},[s,t]),S=l.useCallback((T,M)=>{t&&o(T,M)},[o,t]);l.useLayoutEffect(()=>(t||(f(),c(m.current,!1)),()=>{f(),c(m.current,!1)}),[t,f,c]);const A=l.useMemo(()=>({announcementsEnabled:t,announce:b,announceScreenEntry:v,announceStatus:p,announceError:S,setIsSuppressed:h,setStatusPauseState:_,flush:i}),[t,i,b,S,v,p,h,_]);return a.createElement(of,{value:A},e)},Dn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ta=`${Dn}, [tabindex="-1"]`,Tt=e=>{if(!e.isConnected||e.hidden)return!1;let t=e;const n=e.ownerDocument.defaultView;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!1;if(n){const r=n.getComputedStyle(t);if(r.display==="none"||r.visibility==="hidden")return!1}t=t.parentElement}return!0},Gt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(Gr)&&Tt(n))return n;return null},na=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Dn))r.hasAttribute(Gr)||Tt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},ra=(e,t)=>e instanceof ShadowRoot&&!(t instanceof HTMLElement)?e.host.ownerDocument.activeElement===e.host:t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,cf=(e,t,n)=>ra(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),Yr=e=>Gt(e,lh),sa=e=>Yr(e)??Gt(e,Dn),lf=e=>{const t=Yr(e);if(t)return t;const n=e.querySelector(dh);return(n?Gt(n,ta):null)??Gt(e,Dn)},H=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(mf,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),eo=new WeakMap,uf=(e,t)=>{let n=eo.get(t);n||(n=new Map,eo.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=U.css`font-size:${Ze(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
77
+ ${({$rtlFlip:e})=>e&&Xh};
78
+ `,Jh=()=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},a.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),a.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),a.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Qh,useContext:ef}=be("MessengerIcon",{icons:Qi}),tf=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:Iu(Qi,e)}),[e]);return a.createElement(Qh,{value:n},t)},{Provider:nf,useContext:ea}=be("MessengerTheme");function rf(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(gd,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},a.createElement(sf,{...e}))}function sf({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Ur();return l.useLayoutEffect(()=>{e.setAttribute(wn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(U.ThemeProvider,{theme:n},a.createElement(nf,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const of=(e,t)=>{l.useEffect(()=>{const n=ut(t)instanceof ShadowRoot,r=ut(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const o=r.createElement("link");o.rel="stylesheet",o.href=e,(n?t:r.head).appendChild(o)}},[e,t])},af=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=ut(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let i=s.querySelector(`style#${o}`);i?i.textContent!==e&&(i.textContent=e):(i=s.ownerDocument.createElement("style"),i.id=o,i.textContent=e,s.appendChild(i))},[e,t])},cf=80,lf=()=>{const{stringSet:e}=se(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=l.useRef(t);return n.current=t,n},ta=be("AriaLiveRegion",{announce:ue,announceScreenEntry:ue,announceStatus:ue,announceError:ue,flush:ue,setSuppressionState:ue}),uf=ta.Provider,Wr=ta.useContext,df={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},mf=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(ue),s=lf(),[o]=l.useState(()=>nh(g=>{r.current(g)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=g=>{const b=t.current;b&&(b.textContent="",requestAnimationFrame(()=>{b.textContent=g}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(g=>{const b=sh(g,s.current);i(b)},[i]),d=l.useCallback((g,b)=>{const S=oh(g,s.current),_=(b==null?void 0:b.mode)??rh(g.event);i(S,{mode:_,dedupeKey:b==null?void 0:b.dedupeKey})},[i]),m=l.useCallback((g,b)=>{const S=ih(g,s.current);o.announceIgnoringSuppression(S),b&&setTimeout(()=>{b.focus()},cf)},[o]),h=l.useCallback((g,b)=>{if(b){n.current.add(g);return}n.current.delete(g)},[]),f=l.useMemo(()=>({announce:i,announceScreenEntry:u,announceStatus:d,announceError:m,flush:c,setSuppressionState:h}),[i,m,u,d,c,h]);return a.createElement(uf,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:df}))},na=be("ConversationAnnouncements",{announcementsEnabled:!0,announce:ue,announceScreenEntry:ue,announceStatus:ue,announceError:ue,setIsSuppressed:ue,setStatusPauseState:ue,flush:ue}),hf=na.Provider,ot=na.useContext,ff=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=Wr(),u=l.useRef([]),d=l.useRef(new Set),m=l.useRef(Symbol("conversation-announcements")),h=l.useCallback(T=>{if(!t||!T){c(m.current,!1);return}c(m.current,!0)},[t,c]),f=l.useCallback(()=>{u.current=[]},[]),g=l.useCallback(()=>{if(u.current.length===0)return;if(!t){f();return}const T=[...u.current];f(),T.forEach(M=>{i(),s(M.params,M.options)})},[s,t,f,i]),b=l.useCallback((T,M)=>{if(M){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),S=l.useCallback(T=>{t&&n(T)},[n,t]),_=l.useCallback(T=>{t&&r(T)},[r,t]),p=l.useCallback((T,M)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:M});return}s(T,M)}},[s,t]),y=l.useCallback((T,M)=>{t&&o(T,M)},[o,t]);l.useLayoutEffect(()=>(t||(f(),c(m.current,!1)),()=>{f(),c(m.current,!1)}),[t,f,c]);const A=l.useMemo(()=>({announcementsEnabled:t,announce:S,announceScreenEntry:_,announceStatus:p,announceError:y,setIsSuppressed:h,setStatusPauseState:b,flush:i}),[t,i,S,y,_,p,h,b]);return a.createElement(hf,{value:A},e)},$n=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ra=`${$n}, [tabindex="-1"]`,Tt=e=>{if(!e.isConnected||e.hidden)return!1;let t=e;const n=e.ownerDocument.defaultView;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!1;if(n){const r=n.getComputedStyle(t);if(r.display==="none"||r.visibility==="hidden")return!1}t=t.parentElement}return!0},Gt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(zr)&&Tt(n))return n;return null},sa=e=>{let t=null,n=null;for(const r of e.querySelectorAll($n))r.hasAttribute(zr)||Tt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},oa=(e,t)=>e instanceof ShadowRoot&&!(t instanceof HTMLElement)?e.host.ownerDocument.activeElement===e.host:t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,gf=(e,t,n)=>oa(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),Yr=e=>Gt(e,ph),ia=e=>Yr(e)??Gt(e,$n),pf=e=>{const t=Yr(e);if(t)return t;const n=e.querySelector(Eh);return(n?Gt(n,ra):null)??Gt(e,$n)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(Cf,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),to=new WeakMap,_f=(e,t)=>{let n=to.get(t);n||(n=new Map,to.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=U.css`font-size:${Ze(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
79
79
  ${s.lineHeight?`line-height: ${s.lineHeight};`:"line-height: 100%;"}
80
- `;return n.set(e,o),o},df=e=>e?U.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",mf=C.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>uf(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>df(e)}`;async function Wr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Me(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const pr='[role="dialog"][aria-modal="true"]',hf=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(pr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(pr);return r&&r!==e&&n.add(r),n},ff=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(pr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Tt(n)),gf=e=>{const t=sa(e)??e;t===e&&oa(e),t.focus()},oa=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},pf=(e,t)=>{const n=na(e);if(!n){oa(e),e.focus();return}n[t].focus()},to=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Gr,uh),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>pf(e,t)),n},_f=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(na(t)||(e.preventDefault(),t.focus())))},$n=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=hf(i,u);return()=>{u&&Me(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!ra(c,m)&&m.matches(ta)&&Tt(m)||ff(i,d)||!u.isConnected||!Tt(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&Tt(m)){s.current=!0;return}s.current=!0,gf(o)};if(n)return Me(c),()=>{i=!0};const u=setTimeout(()=>Me(c),Vi);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=to(o,"last"),c=to(o,"first"),u=d=>_f(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},dt=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=Vr();return $n(n,d),Th(n,o?r:ce),n?uc.createPortal(a.createElement(Ef,{onClick:o?r:void 0,style:e},a.createElement(Cf,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Ef=C.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${E.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${gt.MODAL};`,Cf=C.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${gt.MODAL};`,bf=({id:e,children:t})=>a.createElement(vf,{id:e},t),vf=C.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,no=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:Pi}:n},yf=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(bf,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},ro=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ye(t??"")?r.A11Y_FILE_IMAGE(e):zt(t??"")?r.A11Y_FILE_VIDEO(e):Qo({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},Sf=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},$t=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Sf(e)}),Af=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},so=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:Af({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},re=()=>{const{stringSet:e}=oe(),t=yf(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ye(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":ro(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=ah({intent:sh({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:no(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...hh},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?ro({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...$t({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:g})=>{var p;const _=c.trim()||c,b=e.A11Y_HINT_SELECT_RATING,v=t(b,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...so(u,d,m,h,f,S=>g(S+1)),...v.props,"aria-label":((p=e.A11Y_CSAT_RATING_LABEL)==null?void 0:p.call(e,i,_))??`${i} / ${h} — ${_}`},descriptionNode:v.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,f)=>({props:{...so(c,u,d,m,h,f),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:no(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,time:u,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:null};const h=e.A11Y_HINT_OPEN_CONVERSATION,f=t(h,"cli");return{props:{...$t({onActivate:m}),...f.props,"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:f.node}}}}},Tf=({title:e,description:t,highlightedText:n})=>{const r=vm(t,n);return a.createElement(xf,null,a.createElement(Rf,null,a.createElement(H,{as:"div",variant:"h1",color:E.themedColor.textHighEmphasis},e),t&&a.createElement(Mf,null,a.createElement(H,{as:"div",variant:"body3",color:E.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(wf,null,r.highlightedText):null,r.afterText))))},If=()=>{const{components:e}=Fn.useContext(),{stringSet:t}=oe(),{messenger:n}=re(),r=Cm(),s=r.showDescription?bm(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(dt,{portalContainerId:ye.WINDOW,visible:r.visible,onClose:ce,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Fn=je({template:If,components:{Dialog:Tf}}),xf=C.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Rf=C.default.div`display:flex;flex-direction:column;`,Mf=C.default.div`margin-top:16px;`,wf=C.default.strong`font-weight:700;`,kf=({url:e})=>Wr(e),{Provider:Lf,Consumer:ia,useContext:ae}=be("Messenger");function Of({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=Vr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Ih(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const v=g.current&&!m.opened;if(g.current=m.opened,!v)return;const p=ut(o.rootElement),S=h(ye.WINDOW);let A=!1;return Me(()=>{var T;A||cf(p,p.activeElement,S)&&((T=h(ye.LAUNCHER))==null||T.focus())}),()=>{A=!0}},[m.opened,o.rootElement,h]);const{Template:_}=Fn.useContext(),b=l.useMemo(()=>{var v;return{...o.handlers,onClickLink:((v=o.handlers)==null?void 0:v.onClickLink)??kf}},[o.handlers]);return a.createElement(Ru,{...o},v=>a.createElement(Lf,{value:{...o,...v,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:b}},a.createElement(_,null),e))}const aa=/iPad|iPhone|iPod/.test(navigator.userAgent),Nf=/Android/.test(navigator.userAgent),Jt=e=>aa||Nf;let Lt=null,er=null;const Df=(e,t=5e3)=>{Lt&&(clearInterval(Lt),clearTimeout(er));const n=document.title;Lt=setInterval(()=>{document.title=document.title===e?n:e},750),er=setTimeout(()=>{clearInterval(Lt),Lt=null,er=null,document.title=n},t)},ca=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},xe=U.css`&:focus-visible{outline:2px solid ${E.themedColor.primary};outline-offset:2px;}`,oo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Pn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??oo(t)??oo(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,_=()=>{c(),Me(()=>o==null?void 0:o())},b=()=>{c(),Me(()=>i==null?void 0:i())};return a.createElement(dt,{portalContainerId:ye.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement($f,null,a.createElement(Ff,null,t&&a.createElement("div",{id:d},a.createElement(H,{variant:"h1",color:E.themedColor.textHighEmphasis},t)),n&&a.createElement(Pf,{id:m},a.createElement(H,{variant:"body3",color:E.themedColor.textMidEmphasis},n))),a.createElement(Uf,null,s&&a.createElement(io,{onClick:b},a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis},s)),a.createElement(io,{onClick:_},a.createElement(H,{variant:"button",color:E.themedColor.primary},r)))))},$f=C.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Ff=C.default.div`margin-bottom:16px;`,Pf=C.default.div`margin-top:16px;`,Uf=C.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,io=C.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${xe}`,{Provider:Bf,useContext:Oe}=be("MessengerSession"),Hf=l.forwardRef(function({children:e,...t},n){return a.createElement(md,{ref:n,...t},r=>a.createElement(Gf,{...r},e))}),Gf=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=ae(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:_,launcherInfo:b}=t,[v,p]=l.useState(!1),S=l.useRef(null);ht(n,{async onUserJoined(T,M){var N,x,L,z;T.conversation&&T.conversation.type===fe.ConversationType.PROACTIVE&&M.userId===((N=n.currentUser)==null?void 0:N.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(L=m.session)==null||L._updateActiveChannel({url:T.url,status:"open",conversationStatus:(x=T.conversation)==null?void 0:x.status}),c.setOpened(!0),zf({sound:document.hidden||!c.opened}),(z=S.current)==null||z.call(S,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!Jt()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var M;r.error("messengerSession: failed to initialize",T),(M=u==null?void 0:u.onInitializeFailed)==null||M.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>p(!0);return d.subscribe(Ke.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Ke.AnonymousSessionTokenExpired,T)},[d]);const A=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!_||!b?null:a.createElement(Bf,{value:{...t,userSession:g,aiAgentInfo:{..._,...i==null?void 0:i.bot},launcherInfo:{...b,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>S.current=T}},e,a.createElement(Pn,{visible:v,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:ce}))};function zf({sound:e}){Df("🔔You have received a new message"),e&&ca()}const Mn=`@${Ge}-focused-channel`,la=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Vf=()=>{try{const e=localStorage.getItem(Mn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},ao=e=>{try{localStorage.setItem(Mn,JSON.stringify({channelUrl:e,tabId:la}))}catch{}},co=()=>{try{const e=localStorage.getItem(Mn);if(!e)return;JSON.parse(e).tabId===la&&localStorage.removeItem(Mn)}catch{}},qf=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>ao(e),r=()=>co();return document.hasFocus()&&ao(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),co()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Vf()===e}),Kf=e=>{const{config:t,chatSDK:n}=ae(),{sdkUser:r}=Oe(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=qf(e,s);ht(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Qe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ca()}})};function Yf(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),s=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:s})},n.src=URL.createObjectURL(e)})}async function Wf(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Yf(e.file);return new $e.MessageMetaArray({key:Xo,value:[t,n]})}}const jf=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ae(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await Wf(s),i={...s,metaArrays:o?[o]:void 0},c=Xf(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===$e.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===$e.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Xf=e=>{if(!e)return null;const t={};return e.ai&&Object.keys(e.ai).length>0&&(t.ai_attrs=e.ai),e.safeguard&&Object.keys(e.safeguard).length>0&&(t.safeguard_attrs=e.safeguard),typeof e.use_prompt_cache=="boolean"&&(t.use_prompt_cache=e.use_prompt_cache),Object.keys(t).length>0?t:null},St=50,tr=St-40,{Provider:Zf,useContext:ua}=be("ConversationScroll"),lo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},nr=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),uo=e=>Array.from(e.querySelectorAll(`#${Ge}-message-item`));function Jf({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(lo),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[_,b]=l.useState(!1),[v,p]=l.useState(!0),S=$=>{const R=nr($);return o.current.distanceFromBottom=R,h(R),R},A=()=>{const $=i.current;$.reconcileTimer&&(clearTimeout($.reconcileTimer),$.reconcileTimer=null)},T=l.useCallback(()=>{const $=s.current;$.mutation&&($.mutation.disconnect(),$.mutation=null),$.resize&&($.resize.disconnect(),$.resize=null),$.resizeTargets.clear()},[]),M=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),k=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},N=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(R=>{c.current.shouldUpdate=!1;const{contentHeight:O,contentSnapshotHeight:F,shouldRecalc:j}=c.current,X=$.clientHeight;if(F>O)return R;const ne=x($,{messageType:"outgoing"});let Z=0;if(ne){const ge=ne.message.offsetTop-tr+X;Z=Math.max(0,ge-O)}else{const ge=O-F,Xe=X-tr;Z=Math.max(0,ge-Xe)}return R===0||Z!==R||j?(c.current.shouldRecalc=!1,Z):R})},x=l.useCallback(($,R)=>{const{messageType:O="all"}=R??{},F=uo($);let j=F;O==="outgoing"&&(j=F.filter(ie=>ie.getAttribute("data-layout-id")==="outgoingmessage"));const X=j[j.length-1];if(!X)return null;const ne=$.getBoundingClientRect(),Z=X.getBoundingClientRect(),ge=$.scrollTop+(Z.top-ne.top),Xe=ge+X.offsetHeight;return{message:X,scrollTop:ge,lastMessageBottom:Xe}},[]),L=l.useCallback(()=>{const $=r.current;if(!$||M!=="fixed")return;const R=x($);c.current.contentHeight=(R==null?void 0:R.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&k(),i.current.programmatic?o.current.distanceFromBottom=nr($):S($),N()},[M,x]),z=l.useCallback(()=>{T(),A(),c.current=lo,d(0),h(0),p(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),D=l.useCallback(($=!0)=>{const R=o.current.distanceFromBottom>St;if(i.current.awayByUser=!1,h(0),!R){Me(()=>{const O=r.current;O&&!i.current.awayByUser&&O.scrollTo({top:O.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,p(!1),A()),Me(()=>{const O=r.current;if(!O){i.current.programmatic=!1,p(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,S(O),p(!0);return}const F=()=>{if(r.current!==O){i.current.programmatic=!1,r.current&&S(r.current),p(!0);return}i.current.programmatic=!1,S(O),p(!0)};if($&&!i.current.reconcileTimer){const j=setTimeout(F,500);i.current.reconcileTimer=j,O.addEventListener("scrollend",()=>{clearTimeout(j),i.current.reconcileTimer=null,F()},{once:!0})}O.scrollTo({top:O.scrollHeight,behavior:$?"smooth":"auto"}),$||F()})},[]),W=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){S($);return}D(!1)}},[D]),K=l.useCallback(()=>{const $=r.current,R=s.current;if(!$||!R.resize)return;const O=new Set(uo($));for(const F of R.resizeTargets)O.has(F)||(R.resize.unobserve(F),R.resizeTargets.delete(F));for(const F of O)R.resizeTargets.has(F)||(R.resize.observe(F),R.resizeTargets.add(F))},[]),w=l.useCallback($=>{T();const R=s.current;typeof ResizeObserver<"u"&&(R.resize=new ResizeObserver(W),K());const O=new MutationObserver(()=>{K(),W()});R.mutation=O,O.observe($,{childList:!0})},[T,W,K]),V=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,M!=="fixed"){w($);return}z(),c.current.viewport=$.clientHeight;const R=new MutationObserver(()=>{L()});s.current.mutation=R,R.observe($,{childList:!0,subtree:!0})},[T,M,L,z,w]),P=l.useCallback(()=>{const $=r.current;if(!$)return;const R=x($,{messageType:"outgoing"});R&&($.scrollTo({top:R.message.offsetTop-tr,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{b(!1)},500))},[x]),q=($,R,O)=>{const F=nr($);if(O&&F>St){i.current.programmatic=!1,i.current.awayByUser=!0,A(),S($),p(!0),o.current.prevScrollTop=R;return}o.current.distanceFromBottom=F},ue=($,R,O)=>{const j=S($)<=St;R&&!j&&(i.current.awayByUser=!0,A()),O&&j&&(i.current.awayByUser=!1)},Te=$=>{const{scrollTop:R}=$.currentTarget,O=o.current.prevScrollTop;i.current.programmatic?q($.currentTarget,R,R<O):ue($.currentTarget,R<O,R>O),o.current.prevScrollTop=R},B=l.useCallback(()=>{M==="fixed"&&(b(!0),k())},[M]),G=l.useCallback(()=>{M==="fixed"?setTimeout(()=>P(),300):D()},[M,P]),I=l.useCallback($=>{i.current.streaming=$,M==="fixed"?k():i.current.awayByUser||D()},[M,D]),Y=l.useCallback($=>{g($),$&&(d(0),M==="fixed"&&T())},[T,M]),te=l.useCallback($=>{M==="auto"&&$&&!i.current.awayByUser&&D()},[M,D]),Ne=!(m<=St)&&!_,He=l.useCallback(()=>o.current.distanceFromBottom>St,[]);return a.createElement(Zf,{value:{ref:V,state:{bottomSpace:u,isAwayFromBottom:Ne,isScrollPositionReconciled:v,shouldCountNewMessages:He},props:{onScroll:Te},actions:{scrollToBottom:D,onBeforeMessageSend:B,onAfterMessageSend:G,onStreamingUpdate:I,onConversationClosed:Y,onTypingIndicatorUpdate:te}}},n)}const{Provider:Qf,Context:eg,useContext:Ae}=be("Conversation"),tg=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=sm(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},ng=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,children:o})=>{const{activeChannel:i,refreshActiveChannel:c}=Oe(),u=ua(),d=e||(i==null?void 0:i.url);Kf(d);const{onBeforeSendMessage:m,onAfterSendMessage:h}=jf({onScrollAfterSendMessage:()=>{u.actions.onAfterMessageSend()}}),f=l.useCallback(b=>(u.actions.onBeforeMessageSend(),m(b)),[u.actions,m]),g=l.useCallback(b=>{const v=b.some(p=>Re.isStreaming(p));u.actions.onStreamingUpdate(v)},[u.actions.onStreamingUpdate]),_=l.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]);return a.createElement(Ud,{key:d,channelUrl:d,onBeforeSendMessage:f,onAfterSendMessage:h,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:_,onConversationClosedStatusChanged:u.actions.onConversationClosed,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldCountNewMessages:u.state.shouldCountNewMessages},b=>a.createElement(Qf,{value:{...b,conversationStatsEnabled:r??!0,scrollSource:u,goToActiveConversation:_,onNavigateToConversationList:n}},a.createElement(tg,null,o)))},da=({children:e,...t})=>{const{config:n}=we(),{agentPreviewConfigs:r}=ae(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(Jf,{scrollMode:s,messageStackDirection:o},a.createElement(ng,{...t},e))},jr=l.createContext({onDrop:ce,subscribe:()=>ce}),_r=({children:e})=>{const t=l.useRef(new Set);return a.createElement(jr.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},rg=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(jr);l.useEffect(()=>t(e),[e])};_r.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(jr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const ma=be("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>ce,registerWindowTitlePending:()=>ce}),sg=ma.Provider,ha=ma.useContext,mo=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},Xr=({children:e})=>{const[t,n]=mo(),[r,s]=mo(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(sg,{value:i},e)},Un=ha,fa=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=ha(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?ye.WINDOW_TITLE:void 0}},og=(e,t)=>{const r=(t?Gt(e,t):null)??lf(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},ga=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=Yr(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,og(e.current,s))};if(r)return Me(d),()=>{u=!0};const m=setTimeout(()=>Me(d),Vi);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},ig=(e,t)=>{const{announcementsEnabled:n}=ot(),{channelSource:r}=Ae(),{isWindowNameReady:s}=Un(),o=Xi(),i=r.channel!=null||r.error!=null;ga(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?mh:void 0,suppressed:o})},ag=({enabled:e=!0}={})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(js()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Am({channelUrl:n,enabled:e,isInitiallyBackgrounded:js,isForegrounded:hr,subscribeToForegroundState:r})},cg=e=>Ye(e)||zt(e);function lg(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function ug(e,t){return e.filter(n=>Re.isWelcomeMessage(n,t))}const pa=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>lg(r)?!1:t.length>0?!Re.isWelcomeMessage(r,n):!0),dg=[],_a=()=>{var _,b,v,p,S,A;const{agentPreviewConfigs:e={},aiAgentId:t}=ae(),{aiAgentInfo:n,userSession:r}=Oe(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ae(),u=e.welcomeMessages??dg,d=l.useMemo(()=>pa(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=rt(s.channel),h=(b=(_=si(s.channel,r.userId))==null?void 0:_.nickname)==null?void 0:b.trim(),f=m?(p=(v=s.channel)==null?void 0:v.name)==null?void 0:p.trim():(S=n==null?void 0:n.nickname)==null?void 0:S.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(A=s.channel)==null?void 0:A.url,agentName:g,isClosed:Fe(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,subscribeMessageEvents:o.subscribeMessageEvents,currentUserId:r.userId}},mg=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=ot(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(f=>Le.isAdmin(f)&&Le.isCSAT(f)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},hg=()=>{const e=_a();mg(e)},fg=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),ho=(e,t,n=at.format)=>{const r=Wm(e,fg(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},gg={senderName:!0,body:!0,time:!0},pg=Object.keys(gg),_g=(e,t)=>pg.every(n=>e[n]===t[n]),fo=2e3,go=400,Er=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},Ea=e=>{if(!Le.isAdmin(e)||!Le.isCSAT(e))return null;const t=nh(e);return t?`csat:${t}`:null},Eg=e=>{const t=new Set;for(const n of e){const r=Ea(n);r&&t.add(r)}return t},Cg=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Er(r).some(s=>t.includes(s)))return r}},rr=(e,t)=>e.some(n=>t.includes(n)),po=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,sr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),bg=()=>{const{announceStatus:e,announcementsEnabled:t}=ot(),{stringSet:n,format:r}=oe(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,subscribeMessageEvents:g,currentUserId:_}=_a(),{outgoingMessageStates:b,outgoingMessageStatusSignature:v}=l.useMemo(()=>{if(!_)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const B=o.flatMap(G=>{const I=eh(G,_);return!I||!("sendingStatus"in G)?[]:[{key:I,sendingStatus:G.sendingStatus}]});return{outgoingMessageStates:B,outgoingMessageStatusSignature:B.map(({key:G,sendingStatus:I})=>`${G}:${I}`).join(",")}},[_,o]),p=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:sr(b)}),S=l.useRef({messages:o,currentUserId:_,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),T=l.useRef(null),M=l.useRef([]),k=l.useRef(new Set),N=l.useRef(new Set),x=l.useRef(!1),L=l.useRef(s);S.current={messages:o,currentUserId:_,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const z=()=>S.current.isStreamAnimating||S.current.inputDisabledBy==="ai_responding",D=()=>{T.current!=null&&(clearTimeout(T.current),T.current=null)},W=(B,G,I)=>{const Y=I==null?void 0:I.replaceableForMs;if(B.length===0||!Y)return;const te=Date.now();M.current=[...M.current.filter(({replaceableUntil:se})=>se>te),{eventKeys:B,parts:G,replaceableUntil:te+Y}]},K=()=>A.current.length>0,w=()=>{A.current=[]},V=()=>{const[B,...G]=A.current;if(!B)return!1;A.current=G;const{eventKeys:I,parts:Y,dedupeKey:te}=B,se=$=>{W(I,$,{replaceableForMs:I.length>0?fo:void 0}),e({event:"newMessage",...$},te?{dedupeKey:te}:void 0)};if(I.length===0)return se(Y),!0;const Ne=S.current,He=Cg(Ne.messages,I);if(He){const $=ho(He,Ne.stringSet,Ne.format);return se($),!0}return se(Y),!0},P=()=>{for(D();V(););},q=(B=fo)=>{D(),T.current=setTimeout(()=>{if(T.current=null,z())return;const G=po(),[I]=A.current;if(!I)return;if(I.focusTarget!==G){A.current=[{...I,focusTarget:G},...A.current.slice(1)],q(go);return}V()&&K()&&q(go)},B)},ue=(B,G,I)=>{const Y={eventKeys:G,parts:B,focusTarget:po(),dedupeKey:I?I.dedupeKey??void 0:G[0]},te=G.length===0?-1:A.current.findIndex(({eventKeys:se})=>rr(se,G));te>=0?A.current=A.current.map((se,Ne)=>Ne===te?{...Y,dedupeKey:I?Y.dedupeKey:se.dedupeKey}:se):A.current=[...A.current,Y],q()},Te=(B,G,I)=>{if(B!=="messagesUpdated"||G.length===0)return!1;const Y=Date.now(),te=M.current.find(se=>se.replaceableUntil>Y&&rr(se.eventKeys,G));return te?!_g(I,te.parts):!1};l.useEffect(()=>{const B=L.current!==s;(!t||!d||B)&&(x.current=!1,N.current.clear(),w(),M.current=[],k.current.clear(),D(),B&&(L.current=s),!t||!d)||x.current||(x.current=!0,L.current=s,p.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:sr(b)},k.current=new Set(o.flatMap(G=>{if(!Re.isStreaming(G))return[];const I="sender"in G?G.sender:void 0;return(I==null?void 0:I.userId)===S.current.currentUserId?[]:Er(G)})),N.current=Eg(o))},[e,t,s,d,m,i,c,v]),l.useEffect(()=>{const B=(G,I)=>{const Y=S.current,te=Er(G),se=Ea(G);if(se!=null){if(N.current.has(se))return;N.current.add(se),e({event:"csatDisplayed"});return}if(Re.isStreaming(G)){te.forEach(X=>{k.current.add(X)});return}const Ne=te.filter(X=>k.current.has(X)),He=I==="messagesUpdated"&&Ne.length>0;He&&Ne.forEach(X=>{k.current.delete(X)});const $=I==="messagesUpdated"&&A.current.some(({eventKeys:X})=>rr(X,te)),R=ho(G,Y.stringSet,Y.format),O=Te(I,te,R);if(!He&&I!=="messagesAdded"&&!$&&!O)return;const F=O?{dedupeKey:null}:void 0;if(He||z()||$){ue(R,[...new Set([...Ne,...te])],F);return}if(O){ue(R,te,F);return}K()&&P();const j=te[0];e({event:"newMessage",...R},j?{dedupeKey:j}:void 0)};return g(G=>{if(!x.current||G.kind==="initialized"||!rh(G.source))return;const I=S.current.currentUserId;for(const Y of G.messages)Y&&th(Y,I)&&B(Y,G.kind)})},[e,g]),l.useEffect(()=>{x.current&&(z()||K()&&q())},[h,f]),l.useEffect(()=>()=>{D()},[]),l.useEffect(()=>{if(!x.current)return;const B=p.current,G=B.outgoingMessageStatuses;B.outgoingMessageStatuses=sr(b),b.some(({key:Y,sendingStatus:te})=>{const se=G.get(Y);return se!==void 0&&se!=="failed"&&te==="failed"})&&e({event:"sendFailed"})},[e,v]),l.useEffect(()=>{if(!x.current)return;const B=p.current;i&&!B.isClosed&&e({event:"conversationClosed"}),B.isClosed=i},[e,i]),l.useEffect(()=>{if(!x.current)return;const B=p.current;c&&!B.isHandedOff&&e({event:"agentConnected",agentName:u}),B.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!x.current)return;const B=p.current;m&&h!=="ai_responding"&&(!B.inputDisabled||B.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),B.inputDisabled=m,B.inputDisabledBy=h},[e,m,h])},vg=()=>{const{channelSource:e}=Ae(),t=xi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},yg=e=>{const{announceStatus:t,announcementsEnabled:n}=ot();cm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Sg=()=>{const e=vg();yg(e)},J=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=Yh(),o=s[e];return a.createElement(Ag,{className:n},a.createElement(o,{size:t,color:r??E.color.primary.main,flipInRtl:Bh.has(e)}))},Ag=C.default.span.attrs({"aria-hidden":"true"})`
80
+ `;return n.set(e,o),o},Ef=e=>e?U.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Cf=C.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>_f(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Ef(e)}`;async function jr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function we(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const _r='[role="dialog"][aria-modal="true"]',bf=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(_r)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(_r);return r&&r!==e&&n.add(r),n},vf=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(_r)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Tt(n)),Sf=e=>{const t=ia(e)??e;t===e&&aa(e),t.focus()},aa=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},yf=(e,t)=>{const n=sa(e);if(!n){aa(e),e.focus();return}n[t].focus()},no=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(zr,_h),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>yf(e,t)),n},Af=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(sa(t)||(e.preventDefault(),t.focus())))},Fn=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=bf(i,u);return()=>{u&&we(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!oa(c,m)&&m.matches(ra)&&Tt(m)||vf(i,d)||!u.isConnected||!Tt(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&Tt(m)){s.current=!0;return}s.current=!0,Sf(o)};if(n)return we(c),()=>{i=!0};const u=setTimeout(()=>we(c),Ki);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=no(o,"last"),c=no(o,"first"),u=d=>Af(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},dt=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=qr();return Fn(n,d),Lh(n,o?r:ue),n?mc.createPortal(a.createElement(Tf,{onClick:o?r:void 0,style:e},a.createElement(If,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Tf=C.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${E.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${gt.MODAL};`,If=C.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${gt.MODAL};`,xf=({id:e,children:t})=>a.createElement(Rf,{id:e},t),Rf=C.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,ro=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:Bi}:n},Mf=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(xf,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},so=({name:e,mimeType:t,selected:n},r)=>{var o;const s=We(t??"")?r.A11Y_FILE_IMAGE(e):zt(t??"")?r.A11Y_FILE_VIDEO(e):ei({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},wf=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},$t=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:wf(e)}),kf=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},oo=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:kf({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},re=()=>{const{stringSet:e}=se(),t=Mf(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";We(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":so(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=fh({intent:dh({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:ro(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...bh},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?so({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...$t({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:g})=>{var p;const b=c.trim()||c,S=e.A11Y_HINT_SELECT_RATING,_=t(S,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...oo(u,d,m,h,f,y=>g(y+1)),..._.props,"aria-label":((p=e.A11Y_CSAT_RATING_LABEL)==null?void 0:p.call(e,i,b))??`${i} / ${h} — ${b}`},descriptionNode:_.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,f)=>({props:{...oo(c,u,d,m,h,f),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:ro(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,time:u,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:null};const h=e.A11Y_HINT_OPEN_CONVERSATION,f=t(h,"cli");return{props:{...$t({onActivate:m}),...f.props,"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:f.node}}}}},Lf=({title:e,description:t,highlightedText:n})=>{const r=Rm(t,n);return a.createElement(Df,null,a.createElement(Nf,null,a.createElement(B,{as:"div",variant:"h1",color:E.themedColor.textHighEmphasis},e),t&&a.createElement($f,null,a.createElement(B,{as:"div",variant:"body3",color:E.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(Ff,null,r.highlightedText):null,r.afterText))))},Of=()=>{const{components:e}=Pn.useContext(),{stringSet:t}=se(),{messenger:n}=re(),r=Im(),s=r.showDescription?xm(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(dt,{portalContainerId:Se.WINDOW,visible:r.visible,onClose:ue,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Pn=je({template:Of,components:{Dialog:Lf}}),Df=C.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Nf=C.default.div`display:flex;flex-direction:column;`,$f=C.default.div`margin-top:16px;`,Ff=C.default.strong`font-weight:700;`,Pf=({url:e})=>jr(e),{Provider:Uf,Consumer:ca,useContext:le}=be("Messenger");function Bf({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=qr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Oh(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const _=g.current&&!m.opened;if(g.current=m.opened,!_)return;const p=ut(o.rootElement),y=h(Se.WINDOW);let A=!1;return we(()=>{var T;A||gf(p,p.activeElement,y)&&((T=h(Se.LAUNCHER))==null||T.focus())}),()=>{A=!0}},[m.opened,o.rootElement,h]);const{Template:b}=Pn.useContext(),S=l.useMemo(()=>{var _;return{...o.handlers,onClickLink:((_=o.handlers)==null?void 0:_.onClickLink)??Pf}},[o.handlers]);return a.createElement(Nu,{...o},_=>a.createElement(Uf,{value:{...o,..._,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:S}},a.createElement(b,null),e))}const la=/iPad|iPhone|iPod/.test(navigator.userAgent),Hf=/Android/.test(navigator.userAgent),Qt=e=>la||Hf;let Lt=null,tr=null;const Gf=(e,t=5e3)=>{Lt&&(clearInterval(Lt),clearTimeout(tr));const n=document.title;Lt=setInterval(()=>{document.title=document.title===e?n:e},750),tr=setTimeout(()=>{clearInterval(Lt),Lt=null,tr=null,document.title=n},t)},ua=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},xe=U.css`&:focus-visible{outline:2px solid ${E.themedColor.primary};outline-offset:2px;}`,io=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Un=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??io(t)??io(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,b=()=>{c(),we(()=>o==null?void 0:o())},S=()=>{c(),we(()=>i==null?void 0:i())};return a.createElement(dt,{portalContainerId:Se.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(zf,null,a.createElement(Vf,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:E.themedColor.textHighEmphasis},t)),n&&a.createElement(qf,{id:m},a.createElement(B,{variant:"body3",color:E.themedColor.textMidEmphasis},n))),a.createElement(Kf,null,s&&a.createElement(ao,{onClick:S},a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},s)),a.createElement(ao,{onClick:b},a.createElement(B,{variant:"button",color:E.themedColor.primary},r)))))},zf=C.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Vf=C.default.div`margin-bottom:16px;`,qf=C.default.div`margin-top:16px;`,Kf=C.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ao=C.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${xe}`,{Provider:Wf,useContext:Ne}=be("MessengerSession"),Yf=l.forwardRef(function({children:e,...t},n){return a.createElement(Cd,{ref:n,...t},r=>a.createElement(jf,{...r},e))}),jf=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=le(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:b,launcherInfo:S}=t,[_,p]=l.useState(!1),y=l.useRef(null);ht(n,{async onUserJoined(T,M){var N,x,O,H;T.conversation&&T.conversation.type===de.ConversationType.PROACTIVE&&M.userId===((N=n.currentUser)==null?void 0:N.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(O=m.session)==null||O._updateActiveChannel({url:T.url,status:"open",conversationStatus:(x=T.conversation)==null?void 0:x.status}),c.setOpened(!0),Xf({sound:document.hidden||!c.opened}),(H=y.current)==null||H.call(y,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!Qt()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var M;r.error("messengerSession: failed to initialize",T),(M=u==null?void 0:u.onInitializeFailed)==null||M.call(u,T)})},[m,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>p(!0);return d.subscribe(Ke.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Ke.AnonymousSessionTokenExpired,T)},[d]);const A=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!b||!S?null:a.createElement(Wf,{value:{...t,userSession:g,aiAgentInfo:{...b,...i==null?void 0:i.bot},launcherInfo:{...S,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>y.current=T}},e,a.createElement(Un,{visible:_,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:ue}))};function Xf({sound:e}){Gf("🔔You have received a new message"),e&&ua()}const kn=`@${Ge}-focused-channel`,da=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Zf=()=>{try{const e=localStorage.getItem(kn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},co=e=>{try{localStorage.setItem(kn,JSON.stringify({channelUrl:e,tabId:da}))}catch{}},lo=()=>{try{const e=localStorage.getItem(kn);if(!e)return;JSON.parse(e).tabId===da&&localStorage.removeItem(kn)}catch{}},Jf=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>co(e),r=()=>lo();return document.hasFocus()&&co(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),lo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Zf()===e}),Qf=e=>{const{config:t,chatSDK:n}=le(),{sdkUser:r}=Ne(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=Jf(e,s);ht(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Qe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ua()}})};function eg(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),s=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:s})},n.src=URL.createObjectURL(e)})}async function tg(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await eg(e.file);return new Fe.MessageMetaArray({key:Zo,value:[t,n]})}}const ng=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=le(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await tg(s),i={...s,metaArrays:o?[o]:void 0},c=rg(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===Fe.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Fe.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},rg=e=>{if(!e)return null;const t={};return e.ai&&Object.keys(e.ai).length>0&&(t.ai_attrs=e.ai),e.safeguard&&Object.keys(e.safeguard).length>0&&(t.safeguard_attrs=e.safeguard),typeof e.use_prompt_cache=="boolean"&&(t.use_prompt_cache=e.use_prompt_cache),Object.keys(t).length>0?t:null},yt=50,nr=yt-40,{Provider:sg,useContext:ma}=be("ConversationScroll"),uo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},rr=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),mo=e=>Array.from(e.querySelectorAll(`#${Ge}-message-item`));function og({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(uo),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[b,S]=l.useState(!1),[_,p]=l.useState(!0),y=$=>{const I=rr($);return o.current.distanceFromBottom=I,h(I),I},A=()=>{const $=i.current;$.reconcileTimer&&(clearTimeout($.reconcileTimer),$.reconcileTimer=null)},T=l.useCallback(()=>{const $=s.current;$.mutation&&($.mutation.disconnect(),$.mutation=null),$.resize&&($.resize.disconnect(),$.resize=null),$.resizeTargets.clear()},[]),M=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),L=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},N=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(I=>{c.current.shouldUpdate=!1;const{contentHeight:w,contentSnapshotHeight:D,shouldRecalc:z}=c.current,W=$.clientHeight;if(D>w)return I;const te=x($,{messageType:"outgoing"});let Z=0;if(te){const pe=te.message.offsetTop-nr+W;Z=Math.max(0,pe-w)}else{const pe=w-D,Xe=W-nr;Z=Math.max(0,pe-Xe)}return I===0||Z!==I||z?(c.current.shouldRecalc=!1,Z):I})},x=l.useCallback(($,I)=>{const{messageType:w="all"}=I??{},D=mo($);let z=D;w==="outgoing"&&(z=D.filter(ce=>ce.getAttribute("data-layout-id")==="outgoingmessage"));const W=z[z.length-1];if(!W)return null;const te=$.getBoundingClientRect(),Z=W.getBoundingClientRect(),pe=$.scrollTop+(Z.top-te.top),Xe=pe+W.offsetHeight;return{message:W,scrollTop:pe,lastMessageBottom:Xe}},[]),O=l.useCallback(()=>{const $=r.current;if(!$||M!=="fixed")return;const I=x($);c.current.contentHeight=(I==null?void 0:I.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&L(),i.current.programmatic?o.current.distanceFromBottom=rr($):y($),N()},[M,x]),H=l.useCallback(()=>{T(),A(),c.current=uo,d(0),h(0),p(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),F=l.useCallback(($=!0)=>{const I=o.current.distanceFromBottom>yt;if(i.current.awayByUser=!1,h(0),!I){we(()=>{const w=r.current;w&&!i.current.awayByUser&&w.scrollTo({top:w.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,p(!1),A()),we(()=>{const w=r.current;if(!w){i.current.programmatic=!1,p(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,y(w),p(!0);return}const D=()=>{if(r.current!==w){i.current.programmatic=!1,r.current&&y(r.current),p(!0);return}i.current.programmatic=!1,y(w),p(!0)};if($&&!i.current.reconcileTimer){const z=setTimeout(D,500);i.current.reconcileTimer=z,w.addEventListener("scrollend",()=>{clearTimeout(z),i.current.reconcileTimer=null,D()},{once:!0})}w.scrollTo({top:w.scrollHeight,behavior:$?"smooth":"auto"}),$||D()})},[]),Y=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){y($);return}F(!1)}},[F]),q=l.useCallback(()=>{const $=r.current,I=s.current;if(!$||!I.resize)return;const w=new Set(mo($));for(const D of I.resizeTargets)w.has(D)||(I.resize.unobserve(D),I.resizeTargets.delete(D));for(const D of w)I.resizeTargets.has(D)||(I.resize.observe(D),I.resizeTargets.add(D))},[]),k=l.useCallback($=>{T();const I=s.current;typeof ResizeObserver<"u"&&(I.resize=new ResizeObserver(Y),q());const w=new MutationObserver(()=>{q(),Y()});I.mutation=w,w.observe($,{childList:!0})},[T,Y,q]),G=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,M!=="fixed"){k($);return}H(),c.current.viewport=$.clientHeight;const I=new MutationObserver(()=>{O()});s.current.mutation=I,I.observe($,{childList:!0,subtree:!0})},[T,M,O,H,k]),P=l.useCallback(()=>{const $=r.current;if(!$)return;const I=x($,{messageType:"outgoing"});I&&($.scrollTo({top:I.message.offsetTop-nr,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{S(!1)},500))},[x]),V=($,I,w)=>{const D=rr($);if(w&&D>yt){i.current.programmatic=!1,i.current.awayByUser=!0,A(),y($),p(!0),o.current.prevScrollTop=I;return}o.current.distanceFromBottom=D},me=($,I,w)=>{const z=y($)<=yt;I&&!z&&(i.current.awayByUser=!0,A()),w&&z&&(i.current.awayByUser=!1)},Ie=$=>{const{scrollTop:I}=$.currentTarget,w=o.current.prevScrollTop;i.current.programmatic?V($.currentTarget,I,I<w):me($.currentTarget,I<w,I>w),o.current.prevScrollTop=I},j=l.useCallback(()=>{M==="fixed"&&(S(!0),L())},[M]),K=l.useCallback(()=>{M==="fixed"?setTimeout(()=>P(),300):F()},[M,P]),R=l.useCallback($=>{i.current.streaming=$,M==="fixed"?L():i.current.awayByUser||F()},[M,F]),X=l.useCallback($=>{g($),$&&(d(0),M==="fixed"&&T())},[T,M]),ne=l.useCallback($=>{M==="auto"&&$&&!i.current.awayByUser&&F()},[M,F]),Re=!(m<=yt)&&!b,Le=l.useCallback(()=>o.current.distanceFromBottom>yt,[]);return a.createElement(sg,{value:{ref:G,state:{bottomSpace:u,isAwayFromBottom:Re,isScrollPositionReconciled:_,shouldCountNewMessages:Le},props:{onScroll:Ie},actions:{scrollToBottom:F,onBeforeMessageSend:j,onAfterMessageSend:K,onStreamingUpdate:R,onConversationClosed:X,onTypingIndicatorUpdate:ne}}},n)}const{Provider:ig,Context:ag,useContext:Ae}=be("Conversation"),cg=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=dm(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},lg=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,children:o})=>{const{activeChannel:i,refreshActiveChannel:c}=Ne(),u=ma(),d=e||(i==null?void 0:i.url);Qf(d);const{onBeforeSendMessage:m,onAfterSendMessage:h}=ng({onScrollAfterSendMessage:()=>{u.actions.onAfterMessageSend()}}),f=l.useCallback(_=>(u.actions.onBeforeMessageSend(),m(_)),[u.actions,m]),g=l.useCallback(_=>{const p=_.some(y=>Me.isStreaming(y));u.actions.onStreamingUpdate(p)},[u.actions.onStreamingUpdate]),b=l.useCallback(_=>{u.actions.onConversationClosed(_===de.ConversationStatus.CLOSED)},[u.actions.onConversationClosed]),S=l.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]);return a.createElement(Kd,{key:d,channelUrl:d,onBeforeSendMessage:f,onAfterSendMessage:h,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:S,onConversationStatusChanged:b,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldCountNewMessages:u.state.shouldCountNewMessages},_=>a.createElement(ig,{value:{..._,conversationStatsEnabled:r??!0,scrollSource:u,goToActiveConversation:S,onNavigateToConversationList:n}},a.createElement(cg,null,o)))},ha=({children:e,...t})=>{const{config:n}=ke(),{agentPreviewConfigs:r}=le(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(og,{scrollMode:s,messageStackDirection:o},a.createElement(lg,{...t},e))},Xr=l.createContext({onDrop:ue,subscribe:()=>ue}),Er=({children:e})=>{const t=l.useRef(new Set);return a.createElement(Xr.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},ug=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(Xr);l.useEffect(()=>t(e),[e])};Er.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(Xr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const fa=be("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>ue,registerWindowTitlePending:()=>ue}),dg=fa.Provider,ga=fa.useContext,ho=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},Zr=({children:e})=>{const[t,n]=ho(),[r,s]=ho(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(dg,{value:i},e)},Bn=ga,pa=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=ga(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?Se.WINDOW_TITLE:void 0}},mg=(e,t)=>{const r=(t?Gt(e,t):null)??pf(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},_a=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=Yr(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,mg(e.current,s))};if(r)return we(d),()=>{u=!0};const m=setTimeout(()=>we(d),Ki);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},hg=(e,t)=>{const{announcementsEnabled:n}=ot(),{channelSource:r}=Ae(),{isWindowNameReady:s}=Bn(),o=Ji(),i=r.channel!=null||r.error!=null;_a(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?Ch:void 0,suppressed:o})},fg=({enabled:e=!0}={})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(Xs()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);km({channelUrl:n,enabled:e,isInitiallyBackgrounded:Xs,isForegrounded:fr,subscribeToForegroundState:r})},gg=e=>We(e)||zt(e);function pg(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function _g(e,t){return e.filter(n=>Me.isWelcomeMessage(n,t))}const Ea=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>pg(r)?!1:t.length>0?!Me.isWelcomeMessage(r,n):!0),Eg=[],Ca=()=>{var b,S,_,p,y,A;const{agentPreviewConfigs:e={},aiAgentId:t}=le(),{aiAgentInfo:n,userSession:r}=Ne(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ae(),u=e.welcomeMessages??Eg,d=l.useMemo(()=>Ea(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=rt(s.channel),h=(S=(b=oi(s.channel,r.userId))==null?void 0:b.nickname)==null?void 0:S.trim(),f=m?(p=(_=s.channel)==null?void 0:_.name)==null?void 0:p.trim():(y=n==null?void 0:n.nickname)==null?void 0:y.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(A=s.channel)==null?void 0:A.url,agentName:g,isClosed:He(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,subscribeMessageEvents:o.subscribeMessageEvents,currentUserId:r.userId}},Cg=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=ot(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(f=>De.isAdmin(f)&&De.isCSAT(f)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},bg=()=>{const e=Ca();Cg(e)},vg=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),fo=(e,t,n=at.format)=>{const r=th(e,vg(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},Sg={senderName:!0,body:!0,time:!0},yg=Object.keys(Sg),Ag=(e,t)=>yg.every(n=>e[n]===t[n]),go=2e3,po=400,Cr=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},ba=e=>{if(!De.isAdmin(e)||!De.isCSAT(e))return null;const t=lh(e);return t?`csat:${t}`:null},Tg=e=>{const t=new Set;for(const n of e){const r=ba(n);r&&t.add(r)}return t},Ig=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Cr(r).some(s=>t.includes(s)))return r}},sr=(e,t)=>e.some(n=>t.includes(n)),_o=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,or=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),xg=()=>{const{announceStatus:e,announcementsEnabled:t}=ot(),{stringSet:n,format:r}=se(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,subscribeMessageEvents:g,currentUserId:b}=Ca(),{outgoingMessageStates:S,outgoingMessageStatusSignature:_}=l.useMemo(()=>{if(!b)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const j=o.flatMap(K=>{const R=ah(K,b);return!R||!("sendingStatus"in K)?[]:[{key:R,sendingStatus:K.sendingStatus}]});return{outgoingMessageStates:j,outgoingMessageStatusSignature:j.map(({key:K,sendingStatus:R})=>`${K}:${R}`).join(",")}},[b,o]),p=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:or(S)}),y=l.useRef({messages:o,currentUserId:b,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),T=l.useRef(null),M=l.useRef([]),L=l.useRef(new Set),N=l.useRef(new Set),x=l.useRef(!1),O=l.useRef(s);y.current={messages:o,currentUserId:b,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const H=()=>y.current.isStreamAnimating||y.current.inputDisabledBy==="ai_responding",F=()=>{T.current!=null&&(clearTimeout(T.current),T.current=null)},Y=(j,K,R)=>{const X=R==null?void 0:R.replaceableForMs;if(j.length===0||!X)return;const ne=Date.now();M.current=[...M.current.filter(({replaceableUntil:oe})=>oe>ne),{eventKeys:j,parts:K,replaceableUntil:ne+X}]},q=()=>A.current.length>0,k=()=>{A.current=[]},G=()=>{const[j,...K]=A.current;if(!j)return!1;A.current=K;const{eventKeys:R,parts:X,dedupeKey:ne}=j,oe=$=>{Y(R,$,{replaceableForMs:R.length>0?go:void 0}),e({event:"newMessage",...$},ne?{dedupeKey:ne}:void 0)};if(R.length===0)return oe(X),!0;const Re=y.current,Le=Ig(Re.messages,R);if(Le){const $=fo(Le,Re.stringSet,Re.format);return oe($),!0}return oe(X),!0},P=()=>{for(F();G(););},V=(j=go)=>{F(),T.current=setTimeout(()=>{if(T.current=null,H())return;const K=_o(),[R]=A.current;if(!R)return;if(R.focusTarget!==K){A.current=[{...R,focusTarget:K},...A.current.slice(1)],V(po);return}G()&&q()&&V(po)},j)},me=(j,K,R)=>{const X={eventKeys:K,parts:j,focusTarget:_o(),dedupeKey:R?R.dedupeKey??void 0:K[0]},ne=K.length===0?-1:A.current.findIndex(({eventKeys:oe})=>sr(oe,K));ne>=0?A.current=A.current.map((oe,Re)=>Re===ne?{...X,dedupeKey:R?X.dedupeKey:oe.dedupeKey}:oe):A.current=[...A.current,X],V()},Ie=(j,K,R)=>{if(j!=="messagesUpdated"||K.length===0)return!1;const X=Date.now(),ne=M.current.find(oe=>oe.replaceableUntil>X&&sr(oe.eventKeys,K));return ne?!Ag(R,ne.parts):!1};l.useEffect(()=>{const j=O.current!==s;(!t||!d||j)&&(x.current=!1,N.current.clear(),k(),M.current=[],L.current.clear(),F(),j&&(O.current=s),!t||!d)||x.current||(x.current=!0,O.current=s,p.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:or(S)},L.current=new Set(o.flatMap(K=>{if(!Me.isStreaming(K))return[];const R="sender"in K?K.sender:void 0;return(R==null?void 0:R.userId)===y.current.currentUserId?[]:Cr(K)})),N.current=Tg(o))},[e,t,s,d,m,i,c,_]),l.useEffect(()=>{const j=(K,R)=>{const X=y.current,ne=Cr(K),oe=ba(K);if(oe!=null){if(N.current.has(oe))return;N.current.add(oe),e({event:"csatDisplayed"});return}if(Me.isStreaming(K)){ne.forEach(W=>{L.current.add(W)});return}const Re=ne.filter(W=>L.current.has(W)),Le=R==="messagesUpdated"&&Re.length>0;Le&&Re.forEach(W=>{L.current.delete(W)});const $=R==="messagesUpdated"&&A.current.some(({eventKeys:W})=>sr(W,ne)),I=fo(K,X.stringSet,X.format),w=Ie(R,ne,I);if(!Le&&R!=="messagesAdded"&&!$&&!w)return;const D=w?{dedupeKey:null}:void 0;if(Le||H()||$){me(I,[...new Set([...Re,...ne])],D);return}if(w){me(I,ne,D);return}q()&&P();const z=ne[0];e({event:"newMessage",...I},z?{dedupeKey:z}:void 0)};return g(K=>{if(!x.current||K.kind==="initialized"||!uh(K.source))return;const R=y.current.currentUserId;for(const X of K.messages)X&&ch(X,R)&&j(X,K.kind)})},[e,g]),l.useEffect(()=>{x.current&&(H()||q()&&V())},[h,f]),l.useEffect(()=>()=>{F()},[]),l.useEffect(()=>{if(!x.current)return;const j=p.current,K=j.outgoingMessageStatuses;j.outgoingMessageStatuses=or(S),S.some(({key:X,sendingStatus:ne})=>{const oe=K.get(X);return oe!==void 0&&oe!=="failed"&&ne==="failed"})&&e({event:"sendFailed"})},[e,_]),l.useEffect(()=>{if(!x.current)return;const j=p.current;i&&!j.isClosed&&e({event:"conversationClosed"}),j.isClosed=i},[e,i]),l.useEffect(()=>{if(!x.current)return;const j=p.current;c&&!j.isHandedOff&&e({event:"agentConnected",agentName:u}),j.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!x.current)return;const j=p.current;m&&h!=="ai_responding"&&(!j.inputDisabled||j.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),j.inputDisabled=m,j.inputDisabledBy=h},[e,m,h])},Rg=()=>{const{channelSource:e}=Ae(),t=Mi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Mg=e=>{const{announceStatus:t,announcementsEnabled:n}=ot();gm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},wg=()=>{const e=Rg();Mg(e)},J=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=ef(),o=s[e];return a.createElement(kg,{className:n},a.createElement(o,{size:t,color:r??E.color.primary.main,flipInRtl:Wh.has(e)}))},kg=C.default.span.attrs({"aria-hidden":"true"})`
81
81
  display: inline-flex;
82
82
  &:focus {
83
83
  outline: none;
84
84
  }
85
- `,Tg=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(dt,{portalContainerId:ye.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Mg,null,n)),Ig=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(xg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(Rg,null,a.createElement(J,{type:n,size:24,color:E.themedColor.primary})),s),lt=Object.assign(Tg,{ActionItem:Ig}),xg=C.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?E.themedColor.error:E.themedColor.textHighEmphasis};${xe}`,Rg=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Mg=C.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,_o=40,Eo=.9,wg="[data-message-listitem]",kg='input, textarea, select, [role="textbox"], [contenteditable="true"]',Lg=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Eo;case"PageUp":return t.clientHeight*-Eo;case"ArrowDown":return n?_o:void 0;case"ArrowUp":return n?_o*-1:void 0;default:return}},Og=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(kg))return;const o=s===r||s.matches(wg),i=Lg({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),Ng="[data-message-listitem]",Dg=e=>Math.min(Math.max(0,e),1),$g=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Ng),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Fg=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},Pg=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),f=l.useRef(null),g=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const p=t.current;p&&(u.current==="top"&&(p.scrollTop=p.scrollHeight-m.current,Fg({list:p,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(p.scrollTop=d.current),u.current=void 0)},[t,r]);const _=l.useCallback(async p=>{const S=t.current;if(!S||(i==null||i(p),m.current=S.scrollHeight-S.scrollTop,d.current=S.scrollTop,c.current))return;const A=S.clientHeight*Dg(n);if(S.scrollTop<=A){c.current=!0,u.current="top",h.current=$g(S),await o(),c.current=!1;return}if(S.scrollHeight-S.scrollTop-S.clientHeight<=A){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),b=l.useCallback(p=>{const S=t.current;if(!S)return;const A=g.current;if(A!=null){if(A===S.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===S.scrollTop){f.current=null,g.current=S.scrollTop,_(p);return}f.current=null,_(p)},[_,t]),v=l.useCallback(p=>{const S=t.current;S&&(f.current=p,g.current=null,S.scrollTop=p,S.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:b,syncScrollPosition:v}},Ug=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:g,onLoadPrev:_,onLoadNext:b,loadThreshold:v=.05,onScroll:p=ce,depsForResetScrollPositionToBottom:S,stackDirection:A="top",bottomSpacerHeight:T=0,"aria-label":M}=t,k=l.useRef(null),N=l.useCallback(D=>{k.current=D,n&&(typeof n=="function"?n(D):n.current=D)},[n]),{handleScroll:x,syncScrollPosition:L}=Pg({depsForResetScrollPositionToBottom:S,listRef:k,loadThreshold:v,messagesLength:r.length,onLoadNext:b,onLoadPrev:_,onScroll:p}),z=Og({listRef:k,syncScrollPosition:L});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(Bg,{id:"infinite-list-container"},a.createElement(Hg,{id:"infinite-list-inner",ref:N,onScroll:x,onKeyDown:z,role:"list","aria-label":M,tabIndex:0},A==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((D,W)=>s({message:D,index:W})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(Gg,{id:"infinite-list-overlay-container"},a.createElement(zg,{id:"infinite-list-overlay"},g)))}),Bg=C.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Hg=C.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${E.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,Gg=C.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,zg=C.default.div`pointer-events:auto;`,it=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?E.themedColor.textDisabled:E.themedColor.textHighEmphasis;return a.createElement(Vg,{as:e,disabled:s,...i},a.createElement(J,{type:t,size:n,color:r??c}),o)},Vg=C.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,pt=({className:e,children:t,size:n=26})=>a.createElement(qg,{className:e,$size:n},t??a.createElement(J,{type:"spinner",size:n})),qg=C.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ze(e)};height:${({$size:e})=>Ze(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Kg=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=oe(),{config:m}=ae(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,_=h>1,b=(f==null?void 0:f.type)||"",v=Ye(b),p=zt(b),S=!cg(b);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const A=l.useCallback(()=>{s>0&&(o(M=>M-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(M=>M+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const M=k=>{k.key==="ArrowLeft"?A():k.key==="ArrowRight"&&T()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[r,A,T]),!r||!f?null:a.createElement(dt,{onClose:n,visible:r,portalContainerId:ye.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(Yg,null,a.createElement(Wg,null,a.createElement(jg,null,a.createElement(Xg,null,a.createElement(H,{variant:"button",maxTextLines:1,color:E.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(H,{variant:"caption2",color:E.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(Zg,{type:"close",size:18,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(Jg,null,_&&a.createElement(Co,{$position:"left",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(Qg,{onClick:M=>M.currentTarget===M.target&&n()},v&&a.createElement(a.Fragment,null,!i&&a.createElement(ep,null,a.createElement(pt,{size:32},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(tp,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),p&&a.createElement(np,{controls:!0},a.createElement("source",{src:f.url,type:b})),S&&a.createElement(rp,null,a.createElement(H,{variant:"h1",color:E.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),_&&a.createElement(Co,{$position:"right",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(sp,null,_&&a.createElement(H,{variant:"body2",color:E.color.ondark.textHighEmphasis},s+1,"/",h),g&&!S&&a.createElement(op,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},Yg=C.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${E.themedColor.bg_50_600};`,Wg=C.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,jg=C.default.div`flex:1;min-width:0;padding-right:8px;`,Xg=C.default.div`display:flex;flex-direction:column;gap:2px;`,Zg=C.default(it)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Bn=C.default.div`display:flex;align-items:center;justify-content:center;`,Jg=C.default(Bn)`flex:1;min-height:0;position:relative;`,Qg=C.default(Bn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,ep=C.default(Bn)`position:absolute;inset:0;pointer-events:none;`,tp=C.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,np=C.default.video`max-width:100%;max-height:100%;object-fit:contain;`,rp=C.default(Bn)`flex-direction:column;gap:16px;`,Co=C.default(it)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${E.color.overlay.dark};&:disabled{opacity:0.3;}`,sp=C.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,op=C.default(it)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,ip=.75,Ca=6,ap=Ca*2;let Cr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Cr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const cp=e=>Cr?Array.from(Cr.segment(e),t=>t.segment):[...e],lp=e=>{const t=Math.floor(e.length*ip),n=Math.max(0,e.length-Ca);return Math.max(t,n)},bo=(e,t="")=>{if(e.length<ap)return{start:e+t,end:""};const n=cp(e),r=lp(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},up=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return bo(t);const s=t.slice(0,n),o=t.slice(n);return bo(s,o)},ba=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>up(e),[e]);return r?a.createElement(dp,null,a.createElement(mp,{...t},n),a.createElement(hp,{...t},r)):a.createElement(H,{...t},n)},dp=C.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,mp=C.default(H)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,hp=C.default(H)`flex-shrink:0;white-space:nowrap;`,Zr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=U.useTheme(),{conversation:u}=re(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(fp,{...d.props,$clickable:!!o},a.createElement(pp,{$bgColor:s??c.base.primary},a.createElement(J,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(_p,null,a.createElement(ba,{variant:"button",color:E.themedColor.textHighEmphasis},e),a.createElement(H,{color:E.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},fp=C.default.div`border:none;border-radius:12px;gap:8px;width:${ee.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${E.themedColor.textDisabled};background-color:${E.themedColor.bg_50_600};${({$clickable:e})=>e&&gp}`,gp=U.css`cursor:pointer;${xe}&:hover{background-color:${E.themedColor.bg_100_500};}`,pp=C.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,_p=C.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Ep({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Cp,null,a.createElement(Zr,{name:e.name,mimeType:e.type,type:Ir(e.name,e.type),onClick:r}),t)}const Cp=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,tt=`${Ge}-incoming-msg`,bp=`${Ge}-marked-text`;function vp({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=re(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(Ap,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(Tp,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${tt}-media-body`,...c.props};return a.createElement(yp,null,a.createElement(Sp,{...d},u(),c.descriptionNode),r)}return null}const yp=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Sp=C.default.div`width:${ee.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${Q.light`
85
+ `,Lg=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(dt,{portalContainerId:Se.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement($g,null,n)),Og=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(Dg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(Ng,null,a.createElement(J,{type:n,size:24,color:E.themedColor.primary})),s),lt=Object.assign(Lg,{ActionItem:Og}),Dg=C.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?E.themedColor.error:E.themedColor.textHighEmphasis};${xe}`,Ng=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,$g=C.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Eo=40,Co=.9,Fg="[data-message-listitem]",Pg='input, textarea, select, [role="textbox"], [contenteditable="true"]',Ug=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Co;case"PageUp":return t.clientHeight*-Co;case"ArrowDown":return n?Eo:void 0;case"ArrowUp":return n?Eo*-1:void 0;default:return}},Bg=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(Pg))return;const o=s===r||s.matches(Fg),i=Ug({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),Hg="[data-message-listitem]",Gg=e=>Math.min(Math.max(0,e),1),zg=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Hg),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Vg=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},qg=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),f=l.useRef(null),g=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const p=t.current;p&&(u.current==="top"&&(p.scrollTop=p.scrollHeight-m.current,Vg({list:p,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(p.scrollTop=d.current),u.current=void 0)},[t,r]);const b=l.useCallback(async p=>{const y=t.current;if(!y||(i==null||i(p),m.current=y.scrollHeight-y.scrollTop,d.current=y.scrollTop,c.current))return;const A=y.clientHeight*Gg(n);if(y.scrollTop<=A){c.current=!0,u.current="top",h.current=zg(y),await o(),c.current=!1;return}if(y.scrollHeight-y.scrollTop-y.clientHeight<=A){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),S=l.useCallback(p=>{const y=t.current;if(!y)return;const A=g.current;if(A!=null){if(A===y.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===y.scrollTop){f.current=null,g.current=y.scrollTop,b(p);return}f.current=null,b(p)},[b,t]),_=l.useCallback(p=>{const y=t.current;y&&(f.current=p,g.current=null,y.scrollTop=p,y.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:S,syncScrollPosition:_}},Kg=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:g,onLoadPrev:b,onLoadNext:S,loadThreshold:_=.05,onScroll:p=ue,depsForResetScrollPositionToBottom:y,stackDirection:A="top",bottomSpacerHeight:T=0,"aria-label":M}=t,L=l.useRef(null),N=l.useCallback(F=>{L.current=F,n&&(typeof n=="function"?n(F):n.current=F)},[n]),{handleScroll:x,syncScrollPosition:O}=qg({depsForResetScrollPositionToBottom:y,listRef:L,loadThreshold:_,messagesLength:r.length,onLoadNext:S,onLoadPrev:b,onScroll:p}),H=Bg({listRef:L,syncScrollPosition:O});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(Wg,{id:"infinite-list-container"},a.createElement(Yg,{id:"infinite-list-inner",ref:N,onScroll:x,onKeyDown:H,role:"list","aria-label":M,tabIndex:0},A==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((F,Y)=>s({message:F,index:Y})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(jg,{id:"infinite-list-overlay-container"},a.createElement(Xg,{id:"infinite-list-overlay"},g)))}),Wg=C.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Yg=C.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${E.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,jg=C.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,Xg=C.default.div`pointer-events:auto;`,it=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?E.themedColor.textDisabled:E.themedColor.textHighEmphasis;return a.createElement(Zg,{as:e,disabled:s,...i},a.createElement(J,{type:t,size:n,color:r??c}),o)},Zg=C.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,pt=({className:e,children:t,size:n=26})=>a.createElement(Jg,{className:e,$size:n},t??a.createElement(J,{type:"spinner",size:n})),Jg=C.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ze(e)};height:${({$size:e})=>Ze(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Qg=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=se(),{config:m}=le(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,b=h>1,S=(f==null?void 0:f.type)||"",_=We(S),p=zt(S),y=!gg(S);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const A=l.useCallback(()=>{s>0&&(o(M=>M-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(M=>M+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const M=L=>{L.key==="ArrowLeft"?A():L.key==="ArrowRight"&&T()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[r,A,T]),!r||!f?null:a.createElement(dt,{onClose:n,visible:r,portalContainerId:Se.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(ep,null,a.createElement(tp,null,a.createElement(np,null,a.createElement(rp,null,a.createElement(B,{variant:"button",maxTextLines:1,color:E.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(B,{variant:"caption2",color:E.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(sp,{type:"close",size:18,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(op,null,b&&a.createElement(bo,{$position:"left",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(ip,{onClick:M=>M.currentTarget===M.target&&n()},_&&a.createElement(a.Fragment,null,!i&&a.createElement(ap,null,a.createElement(pt,{size:32},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(cp,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),p&&a.createElement(lp,{controls:!0},a.createElement("source",{src:f.url,type:S})),y&&a.createElement(up,null,a.createElement(B,{variant:"h1",color:E.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),b&&a.createElement(bo,{$position:"right",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(dp,null,b&&a.createElement(B,{variant:"body2",color:E.color.ondark.textHighEmphasis},s+1,"/",h),g&&!y&&a.createElement(mp,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},ep=C.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${E.themedColor.bg_50_600};`,tp=C.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,np=C.default.div`flex:1;min-width:0;padding-right:8px;`,rp=C.default.div`display:flex;flex-direction:column;gap:2px;`,sp=C.default(it)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Hn=C.default.div`display:flex;align-items:center;justify-content:center;`,op=C.default(Hn)`flex:1;min-height:0;position:relative;`,ip=C.default(Hn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,ap=C.default(Hn)`position:absolute;inset:0;pointer-events:none;`,cp=C.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,lp=C.default.video`max-width:100%;max-height:100%;object-fit:contain;`,up=C.default(Hn)`flex-direction:column;gap:16px;`,bo=C.default(it)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${E.color.overlay.dark};&:disabled{opacity:0.3;}`,dp=C.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,mp=C.default(it)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,hp=.75,va=6,fp=va*2;let br=null;typeof Intl<"u"&&"Segmenter"in Intl&&(br=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const gp=e=>br?Array.from(br.segment(e),t=>t.segment):[...e],pp=e=>{const t=Math.floor(e.length*hp),n=Math.max(0,e.length-va);return Math.max(t,n)},vo=(e,t="")=>{if(e.length<fp)return{start:e+t,end:""};const n=gp(e),r=pp(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},_p=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return vo(t);const s=t.slice(0,n),o=t.slice(n);return vo(s,o)},Sa=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>_p(e),[e]);return r?a.createElement(Ep,null,a.createElement(Cp,{...t},n),a.createElement(bp,{...t},r)):a.createElement(B,{...t},n)},Ep=C.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,Cp=C.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,bp=C.default(B)`flex-shrink:0;white-space:nowrap;`,Jr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=U.useTheme(),{conversation:u}=re(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(vp,{...d.props,$clickable:!!o},a.createElement(yp,{$bgColor:s??c.base.primary},a.createElement(J,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(Ap,null,a.createElement(Sa,{variant:"button",color:E.themedColor.textHighEmphasis},e),a.createElement(B,{color:E.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},vp=C.default.div`border:none;border-radius:12px;gap:8px;width:${ee.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${E.themedColor.textDisabled};background-color:${E.themedColor.bg_50_600};${({$clickable:e})=>e&&Sp}`,Sp=U.css`cursor:pointer;${xe}&:hover{background-color:${E.themedColor.bg_100_500};}`,yp=C.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Ap=C.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Tp({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Ip,null,a.createElement(Jr,{name:e.name,mimeType:e.type,type:xr(e.name,e.type),onClick:r}),t)}const Ip=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,tt=`${Ge}-incoming-msg`,xp=`${Ge}-marked-text`;function Rp({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=re(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(kp,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(Lp,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${tt}-media-body`,...c.props};return a.createElement(Mp,null,a.createElement(wp,{...d},u(),c.descriptionNode),r)}return null}const Mp=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,wp=C.default.div`width:${ee.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${Q.light`
86
86
  background-color: ${E.color.background100};
87
87
  `}
88
88
  ${Q.dark`
89
89
  background-color: ${E.color.background400};
90
90
  `}
91
- `,Ap=C.default.img`width:100%;height:100%;object-fit:cover;`,Tp=C.default.video`width:100%;height:100%;object-fit:cover;`,va=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=re(),s=e.length;if(s===0)return null;const o=Tu(s),i=!!n&&!t;return a.createElement(xp,{$width:ee.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=Iu({index:u,itemCount:s}),m=c.name||"",h=()=>{t||n==null||n(u)},f=c.type??"image/*",g=i?r.file.buttonLikePreview({name:m,mimeType:f,onActivate:h},u):r.file.preview({name:m,mimeType:f});return a.createElement(Rp,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(Ip,{src:c.url,alt:c.name||""}),t&&a.createElement(Mp,null),g.descriptionNode)}))},Ip=({src:e,alt:t})=>{const[n,r]=l.useState(!1),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(wp,null,a.createElement(pt,{size:20},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(kp,null,a.createElement(J,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(Lp,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},xp=C.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Rp=C.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${Q.light`
91
+ `,kp=C.default.img`width:100%;height:100%;object-fit:cover;`,Lp=C.default.video`width:100%;height:100%;object-fit:cover;`,ya=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=re(),s=e.length;if(s===0)return null;const o=ku(s),i=!!n&&!t;return a.createElement(Dp,{$width:ee.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=Lu({index:u,itemCount:s}),m=c.name||"",h=()=>{t||n==null||n(u)},f=c.type??"image/*",g=i?r.file.buttonLikePreview({name:m,mimeType:f,onActivate:h},u):r.file.preview({name:m,mimeType:f});return a.createElement(Np,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(Op,{src:c.url,alt:c.name||""}),t&&a.createElement($p,null),g.descriptionNode)}))},Op=({src:e,alt:t})=>{const[n,r]=l.useState(!1),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(Fp,null,a.createElement(pt,{size:20},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(Pp,null,a.createElement(J,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(Up,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},Dp=C.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Np=C.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${Q.light`
92
92
  background-color: ${E.color.background100};
93
93
  `}
94
94
  ${Q.dark`
@@ -111,19 +111,19 @@
111
111
  }
112
112
  `}
113
113
  }
114
- `,Mp=C.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${E.color.overlay.dark};pointer-events:none;`,ya=C.default.div`display:flex;align-items:center;justify-content:center;`,wp=C.default(ya)`position:absolute;inset:0;`,kp=C.default(ya)`position:absolute;inset:0;${Q.light`
114
+ `,$p=C.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${E.color.overlay.dark};pointer-events:none;`,Aa=C.default.div`display:flex;align-items:center;justify-content:center;`,Fp=C.default(Aa)`position:absolute;inset:0;`,Pp=C.default(Aa)`position:absolute;inset:0;${Q.light`
115
115
  background-color: ${E.color.background200};
116
116
  `}
117
117
  ${Q.dark`
118
118
  background-color: ${E.color.background500};
119
119
  `}
120
- `,Lp=C.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Op=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=o=>{const i=e[o];i&&(r?r({files:e,index:o}):n&&n({url:i.url,type:i.type||"image/*"}))};return a.createElement(Np,null,a.createElement(va,{images:e,onClickImage:s}),t)},Np=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Dp="✱",Sa=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Dp}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${bp} aria-label="masked-text">${o}</span>`:n)},$p=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),vo=e=>{var t;return{files:e.fileInfoList.map(n=>({url:n.url,type:n.mimeType??"",name:n.fileName??""})),metadata:{localFiles:(t=e.messageParams)==null?void 0:t.fileInfoList.map(n=>n.file)}}},Fp=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),yo=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function Pp(e){var s,o;const t=e.maxBodyWidth??ee.BODY_MAX_WIDTH,n=l.useMemo(()=>xc(e.message,Sa),[e.message]),r={id:`${tt}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor,$surface:e.surface??"bubble"};return n.length===0?e.children?a.createElement(So,{...r},e.children):null:a.createElement(So,{...r},n.map((i,c)=>i.type==="text"?a.createElement(Ao,{key:c,variant:"body3"},a.createElement(Ht,{fallback:i.value},a.createElement(Fp,{onClickImage:u=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:u,type:"image/*"})},onClickLink:e.onClickLink},i.value))):i.type==="code"?yo?a.createElement(Ht,{key:c,fallback:a.createElement(Ao,{variant:"body3"},i.value)},a.createElement(yo,{code:i.value,language:i.language})):a.createElement(Up,{key:c},a.createElement("code",null,i.value)):null),e.children)}const So=C.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);${({theme:e,$color:t,$bgColor:n,$surface:r})=>U.css`
120
+ `,Up=C.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Bp=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=o=>{const i=e[o];i&&(r?r({files:e,index:o}):n&&n({url:i.url,type:i.type||"image/*"}))};return a.createElement(Hp,null,a.createElement(ya,{images:e,onClickImage:s}),t)},Hp=C.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Gp="✱",Ta=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Gp}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${xp} aria-label="masked-text">${o}</span>`:n)},zp=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),So=e=>{var t;return{files:e.fileInfoList.map(n=>({url:n.url,type:n.mimeType??"",name:n.fileName??""})),metadata:{localFiles:(t=e.messageParams)==null?void 0:t.fileInfoList.map(n=>n.file)}}},Vp=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),yo=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function qp(e){var s,o;const t=e.maxBodyWidth??ee.BODY_MAX_WIDTH,n=l.useMemo(()=>Mc(e.message,Ta),[e.message]),r={id:`${tt}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor,$surface:e.surface??"bubble"};return n.length===0?e.children?a.createElement(Ao,{...r},e.children):null:a.createElement(Ao,{...r},n.map((i,c)=>i.type==="text"?a.createElement(To,{key:c,variant:"body3"},a.createElement(Ht,{fallback:i.value},a.createElement(Vp,{onClickImage:u=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:u,type:"image/*"})},onClickLink:e.onClickLink},i.value))):i.type==="code"?yo?a.createElement(Ht,{key:c,fallback:a.createElement(To,{variant:"body3"},i.value)},a.createElement(yo,{code:i.value,language:i.language})):a.createElement(Kp,{key:c},a.createElement("code",null,i.value)):null),e.children)}const Ao=C.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);${({theme:e,$color:t,$bgColor:n,$surface:r})=>U.css`
121
121
  color: ${t||e.colors.messageIncoming.text};
122
122
  ${r==="bubble"?U.css`background-color:${n||e.colors.messageIncoming.background};border-radius:12px;overflow:hidden;padding:12px 0;`:U.css`background-color:transparent;border-radius:0;overflow:visible;padding:0;`}
123
123
  `}
124
124
  transition: max-width 0.3s;
125
125
  overflow-wrap: break-word;
126
- `,Ao=C.default(H)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Up=C.default.pre`margin:0;padding:1em;overflow-x:auto;white-space:pre;font-family:monospace;font-size:13px;line-height:1.5;color:#d4d4d4;background:#1e1e1e;border-radius:4px;`;function Aa({id:e,src:t,size:n=56,onClick:r,onImageError:s,style:o,...i}){const[c,u]=l.useState();return a.createElement(Bp,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ze(n),style:o,...i},t&&t!==c?a.createElement(Hp,{src:t,alt:"",onError:()=>{u(t),s==null||s(t)}}):a.createElement(J,{type:"user",size:n}))}const Bp=C.default.div`border-radius:50%;display:inline-block;overflow:hidden;position:relative;flex-shrink:0;height:${e=>e.$size};width:${e=>e.$size};background-color:${E.themedColor.bg_100_500};&:focus{outline:none;}${xe}`,Hp=C.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,Gp=({sender:e,isBotMessage:t})=>{const n=`${tt}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(zp,{id:n},a.createElement(J,{type:"delight",size:"100%"})):a.createElement(Aa,{id:n,size:ee.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},zp=C.default.div`flex-shrink:0;width:${ee.AVATAR_SIZE}px;height:${ee.AVATAR_SIZE}px;box-sizing:border-box;padding:4px;border-radius:50%;display:flex;justify-content:center;align-items:center;background-color:${({theme:e})=>e.colors.base.primary}!important;ellipse,path{fill:${({theme:e})=>e.colors.base.primaryContrastContent}!important;}}`,Vp=({sender:e})=>a.createElement(qp,{id:`${tt}-sender-name`,variant:"caption1",color:E.themedColor.textMidEmphasis},e.nickname),qp=C.default(H)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Kp=({createdAt:e})=>{const{stringSet:t,format:n}=oe();return e?a.createElement(H,{id:`${tt}-sent-time`,variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Ta="(prefers-reduced-motion: reduce)",Yp=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Ta).matches,Ia=()=>{const[e,t]=l.useState(Yp);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(Ta);t(n.matches);const r=s=>{t(s.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},Wp=({thinkingMessage:e,customStyle:t})=>{const n=Ia();return e?a.createElement(Zp,{$prefersReducedMotion:n},a.createElement(Jp,null,e),!n&&a.createElement(Qp,null)):a.createElement(jp,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(Xp,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},jp=C.default.div`align-items:center;border-radius:16px;display:flex;gap:6px;height:26px;justify-content:center;padding:0 12px;background-color:${({theme:e,$bgColor:t})=>t||e.colors.messageIncoming.background};`,Xp=C.default.span`animation:${({$prefersReducedMotion:e})=>e?"none":"blink 1.4s infinite"};animation-fill-mode:both;border-radius:50%;height:8px;width:8px;background:${({theme:e,$color:t})=>t||e.colors.messageIncoming.text};opacity:${({$prefersReducedMotion:e})=>e?.38:void 0};@keyframes blink{0%{opacity:0.12;transform:scale(1);}21.43%{opacity:0.38;transform:scale(1.2);}42.86%{opacity:0.12;transform:scale(1);}100%{opacity:0.12;transform:scale(1);}}&:nth-child(1){animation-delay:0.4s;}&:nth-child(2){animation-delay:0.6s;}&:nth-child(3){animation-delay:0.8s;}`,Zp=C.default.div.attrs({id:`${tt}-typing-indicator`})`
126
+ `,To=C.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Kp=C.default.pre`margin:0;padding:1em;overflow-x:auto;white-space:pre;font-family:monospace;font-size:13px;line-height:1.5;color:#d4d4d4;background:#1e1e1e;border-radius:4px;`;function Ia({id:e,src:t,size:n=56,onClick:r,onImageError:s,style:o,...i}){const[c,u]=l.useState();return a.createElement(Wp,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ze(n),style:o,...i},t&&t!==c?a.createElement(Yp,{src:t,alt:"",onError:()=>{u(t),s==null||s(t)}}):a.createElement(J,{type:"user",size:n}))}const Wp=C.default.div`border-radius:50%;display:inline-block;overflow:hidden;position:relative;flex-shrink:0;height:${e=>e.$size};width:${e=>e.$size};background-color:${E.themedColor.bg_100_500};&:focus{outline:none;}${xe}`,Yp=C.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,jp=({sender:e,isBotMessage:t})=>{const n=`${tt}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(Xp,{id:n},a.createElement(J,{type:"delight",size:"100%"})):a.createElement(Ia,{id:n,size:ee.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},Xp=C.default.div`flex-shrink:0;width:${ee.AVATAR_SIZE}px;height:${ee.AVATAR_SIZE}px;box-sizing:border-box;padding:4px;border-radius:50%;display:flex;justify-content:center;align-items:center;background-color:${({theme:e})=>e.colors.base.primary}!important;ellipse,path{fill:${({theme:e})=>e.colors.base.primaryContrastContent}!important;}}`,Zp=({sender:e})=>a.createElement(Jp,{id:`${tt}-sender-name`,variant:"caption1",color:E.themedColor.textMidEmphasis},e.nickname),Jp=C.default(B)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Qp=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?a.createElement(B,{id:`${tt}-sent-time`,variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},xa="(prefers-reduced-motion: reduce)",e_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(xa).matches,Ra=()=>{const[e,t]=l.useState(e_);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(xa);t(n.matches);const r=s=>{t(s.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},t_=({thinkingMessage:e,customStyle:t})=>{const n=Ra();return e?a.createElement(s_,{$prefersReducedMotion:n},a.createElement(o_,null,e),!n&&a.createElement(i_,null)):a.createElement(n_,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(r_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},n_=C.default.div`align-items:center;border-radius:16px;display:flex;gap:6px;height:26px;justify-content:center;padding:0 12px;background-color:${({theme:e,$bgColor:t})=>t||e.colors.messageIncoming.background};`,r_=C.default.span`animation:${({$prefersReducedMotion:e})=>e?"none":"blink 1.4s infinite"};animation-fill-mode:both;border-radius:50%;height:8px;width:8px;background:${({theme:e,$color:t})=>t||e.colors.messageIncoming.text};opacity:${({$prefersReducedMotion:e})=>e?.38:void 0};@keyframes blink{0%{opacity:0.12;transform:scale(1);}21.43%{opacity:0.38;transform:scale(1.2);}42.86%{opacity:0.12;transform:scale(1);}100%{opacity:0.12;transform:scale(1);}}&:nth-child(1){animation-delay:0.4s;}&:nth-child(2){animation-delay:0.6s;}&:nth-child(3){animation-delay:0.8s;}`,s_=C.default.div.attrs({id:`${tt}-typing-indicator`})`
127
127
  position: relative;
128
128
  overflow: hidden;
129
129
  animation: ${({$prefersReducedMotion:e})=>e?"none":"fadeIn 0.4s ease-in-out"};
@@ -135,12 +135,12 @@
135
135
  opacity: 1;
136
136
  }
137
137
  }
138
- `,Jp=C.default(H).attrs({variant:"body3"})`
138
+ `,o_=C.default(B).attrs({variant:"body3"})`
139
139
  white-space: pre-wrap;
140
140
  word-break: break-word;
141
141
  color: ${E.themedColor.textHighEmphasis};
142
- `,Qp=C.default.div`position:absolute;inset:0;pointer-events:none;background-size:33% 100%;background-repeat:no-repeat;animation:shimmerSweepLtr 1.6s linear infinite;@keyframes shimmerSweepLtr{from{background-position:-33% 0;}to{background-position:133% 0;}}[dir='rtl'] &{animation-name:shimmerSweepRtl;@keyframes shimmerSweepRtl{from{background-position:133% 0;}to{background-position:-33% 0;}}}background-image:${({theme:e})=>{const t=Ts(e.colors.base.background,.5),n=Ts(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
143
- `,e_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Wr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(t_,{id:`${tt}-ext-cta-button`,onClick:r},a.createElement(n_,{variant:"button"},n.label))},t_=C.default.button.attrs({type:"button"})`
142
+ `,i_=C.default.div`position:absolute;inset:0;pointer-events:none;background-size:33% 100%;background-repeat:no-repeat;animation:shimmerSweepLtr 1.6s linear infinite;@keyframes shimmerSweepLtr{from{background-position:-33% 0;}to{background-position:133% 0;}}[dir='rtl'] &{animation-name:shimmerSweepRtl;@keyframes shimmerSweepRtl{from{background-position:133% 0;}to{background-position:-33% 0;}}}background-image:${({theme:e})=>{const t=Is(e.colors.base.background,.5),n=Is(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
143
+ `,a_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>jr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(c_,{id:`${tt}-ext-cta-button`,onClick:r},a.createElement(l_,{variant:"button"},n.label))},c_=C.default.button.attrs({type:"button"})`
144
144
  all: unset;
145
145
  display: flex;
146
146
  width: 100%;
@@ -157,7 +157,7 @@
157
157
  `}
158
158
 
159
159
  ${xe}
160
- `,n_=C.default(H)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,r_=e=>a.createElement(a.Fragment,null),s_=({extendedMessagePayload:e,onClickCitation:t=n=>Wr(n.link)})=>{const{stringSet:n}=oe(),{theme:r}=Pr(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(o_,{id:`${tt}-ext-citation`},a.createElement(i_,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(a_,null,s.map((o,i)=>a.createElement(l_,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(J,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(c_,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},o_=C.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,i_=C.default(H)`opacity:0.5;`,a_=C.default.div`display:flex;flex-direction:column;gap:8px;`,c_=C.default(H)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,l_=C.default.button.attrs({type:"button"})`
160
+ `,l_=C.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,u_=e=>a.createElement(a.Fragment,null),d_=({extendedMessagePayload:e,onClickCitation:t=n=>jr(n.link)})=>{const{stringSet:n}=se(),{theme:r}=Ur(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(m_,{id:`${tt}-ext-citation`},a.createElement(h_,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(f_,null,s.map((o,i)=>a.createElement(p_,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(J,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(g_,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},m_=C.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,h_=C.default(B)`opacity:0.5;`,f_=C.default.div`display:flex;flex-direction:column;gap:8px;`,g_=C.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,p_=C.default.button.attrs({type:"button"})`
161
161
  background: none;
162
162
  border: none;
163
163
  padding: 0;
@@ -172,25 +172,25 @@
172
172
  &:hover {
173
173
  opacity: 0.5;
174
174
  }
175
- `,u_=e=>a.createElement(a.Fragment,null),br=e=>`${e}-filled`,d_=e=>e==="good"?fe.AIAgentMessageFeedbackRating.GOOD:fe.AIAgentMessageFeedbackRating.BAD,Jr=U.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,dn={good:{onlight:E.color.secondary.dark,ondark:E.color.secondary.light},bad:{onlight:E.color.error.dark,ondark:E.color.error.light}},m_={good:E.themedColor.secondary,bad:E.themedColor.error},xa=e=>U.css`color:${dn[e].onlight};border-color:${dn[e].onlight};${Q.dark`
176
- color: ${dn[e].ondark};
177
- border-color: ${dn[e].ondark};
175
+ `,__=e=>a.createElement(a.Fragment,null),vr=e=>`${e}-filled`,E_=e=>e==="good"?de.AIAgentMessageFeedbackRating.GOOD:de.AIAgentMessageFeedbackRating.BAD,Qr=U.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,mn={good:{onlight:E.color.secondary.dark,ondark:E.color.secondary.light},bad:{onlight:E.color.error.dark,ondark:E.color.error.light}},C_={good:E.themedColor.secondary,bad:E.themedColor.error},Ma=e=>U.css`color:${mn[e].onlight};border-color:${mn[e].onlight};${Q.dark`
176
+ color: ${mn[e].ondark};
177
+ border-color: ${mn[e].ondark};
178
178
  `}
179
- `,h_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=oe(),{conversation:u}=re(),{rootElement:d}=Ji(),m=ut(d),[h,f]=l.useState(r),[g,_]=l.useState(s),[b,v]=l.useState(!1),p=l.useRef(!1),S=h??r??"good",A=u.feedback;l.useLayoutEffect(()=>{e?(f(r),_(s)):(f(void 0),_(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const N=L=>{const z=L;z.metaKey||z.altKey||z.ctrlKey||(p.current=!0)},x=()=>{p.current=!1,v(!1)};return m.addEventListener("keydown",N),m.addEventListener("pointerdown",x),()=>{m.removeEventListener("keydown",N),m.removeEventListener("pointerdown",x)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},M=()=>{t()};if(!e)return null;const k={feedback:A.container()};return a.createElement(dt,{portalContainerId:ye.WINDOW,visible:e,onClose:M,"aria-label":c.FEEDBACK_TITLE},a.createElement(f_,null,a.createElement(g_,null,a.createElement(H,{variant:"h2",color:E.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(p_,null,a.createElement(__,{...k.feedback.props},["good","bad"].map(N=>{const x=h===N,L=N==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,z=A.button(N,x);return a.createElement(l.Fragment,{key:N},a.createElement(E_,{type:"button",$selected:x,$rating:N,...z.props,onClick:()=>f(N),"data-sb-initial-focus":N===S?"true":void 0},a.createElement(J,{type:x?br(N):N,size:24,color:"currentColor"}),a.createElement(H,{variant:"caption1",color:"currentColor"},L)),z.descriptionNode)}),k.feedback.descriptionNode),i&&a.createElement(C_,null,a.createElement(H,{variant:"caption3",color:E.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(b_,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:N=>_(N.target.value),onFocus:()=>v(p.current),onBlur:()=>v(!1),maxLength:100,$focusVisible:b,"data-focus-visible":b?"true":"false"}))),a.createElement(v_,null,a.createElement(y_,{onClick:M},a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(S_,{onClick:T,disabled:!h},a.createElement(H,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},f_=C.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,g_=C.default.div`padding:24px;`,p_=C.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,__=C.default.div`display:flex;gap:4px;`,E_=C.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${E.themedColor.textDisabled};box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:0;gap:0;transition:background-color 0.2s;color:${E.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&xa(t)}${Jr}`,C_=C.default.label`display:flex;flex-direction:column;gap:6px;`,b_=C.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${E.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${E.themedColor.textHighEmphasis};background-color:${E.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${E.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&U.css`
179
+ `,b_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=se(),{conversation:u}=re(),{rootElement:d}=ea(),m=ut(d),[h,f]=l.useState(r),[g,b]=l.useState(s),[S,_]=l.useState(!1),p=l.useRef(!1),y=h??r??"good",A=u.feedback;l.useLayoutEffect(()=>{e?(f(r),b(s)):(f(void 0),b(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const N=O=>{const H=O;H.metaKey||H.altKey||H.ctrlKey||(p.current=!0)},x=()=>{p.current=!1,_(!1)};return m.addEventListener("keydown",N),m.addEventListener("pointerdown",x),()=>{m.removeEventListener("keydown",N),m.removeEventListener("pointerdown",x)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},M=()=>{t()};if(!e)return null;const L={feedback:A.container()};return a.createElement(dt,{portalContainerId:Se.WINDOW,visible:e,onClose:M,"aria-label":c.FEEDBACK_TITLE},a.createElement(v_,null,a.createElement(S_,null,a.createElement(B,{variant:"h2",color:E.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(y_,null,a.createElement(A_,{...L.feedback.props},["good","bad"].map(N=>{const x=h===N,O=N==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,H=A.button(N,x);return a.createElement(l.Fragment,{key:N},a.createElement(T_,{type:"button",$selected:x,$rating:N,...H.props,onClick:()=>f(N),"data-sb-initial-focus":N===y?"true":void 0},a.createElement(J,{type:x?vr(N):N,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},O)),H.descriptionNode)}),L.feedback.descriptionNode),i&&a.createElement(I_,null,a.createElement(B,{variant:"caption3",color:E.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(x_,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:N=>b(N.target.value),onFocus:()=>_(p.current),onBlur:()=>_(!1),maxLength:100,$focusVisible:S,"data-focus-visible":S?"true":"false"}))),a.createElement(R_,null,a.createElement(M_,{onClick:M},a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(w_,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},v_=C.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,S_=C.default.div`padding:24px;`,y_=C.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,A_=C.default.div`display:flex;gap:4px;`,T_=C.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${E.themedColor.textDisabled};box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:0;gap:0;transition:background-color 0.2s;color:${E.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Ma(t)}${Qr}`,I_=C.default.label`display:flex;flex-direction:column;gap:6px;`,x_=C.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${E.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${E.themedColor.textHighEmphasis};background-color:${E.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${E.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&U.css`
180
180
  outline: 2px solid ${E.themedColor.primary};
181
181
  outline-offset: 2px;
182
182
  `}
183
- `,v_=C.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Ra=C.default.button`width:86px;height:40px;border-radius:20px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:opacity 0.2s;`,y_=C.default(Ra)`background-color:transparent;${Jr}`,S_=C.default(Ra)`cursor:${({disabled:e})=>e?"not-allowed":"pointer"};opacity:${({disabled:e})=>e?.4:1};&:hover:not(:disabled){opacity:0.8;}&:active:not(:disabled){opacity:0.6;}background-color:${({theme:e})=>e.colors.base.primary};span{color:${({theme:e})=>e.colors.base.primaryContrastContent};}`,A_=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=oe(),{conversation:u}=re(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,_]=l.useState(void 0),[b,v]=l.useState(""),p=l.useRef(null),S=l.useRef(null),A=l.useRef(null),T=l.useRef(!1),M=u.feedback,k=o==null?void 0:o.feedback,N=(k==null?void 0:k.rating)??"none";if(N!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const L=P=>{P&&Me(()=>{const q=P==="good"?p.current:S.current;q==null||q.focus()})},z=({restoreTrigger:P=!0}={})=>{f(!1),P&&L(A.current)},D=P=>{N==="none"?(_(P),v(""),m(!0)):(A.current=P,f(!0))},W=()=>{i==null||i(null),z()},K=()=>{T.current=!0,z({restoreTrigger:!1}),_(k==null?void 0:k.rating),v((k==null?void 0:k.comment)??""),m(!0)},w=P=>{T.current=!1,i==null||i(P),m(!1),L(A.current)},V=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&N!=="none"?a.createElement(To,{role:"presentation",$horizontal:!0},a.createElement(T_,null,a.createElement(J,{type:br(N),size:12,color:m_[N]})),(k==null?void 0:k.comment)&&a.createElement(Io,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):a.createElement(a.Fragment,null,a.createElement(To,{role:"presentation"},a.createElement(I_,{role:"presentation"},["good","bad"].map(P=>{const q=N===P,ue=M.button(P,q);return a.createElement(l.Fragment,{key:P},a.createElement(x_,{$selected:q,$rating:P,ref:P==="good"?p:S,...ue.props,onClick:()=>D(P)},a.createElement(J,{type:q?br(P):P,size:14,color:"currentColor"})),ue.descriptionNode)})),N!=="none"&&(k==null?void 0:k.comment)&&a.createElement(Io,{variant:"caption2"},k.comment)),a.createElement(lt,{visible:h,onClose:z,...M.optionsBottomSheet().props},a.createElement(lt.ActionItem,{onClick:K,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(lt.ActionItem,{onClick:W,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(h_,{visible:d,onClose:V,isEdit:N!=="none",initialRating:g,initialComment:b,onSubmit:w,isCommentEnabled:s}))},To=C.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${ee.BODY_MAX_WIDTH}px;`,T_=C.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,I_=C.default.div`display:flex;gap:2px;`,x_=C.default.button`width:38px;height:20px;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;transition:opacity 0.2s;box-sizing:border-box;color:${E.themedColor.textMidEmphasis};border:1px solid ${E.color.background200};background-color:transparent;${Q.dark`
183
+ `,R_=C.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,wa=C.default.button`width:86px;height:40px;border-radius:20px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:opacity 0.2s;`,M_=C.default(wa)`background-color:transparent;${Qr}`,w_=C.default(wa)`cursor:${({disabled:e})=>e?"not-allowed":"pointer"};opacity:${({disabled:e})=>e?.4:1};&:hover:not(:disabled){opacity:0.8;}&:active:not(:disabled){opacity:0.6;}background-color:${({theme:e})=>e.colors.base.primary};span{color:${({theme:e})=>e.colors.base.primaryContrastContent};}`,k_=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=se(),{conversation:u}=re(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,b]=l.useState(void 0),[S,_]=l.useState(""),p=l.useRef(null),y=l.useRef(null),A=l.useRef(null),T=l.useRef(!1),M=u.feedback,L=o==null?void 0:o.feedback,N=(L==null?void 0:L.rating)??"none";if(N!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const O=P=>{P&&we(()=>{const V=P==="good"?p.current:y.current;V==null||V.focus()})},H=({restoreTrigger:P=!0}={})=>{f(!1),P&&O(A.current)},F=P=>{N==="none"?(b(P),_(""),m(!0)):(A.current=P,f(!0))},Y=()=>{i==null||i(null),H()},q=()=>{T.current=!0,H({restoreTrigger:!1}),b(L==null?void 0:L.rating),_((L==null?void 0:L.comment)??""),m(!0)},k=P=>{T.current=!1,i==null||i(P),m(!1),O(A.current)},G=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&N!=="none"?a.createElement(Io,{role:"presentation",$horizontal:!0},a.createElement(L_,null,a.createElement(J,{type:vr(N),size:12,color:C_[N]})),(L==null?void 0:L.comment)&&a.createElement(xo,{variant:"caption2",style:{lineHeight:"16px"}},L.comment)):a.createElement(a.Fragment,null,a.createElement(Io,{role:"presentation"},a.createElement(O_,{role:"presentation"},["good","bad"].map(P=>{const V=N===P,me=M.button(P,V);return a.createElement(l.Fragment,{key:P},a.createElement(D_,{$selected:V,$rating:P,ref:P==="good"?p:y,...me.props,onClick:()=>F(P)},a.createElement(J,{type:V?vr(P):P,size:14,color:"currentColor"})),me.descriptionNode)})),N!=="none"&&(L==null?void 0:L.comment)&&a.createElement(xo,{variant:"caption2"},L.comment)),a.createElement(lt,{visible:h,onClose:H,...M.optionsBottomSheet().props},a.createElement(lt.ActionItem,{onClick:q,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(lt.ActionItem,{onClick:Y,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(b_,{visible:d,onClose:G,isEdit:N!=="none",initialRating:g,initialComment:S,onSubmit:k,isCommentEnabled:s}))},Io=C.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${ee.BODY_MAX_WIDTH}px;`,L_=C.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,O_=C.default.div`display:flex;gap:2px;`,D_=C.default.button`width:38px;height:20px;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;transition:opacity 0.2s;box-sizing:border-box;color:${E.themedColor.textMidEmphasis};border:1px solid ${E.color.background200};background-color:transparent;${Q.dark`
184
184
  border: 1px solid ${E.color.background400};
185
185
  `}
186
186
 
187
- ${({$selected:e,$rating:t})=>e&&xa(t)}
187
+ ${({$selected:e,$rating:t})=>e&&Ma(t)}
188
188
 
189
- ${Jr}
190
- `,Io=C.default(H)`color:${E.themedColor.textMidEmphasis};${Q.dark`
189
+ ${Qr}
190
+ `,xo=C.default(B)`color:${E.themedColor.textMidEmphasis};${Q.dark`
191
191
  color: ${E.themedColor.textHighEmphasis};
192
192
  `}
193
- `,Qr=U.css`width:100%;height:36px;border-radius:6px;cursor:pointer;transition:all 0.2s ease;padding:0 12px;border:none;outline:none;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,xo=C.default.button`${Qr};background-color:${E.themedColor.primary};color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,R_=C.default.button`${Qr};color:${E.themedColor.primary};${Q.light`
193
+ `,es=U.css`width:100%;height:36px;border-radius:6px;cursor:pointer;transition:all 0.2s ease;padding:0 12px;border:none;outline:none;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,Ro=C.default.button`${es};background-color:${E.themedColor.primary};color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,N_=C.default.button`${es};color:${E.themedColor.primary};${Q.light`
194
194
  background-color: ${E.color.background50};
195
195
  `};
196
196
  ${Q.dark`
@@ -200,7 +200,7 @@
200
200
  &:hover:not(:disabled) {
201
201
  opacity: 0.9;
202
202
  }
203
- `,M_=C.default.button`${Qr};background-color:transparent;color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,w_=e=>{switch(e){case"primary":return xo;case"secondary":return R_;case"clear":return M_;default:return xo}},k_=C.default.div`animation:1s infinite linear;animation-name:rotate;display:flex;align-items:center;justify-content:center;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,L_=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return E.themedColor.textHighEmphasisInverse;case"secondary":return E.themedColor.primary;case"clear":return E.themedColor.textHighEmphasis;default:return E.themedColor.textHighEmphasisInverse}},u=w_(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(k_,null,a.createElement(J,{type:"spinner",size:22,color:c()})):a.createElement(H,{variant:"button",color:c()},e))},O_=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(H,{variant:"caption4",color:E.themedColor.error,className:t,style:n,id:r,role:s},e),N_=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=oe();return a.createElement(H,{id:e,variant:"caption3",color:E.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:E.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},D_=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:i=!1,max:c,...u})=>{const d=h=>{const g=h.target.value.replace(/[^0-9.-]/g,""),_=g.split("."),v=_.length>1?_[0]+"."+_.slice(1).join("").replace(/\./g,""):g;if(h.target.value=v,v===""||v==="-")t==null||t(null);else{const p=Number(v);if(!isNaN(p)){if(c!==void 0&&p>c)return;t==null||t(p)}}},m=e==null?"":String(e);return a.createElement(B_,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},$_=U.css`width:100%;height:36px;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${xe}&::placeholder{color:${E.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,F_=U.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${Q.light`
203
+ `,$_=C.default.button`${es};background-color:transparent;color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,F_=e=>{switch(e){case"primary":return Ro;case"secondary":return N_;case"clear":return $_;default:return Ro}},P_=C.default.div`animation:1s infinite linear;animation-name:rotate;display:flex;align-items:center;justify-content:center;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,U_=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return E.themedColor.textHighEmphasisInverse;case"secondary":return E.themedColor.primary;case"clear":return E.themedColor.textHighEmphasis;default:return E.themedColor.textHighEmphasisInverse}},u=F_(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(P_,null,a.createElement(J,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},B_=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(B,{variant:"caption4",color:E.themedColor.error,className:t,style:n,id:r,role:s},e),H_=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=se();return a.createElement(B,{id:e,variant:"caption3",color:E.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:E.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},G_=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:i=!1,max:c,...u})=>{const d=h=>{const g=h.target.value.replace(/[^0-9.-]/g,""),b=g.split("."),_=b.length>1?b[0]+"."+b.slice(1).join("").replace(/\./g,""):g;if(h.target.value=_,_===""||_==="-")t==null||t(null);else{const p=Number(_);if(!isNaN(p)){if(c!==void 0&&p>c)return;t==null||t(p)}}},m=e==null?"":String(e);return a.createElement(W_,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},z_=U.css`width:100%;height:36px;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${xe}&::placeholder{color:${E.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,V_=U.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${Q.light`
204
204
  background-color: ${E.color.ondark.textMidEmphasis};
205
205
  `}
206
206
  ${Q.dark`
@@ -210,13 +210,13 @@
210
210
  &::placeholder {
211
211
  color: ${E.themedColor.textLowEmphasis};
212
212
  }
213
- `,P_=U.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${Q.light`
213
+ `,q_=U.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${Q.light`
214
214
  background-color: ${E.color.background50};
215
215
  `}
216
216
  ${Q.dark`
217
217
  background-color: ${E.color.onlight.textLowEmphasis};
218
218
  `}
219
- `,U_=U.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${Q.light`
219
+ `,K_=U.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${Q.light`
220
220
  background-color: ${E.color.background50};
221
221
  `}
222
222
  ${Q.dark`
@@ -226,12 +226,12 @@
226
226
  &:focus {
227
227
  border-color: ${E.themedColor.primary};
228
228
  }
229
- `,B_=C.default.input`${$_}${({$error:e,$submitted:t})=>t?F_:e?P_:U_}`,H_=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:i=>{if(s)return;if(t.includes(i)){const u=t.filter(d=>d!==i);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,i];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},Ma=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=re(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=H_(e),m=t.some(h=>u.includes(h.value));return a.createElement(z_,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,f)=>{const g=u.includes(h.value),_=o?`${o}, ${h.label}`:h.label;return a.createElement(X_,{key:h.value,type:"button",$active:g,$submitted:n,$error:r,...(c?i.form.multiSelectOption(_,g,n):i.form.singleSelectOption(_,g,n,f,t.length,m,b=>{const v=t[b];v&&d(v.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(H,{variant:"caption1",color:G_(g,n)},h.label))}))},G_=(e,t)=>t?e?E.themedColor.textHighEmphasis:E.themedColor.textDisabled:e?E.themedColor.primary:E.themedColor.textMidEmphasis,z_=C.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,V_=U.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,q_=U.css`cursor:default;background-color:${E.color.ondark.textMidEmphasis};color:${E.themedColor.textHighEmphasis};${Q.dark`
229
+ `,W_=C.default.input`${z_}${({$error:e,$submitted:t})=>t?V_:e?q_:K_}`,Y_=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:i=>{if(s)return;if(t.includes(i)){const u=t.filter(d=>d!==i);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,i];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},ka=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=re(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=Y_(e),m=t.some(h=>u.includes(h.value));return a.createElement(X_,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,f)=>{const g=u.includes(h.value),b=o?`${o}, ${h.label}`:h.label;return a.createElement(rE,{key:h.value,type:"button",$active:g,$submitted:n,$error:r,...(c?i.form.multiSelectOption(b,g,n):i.form.singleSelectOption(b,g,n,f,t.length,m,S=>{const _=t[S];_&&d(_.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:j_(g,n)},h.label))}))},j_=(e,t)=>t?e?E.themedColor.textHighEmphasis:E.themedColor.textDisabled:e?E.themedColor.primary:E.themedColor.textMidEmphasis,X_=C.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,Z_=U.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,J_=U.css`cursor:default;background-color:${E.color.ondark.textMidEmphasis};color:${E.themedColor.textHighEmphasis};${Q.dark`
230
230
  background-color: transparent;
231
231
  border: 1px solid white;
232
232
  color: white;
233
233
  `}
234
- `,K_=U.css`cursor:default;${Q.light`
234
+ `,Q_=U.css`cursor:default;${Q.light`
235
235
  background-color: ${E.color.ondark.textMidEmphasis};
236
236
  color: ${E.themedColor.textDisabled};
237
237
  `}
@@ -240,7 +240,7 @@
240
240
  border: 1px solid ${E.color.onlight.textLowEmphasis};
241
241
  color: ${E.themedColor.textDisabled};
242
242
  `}
243
- `,Y_=U.css`cursor:pointer;border:1px solid ${E.themedColor.primary};${Q.light`
243
+ `,eE=U.css`cursor:pointer;border:1px solid ${E.themedColor.primary};${Q.light`
244
244
  background-color: ${E.color.background50};
245
245
  color: ${E.themedColor.primary};
246
246
  `}
@@ -248,7 +248,7 @@
248
248
  background-color: ${E.color.onlight.textLowEmphasis};
249
249
  color: ${E.themedColor.primary};
250
250
  `}
251
- `,W_=U.css`cursor:pointer;border:1px solid ${E.themedColor.textDisabled};${Q.light`
251
+ `,tE=U.css`cursor:pointer;border:1px solid ${E.themedColor.textDisabled};${Q.light`
252
252
  background-color: ${E.color.background50};
253
253
  color: ${E.themedColor.textMidEmphasis};
254
254
  `}
@@ -256,10 +256,10 @@
256
256
  background-color: ${E.color.onlight.textLowEmphasis};
257
257
  color: ${E.themedColor.textMidEmphasis};
258
258
  `}
259
- `,j_=U.css`border-color:${E.themedColor.error}!important;`,X_=C.default.button`${V_}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?q_:K_;const r=e?Y_:W_;return n?U.css`
260
- ${r} ${j_}
259
+ `,nE=U.css`border-color:${E.themedColor.error}!important;`,rE=C.default.button`${Z_}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?J_:Q_;const r=e?eE:tE;return n?U.css`
260
+ ${r} ${nE}
261
261
  `:r}}
262
- `,Z_=e=>a.createElement(Ma,{...e,multiple:!1}),J_=e=>a.createElement(Ma,{...e,multiple:!0}),Q_=C.default.div`width:100%;height:1px;background-color:${E.themedColor.textDisabled};`,eE=({className:e})=>a.createElement(Q_,{className:e}),tE=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:i=!1,className:c,disabled:u=!1,maxLength:d,...m})=>{const f={id:e,value:t,onChange:g=>{const _=g.target.value;d&&_.length>d||n==null||n(_)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(rE,{...f}):a.createElement(nE,{...f})},wa=U.css`width:100%;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${xe}&::placeholder{color:${E.themedColor.textLowEmphasis};}`,ka=U.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${Q.light`
262
+ `,sE=e=>a.createElement(ka,{...e,multiple:!1}),oE=e=>a.createElement(ka,{...e,multiple:!0}),iE=C.default.div`width:100%;height:1px;background-color:${E.themedColor.textDisabled};`,aE=({className:e})=>a.createElement(iE,{className:e}),cE=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:i=!1,className:c,disabled:u=!1,maxLength:d,...m})=>{const f={id:e,value:t,onChange:g=>{const b=g.target.value;d&&b.length>d||n==null||n(b)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(uE,{...f}):a.createElement(lE,{...f})},La=U.css`width:100%;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${xe}&::placeholder{color:${E.themedColor.textLowEmphasis};}`,Oa=U.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${Q.light`
263
263
  background-color: ${E.color.ondark.textMidEmphasis};
264
264
  `}
265
265
  ${Q.dark`
@@ -269,13 +269,13 @@
269
269
  &::placeholder {
270
270
  color: ${E.themedColor.textLowEmphasis};
271
271
  }
272
- `,La=U.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${Q.light`
272
+ `,Da=U.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${Q.light`
273
273
  background-color: ${E.color.background50};
274
274
  `}
275
275
  ${Q.dark`
276
276
  background-color: ${E.color.onlight.textLowEmphasis};
277
277
  `}
278
- `,Oa=U.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${Q.light`
278
+ `,Na=U.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${Q.light`
279
279
  background-color: ${E.color.background50};
280
280
  `}
281
281
  ${Q.dark`
@@ -285,14 +285,14 @@
285
285
  &:focus {
286
286
  border-color: ${E.themedColor.primary};
287
287
  }
288
- `,nE=C.default.input`${wa};height:36px;${({$error:e,$submitted:t})=>t?ka:e?La:Oa}`,rE=C.default.textarea`${wa};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?ka:e?La:Oa}`,sE=({children:e,className:t,style:n})=>a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis,className:t,style:n},e),ke={Title:sE,Label:N_,ErrorLabel:O_,Separator:eE,Button:L_,TextInput:tE,NumberInput:D_,SingleSelect:Z_,MultiSelect:J_},oE=1,iE=new Set(["text","number","single-select","multi-select"]),Na=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,aE=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Na||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},cE=e=>{var p,S;const t=(p=e.extendedMessagePayload)==null?void 0:p.form;if(aE({messageForm:t,onError:(S=e.statsCallbacks)==null?void 0:S.onFormRenderError}),!Na)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=oe(),{conversation:r}=re(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=rm(t,{labels:{required:n.FORM_VALIDATION_REQUIRED,regex:n.FORM_VALIDATION_REGEX_FAILED,minLength:n.FORM_VALIDATION_MIN_LENGTH,maxLength:n.FORM_VALIDATION_MAX_LENGTH,min:n.FORM_VALIDATION_MIN,max:n.FORM_VALIDATION_MAX,minSelect:n.FORM_VALIDATION_MIN_SELECT,maxSelect:n.FORM_VALIDATION_MAX_SELECT},onSubmit:A=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:A})},onCancel:()=>{var A;return(A=e.onCancelForm)==null?void 0:A.call(e,{key:t.key})}}),g=u==="submitted",_=async()=>{o(A=>({...A,submitting:!0}));try{await m()}catch(A){c({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{o(A=>({...A,submitting:!1}))}},b=async()=>{o(A=>({...A,canceling:!0}));try{await h()}catch(A){c({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{o(A=>({...A,canceling:!1}))}},v=l.useMemo(()=>{const A=()=>t.version>oE,T=()=>t.fields.some(M=>!iE.has(M.type));return A()||T()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:v.visible?a.createElement(l.Fragment,null,a.createElement(Ro,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},a.createElement(ke.Title,null,t.title),a.createElement(lE,null,d.map(A=>a.createElement(uE,{key:A.key},a.createElement(ke.Label,{style:{marginBottom:"6px"},required:A.required},A.label),A.type==="text"&&a.createElement(ke.TextInput,{value:A.value||"",placeholder:A.placeholder,onChange:T=>f(A.key,T),disabled:g,error:!!A.error,submitted:g,variant:A.layout==="multiline"?"multi-line":"single-line",maxLength:A.maxLength,...r.form.textInput(A.label,A.required??!1,g).props}),A.type==="number"&&a.createElement(ke.NumberInput,{value:A.value||null,placeholder:A.placeholder,onChange:T=>f(A.key,T),disabled:g,error:!!A.error,submitted:g,max:A.max,...r.form.numberInput(A.label,A.required??!1,g).props}),A.type==="single-select"&&a.createElement(ke.SingleSelect,{options:A.options.map(T=>({label:T,value:T})),value:A.value||"",onChange:T=>f(A.key,T),submitted:g,groupLabel:A.label}),A.type==="multi-select"&&a.createElement(ke.MultiSelect,{options:A.options.map(T=>({label:T,value:T})),value:A.value||[],onChange:T=>f(A.key,T),submitted:g,maxSelect:A.maxSelect,groupLabel:A.label}),A.error&&a.createElement(ke.ErrorLabel,{style:{marginTop:"4px"}},A.error)))),a.createElement(ke.Separator,null),a.createElement(dE,null,a.createElement(ke.Button,{variant:g?"clear":"primary",...r.form.button(g?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:_,disabled:g||s.canceling,loading:s.submitting},g?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&a.createElement(ke.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:b,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(Pn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Ro,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},a.createElement(H,{variant:"body3"},v.reason),v.cancelable&&a.createElement(ke.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:b,loading:s.canceling},n.BUTTON__CANCEL))},Ro=C.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>U.css`
288
+ `,lE=C.default.input`${La};height:36px;${({$error:e,$submitted:t})=>t?Oa:e?Da:Na}`,uE=C.default.textarea`${La};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Oa:e?Da:Na}`,dE=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis,className:t,style:n},e),Oe={Title:dE,Label:H_,ErrorLabel:B_,Separator:aE,Button:U_,TextInput:cE,NumberInput:G_,SingleSelect:sE,MultiSelect:oE},mE=1,hE=new Set(["text","number","single-select","multi-select"]),$a=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,fE=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if($a||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},gE=e=>{var p,y;const t=(p=e.extendedMessagePayload)==null?void 0:p.form;if(fE({messageForm:t,onError:(y=e.statsCallbacks)==null?void 0:y.onFormRenderError}),!$a)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=se(),{conversation:r}=re(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=um(t,{labels:{required:n.FORM_VALIDATION_REQUIRED,regex:n.FORM_VALIDATION_REGEX_FAILED,minLength:n.FORM_VALIDATION_MIN_LENGTH,maxLength:n.FORM_VALIDATION_MAX_LENGTH,min:n.FORM_VALIDATION_MIN,max:n.FORM_VALIDATION_MAX,minSelect:n.FORM_VALIDATION_MIN_SELECT,maxSelect:n.FORM_VALIDATION_MAX_SELECT},onSubmit:A=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:A})},onCancel:()=>{var A;return(A=e.onCancelForm)==null?void 0:A.call(e,{key:t.key})}}),g=u==="submitted",b=async()=>{o(A=>({...A,submitting:!0}));try{await m()}catch(A){c({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{o(A=>({...A,submitting:!1}))}},S=async()=>{o(A=>({...A,canceling:!0}));try{await h()}catch(A){c({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{o(A=>({...A,canceling:!1}))}},_=l.useMemo(()=>{const A=()=>t.version>mE,T=()=>t.fields.some(M=>!hE.has(M.type));return A()||T()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:_.visible?a.createElement(l.Fragment,null,a.createElement(Mo,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},a.createElement(Oe.Title,null,t.title),a.createElement(pE,null,d.map(A=>a.createElement(_E,{key:A.key},a.createElement(Oe.Label,{style:{marginBottom:"6px"},required:A.required},A.label),A.type==="text"&&a.createElement(Oe.TextInput,{value:A.value||"",placeholder:A.placeholder,onChange:T=>f(A.key,T),disabled:g,error:!!A.error,submitted:g,variant:A.layout==="multiline"?"multi-line":"single-line",maxLength:A.maxLength,...r.form.textInput(A.label,A.required??!1,g).props}),A.type==="number"&&a.createElement(Oe.NumberInput,{value:A.value||null,placeholder:A.placeholder,onChange:T=>f(A.key,T),disabled:g,error:!!A.error,submitted:g,max:A.max,...r.form.numberInput(A.label,A.required??!1,g).props}),A.type==="single-select"&&a.createElement(Oe.SingleSelect,{options:A.options.map(T=>({label:T,value:T})),value:A.value||"",onChange:T=>f(A.key,T),submitted:g,groupLabel:A.label}),A.type==="multi-select"&&a.createElement(Oe.MultiSelect,{options:A.options.map(T=>({label:T,value:T})),value:A.value||[],onChange:T=>f(A.key,T),submitted:g,maxSelect:A.maxSelect,groupLabel:A.label}),A.error&&a.createElement(Oe.ErrorLabel,{style:{marginTop:"4px"}},A.error)))),a.createElement(Oe.Separator,null),a.createElement(EE,null,a.createElement(Oe.Button,{variant:g?"clear":"primary",...r.form.button(g?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:b,disabled:g||s.canceling,loading:s.submitting},g?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&a.createElement(Oe.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:S,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(Un,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Mo,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},_.reason),_.cancelable&&a.createElement(Oe.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:S,loading:s.canceling},n.BUTTON__CANCEL))},Mo=C.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>U.css`
289
289
  color: ${e.colors.messageIncoming.text};
290
290
  background-color: ${e.colors.messageIncoming.background};
291
291
  `}
292
292
  padding: 16px 12px;
293
293
  transition: max-width 0.3s;
294
294
  overflow-wrap: break-word;
295
- `,lE=C.default.div`display:flex;flex-direction:column;gap:12px;`,uE=C.default.div`display:flex;flex-direction:column;`,dE=C.default.div`display:flex;flex-direction:column;gap:8px;`,mE=e=>a.createElement(a.Fragment,null),vr=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BjKg30ip.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,hE=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(vr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},fE=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return hE({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),vr?a.createElement(Ht,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(vr,{...e})):null},gE=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=re(),[s,o]=l.useState(!1),{suggestedReplies:i}=r,c=(e==null?void 0:e.suggested_replies)??[];if(c.length===0||s)return null;const u=d=>{t&&(t({reply:d}),o(!0))};return a.createElement(pE,{id:`${tt}-ext-suggested-replies`,role:"presentation",$type:n},c.map((d,m)=>{const h=i.item(d,m);return a.createElement(l.Fragment,{key:m},a.createElement(_E,{$type:n,...h.props,onClick:()=>u(d)},a.createElement(EE,{variant:"body3"},d)),h.descriptionNode)}))},pE=C.default.div`margin:16px 0;padding:0 ${ee.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?CE:bE};`,_E=C.default.button.attrs({type:"button"})`
295
+ `,pE=C.default.div`display:flex;flex-direction:column;gap:12px;`,_E=C.default.div`display:flex;flex-direction:column;`,EE=C.default.div`display:flex;flex-direction:column;gap:8px;`,CE=e=>a.createElement(a.Fragment,null),Sr=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ZOM6SoNd.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,bE=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Sr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},vE=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return bE({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),Sr?a.createElement(Ht,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(Sr,{...e})):null},SE=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=re(),[s,o]=l.useState(!1),{suggestedReplies:i}=r,c=(e==null?void 0:e.suggested_replies)??[];if(c.length===0||s)return null;const u=d=>{t&&(t({reply:d}),o(!0))};return a.createElement(yE,{id:`${tt}-ext-suggested-replies`,role:"presentation",$type:n},c.map((d,m)=>{const h=i.item(d,m);return a.createElement(l.Fragment,{key:m},a.createElement(AE,{$type:n,...h.props,onClick:()=>u(d)},a.createElement(TE,{variant:"body3"},d)),h.descriptionNode)}))},yE=C.default.div`margin:16px 0;padding:0 ${ee.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?IE:xE};`,AE=C.default.button.attrs({type:"button"})`
296
296
  all: unset;
297
297
  box-sizing: border-box;
298
298
  padding: 8px 12px;
@@ -312,20 +312,20 @@
312
312
 
313
313
  ${xe}
314
314
 
315
- ${({$type:e,theme:t})=>U.css`${e==="vertical"?vE:yE};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
316
- `,EE=C.default(H)`color:inherit;`,CE=U.css`flex-direction:column;align-items:flex-end;`,bE=U.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,vE=U.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,yE=U.css`white-space:nowrap;`,SE=e=>{const{components:t}=_t.useContext(),{stringSet:n}=oe(),r=ei(e)?a.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const s=e.file;return s.type.startsWith("image")||s.type.startsWith("video")?a.createElement(t.MediaMessageBody,{...e},r):a.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},r):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},AE=e=>{var S,A,T,M,k;const{components:t}=_t.useContext(),{streamText:n,isAnimating:r}=pm({text:e.message,enabled:e.isStreaming,snapOnDisable:((S=e.extendedMessagePayload)==null?void 0:S.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onVisibleTextProgress:(A=e.statsCallbacks)==null?void 0:A.onVisibleTextProgress,onRenderedTextProgress:(T=e.statsCallbacks)==null?void 0:T.onRenderedTextProgress}),s={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},o=!!s.isTyping,i=!!s.isSenderAvatarVisible,c=kn(s.extendedMessagePayload),u=c.hasCTAButton,d=c.hasChallenge,m=c.hasCitations,h=c.hasForm,f=c.hasMessageTemplate,g=!!s.createdAt,_=u||m,b=s.groupType==="top"||s.groupType==="single",v=s.groupType==="bottom"||s.groupType==="single",p=i?ee.AVATAR_SIZE:0;return a.createElement(TE,{$marginBottom:o?0:Ln(s.groupType)},b&&a.createElement(RE,null,i&&a.createElement(t.SenderAvatar,{...s}),a.createElement(t.SenderName,{...s})),a.createElement(wE,null,a.createElement(or,{$extraStartPadding:p},o?a.createElement(t.TypingIndicator,{...s}):_?a.createElement(IE,{$maxWidth:s.maxBodyWidth??ee.BODY_MAX_WIDTH},a.createElement(t.MessageBody,{...s,surface:"plain"}),u&&a.createElement(xE,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...s})),m&&a.createElement(t.Citation,{...s})):a.createElement(t.MessageBody,{...s})),f&&a.createElement(Mo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??a.createElement(or,{$extraStartPadding:p},a.createElement(t.MessageBody,{...s,messageType:"user",message:((k=(M=s.extendedMessagePayload)==null?void 0:M.message_template)==null?void 0:k.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??a.createElement(or,{$extraStartPadding:p},a.createElement(t.TypingIndicator,{...s}))})),a.createElement(t.CustomMessageTemplate,{...s}),d&&a.createElement(t.Challenge,{...s}),h&&a.createElement(Mo,{$extraStartPadding:p},a.createElement(t.Form,{...s}))),a.createElement(t.MessageLogs,{...s}),v&&g&&a.createElement(ME,{$extraStartPadding:p+8},a.createElement(t.SentTime,{...s})),a.createElement(l.Fragment,null,!o&&a.createElement(Qt,{$extraStartPadding:p+8},a.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...s})))},_t=je({template:AE,components:{SenderName:Vp,SenderAvatar:Gp,SentTime:Kp,MessageBody:SE,TextMessageBody:Pp,MediaMessageBody:vp,FileMessageBody:Ep,MultipleFilesMessageBody:Op,TypingIndicator:Wp,SuggestedReplies:gE,MessageTemplate:fE,CustomMessageTemplate:u_,Challenge:r_,CTAButton:e_,Citation:s_,Form:cE,Feedback:A_,MessageLogs:mE}}),TE=C.default.div.attrs({role:"presentation"})`
315
+ ${({$type:e,theme:t})=>U.css`${e==="vertical"?RE:ME};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
316
+ `,TE=C.default(B)`color:inherit;`,IE=U.css`flex-direction:column;align-items:flex-end;`,xE=U.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,RE=U.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,ME=U.css`white-space:nowrap;`,wE=e=>{const{components:t}=_t.useContext(),{stringSet:n}=se(),r=ti(e)?a.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const s=e.file;return s.type.startsWith("image")||s.type.startsWith("video")?a.createElement(t.MediaMessageBody,{...e},r):a.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},r):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},kE=e=>{var y,A,T,M,L;const{components:t}=_t.useContext(),{streamText:n,isAnimating:r}=ym({text:e.message,enabled:e.isStreaming,snapOnDisable:((y=e.extendedMessagePayload)==null?void 0:y.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onVisibleTextProgress:(A=e.statsCallbacks)==null?void 0:A.onVisibleTextProgress,onRenderedTextProgress:(T=e.statsCallbacks)==null?void 0:T.onRenderedTextProgress}),s={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},o=!!s.isTyping,i=!!s.isSenderAvatarVisible,c=On(s.extendedMessagePayload),u=c.hasCTAButton,d=c.hasChallenge,m=c.hasCitations,h=c.hasForm,f=c.hasMessageTemplate,g=!!s.createdAt,b=u||m,S=s.groupType==="top"||s.groupType==="single",_=s.groupType==="bottom"||s.groupType==="single",p=i?ee.AVATAR_SIZE:0;return a.createElement(LE,{$marginBottom:o?0:Dn(s.groupType)},S&&a.createElement(NE,null,i&&a.createElement(t.SenderAvatar,{...s}),a.createElement(t.SenderName,{...s})),a.createElement(FE,null,a.createElement(ir,{$extraStartPadding:p},o?a.createElement(t.TypingIndicator,{...s}):b?a.createElement(OE,{$maxWidth:s.maxBodyWidth??ee.BODY_MAX_WIDTH},a.createElement(t.MessageBody,{...s,surface:"plain"}),u&&a.createElement(DE,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...s})),m&&a.createElement(t.Citation,{...s})):a.createElement(t.MessageBody,{...s})),f&&a.createElement(wo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??a.createElement(ir,{$extraStartPadding:p},a.createElement(t.MessageBody,{...s,messageType:"user",message:((L=(M=s.extendedMessagePayload)==null?void 0:M.message_template)==null?void 0:L.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??a.createElement(ir,{$extraStartPadding:p},a.createElement(t.TypingIndicator,{...s}))})),a.createElement(t.CustomMessageTemplate,{...s}),d&&a.createElement(t.Challenge,{...s}),h&&a.createElement(wo,{$extraStartPadding:p},a.createElement(t.Form,{...s}))),a.createElement(t.MessageLogs,{...s}),_&&g&&a.createElement($E,{$extraStartPadding:p+8},a.createElement(t.SentTime,{...s})),a.createElement(l.Fragment,null,!o&&a.createElement(en,{$extraStartPadding:p+8},a.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...s})))},_t=je({template:kE,components:{SenderName:Zp,SenderAvatar:jp,SentTime:Qp,MessageBody:wE,TextMessageBody:qp,MediaMessageBody:Rp,FileMessageBody:Tp,MultipleFilesMessageBody:Bp,TypingIndicator:t_,SuggestedReplies:SE,MessageTemplate:vE,CustomMessageTemplate:__,Challenge:u_,CTAButton:a_,Citation:d_,Form:gE,Feedback:k_,MessageLogs:CE}}),LE=C.default.div.attrs({role:"presentation"})`
317
317
  display: flex;
318
318
  flex-direction: column;
319
319
  align-items: flex-start;
320
320
  margin-bottom: ${({$marginBottom:e})=>`${e}px`};
321
- `,Qt=C.default.div.attrs({role:"presentation"})`
321
+ `,en=C.default.div.attrs({role:"presentation"})`
322
322
  display: flex;
323
323
  align-self: stretch;
324
324
  justify-content: flex-start;
325
325
  ${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
326
326
  padding-inline: ${e+n}px ${t}px;
327
327
  `}
328
- `,IE=C.default.div.attrs({role:"presentation"})`
328
+ `,OE=C.default.div.attrs({role:"presentation"})`
329
329
  display: flex;
330
330
  flex-direction: column;
331
331
  min-width: 0;
@@ -334,46 +334,46 @@
334
334
  overflow: hidden;
335
335
  padding: 12px 0;
336
336
  ${({theme:e})=>U.css`color:${e.colors.messageIncoming.text};background-color:${e.colors.messageIncoming.background};`}
337
- `,xE=C.default.div.attrs({role:"presentation"})`
337
+ `,DE=C.default.div.attrs({role:"presentation"})`
338
338
  display: flex;
339
339
  flex-direction: column;
340
340
  min-width: 0;
341
341
  ${({$marginTop:e=0,$paddingInline:t=0})=>U.css`margin-top:${e}px;padding-inline:${t}px;`}
342
- `,RE=C.default(Qt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,or=C.default(Qt)`display:flex;`,ME=C.default(Qt)`margin-top:${ee.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Mo=C.default(Qt).attrs({role:"presentation"})`
342
+ `,NE=C.default(en)`display:flex;flex-direction:row;align-items:center;gap:8px;`,ir=C.default(en)`display:flex;`,$E=C.default(en)`margin-top:${ee.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,wo=C.default(en).attrs({role:"presentation"})`
343
343
  display: flex;
344
344
  ${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
345
345
  padding-inline: ${e+n}px ${t}px;
346
346
  `}
347
- `,wE=C.default.div.attrs({role:"presentation"})`
347
+ `,FE=C.default.div.attrs({role:"presentation"})`
348
348
  display: flex;
349
349
  flex-direction: column;
350
350
  min-width: 0;
351
351
  max-width: 100%;
352
352
  gap: ${ee.GAP_GROUPED}px;
353
- `;function kE({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(LE,null,a.createElement(Zr,{name:e.name,mimeType:e.type,type:Ir(e.name,e.type),onClick:s}),t)}const LE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function OE({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=re(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?URL.createObjectURL(u):t.url),[m,h]=l.useState(!1),f=(()=>{if(e!=="failed"){if(s)return()=>s({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),g=f?i.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:f}):i.file.preview({name:t.name,mimeType:t.type}),_={...g.props,$ratio:c,$clickable:!!f};return a.createElement(NE,null,a.createElement(DE,{..._},!m&&a.createElement(pt,{size:26},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement($E,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const NE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`,DE=C.default.div`width:${ee.BODY_MAX_WIDTH}px;border-radius:12px;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};height:auto;aspect-ratio:${e=>e.$ratio};position:relative;display:flex;align-items:center;justify-content:center;${Q.light`
353
+ `;function PE({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(UE,null,a.createElement(Jr,{name:e.name,mimeType:e.type,type:xr(e.name,e.type),onClick:s}),t)}const UE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function BE({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=re(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?URL.createObjectURL(u):t.url),[m,h]=l.useState(!1),f=(()=>{if(e!=="failed"){if(s)return()=>s({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),g=f?i.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:f}):i.file.preview({name:t.name,mimeType:t.type}),b={...g.props,$ratio:c,$clickable:!!f};return a.createElement(HE,null,a.createElement(GE,{...b},!m&&a.createElement(pt,{size:26},a.createElement(J,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement(zE,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const HE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`,GE=C.default.div`width:${ee.BODY_MAX_WIDTH}px;border-radius:12px;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};height:auto;aspect-ratio:${e=>e.$ratio};position:relative;display:flex;align-items:center;justify-content:center;${Q.light`
354
354
  background-color: ${E.color.background100};
355
355
  `}
356
356
  ${Q.dark`
357
357
  background-color: ${E.color.background400};
358
358
  `}
359
- `,$E=C.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`,FE=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[i]=l.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),c=e==="pending",u=e==="failed",d=m=>{if(u||c)return;const h=i[m];h&&(s?s({files:i,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return a.createElement(PE,null,a.createElement(va,{images:i,isPending:c,onClickImage:d}),o)},PE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function UE(e){var n,r;const t=l.useMemo(()=>{const s=$p(Sa(e.message));return Ko.default.sanitize(s)},[e.message]);return a.createElement(BE,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(HE,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const BE=C.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>U.css`
359
+ `,zE=C.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`,VE=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[i]=l.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),c=e==="pending",u=e==="failed",d=m=>{if(u||c)return;const h=i[m];h&&(s?s({files:i,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return a.createElement(qE,null,a.createElement(ya,{images:i,isPending:c,onClickImage:d}),o)},qE=C.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function KE(e){var n,r;const t=l.useMemo(()=>{const s=zp(Ta(e.message));return Wo.default.sanitize(s)},[e.message]);return a.createElement(WE,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(YE,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const WE=C.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>U.css`
360
360
  color: ${t||e.colors.messageOutgoing.text};
361
361
  background-color: ${n||e.colors.messageOutgoing.background};
362
362
  `}
363
363
  padding: 12px 0;
364
364
  transition: max-width 0.3s;
365
365
  overflow-wrap: break-word;
366
- `,HE=C.default(H)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,GE=({sendingStatus:e})=>{const t=U.useTheme();switch(e){case"pending":return a.createElement(zE,{size:16},a.createElement(J,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(J,{type:"error",color:E.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(J,{type:"done",color:E.themedColor.secondary,size:16}))}},zE=C.default(pt)`margin-bottom:2px;width:16px;height:16px;`,VE=({createdAt:e})=>{const{stringSet:t,format:n}=oe();return e?a.createElement(H,{variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},qE=e=>{const{components:t}=xt.useContext(),{stringSet:n}=oe(),r=()=>{const i=ei(e)?a.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?i:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(t.MediaMessageBody,{...e},i):a.createElement(t.FileMessageBody,{...e},i):e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},i):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,o=s?$t({onActivate:()=>{var i;return(i=e.onClickFailedMessage)==null?void 0:i.call(e)}}):{};return a.createElement("div",{...o,style:{display:"contents",cursor:s?"pointer":"default"}},r())},KE=e=>a.createElement(a.Fragment,null),YE=e=>{const{components:t}=xt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(WE,{$marginBottom:Ln(e.groupType)},a.createElement(jE,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(XE,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},xt=je({template:YE,components:{SendingStatus:GE,SentTime:VE,MessageBody:qE,TextMessageBody:UE,MediaMessageBody:OE,FileMessageBody:kE,MultipleFilesMessageBody:FE,MessageLogs:KE}}),WE=C.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
367
- `,Da=C.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
368
- `,jE=C.default(Da)``,XE=C.default(Da)`margin-top:${ee.BODY_TIME_GAP}px;`,ZE=e=>e.messageType!=="admin"?null:a.createElement(JE,null,a.createElement(H,{variant:"caption2",color:E.themedColor.textMidEmphasis},QE(Ko.default.sanitize(e.message),e.onClickLink))),JE=C.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ee.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,QE=(e,t)=>{try{const n=[];let r=e,s=0;for(;r;){const o=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),i=r.match(/\*\*([^*]+)\*\*/),c=[o&&{match:o,type:"link"},i&&{match:i,type:"bold"}].filter(f=>!!f);if(!c.length){n.push(r);break}const u=c.reduce((f,g)=>g.match.index<f.match.index?g:f),{match:d,type:m}=u,h=d.index;h>0&&n.push(r.slice(0,h)),m==="link"?n.push(a.createElement("a",{key:s++,href:d[2],target:"_blank",rel:zr,onClick:f=>{f.preventDefault();const g=d[2];g&&(t==null||t({url:g}))}},d[1])):m==="bold"&&n.push(a.createElement("strong",{key:s++},d[1])),r=r.slice(h+d[0].length)}return n.filter(o=>o!=="")}catch{return[e]}},eC=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,$a=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(eC({direction:f,currentIndex:h,totalCount:e.length}))}})}},tC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},nC=({event:e,onClick:t,onArrowNavigate:n})=>{if(rC(e))return;const r=tC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},rC=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",es=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?E.themedColor.primary:r?E.themedColor.textDisabled:E.themedColor.textLowEmphasis,m=t?E.themedColor.textHighEmphasis:r?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis;return a.createElement(iC,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>nC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(sC,{"aria-hidden":"true"},a.createElement(J,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(oC,{"aria-hidden":"true",variant:o,color:m},n))});es.displayName="Radio";const sC=C.default.div`width:20px;height:20px;`,oC=C.default(H)`line-height:20px;word-break:break-word;`,iC=C.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${xe}&[aria-disabled='false']{cursor:pointer;}`,aC=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=$a({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(cC,null,a.createElement(ke.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(lC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(es,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},cC=C.default.div`display:flex;flex-direction:column;gap:8px;`,lC=C.default.div`display:flex;flex-direction:column;gap:8px;`,uC=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=oe(),{conversation:i}=re(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],h=$a({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(dC,null,a.createElement(ke.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(ke.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(mC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(es,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...h.getRadioProps(g),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),s&&a.createElement(hC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},dC=C.default.div`display:flex;flex-direction:column;gap:8px;`,mC=C.default.div`display:flex;flex-direction:column;gap:8px;`,hC=C.default(ke.ErrorLabel)``,fC=({value:e,selected:t})=>a.createElement(gC,{$selected:t,"aria-hidden":"true"},pC[e-1]),gC=C.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,pC=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],_C=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=re(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(CC,null,a.createElement(H,{variant:"caption3",color:E.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(bC,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,g=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return a.createElement(vC,{key:d,type:"button",...g.props},a.createElement(EC,{value:m,selected:s||h,src:u}),!!c&&a.createElement(H,{"aria-hidden":"true",color:h?E.themedColor.textHighEmphasis:E.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},EC=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(fC,{value:e,selected:n}):a.createElement(SC,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(yC,null,o)},CC=C.default.div`display:flex;flex-direction:column;gap:8px;`,bC=C.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,vC=C.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${xe}&:not(:disabled):hover span{color:${E.themedColor.textHighEmphasis};}`,yC=C.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${E.color.background200};${Q.dark`
366
+ `,YE=C.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,jE=({sendingStatus:e})=>{const t=U.useTheme();switch(e){case"pending":return a.createElement(XE,{size:16},a.createElement(J,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(J,{type:"error",color:E.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(J,{type:"done",color:E.themedColor.secondary,size:16}))}},XE=C.default(pt)`margin-bottom:2px;width:16px;height:16px;`,ZE=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?a.createElement(B,{variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},JE=e=>{const{components:t}=xt.useContext(),{stringSet:n}=se(),r=()=>{const i=ti(e)?a.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?i:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(t.MediaMessageBody,{...e},i):a.createElement(t.FileMessageBody,{...e},i):e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},i):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,o=s?$t({onActivate:()=>{var i;return(i=e.onClickFailedMessage)==null?void 0:i.call(e)}}):{};return a.createElement("div",{...o,style:{display:"contents",cursor:s?"pointer":"default"}},r())},QE=e=>a.createElement(a.Fragment,null),eC=e=>{const{components:t}=xt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(tC,{$marginBottom:Dn(e.groupType)},a.createElement(nC,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(rC,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},xt=je({template:eC,components:{SendingStatus:jE,SentTime:ZE,MessageBody:JE,TextMessageBody:KE,MediaMessageBody:BE,FileMessageBody:PE,MultipleFilesMessageBody:VE,MessageLogs:QE}}),tC=C.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
367
+ `,Fa=C.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
368
+ `,nC=C.default(Fa)``,rC=C.default(Fa)`margin-top:${ee.BODY_TIME_GAP}px;`,sC=e=>e.messageType!=="admin"?null:a.createElement(oC,null,a.createElement(B,{variant:"caption2",color:E.themedColor.textMidEmphasis},iC(Wo.default.sanitize(e.message),e.onClickLink))),oC=C.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ee.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,iC=(e,t)=>{try{const n=[];let r=e,s=0;for(;r;){const o=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),i=r.match(/\*\*([^*]+)\*\*/),c=[o&&{match:o,type:"link"},i&&{match:i,type:"bold"}].filter(f=>!!f);if(!c.length){n.push(r);break}const u=c.reduce((f,g)=>g.match.index<f.match.index?g:f),{match:d,type:m}=u,h=d.index;h>0&&n.push(r.slice(0,h)),m==="link"?n.push(a.createElement("a",{key:s++,href:d[2],target:"_blank",rel:Vr,onClick:f=>{f.preventDefault();const g=d[2];g&&(t==null||t({url:g}))}},d[1])):m==="bold"&&n.push(a.createElement("strong",{key:s++},d[1])),r=r.slice(h+d[0].length)}return n.filter(o=>o!=="")}catch{return[e]}},aC=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Pa=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(aC({direction:f,currentIndex:h,totalCount:e.length}))}})}},cC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},lC=({event:e,onClick:t,onArrowNavigate:n})=>{if(uC(e))return;const r=cC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},uC=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",ts=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?E.themedColor.primary:r?E.themedColor.textDisabled:E.themedColor.textLowEmphasis,m=t?E.themedColor.textHighEmphasis:r?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis;return a.createElement(hC,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>lC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(dC,{"aria-hidden":"true"},a.createElement(J,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(mC,{"aria-hidden":"true",variant:o,color:m},n))});ts.displayName="Radio";const dC=C.default.div`width:20px;height:20px;`,mC=C.default(B)`line-height:20px;word-break:break-word;`,hC=C.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${xe}&[aria-disabled='false']{cursor:pointer;}`,fC=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=Pa({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(gC,null,a.createElement(Oe.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(pC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(ts,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},gC=C.default.div`display:flex;flex-direction:column;gap:8px;`,pC=C.default.div`display:flex;flex-direction:column;gap:8px;`,_C=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=se(),{conversation:i}=re(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],h=Pa({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(EC,null,a.createElement(Oe.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Oe.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(CC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(ts,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...h.getRadioProps(g),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),s&&a.createElement(bC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},EC=C.default.div`display:flex;flex-direction:column;gap:8px;`,CC=C.default.div`display:flex;flex-direction:column;gap:8px;`,bC=C.default(Oe.ErrorLabel)``,vC=({value:e,selected:t})=>a.createElement(SC,{$selected:t,"aria-hidden":"true"},yC[e-1]),SC=C.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,yC=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],AC=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=re(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(IC,null,a.createElement(B,{variant:"caption3",color:E.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(xC,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,g=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return a.createElement(RC,{key:d,type:"button",...g.props},a.createElement(TC,{value:m,selected:s||h,src:u}),!!c&&a.createElement(B,{"aria-hidden":"true",color:h?E.themedColor.textHighEmphasis:E.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},TC=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(vC,{value:e,selected:n}):a.createElement(wC,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(MC,null,o)},IC=C.default.div`display:flex;flex-direction:column;gap:8px;`,xC=C.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,RC=C.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${xe}&:not(:disabled):hover span{color:${E.themedColor.textHighEmphasis};}`,MC=C.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${E.color.background200};${Q.dark`
369
369
  background-color: ${E.color.background500};
370
370
  `}
371
371
  }
372
- `,SC=C.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,AC=({csatPayload:e})=>a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis},e.title),ir=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:i,setParams:c,error:u,setError:d,followUpItem:m,state:h,validateParams:f,itemProps:g}=dm({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(TC,null,a.createElement(AC,{...g}),t===Je.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(aC,{...g,defaultValue:o,value:i.isResolved,onChange:_=>c({isResolved:_})}),a.createElement(_C,{...g,value:i.csat,onChange:_=>c({csat:_})}),m&&a.createElement(uC,{...g,followUpItem:m,value:i.csatReason,onChange:_=>{c({csatReason:_}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(ke.Separator,null),n({state:h,params:i,validateParams:f})))},TC=C.default.div`display:flex;flex-direction:column;gap:12px;`,IC=e=>{const{stringSet:t}=oe();return rl(e,{title:t.CSAT_TITLE_UNSUBMITTED,question:t.CSAT_RATING_TITLE,cre:{question:t.CSAT_CRE_TITLE,positive_label:t.CSAT_CRE_SOLVED,negative_label:t.CSAT_CRE_NOT_SOLVED},followUp:{question:t.CSAT_REASON_PLACEHOLDER},submit_label:t.CSAT_SUBMIT_LABEL,submitted_label:t.CSAT_TITLE_SUBMITTED})},xC=()=>{const{stringSet:e}=oe();return a.createElement(H,{variant:"body2",color:E.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},RC=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Me(e)},[]),t),MC=e=>{const{conversation:t}=re();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:n,onSubmitCSAT:r,onScrollToBottom:s}=e,{csat:o,csatReason:i,csatExpireAt:c,isResolvedWhenDeterminedByUser:u}=e,d=Nn(),m=IC(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,_]=l.useState(!1),b=l.useRef(!1),v=l.useCallback(()=>{Me(()=>{var M;return(M=f.current)==null?void 0:M.focus()})},[]),{isExpiredNow:p,isRenderableCSAT:S}=mm({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(lm({csat:o,csatPayload:m,isRenderableCSAT:S,isExpiredNow:p,announceStatus:e.announceStatus,onSubmittedAnnounced:v}),!S||!m)return null;const A=()=>{var k;const M=(k=h.current)==null?void 0:k.querySelector('[aria-invalid="true"]');return M?M.getAttribute("role")==="radiogroup"?M.querySelector('[role="radio"]'):M:null},T=m.type===Je.AI_AGENT_CSAT_5||m.type===Je.AI_AGENT_CSAT_5_WITH_CRE||m.type===Je.HELPDESK_CSAT_5?ir:()=>null;return a.createElement(wC,{ref:h},!o&&p?a.createElement(xC,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:M,params:k,validateParams:N})=>M==="submitted"?a.createElement(LC,{ref:f,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(H,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(RC,{onMount:s},a.createElement(kC,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(b.current)return;const x=oi(c);if(!x&&N()){b.current=!0,_(!0);try{await r(k)}catch(L){throw b.current=!1,_(!1),L}}else d(),x||Me(()=>{var L;(L=e.announceError)==null||L.call(e,{type:"csatFormError"},A())})}},a.createElement(H,{variant:"button"},m.csat_submit_label)))}))},wC=C.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,kC=C.default.button`all:unset;width:100%;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.primary};color:${({theme:e})=>e.colors.base.primaryContrastContent};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;cursor:pointer;text-align:center;word-break:break-word;${xe}&:hover{background-color:${E.color.primary.dark};}`,LC=C.default.div`width:100%;box-sizing:border-box;color:${E.themedColor.textHighEmphasis};background-color:${E.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${Q.dark`
372
+ `,wC=C.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,kC=({csatPayload:e})=>a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},e.title),ar=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:i,setParams:c,error:u,setError:d,followUpItem:m,state:h,validateParams:f,itemProps:g}=Em({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(LC,null,a.createElement(kC,{...g}),t===Je.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(fC,{...g,defaultValue:o,value:i.isResolved,onChange:b=>c({isResolved:b})}),a.createElement(AC,{...g,value:i.csat,onChange:b=>c({csat:b})}),m&&a.createElement(_C,{...g,followUpItem:m,value:i.csatReason,onChange:b=>{c({csatReason:b}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Oe.Separator,null),n({state:h,params:i,validateParams:f})))},LC=C.default.div`display:flex;flex-direction:column;gap:12px;`,OC=e=>{const{stringSet:t}=se();return ol(e,{title:t.CSAT_TITLE_UNSUBMITTED,question:t.CSAT_RATING_TITLE,cre:{question:t.CSAT_CRE_TITLE,positive_label:t.CSAT_CRE_SOLVED,negative_label:t.CSAT_CRE_NOT_SOLVED},followUp:{question:t.CSAT_REASON_PLACEHOLDER},submit_label:t.CSAT_SUBMIT_LABEL,submitted_label:t.CSAT_TITLE_SUBMITTED})},DC=()=>{const{stringSet:e}=se();return a.createElement(B,{variant:"body2",color:E.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},NC=({onMount:e,children:t})=>(l.useEffect(()=>{e&&we(e)},[]),t),$C=e=>{const{conversation:t}=re();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:n,onSubmitCSAT:r,onScrollToBottom:s}=e,{csat:o,csatReason:i,csatExpireAt:c,isResolvedWhenDeterminedByUser:u}=e,d=jt(),m=OC(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,b]=l.useState(!1),S=l.useRef(!1),_=l.useCallback(()=>{we(()=>{var M;return(M=f.current)==null?void 0:M.focus()})},[]),{isExpiredNow:p,isRenderableCSAT:y}=Cm({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(pm({csat:o,csatPayload:m,isRenderableCSAT:y,isExpiredNow:p,announceStatus:e.announceStatus,onSubmittedAnnounced:_}),!y||!m)return null;const A=()=>{var L;const M=(L=h.current)==null?void 0:L.querySelector('[aria-invalid="true"]');return M?M.getAttribute("role")==="radiogroup"?M.querySelector('[role="radio"]'):M:null},T=m.type===Je.AI_AGENT_CSAT_5||m.type===Je.AI_AGENT_CSAT_5_WITH_CRE||m.type===Je.HELPDESK_CSAT_5?ar:()=>null;return a.createElement(FC,{ref:h},!o&&p?a.createElement(DC,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:M,params:L,validateParams:N})=>M==="submitted"?a.createElement(UC,{ref:f,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(B,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(NC,{onMount:s},a.createElement(PC,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(S.current)return;const x=ii(c);if(!x&&N()){S.current=!0,b(!0);try{await r(L)}catch(O){throw S.current=!1,b(!1),O}}else d(),x||we(()=>{var O;(O=e.announceError)==null||O.call(e,{type:"csatFormError"},A())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},FC=C.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,PC=C.default.button`all:unset;width:100%;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.primary};color:${({theme:e})=>e.colors.base.primaryContrastContent};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;cursor:pointer;text-align:center;word-break:break-word;${xe}&:hover{background-color:${E.color.primary.dark};}`,UC=C.default.div`width:100%;box-sizing:border-box;color:${E.themedColor.textHighEmphasis};background-color:${E.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${Q.dark`
373
373
  background-color: ${E.color.onlight.textDisabled};
374
374
  `}
375
- `,OC=e=>{const{components:t}=Hn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(NC,{$marginBottom:Ln(e.groupType)},n)},Hn=je({template:OC,components:{AdminMessage:ZE,CSATMessage:MC}}),NC=C.default.div`padding-inline:${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,ts=({title:e,titleId:t,description:n,descriptionId:r,negativeText:s,positiveText:o,onCancel:i,onConfirm:c,buttonLayout:u="horizontal",styles:d})=>{const m=s!==void 0&&i!==void 0,h=o!==void 0&&c!==void 0,f=m?a.createElement(UC,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(H,{variant:"button",color:(d==null?void 0:d.negativeText)??E.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(BC,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(H,{variant:"button",color:(d==null?void 0:d.positiveText)??E.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(DC,null,a.createElement($C,null,a.createElement(H,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??E.themedColor.textHighEmphasis},e)),a.createElement(FC,null,a.createElement(H,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??E.themedColor.textMidEmphasis},n)),a.createElement(PC,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},DC=C.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,$C=C.default.div`padding:24px 24px 16px;`,FC=C.default.div`padding-inline:24px;`,PC=C.default.div`display:flex;flex-direction:${({$buttonLayout:e})=>e==="vertical-full-width"?"column":"row"};align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,UC=C.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background:${({$background:e})=>e??"none"};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,BC=C.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background-color:${({$background:e})=>e??E.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,mn=16,HC=({status:e})=>e===bn.COMPLETED?a.createElement(J,{type:"done-circle",size:mn,color:E.themedColor.textHighEmphasis}):e===bn.CANCELED?a.createElement(J,{type:"stop-circle",size:mn,color:E.themedColor.textLowEmphasis}):a.createElement(pt,{size:mn},a.createElement(J,{type:"spinner",size:mn,color:E.themedColor.textHighEmphasis})),Fa=24,GC=8,zC=40,VC=({task:e,isFirst:t,isLast:n})=>a.createElement(qC,{role:"listitem"},a.createElement(KC,null,a.createElement(wo,{$hidden:t}),a.createElement(YC,null,a.createElement(HC,{status:e.status})),a.createElement(wo,{$hidden:n})),a.createElement(WC,null,a.createElement(H,{as:"div",variant:"body3",color:e.status===bn.CANCELED?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis},e.user_facing_title))),qC=C.default.div`display:flex;gap:4px;`,KC=C.default.div`display:flex;flex-direction:column;align-items:center;width:${Fa}px;flex-shrink:0;`,wo=C.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${E.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,YC=C.default.div`display:flex;height:${Fa}px;align-items:center;justify-content:center;`,WC=C.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${zC}px;padding-block:${GC}px;`,jC=({steward:e,onCancelSteward:t})=>{const{logger:n}=ae(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=yc(e.status);return a.createElement(XC,{$marginBottom:Ln("single")},a.createElement(ZC,null,a.createElement(JC,null,a.createElement(QC,null,a.createElement(H,{as:"div",variant:"caption1",color:E.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(H,{as:"div",variant:"caption4",color:E.themedColor.textLowEmphasis},e.description)),c&&a.createElement(rb,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(J,{type:"stop",size:16,color:o?E.themedColor.textDisabled:E.themedColor.textHighEmphasis}))),a.createElement(eb,null),e.tasks.length===0?u!==Pt.IN_PROGRESS?null:a.createElement(nb,null,a.createElement(pt,{size:16},a.createElement(J,{type:"spinner",size:16,color:E.themedColor.textHighEmphasis}))):a.createElement(tb,{role:"list"},e.tasks.map((d,m)=>a.createElement(VC,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(dt,{portalContainerId:ye.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(ts,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>s(!1),onConfirm:async()=>{s(!1),i(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{i(!1)}}})))},XC=C.default.div`display:flex;flex-direction:column;margin:0 ${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
376
- `,ZC=C.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${E.themedColor.bg_300_500};background-color:${E.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,JC=C.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,QC=C.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,eb=C.default.div`height:1px;margin-block:12px;background-color:${E.themedColor.bg_200_400};`,tb=C.default.div`display:flex;flex-direction:column;`,nb=C.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,rb=C.default.button`width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:none;cursor:pointer;color:${E.themedColor.textHighEmphasis};background-color:${E.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,sb=({className:e,label:t,onClick:n})=>{const{colors:r}=U.useTheme(),{conversation:s}=re(),o={newMessages:s.newMessagesButton()};return a.createElement(ob,{className:e,onClick:n,...o.newMessages.props},a.createElement(H,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(J,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},ob=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;gap:4px;padding:10px 12px 10px 16px;border-radius:24px;background-color:${({theme:e})=>e.colors.base.primary};box-shadow:0 8px 10px 1px rgba(13,13,13,0.12),0 3px 14px 2px rgba(13,13,13,0.08),0 3px 5px -3px rgba(13,13,13,0.04);&:focus{outline:none;}${xe}`,ns=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(ab,{className:n},t&&a.createElement(J,{type:t,size:e,color:E.themedColor.textLowEmphasis}),r&&a.createElement(H,{variant:"body1",color:E.themedColor.textMidEmphasis},r),s),ib=C.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,ab=C.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,cb=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(ns,{icon:t,label:e,...r},n&&a.createElement(lb,{onClick:n.onClick,label:n.label??"Retry"})),lb=({label:e,onClick:t})=>{const{conversation:n}=re();return a.createElement(ub,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(J,{type:"refresh",size:20}),a.createElement(H,{variant:"button",color:E.color.primary.main},e))},ub=C.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${xe}`,db=({iconSize:e=48,className:t})=>a.createElement(pt,{size:e,className:t}),mb=({label:e="No channels",icon:t="chat",...n})=>a.createElement(ns,{icon:t,label:e,...n}),hb=({label:e="No messages",icon:t="message",...n})=>a.createElement(ns,{icon:t,label:e,...n}),fb=e=>{const{components:t}=Gn.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(ib,null,n)},Gn=je({template:fb,components:{Loading:db,Error:cb,NoChannels:mb,NoMessages:hb}}),Ut=e=>{const{Template:t}=Gn.useContext();return a.createElement(t,{...e})},gb=[0,150,450];function pb({enabled:e}){const{state:t,actions:n}=ua(),r=l.useRef(0),s=l.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,l.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const i=gb.map(c=>setTimeout(()=>{Me(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const _b=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=oe();return a.createElement(Eb,{id:`${Ge}-date-separator`,role:n,style:r,className:e},a.createElement(H,{variant:"caption4",color:E.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},Eb=C.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Cb=({className:e,style:t,onClick:n})=>{const{conversation:r}=re(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(bb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(J,{size:24,type:"chevron-down",color:E.color.primary.main}),s.scrollToBottom.descriptionNode??null)},bb=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:24px;box-shadow:0 2px 8px 0 rgba(0,0,0,0.08),0 4px 6px 0 rgba(0,0,0,0.12);${Q.light`
375
+ `,BC=e=>{const{components:t}=Gn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(HC,{$marginBottom:Dn(e.groupType)},n)},Gn=je({template:BC,components:{AdminMessage:sC,CSATMessage:$C}}),HC=C.default.div`padding-inline:${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,ns=({title:e,titleId:t,description:n,descriptionId:r,negativeText:s,positiveText:o,onCancel:i,onConfirm:c,buttonLayout:u="horizontal",styles:d})=>{const m=s!==void 0&&i!==void 0,h=o!==void 0&&c!==void 0,f=m?a.createElement(KC,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.negativeText)??E.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(WC,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.positiveText)??E.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(GC,null,a.createElement(zC,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??E.themedColor.textHighEmphasis},e)),a.createElement(VC,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??E.themedColor.textMidEmphasis},n)),a.createElement(qC,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},GC=C.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,zC=C.default.div`padding:24px 24px 16px;`,VC=C.default.div`padding-inline:24px;`,qC=C.default.div`display:flex;flex-direction:${({$buttonLayout:e})=>e==="vertical-full-width"?"column":"row"};align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,KC=C.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background:${({$background:e})=>e??"none"};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,WC=C.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background-color:${({$background:e})=>e??E.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,hn=16,YC=({status:e})=>e===Sn.COMPLETED?a.createElement(J,{type:"done-circle",size:hn,color:E.themedColor.textHighEmphasis}):e===Sn.CANCELED?a.createElement(J,{type:"stop-circle",size:hn,color:E.themedColor.textLowEmphasis}):a.createElement(pt,{size:hn},a.createElement(J,{type:"spinner",size:hn,color:E.themedColor.textHighEmphasis})),Ua=24,jC=8,XC=40,ZC=({task:e,isFirst:t,isLast:n})=>a.createElement(JC,{role:"listitem"},a.createElement(QC,null,a.createElement(ko,{$hidden:t}),a.createElement(eb,null,a.createElement(YC,{status:e.status})),a.createElement(ko,{$hidden:n})),a.createElement(tb,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===Sn.CANCELED?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis},e.user_facing_title))),JC=C.default.div`display:flex;gap:4px;`,QC=C.default.div`display:flex;flex-direction:column;align-items:center;width:${Ua}px;flex-shrink:0;`,ko=C.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${E.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,eb=C.default.div`display:flex;height:${Ua}px;align-items:center;justify-content:center;`,tb=C.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${XC}px;padding-block:${jC}px;`,nb=({steward:e,onCancelSteward:t})=>{const{logger:n}=le(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=Ac(e.status);return a.createElement(rb,{$marginBottom:Dn("single")},a.createElement(sb,null,a.createElement(ob,null,a.createElement(ib,null,a.createElement(B,{as:"div",variant:"caption1",color:E.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(B,{as:"div",variant:"caption4",color:E.themedColor.textLowEmphasis},e.description)),c&&a.createElement(ub,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(J,{type:"stop",size:16,color:o?E.themedColor.textDisabled:E.themedColor.textHighEmphasis}))),a.createElement(ab,null),e.tasks.length===0?u!==Pt.IN_PROGRESS?null:a.createElement(lb,null,a.createElement(pt,{size:16},a.createElement(J,{type:"spinner",size:16,color:E.themedColor.textHighEmphasis}))):a.createElement(cb,{role:"list"},e.tasks.map((d,m)=>a.createElement(ZC,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(dt,{portalContainerId:Se.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(ns,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>s(!1),onConfirm:async()=>{s(!1),i(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{i(!1)}}})))},rb=C.default.div`display:flex;flex-direction:column;margin:0 ${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
376
+ `,sb=C.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${E.themedColor.bg_300_500};background-color:${E.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,ob=C.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,ib=C.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,ab=C.default.div`height:1px;margin-block:12px;background-color:${E.themedColor.bg_200_400};`,cb=C.default.div`display:flex;flex-direction:column;`,lb=C.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,ub=C.default.button`width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:none;cursor:pointer;color:${E.themedColor.textHighEmphasis};background-color:${E.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,db=({className:e,label:t,onClick:n})=>{const{colors:r}=U.useTheme(),{conversation:s}=re(),o={newMessages:s.newMessagesButton()};return a.createElement(mb,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(J,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},mb=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;gap:4px;padding:10px 12px 10px 16px;border-radius:24px;background-color:${({theme:e})=>e.colors.base.primary};box-shadow:0 8px 10px 1px rgba(13,13,13,0.12),0 3px 14px 2px rgba(13,13,13,0.08),0 3px 5px -3px rgba(13,13,13,0.04);&:focus{outline:none;}${xe}`,rs=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(fb,{className:n},t&&a.createElement(J,{type:t,size:e,color:E.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:E.themedColor.textMidEmphasis},r),s),hb=C.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,fb=C.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,gb=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(rs,{icon:t,label:e,...r},n&&a.createElement(pb,{onClick:n.onClick,label:n.label??"Retry"})),pb=({label:e,onClick:t})=>{const{conversation:n}=re();return a.createElement(_b,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(J,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:E.color.primary.main},e))},_b=C.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${xe}`,Eb=({iconSize:e=48,className:t})=>a.createElement(pt,{size:e,className:t}),Cb=({label:e="No channels",icon:t="chat",...n})=>a.createElement(rs,{icon:t,label:e,...n}),bb=({label:e="No messages",icon:t="message",...n})=>a.createElement(rs,{icon:t,label:e,...n}),vb=e=>{const{components:t}=zn.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(hb,null,n)},zn=je({template:vb,components:{Loading:Eb,Error:gb,NoChannels:Cb,NoMessages:bb}}),Ut=e=>{const{Template:t}=zn.useContext();return a.createElement(t,{...e})},Sb=[0,150,450];function yb({enabled:e}){const{state:t,actions:n}=ma(),r=l.useRef(0),s=l.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,l.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const i=Sb.map(c=>setTimeout(()=>{we(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const Ab=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=se();return a.createElement(Tb,{id:`${Ge}-date-separator`,role:n,style:r,className:e},a.createElement(B,{variant:"caption4",color:E.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},Tb=C.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Ib=({className:e,style:t,onClick:n})=>{const{conversation:r}=re(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(xb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(J,{size:24,type:"chevron-down",color:E.color.primary.main}),s.scrollToBottom.descriptionNode??null)},xb=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:24px;box-shadow:0 2px 8px 0 rgba(0,0,0,0.08),0 4px 6px 0 rgba(0,0,0,0.12);${Q.light`
377
377
  background-color: ${E.color.background50};
378
378
  &:hover {
379
379
  background-color: ${E.color.background100};
@@ -397,18 +397,18 @@
397
397
  }
398
398
 
399
399
  ${xe}
400
- `,vb=()=>null,zn=je({template:vb,components:{DateSeparator:_b,ScrollToBottomButton:Cb}}),yb=()=>{const{stringSet:e,format:t}=oe(),{agentPreviewConfigs:n={},aiAgentId:r}=ae(),{aiAgentInfo:s}=Oe(),{messageSource:o}=Ae(),{Template:i}=_t.useContext(),{components:c}=zn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=ug(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:pa(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!at.isSameDay(h.createdAt,(f==null?void 0:f.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:a.createElement(a.Fragment,null,a.createElement(c.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:f==null?void 0:f.createdAt}),u.map((g,_)=>{const b=_===u.length-1,v=m.length!==d.length,p=u.length===1?"single":_===0?"top":b||v?"bottom":"middle",S=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:_,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:(s==null?void 0:s.nickname)||"",message:g.message,messageFormat:"markdown",time:t(S,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},a.createElement(i,{messageType:"user",message:g.message,sender:s,groupType:p,createdAt:S,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:b&&!v,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{o.sendUserMessage({message:A})}}))}))}},Sb=()=>{const{messageSource:e,scrollSource:t}=Ae();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},ko="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",Ab=({style:e})=>{const{stringSet:t}=oe(),{handlers:n}=ae(),{conversation:r}=re();return Ur("powered-by")?a.createElement(Tb,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Ib,{variant:"caption2",forwardedAs:"a",href:ko,...r.poweredByLink().props,rel:zr,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:ko})}},"Sendbird")):null},Tb=C.default(H)`color:${E.themedColor.textLowEmphasis};text-align:center;`,Ib=C.default(H)`color:${E.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,xb=()=>{var c;const{stringSet:e}=oe(),{conversation:t}=re(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Ae(),o=Fe(n.channel),i=l.useRef(o);return l.useEffect(()=>{if(!i.current&&o){const m=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(m)}i.current=o},[o,s.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!o?null:a.createElement(Rb,null,a.createElement(Mb,{variant:"button",color:E.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},Rb=C.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Mb=C.default(H)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${E.color.background50};border:1px solid ${E.color.onlight.textDisabled};${Q.dark`
400
+ `,Rb=()=>null,Vn=je({template:Rb,components:{DateSeparator:Ab,ScrollToBottomButton:Ib}}),Mb=()=>{const{stringSet:e,format:t}=se(),{agentPreviewConfigs:n={},aiAgentId:r}=le(),{aiAgentInfo:s}=Ne(),{messageSource:o}=Ae(),{Template:i}=_t.useContext(),{components:c}=Vn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=_g(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:Ea(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!at.isSameDay(h.createdAt,(f==null?void 0:f.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:a.createElement(a.Fragment,null,a.createElement(c.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:f==null?void 0:f.createdAt}),u.map((g,b)=>{const S=b===u.length-1,_=m.length!==d.length,p=u.length===1?"single":b===0?"top":S||_?"bottom":"middle",y=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:b,role:"listitem",tabIndex:-1,"aria-label":Nt({sender:(s==null?void 0:s.nickname)||"",message:g.message,messageFormat:"markdown",time:t(y,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},a.createElement(i,{messageType:"user",message:g.message,sender:s,groupType:p,createdAt:y,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:S&&!_,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{o.sendUserMessage({message:A})}}))}))}},wb=()=>{const{messageSource:e,scrollSource:t}=Ae();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Lo="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",kb=({style:e})=>{const{stringSet:t}=se(),{handlers:n}=le(),{conversation:r}=re();return Br("powered-by")?a.createElement(Lb,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Ob,{variant:"caption2",forwardedAs:"a",href:Lo,...r.poweredByLink().props,rel:Vr,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:Lo})}},"Sendbird")):null},Lb=C.default(B)`color:${E.themedColor.textLowEmphasis};text-align:center;`,Ob=C.default(B)`color:${E.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,Db=()=>{var c;const{stringSet:e}=se(),{conversation:t}=re(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Ae(),o=He(n.channel),i=l.useRef(o);return l.useEffect(()=>{if(!i.current&&o){const m=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(m)}i.current=o},[o,s.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!o?null:a.createElement(Nb,null,a.createElement($b,{variant:"button",color:E.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},Nb=C.default.div`display:flex;justify-content:center;margin-bottom:16px;`,$b=C.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${E.color.background50};border:1px solid ${E.color.onlight.textDisabled};${Q.dark`
401
401
  background-color: ${E.color.background700};
402
402
  border-color: ${E.color.ondark.textLowEmphasis};
403
403
  `}
404
- `,wb=({statsCallbacks:e,...t})=>(Sm(e),a.createElement(jC,{...t})),kb=(e,t,n)=>t&&Re.isWelcomeMessage(e,n)&&Re.isWelcomeMessage(t,n)?!1:!dc.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Lb=()=>{var G;const{Template:e}=xt.useContext(),{Template:t}=_t.useContext(),{Template:n}=Hn.useContext(),{components:r}=zn.useContext(),{stringSet:s,format:o}=oe(),{announceError:i,announceStatus:c}=ot(),{file:u}=re().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:_}=ae(),{userSession:b,aiAgentInfo:v,connectionError:p}=Oe(),{conversationStatsEnabled:S=!0,conversation:A,channelSource:T,messageSource:M,scrollSource:k,state:{input:N,streamAnimation:x}}=Ae(),{filteredMessages:L,shouldShowOriginalDate:z,renderAgentPreviewWelcomeMessages:D}=yb(),W=xi(T.channel),K=ym({enabled:S}),[w,V]=l.useState(null),[P,q]=l.useState(null);l.useEffect(()=>{k.actions.onTypingIndicatorUpdate(!!W)},[!!W,k.actions.onTypingIndicatorUpdate]),Sb(),pb({enabled:M.initialized&&M.messages.length>0});const ue=(I,Y=!1)=>{var te;return Y?v:((te=T.channel)==null?void 0:te.members.find(se=>se.userId===I.sender.userId))??I.sender},Te=I=>{if(I.sendingStatus==="failed"&&!N.disabled)return()=>q(I)},B=({message:I,index:Y})=>{const te=Sc(I),se=L[Y-1],Ne=L[Y+1],He=L[L.length-1],$=I===He,R=st(I,v.userId),O=!(v.isUserFeedbackEnabled&&R&&!Re.isWelcomeMessage(I)),F=Ac(I,se,Ne,O),j=kb(I,se,v.userId)&&z(Y),X=Ee=>{V({files:Ee.files.map(Ie=>({...Ie,timestamp:I.createdAt})),index:Ee.index})},ne=Ee=>{X({files:[Ee],index:0})},Z=j?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:I.createdAt}):null,ge={data:I.data,maxBodyWidth:_.expanded?ee.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:I.extendedMessagePayload,createdAt:I.createdAt,groupType:F,onClickMedia:ne,onClickMediaFiles:X,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:Ee=>g.onClickLink({url:Ee.link}),onClickLink:g.onClickLink},Xe=()=>{if(Le.isOutgoing(I,b.userId))return"outgoingmessage";if(Le.isIncoming(I,b.userId))return"incomingmessage"},ie=I.createdAt!=null&&I.createdAt!==0?o(I.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,de=(()=>{var Ie,ve,De,Pe,me,Ue;const Ee=(Ie=I.message)==null?void 0:Ie.trim();if(I.isFileMessage()){const Be=((ve=I.name)==null?void 0:ve.trim())||"";return Qn({markdownText:Ee,comparisonText:Be,plainText:u.label(Be,I.type)})}if(I.isMultipleFilesMessage()){const Be=((me=(Pe=(De=I.fileInfoList)==null?void 0:De[0])==null?void 0:Pe.fileName)==null?void 0:me.trim())||"",nn=((Ue=I.fileInfoList)==null?void 0:Ue.length)??0;return Qn({markdownText:Ee,comparisonText:Be,plainText:nn>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(nn):""})}return Ee?Qn({markdownText:Ee}):Ni("")})(),pe=(()=>{if(Le.isAdmin(I))return Dt({message:de.text,messageFormat:de.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Le.isOutgoing(I,b.userId))return Dt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:de.text,messageFormat:"plain",time:ie,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Le.isIncoming(I,b.userId))return Dt({sender:ue(I,R).nickname,message:de.text,messageFormat:de.format,time:ie,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),_e=(()=>{var Ee,Ie;if(Le.isAdmin(I))return Le.isCSAT(I)?A?a.createElement(n,{...ge,...A,isResolvedWhenDeterminedByUser:tl(A),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async ve=>{var De;await((De=T.channel)==null?void 0:De.submitCSAT(ve))},onScrollToBottom:()=>k.actions.scrollToBottom()}):null:a.createElement(n,{...ge,messageType:"admin",message:I.message});if(Le.isSteward(I)){const ve=K({message:I,isBotMessage:R,aiAgentUserId:v.userId});return a.createElement(wb,{steward:I.extendedMessagePayload.steward,statsCallbacks:ve,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:I.channelUrl,messageId:I.messageId})}})}if(Le.isOutgoing(I,b.userId)){const ve={...ge,message:I.message,sender:ue(I),sendingStatus:I.sendingStatus,onClickFailedMessage:Te(I)};if(I.isUserMessage())return a.createElement(e,{messageType:"user",...ve});if(I.isFileMessage()){const[De,Pe]=((Ee=I.metaArrays.find(me=>me.key===Xo))==null?void 0:Ee.value)??[];return a.createElement(e,{messageType:"file",file:I,metadata:{aspectRatio:De&&Pe?`${De}/${Pe}`:"1/1",localFile:(Ie=I.messageParams)==null?void 0:Ie.file},...ve})}if(I.isMultipleFilesMessage()){const{files:De,metadata:Pe}=vo(I);return a.createElement(e,{messageType:"multipleFiles",files:De,metadata:Pe,...ve})}}if(Le.isIncoming(I,b.userId)){const ve=Re.isStreaming(I),De=K({message:I,isBotMessage:R,aiAgentUserId:v.userId}),Pe={...ge,statsCallbacks:De,sender:ue(I,R),message:I.message,suggestedRepliesVisible:$,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:R,isStreaming:ve,isHandedOff:rt(T.channel),isConversationClosed:Fe(T.channel),isFeedbackEnabled:v.isUserFeedbackEnabled,isFeedbackCommentEnabled:v.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:me})=>{M.sendUserMessage({message:me})},onRequestMessageTemplate:async me=>{const{template:Ue}=await f.aiAgent.getMessageTemplate(me);return m.template.set(me,Ue),Ue},onGetCachedMessageTemplate:me=>m.template.get(me),onHandleTemplateInternalAction:me=>{if(me.type==="internal"&&me.internalData){const{method:Ue,payload:Be}=me.internalData;Ue==="message.send"&&(Be!=null&&Be.message)&&M.sendUserMessage({message:Be.message})}},onFeedbackUpdate:me=>{const Ue={messageId:I.messageId,channelUrl:I.channelUrl};if(!me)return f.aiAgent.deleteMessageFeedback(Ue);const Be={...Ue,rating:d_(me.rating),comment:me.comment};return Re.hasFeedback(I)?f.aiAgent.updateMessageFeedback(Be):f.aiAgent.createMessageFeedback(Be)},onSubmitForm:({key:me,data:Ue})=>f.aiAgent.submitForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:me,formData:Ue}),onCancelForm:({key:me})=>f.aiAgent.cancelForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:me}),onSendChallengeAction:({key:me,requestId:Ue,action:Be,data:nn})=>f.aiAgent.sendChallengeAction({channelUrl:I.channelUrl,key:me,requestId:Ue,action:Be,data:nn}),onStreamAnimationStart:()=>{x.start(I.messageId)},onStreamAnimationProgress:()=>{k.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{x.stop(I.messageId),k.actions.onStreamingUpdate(!1)}};if(I.isUserMessage())return a.createElement(t,{messageType:"user",...Pe});if(I.isFileMessage())return a.createElement(t,{messageType:"file",file:I,...Pe});if(I.isMultipleFilesMessage()){const{files:me}=vo(I);return a.createElement(t,{messageType:"multipleFiles",files:me,...Pe})}}})();return a.createElement(l.Fragment,{key:te},Z,a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":pe,"data-message-listitem":"","data-layout-id":Xe()},_e))};return a.createElement(Ob,{id:`${Ge}-message-list`},a.createElement(Ug,{ref:k.ref,onScroll:k.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:L,renderMessage:B,onLoadPrev:M.loadPrevious,onLoadNext:M.loadNext,depsForResetScrollPositionToBottom:[M.initialized,M.messages.length!==0],bottomSpacerHeight:k.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!M.initialized||!T.channel,empty:L.length===0&&!W,error:!!(p||T.error),LoadingComponent:a.createElement(Ut,{type:"loading"}),EmptyComponent:(()=>{const I=D();return I?a.createElement("div",{style:{width:"100%"}},I):a.createElement(Ut,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Ut,{type:"error",label:(p==null?void 0:p.message)??((G=T.error)==null?void 0:G.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Ab,{style:{marginTop:16}}),D()),messageBottomArea:a.createElement(a.Fragment,null,W&&a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:W.user.nickname,message:s.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:L.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:W.isBot,sender:W.user,thinkingMessage:W.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(xb,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&k.state.isAwayFromBottom&&M.newMessages.length>0&&a.createElement(Nb,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(M.newMessages),onClick:()=>k.actions.scrollToBottom()}),k.state.isAwayFromBottom&&M.newMessages.length===0&&!W&&a.createElement(r.ScrollToBottomButton,{onClick:()=>k.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),w&&a.createElement(Kg,{files:w.files,initialIndex:w.index,onClose:()=>V(null),visible:!0}),P&&a.createElement(lt,{visible:!0,onClose:()=>q(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(lt.ActionItem,{onClick:()=>{M.resendMessage(P),q(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(lt.ActionItem,{destructive:!0,onClick:()=>{M.deleteMessage(P),q(null)}},s.FAILED_MESSAGE_REMOVE)))},Ob=C.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Nb=C.default(sb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Db=()=>a.createElement(Lb,null),Lo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Pa=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:f=_=>_.default,style:g={}})=>{const{iconColor:_="#000000",textColor:b="#000000",highlightColor:v=Bt.DEFAULT_PRIMARY}=g;return a.createElement(Oo,null,m,e&&a.createElement(Oo,null,a.createElement(wn,null,a.createElement(Ot,null,a.createElement(J,{size:16,type:"actionbook",color:_})),a.createElement(hn,{$clickable:!!o,$highlightColor:v,variant:"body2",color:b,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(p=>a.createElement(_n,{key:p.key},a.createElement(Ot,null,a.createElement(J,{size:16,type:"function",color:_})),a.createElement(wn,null,a.createElement(hn,{$clickable:!!i,$highlightColor:v,variant:"body2",color:b,onClick:()=>i==null?void 0:i(p),maxTextLines:1},p.name),c&&a.createElement($b,{role:"button",onClick:()=>c==null?void 0:c(p)},a.createElement(H,{variant:"body2",color:v},"View details"),a.createElement(J,{type:"chevron-right",size:16,color:v}))))),n==null?void 0:n.map(p=>a.createElement(_n,{key:p.id},a.createElement(Ot,null,f({default:a.createElement(J,{size:16,type:Lo[p.source_type]??Lo.snippet,color:_}),sourceType:p.source_type})),a.createElement(hn,{$clickable:!!u,$highlightColor:v,variant:"body2",color:b,onClick:()=>u==null?void 0:u(p),maxTextLines:1},p.preview_title))),r==null?void 0:r.map(p=>a.createElement(_n,{key:p.key},a.createElement(Ot,null,a.createElement(J,{size:16,type:"template",color:_})),a.createElement(hn,{$clickable:!!d,$highlightColor:v,variant:"body2",color:b,onClick:()=>d==null?void 0:d(p),maxTextLines:1},p.name))),!!(s!=null&&s.length)&&a.createElement(Fb,null,a.createElement(Ot,null,a.createElement(J,{size:16,type:"activity",color:_})),a.createElement(Pb,{variant:"body2",color:b},s.map(p=>p.replace(/_/g," ")).join(" · "))),h)},Ua=C.default(H)`font-weight:400;`,hn=C.default(Ua)`${({$clickable:e,$highlightColor:t})=>e&&U.css`
404
+ `,Fb=({statsCallbacks:e,...t})=>(wm(e),a.createElement(nb,{...t})),Pb=(e,t,n)=>t&&Me.isWelcomeMessage(e,n)&&Me.isWelcomeMessage(t,n)?!1:!hc.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Ub=()=>{var K;const{Template:e}=xt.useContext(),{Template:t}=_t.useContext(),{Template:n}=Gn.useContext(),{components:r}=Vn.useContext(),{stringSet:s,format:o}=se(),{announceError:i,announceStatus:c}=ot(),{file:u}=re().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:b}=le(),{userSession:S,aiAgentInfo:_,connectionError:p}=Ne(),{conversationStatsEnabled:y=!0,conversation:A,channelSource:T,messageSource:M,scrollSource:L,state:{input:N,streamAnimation:x}}=Ae(),{filteredMessages:O,shouldShowOriginalDate:H,renderAgentPreviewWelcomeMessages:F}=Mb(),Y=Mi(T.channel),q=Mm({enabled:y}),[k,G]=l.useState(null),[P,V]=l.useState(null);l.useEffect(()=>{L.actions.onTypingIndicatorUpdate(!!Y)},[!!Y,L.actions.onTypingIndicatorUpdate]),wb(),yb({enabled:M.initialized&&M.messages.length>0});const me=(R,X=!1)=>{var ne;return X?_:((ne=T.channel)==null?void 0:ne.members.find(oe=>oe.userId===R.sender.userId))??R.sender},Ie=R=>{if(R.sendingStatus==="failed"&&!N.disabled)return()=>V(R)},j=({message:R,index:X})=>{const ne=Tc(R),oe=O[X-1],Re=O[X+1],Le=O[O.length-1],$=R===Le,I=st(R,_.userId),w=!(_.isUserFeedbackEnabled&&I&&!Me.isWelcomeMessage(R)),D=Ic(R,oe,Re,w),z=Pb(R,oe,_.userId)&&H(X),W=Ce=>{G({files:Ce.files.map(Te=>({...Te,timestamp:R.createdAt})),index:Ce.index})},te=Ce=>{W({files:[Ce],index:0})},Z=z?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:R.createdAt}):null,pe={data:R.data,maxBodyWidth:b.expanded?ee.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:R.extendedMessagePayload,createdAt:R.createdAt,groupType:D,onClickMedia:te,onClickMediaFiles:W,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:Ce=>g.onClickLink({url:Ce.link}),onClickLink:g.onClickLink},Xe=()=>{if(De.isOutgoing(R,S.userId))return"outgoingmessage";if(De.isIncoming(R,S.userId))return"incomingmessage"},ce=R.createdAt!=null&&R.createdAt!==0?o(R.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,he=(()=>{var Te,ve,$e,Pe,fe,Ue;const Ce=(Te=R.message)==null?void 0:Te.trim();if(R.isFileMessage()){const Be=((ve=R.name)==null?void 0:ve.trim())||"";return er({markdownText:Ce,comparisonText:Be,plainText:u.label(Be,R.type)})}if(R.isMultipleFilesMessage()){const Be=((fe=(Pe=($e=R.fileInfoList)==null?void 0:$e[0])==null?void 0:Pe.fileName)==null?void 0:fe.trim())||"",rn=((Ue=R.fileInfoList)==null?void 0:Ue.length)??0;return er({markdownText:Ce,comparisonText:Be,plainText:rn>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(rn):""})}return Ce?er({markdownText:Ce}):$i("")})(),_e=(()=>{if(De.isAdmin(R))return Nt({message:he.text,messageFormat:he.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(De.isOutgoing(R,S.userId))return Nt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:he.text,messageFormat:"plain",time:ce,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(De.isIncoming(R,S.userId))return Nt({sender:me(R,I).nickname,message:he.text,messageFormat:he.format,time:ce,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),Ee=(()=>{var Ce,Te;if(De.isAdmin(R))return De.isCSAT(R)?A?a.createElement(n,{...pe,...A,isResolvedWhenDeterminedByUser:rl(A),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async ve=>{var $e;await(($e=T.channel)==null?void 0:$e.submitCSAT(ve))},onScrollToBottom:()=>L.actions.scrollToBottom()}):null:a.createElement(n,{...pe,messageType:"admin",message:R.message});if(De.isSteward(R)){const ve=q({message:R,isBotMessage:I,aiAgentUserId:_.userId});return a.createElement(Fb,{steward:R.extendedMessagePayload.steward,statsCallbacks:ve,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:R.channelUrl,messageId:R.messageId})}})}if(De.isOutgoing(R,S.userId)){const ve={...pe,message:R.message,sender:me(R),sendingStatus:R.sendingStatus,onClickFailedMessage:Ie(R)};if(R.isUserMessage())return a.createElement(e,{messageType:"user",...ve});if(R.isFileMessage()){const[$e,Pe]=((Ce=R.metaArrays.find(fe=>fe.key===Zo))==null?void 0:Ce.value)??[];return a.createElement(e,{messageType:"file",file:R,metadata:{aspectRatio:$e&&Pe?`${$e}/${Pe}`:"1/1",localFile:(Te=R.messageParams)==null?void 0:Te.file},...ve})}if(R.isMultipleFilesMessage()){const{files:$e,metadata:Pe}=So(R);return a.createElement(e,{messageType:"multipleFiles",files:$e,metadata:Pe,...ve})}}if(De.isIncoming(R,S.userId)){const ve=Me.isStreaming(R),$e=q({message:R,isBotMessage:I,aiAgentUserId:_.userId}),Pe={...pe,statsCallbacks:$e,sender:me(R,I),message:R.message,suggestedRepliesVisible:$,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:I,isStreaming:ve,isHandedOff:rt(T.channel),isConversationClosed:He(T.channel),isFeedbackEnabled:_.isUserFeedbackEnabled,isFeedbackCommentEnabled:_.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:fe})=>{M.sendUserMessage({message:fe})},onRequestMessageTemplate:async fe=>{const{template:Ue}=await f.aiAgent.getMessageTemplate(fe);return m.template.set(fe,Ue),Ue},onGetCachedMessageTemplate:fe=>m.template.get(fe),onHandleTemplateInternalAction:fe=>{if(fe.type==="internal"&&fe.internalData){const{method:Ue,payload:Be}=fe.internalData;Ue==="message.send"&&(Be!=null&&Be.message)&&M.sendUserMessage({message:Be.message})}},onFeedbackUpdate:fe=>{const Ue={messageId:R.messageId,channelUrl:R.channelUrl};if(!fe)return f.aiAgent.deleteMessageFeedback(Ue);const Be={...Ue,rating:E_(fe.rating),comment:fe.comment};return Me.hasFeedback(R)?f.aiAgent.updateMessageFeedback(Be):f.aiAgent.createMessageFeedback(Be)},onSubmitForm:({key:fe,data:Ue})=>f.aiAgent.submitForm({messageId:R.messageId,channelUrl:R.channelUrl,formKey:fe,formData:Ue}),onCancelForm:({key:fe})=>f.aiAgent.cancelForm({messageId:R.messageId,channelUrl:R.channelUrl,formKey:fe}),onSendChallengeAction:({key:fe,requestId:Ue,action:Be,data:rn})=>f.aiAgent.sendChallengeAction({channelUrl:R.channelUrl,key:fe,requestId:Ue,action:Be,data:rn}),onStreamAnimationStart:()=>{x.start(R.messageId)},onStreamAnimationProgress:()=>{L.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{x.stop(R.messageId),L.actions.onStreamingUpdate(!1)}};if(R.isUserMessage())return a.createElement(t,{messageType:"user",...Pe});if(R.isFileMessage())return a.createElement(t,{messageType:"file",file:R,...Pe});if(R.isMultipleFilesMessage()){const{files:fe}=So(R);return a.createElement(t,{messageType:"multipleFiles",files:fe,...Pe})}}})();return a.createElement(l.Fragment,{key:ne},Z,a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":_e,"data-message-listitem":"","data-layout-id":Xe()},Ee))};return a.createElement(Bb,{id:`${Ge}-message-list`},a.createElement(Kg,{ref:L.ref,onScroll:L.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:O,renderMessage:j,onLoadPrev:M.loadPrevious,onLoadNext:M.loadNext,depsForResetScrollPositionToBottom:[M.initialized,M.messages.length!==0],bottomSpacerHeight:L.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!M.initialized||!T.channel,empty:O.length===0&&!Y,error:!!(p||T.error),LoadingComponent:a.createElement(Ut,{type:"loading"}),EmptyComponent:(()=>{const R=F();return R?a.createElement("div",{style:{width:"100%"}},R):a.createElement(Ut,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Ut,{type:"error",label:(p==null?void 0:p.message)??((K=T.error)==null?void 0:K.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(kb,{style:{marginTop:16}}),F()),messageBottomArea:a.createElement(a.Fragment,null,Y&&a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Nt({sender:Y.user.nickname,message:s.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:O.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:Y.isBot,sender:Y.user,thinkingMessage:Y.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(Db,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&L.state.isAwayFromBottom&&M.newMessages.length>0&&a.createElement(Hb,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(M.newMessages),onClick:()=>L.actions.scrollToBottom()}),L.state.isAwayFromBottom&&M.newMessages.length===0&&!Y&&a.createElement(r.ScrollToBottomButton,{onClick:()=>L.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),k&&a.createElement(Qg,{files:k.files,initialIndex:k.index,onClose:()=>G(null),visible:!0}),P&&a.createElement(lt,{visible:!0,onClose:()=>V(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(lt.ActionItem,{onClick:()=>{M.resendMessage(P),V(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(lt.ActionItem,{destructive:!0,onClick:()=>{M.deleteMessage(P),V(null)}},s.FAILED_MESSAGE_REMOVE)))},Bb=C.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Hb=C.default(db)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Gb=()=>a.createElement(Ub,null),Oo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Ba=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:f=b=>b.default,style:g={}})=>{const{iconColor:b="#000000",textColor:S="#000000",highlightColor:_=Bt.DEFAULT_PRIMARY}=g;return a.createElement(Do,null,m,e&&a.createElement(Do,null,a.createElement(Ln,null,a.createElement(Ot,null,a.createElement(J,{size:16,type:"actionbook",color:b})),a.createElement(fn,{$clickable:!!o,$highlightColor:_,variant:"body2",color:S,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(p=>a.createElement(Cn,{key:p.key},a.createElement(Ot,null,a.createElement(J,{size:16,type:"function",color:b})),a.createElement(Ln,null,a.createElement(fn,{$clickable:!!i,$highlightColor:_,variant:"body2",color:S,onClick:()=>i==null?void 0:i(p),maxTextLines:1},p.name),c&&a.createElement(zb,{role:"button",onClick:()=>c==null?void 0:c(p)},a.createElement(B,{variant:"body2",color:_},"View details"),a.createElement(J,{type:"chevron-right",size:16,color:_}))))),n==null?void 0:n.map(p=>a.createElement(Cn,{key:p.id},a.createElement(Ot,null,f({default:a.createElement(J,{size:16,type:Oo[p.source_type]??Oo.snippet,color:b}),sourceType:p.source_type})),a.createElement(fn,{$clickable:!!u,$highlightColor:_,variant:"body2",color:S,onClick:()=>u==null?void 0:u(p),maxTextLines:1},p.preview_title))),r==null?void 0:r.map(p=>a.createElement(Cn,{key:p.key},a.createElement(Ot,null,a.createElement(J,{size:16,type:"template",color:b})),a.createElement(fn,{$clickable:!!d,$highlightColor:_,variant:"body2",color:S,onClick:()=>d==null?void 0:d(p),maxTextLines:1},p.name))),!!(s!=null&&s.length)&&a.createElement(Vb,null,a.createElement(Ot,null,a.createElement(J,{size:16,type:"activity",color:b})),a.createElement(qb,{variant:"body2",color:S},s.map(p=>p.replace(/_/g," ")).join(" · "))),h)},Ha=C.default(B)`font-weight:400;`,fn=C.default(Ha)`${({$clickable:e,$highlightColor:t})=>e&&U.css`
405
405
  cursor: pointer;
406
406
  text-decoration: underline;
407
407
  &:hover {
408
408
  color: ${t};
409
409
  }
410
410
  `}
411
- `,Ot=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,wn=C.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,$b=C.default(wn)`cursor:pointer;gap:4px;`,_n=C.default(wn)`flex-direction:row;align-items:center;`,Fb=C.default(_n)`align-items:flex-start;max-width:100%;`,Pb=C.default(Ua)`min-width:0;`,Oo=C.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ba=be("DashboardTester"),Ub=Ba.Provider;function Bb({testerType:e,origin:t,children:n}){return a.createElement(Ub,{value:{testerType:e,origin:t}},e&&a.createElement(Hb,null),n)}const Ha=Ba.useContext,Hb=()=>a.createElement(a.Fragment,null,a.createElement(_t.MessageLogs,{component:No}),a.createElement(xt.MessageLogs,{component:No})),No=({extendedMessagePayload:e={}})=>{const{handlers:t}=ae(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:o,flagged_types:i,is_thinking:c}=e,u=!!n||[r,s,o,i].some(d=>d==null?void 0:d.length);return c||!u?a.createElement(a.Fragment,null):a.createElement(Gb,null,a.createElement(zb,{$width:4}),a.createElement(Pa,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:E.themedColor.textHighEmphasis,textColor:E.themedColor.textHighEmphasis,barColor:E.themedColor.textDisabled},topContent:a.createElement(H,{variant:"caption4",color:E.themedColor.textLowEmphasis},"Only visible in the tester")}))},Gb=C.default.div`display:flex;gap:16px;margin:6px ${ee.HORIZONTAL_PADDING}px 4px ${ee.HORIZONTAL_PADDING+ee.AVATAR_SIZE}px;align-self:stretch;`,zb=C.default.div`width:${({$width:e})=>e}px;background-color:${E.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Vb=()=>{var s;const{origin:e}=Ha(),{appId:t,aiAgentId:n}=we(),{channelSource:r}=Ae();return(s=r.channel)!=null&&s.conversation?a.createElement(qb,null,a.createElement(yr,{style:{gap:4}},a.createElement(J,{color:E.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(H,{as:"i",color:E.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(yr,{role:"button",style:{gap:4},onClick:()=>{var u,d;const o=e??window.location.origin,i=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,c=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(c)}},a.createElement(H,{variant:"body3",color:E.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:E.themedColor.primary}},"conversation link")),a.createElement(J,{color:E.themedColor.primary,size:14,type:"copy"}))):null},yr=C.default.div`display:flex;justify-content:center;align-items:center;`,qb=C.default(yr)`flex-direction:column;padding-block:16px;background-color:${E.themedColor.bg_100_500};gap:8px;`,Kb=(e,t)=>{const n=[],r=[],s=[];for(const o of e){const i=t.isSupportedMimeType(o.type),c=o.size<=t.getUploadSizeLimit(o.type);i&&c?n.push(o):i?r.push(o):s.push(o)}return{passed:n,failedBySize:r,failedByType:s}},Ga=l.createContext(void 0),Yb=({children:e})=>{var W,K;const{chatSDK:t}=ae(),{createAttachmentRules:n}=Oe(),{stringSet:r}=oe(),{channelSource:s,state:o}=Ae(),[i,c]=l.useState([]),{announceError:u}=Kr(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(W=t.appInfo)==null?void 0:W.uploadSizeLimit}),f=((K=o==null?void 0:o.input)==null?void 0:K.disabled)??!1,g=h.isEnabled(),_=h.maxAttachmentCount,b=()=>m(null),v=w=>m(w),p=()=>{v({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",_.toString())})},S=w=>{v({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",w.toString())}),u({type:"fileSizeExceeded",maxSizeMB:w})},A=w=>{v({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",w.toString())})},T=w=>w.map(V=>({file:V,preview:{url:URL.createObjectURL(V),type:V.type,name:V.name}})),M=w=>{c(V=>[...V,...T(w)])},k=w=>{c(V=>(V.forEach(P=>URL.revokeObjectURL(P.preview.url)),T(w)))},N=w=>{const{passed:V,failedBySize:P,failedByType:q}=Kb(w,h),ue=P.length+q.length,Te=w.length===1?P[0]:void 0;return Te?S(h.getUploadSizeLimitInMB(Te.type)):ue>0&&A(ue),V},x=w=>{const V=N(w.files);V.length!==0&&(w.type==="append"?M(V):k(V))},L=w=>{if(!g||f||!yu(w))return;const V=Au({currentFiles:i.map(({file:P})=>P),incomingFiles:w,maxAttachmentCount:_});switch(V.type){case"reject":p();return;case"confirm_replace":v({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>x(V.action)});return;case"apply":x(V.action);return}},z=w=>{c(V=>{var q;const P=(q=V[w])==null?void 0:q.preview;return P&&URL.revokeObjectURL(P.url),V.filter((ue,Te)=>Te!==w)})},D=()=>{c(w=>(w.forEach(V=>URL.revokeObjectURL(V.preview.url)),[]))};return a.createElement(Ga.Provider,{value:{files:i,addFiles:L,removeFile:z,clearFiles:D,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:v}},e,a.createElement(Pn,{visible:!!d,...d??{},onClose:b}))},rs=()=>{const e=l.useContext(Ga);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Wb({elementRef:e,ready:t,onRestore:n}){const r=l.useRef(!1);l.useEffect(()=>{var i;!t||!r.current||(n==null||n(),(i=e.current)==null||i.focus(),r.current=!1)},[t,n]);const s=l.useCallback(()=>{r.current=!0},[]),o=l.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function jb({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=l.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),l.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const Xb=()=>{const{announceError:e}=ot();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},Zb=1e3,Jb=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=ot(),o=n??!0,i=l.useRef(!1),c=l.useRef(void 0),u=l.useCallback(d=>{var m;d&&o&&(i.current=!0,c.current=e,e==null||e.startTyping()),d||(i.current&&o&&((m=c.current)==null||m.endTyping()),i.current=!1,c.current=void 0),s(d)},[e,s,o]);l.useLayoutEffect(()=>{s(i.current)},[r,s]),im(t,u,{enabled:o,idleMs:Zb})},Qb=({enabled:e=!0,focusRoot:t})=>{const[n,r]=l.useState(!1),s=l.useRef(!1),o=l.useRef(!1);l.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const f=h;f.metaKey||f.altKey||f.ctrlKey||(s.current=!0)},m=()=>{s.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const i=l.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),c=l.useCallback(()=>{r(!1)},[]),u=l.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:i,onBlur:c}}},ev=C.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,tv=C.default.div`display:flex;flex-shrink:0;position:relative;margin-block-start:8px;border-radius:12px;height:64px;img{border-radius:12px;object-fit:cover;width:64px;-webkit-user-drag:none;}&:hover button,&:focus-within button{opacity:1;}`,nv=C.default.button`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;border:none;padding:0;opacity:${({$mobile:e})=>e?1:0};transition:opacity 0.12s ease-in-out;${Q.light`
411
+ `,Ot=C.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Ln=C.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,zb=C.default(Ln)`cursor:pointer;gap:4px;`,Cn=C.default(Ln)`flex-direction:row;align-items:center;`,Vb=C.default(Cn)`align-items:flex-start;max-width:100%;`,qb=C.default(Ha)`min-width:0;`,Do=C.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ga=be("DashboardTester"),Kb=Ga.Provider;function Wb({testerType:e,origin:t,children:n}){return a.createElement(Kb,{value:{testerType:e,origin:t}},e&&a.createElement(Yb,null),n)}const za=Ga.useContext,Yb=()=>a.createElement(a.Fragment,null,a.createElement(_t.MessageLogs,{component:No}),a.createElement(xt.MessageLogs,{component:No})),No=({extendedMessagePayload:e={}})=>{const{handlers:t}=le(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:o,flagged_types:i,is_thinking:c}=e,u=!!n||[r,s,o,i].some(d=>d==null?void 0:d.length);return c||!u?a.createElement(a.Fragment,null):a.createElement(jb,null,a.createElement(Xb,{$width:4}),a.createElement(Ba,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:E.themedColor.textHighEmphasis,textColor:E.themedColor.textHighEmphasis,barColor:E.themedColor.textDisabled},topContent:a.createElement(B,{variant:"caption4",color:E.themedColor.textLowEmphasis},"Only visible in the tester")}))},jb=C.default.div`display:flex;gap:16px;margin:6px ${ee.HORIZONTAL_PADDING}px 4px ${ee.HORIZONTAL_PADDING+ee.AVATAR_SIZE}px;align-self:stretch;`,Xb=C.default.div`width:${({$width:e})=>e}px;background-color:${E.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Zb=()=>{var s;const{origin:e}=za(),{appId:t,aiAgentId:n}=ke(),{channelSource:r}=Ae();return(s=r.channel)!=null&&s.conversation?a.createElement(Jb,null,a.createElement(yr,{style:{gap:4}},a.createElement(J,{color:E.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(B,{as:"i",color:E.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(yr,{role:"button",style:{gap:4},onClick:()=>{var u,d;const o=e??window.location.origin,i=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,c=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(c)}},a.createElement(B,{variant:"body3",color:E.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:E.themedColor.primary}},"conversation link")),a.createElement(J,{color:E.themedColor.primary,size:14,type:"copy"}))):null},yr=C.default.div`display:flex;justify-content:center;align-items:center;`,Jb=C.default(yr)`flex-direction:column;padding-block:16px;background-color:${E.themedColor.bg_100_500};gap:8px;`,Qb=(e,t)=>{const n=[],r=[],s=[];for(const o of e){const i=t.isSupportedMimeType(o.type),c=o.size<=t.getUploadSizeLimit(o.type);i&&c?n.push(o):i?r.push(o):s.push(o)}return{passed:n,failedBySize:r,failedByType:s}},Va=l.createContext(void 0),ev=({children:e})=>{var Y,q;const{chatSDK:t}=le(),{createAttachmentRules:n}=Ne(),{stringSet:r}=se(),{channelSource:s,state:o}=Ae(),[i,c]=l.useState([]),{announceError:u}=Wr(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(Y=t.appInfo)==null?void 0:Y.uploadSizeLimit}),f=((q=o==null?void 0:o.input)==null?void 0:q.disabled)??!1,g=h.isEnabled(),b=h.maxAttachmentCount,S=()=>m(null),_=k=>m(k),p=()=>{_({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",b.toString())})},y=k=>{_({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",k.toString())}),u({type:"fileSizeExceeded",maxSizeMB:k})},A=k=>{_({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",k.toString())})},T=k=>k.map(G=>({file:G,preview:{url:URL.createObjectURL(G),type:G.type,name:G.name}})),M=k=>{c(G=>[...G,...T(k)])},L=k=>{c(G=>(G.forEach(P=>URL.revokeObjectURL(P.preview.url)),T(k)))},N=k=>{const{passed:G,failedBySize:P,failedByType:V}=Qb(k,h),me=P.length+V.length,Ie=k.length===1?P[0]:void 0;return Ie?y(h.getUploadSizeLimitInMB(Ie.type)):me>0&&A(me),G},x=k=>{const G=N(k.files);G.length!==0&&(k.type==="append"?M(G):L(G))},O=k=>{if(!g||f||!Ru(k))return;const G=wu({currentFiles:i.map(({file:P})=>P),incomingFiles:k,maxAttachmentCount:b});switch(G.type){case"reject":p();return;case"confirm_replace":_({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>x(G.action)});return;case"apply":x(G.action);return}},H=k=>{c(G=>{var V;const P=(V=G[k])==null?void 0:V.preview;return P&&URL.revokeObjectURL(P.url),G.filter((me,Ie)=>Ie!==k)})},F=()=>{c(k=>(k.forEach(G=>URL.revokeObjectURL(G.preview.url)),[]))};return a.createElement(Va.Provider,{value:{files:i,addFiles:O,removeFile:H,clearFiles:F,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:_}},e,a.createElement(Un,{visible:!!d,...d??{},onClose:S}))},ss=()=>{const e=l.useContext(Va);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function tv({elementRef:e,ready:t,onRestore:n}){const r=l.useRef(!1);l.useEffect(()=>{var i;!t||!r.current||(n==null||n(),(i=e.current)==null||i.focus(),r.current=!1)},[t,n]);const s=l.useCallback(()=>{r.current=!0},[]),o=l.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function nv({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=l.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),l.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const rv=()=>{const{announceError:e}=ot();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},sv=1e3,ov=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=ot(),o=n??!0,i=l.useRef(!1),c=l.useRef(void 0),u=l.useCallback(d=>{var m;d&&o&&(i.current=!0,c.current=e,e==null||e.startTyping()),d||(i.current&&o&&((m=c.current)==null||m.endTyping()),i.current=!1,c.current=void 0),s(d)},[e,s,o]);l.useLayoutEffect(()=>{s(i.current)},[r,s]),hm(t,u,{enabled:o,idleMs:sv})},iv=({enabled:e=!0,focusRoot:t})=>{const[n,r]=l.useState(!1),s=l.useRef(!1),o=l.useRef(!1);l.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const f=h;f.metaKey||f.altKey||f.ctrlKey||(s.current=!0)},m=()=>{s.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const i=l.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),c=l.useCallback(()=>{r(!1)},[]),u=l.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:i,onBlur:c}}},av=C.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,cv=C.default.div`display:flex;flex-shrink:0;position:relative;margin-block-start:8px;border-radius:12px;height:64px;img{border-radius:12px;object-fit:cover;width:64px;-webkit-user-drag:none;}&:hover button,&:focus-within button{opacity:1;}`,lv=C.default.button`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;border:none;padding:0;opacity:${({$mobile:e})=>e?1:0};transition:opacity 0.12s ease-in-out;${Q.light`
412
412
  background-color: ${E.color.background50};
413
413
  `}
414
414
  ${Q.dark`
@@ -433,7 +433,7 @@
433
433
  circle {
434
434
  stroke: ${E.themedColor.bg_50_600};
435
435
  }
436
- `,rv=()=>{const e=Jt(),{conversation:t}=re(),{files:n,removeFile:r,isFileUploadEnabled:s}=rs();return s&&n.length>0?a.createElement(ev,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Zr,{name:c,mimeType:i,type:Ir(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(tv,{key:u},a.createElement(nv,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(J,{type:"close-filled",color:E.themedColor.textMidEmphasis})),m)})):null},sv={textArea:U.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},za=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${xe}`,Do=C.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,$o=C.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Fo=C.default.textarea`all:unset;display:block;flex:1;min-width:0;padding-top:8px;padding-bottom:8px;padding-inline-start:16px;padding-inline-end:12px;box-sizing:border-box;font-size:14px;line-height:20px;color:${({theme:e})=>e.colors.messageInput.text};resize:none;width:100%;height:${qi}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${aa&&sv.textArea};${({$focusVisible:e})=>e&&U.css`
436
+ `,uv=()=>{const e=Qt(),{conversation:t}=re(),{files:n,removeFile:r,isFileUploadEnabled:s}=ss();return s&&n.length>0?a.createElement(av,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Jr,{name:c,mimeType:i,type:xr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(cv,{key:u},a.createElement(lv,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(J,{type:"close-filled",color:E.themedColor.textMidEmphasis})),m)})):null},dv={textArea:U.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},qa=C.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${xe}`,$o=C.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,Fo=C.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Po=C.default.textarea`all:unset;display:block;flex:1;min-width:0;padding-top:8px;padding-bottom:8px;padding-inline-start:16px;padding-inline-end:12px;box-sizing:border-box;font-size:14px;line-height:20px;color:${({theme:e})=>e.colors.messageInput.text};resize:none;width:100%;height:${Wi}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${la&&dv.textArea};${({$focusVisible:e})=>e&&U.css`
437
437
  outline: 2px solid ${E.themedColor.primary};
438
438
  outline-offset: 2px;
439
439
  `}
@@ -450,17 +450,17 @@
450
450
  }
451
451
 
452
452
  ${({$blocked:e})=>e&&U.css`cursor:not-allowed;&::placeholder{color:${E.themedColor.textDisabled};}`}
453
- `,ov=C.default.input`display:none;`;C.default.div`display:flex;align-items:center;gap:24px;`;const iv=C.default(za)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${E.themedColor.bg_100_500};path{fill:${E.themedColor.textHighEmphasis};}}&:active{background-color:${E.themedColor.bg_200_400};}}`,Po=C.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Uo=e=>e.startsWith("image/"),Bo=({disabled:e})=>{const{stringSet:t}=oe(),{conversation:n}=re(),{config:r}=ae(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=rs(),f=m.includes(lr),g=f?["image/*"]:m.filter(Uo),_=f?[lr]:m.filter(N=>!Uo(N)),b=r.conversation.input.gallery.photoEnabled,v=r.conversation.input.fileEnabled,p=()=>f||g.length>0,S=()=>f||_.length>0,A=N=>{const x=N.currentTarget.files;x&&u(Array.from(x)),N.target.value=""},T=()=>{c(!0)},M=l.useMemo(()=>{const N=[];return b&&N.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!p()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=s.current)==null?void 0:x.click()},100)}}),v&&N.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!S()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=o.current)==null?void 0:x.click()},100)}}),N},[g,m,t,b,v]);if(!d)return null;const k={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(iv,{...k.attach.props,disabled:e,onClick:T},a.createElement(J,{type:"add",color:e?E.themedColor.textDisabled:E.color.primary.main,size:20}),k.attach.descriptionNode),M.map(N=>a.createElement(ov,{key:N.type,type:"file",ref:N.inputRef,multiple:N.type==="image",onChange:A,accept:N.accept})),a.createElement(lt,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},M.map(N=>a.createElement(lt.ActionItem,{key:N.type,onClick:N.onSelect,icon:N.icon},N.label))))},av=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=oe(),{conversation:s}=re(),{rootElement:o}=ae(),i=ut(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=Qb({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Ae(),{files:g,addFiles:_,clearFiles:b}=rs(),v=Xb(),{focusPolicy:p,disabled:S,disabledBy:A}=f.input,T=p==="preserve",M=p==="release",k=(()=>{if(!S)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(A){case"form_active":return r.FORM_PLACEHOLDER;case"ai_responding":return r.MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE;case"suggested_replies":return r.MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES;case"steward":return r.MESSAGE_INPUT__PLACE_HOLDER__STEWARD;case"system":return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED;case"reconnecting":return r.MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING;case"unavailable":case"conversation_closed":default:return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED}})();rg({onDropFiles:I=>{_(I)}}),jb({blurred:M,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),Jb(m.channel,t,!S);const N=t.trim().length>0,x=g.length>0,L=!S&&(N||x),z={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},D=()=>{e.current&&(e.current.value="",e.current.style.height=""),b(),n("")},W=()=>{var I;d(),(I=e.current)==null||I.focus()},{requestRestore:K,cancelRestore:w}=Wb({elementRef:e,ready:T,onRestore:d}),V=I=>{w(),v(I)},P=()=>{w()},q=async I=>{try{await I(),P()}catch{V(e.current)}},ue=async()=>{if(S)return;const I=t.trim();if(!I&&!g.length)return;const Y=[...g];if(K(),D(),W(),Y.length===0){await q(()=>h.sendUserMessage({message:I}));return}if(Y.length===1)await q(()=>h.sendFileMessage({message:I,file:Y[0].file}));else{const te=Y.map(({file:se})=>({file:se}));await q(()=>h.sendMultipleFilesMessage({message:I,fileInfoList:te}))}},Te=I=>{const Y=Array.from(I.clipboardData.files);Y.length>0&&(I.preventDefault(),_(Y))},B=I=>{I.key!=="Enter"||I.nativeEvent.isComposing||I.shiftKey||(I.preventDefault(),ue())},G=I=>{if(S){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const Y=Math.min(fh,e.current.scrollHeight);qi<Y&&(e.current.style.height=`${Y}px`)}n(I.target.value)};return M?a.createElement(Po,null,a.createElement(Bo,{disabled:!0}),a.createElement(Do,null,a.createElement($o,null,a.createElement(Fo,{rows:1,...z.input.props,disabled:!0,placeholder:k,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(Po,{"data-message-composer":""},a.createElement(Bo,{disabled:S}),a.createElement(Do,null,a.createElement(rv,null),a.createElement($o,null,a.createElement(Fo,{ref:e,rows:1,...z.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:k,maxLength:5e3,$blocked:S,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:B,onChange:G,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:Te}))),L&&a.createElement(za,{...z.send.props,onClick:()=>ue()},a.createElement(J,{type:"send",color:E.color.primary.main,size:20}),z.send.descriptionNode))},cv=C.default.div`padding:8px 16px;text-align:center;word-break:break-word;white-space:pre-wrap;line-height:1.43;letter-spacing:-0.2px;font-size:14px;font-weight:400;color:${E.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${Q.light`
453
+ `,mv=C.default.input`display:none;`;C.default.div`display:flex;align-items:center;gap:24px;`;const hv=C.default(qa)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${E.themedColor.bg_100_500};path{fill:${E.themedColor.textHighEmphasis};}}&:active{background-color:${E.themedColor.bg_200_400};}}`,Uo=C.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Bo=e=>e.startsWith("image/"),Ho=({disabled:e})=>{const{stringSet:t}=se(),{conversation:n}=re(),{config:r}=le(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=ss(),f=m.includes(ur),g=f?["image/*"]:m.filter(Bo),b=f?[ur]:m.filter(N=>!Bo(N)),S=r.conversation.input.gallery.photoEnabled,_=r.conversation.input.fileEnabled,p=()=>f||g.length>0,y=()=>f||b.length>0,A=N=>{const x=N.currentTarget.files;x&&u(Array.from(x)),N.target.value=""},T=()=>{c(!0)},M=l.useMemo(()=>{const N=[];return S&&N.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!p()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=s.current)==null?void 0:x.click()},100)}}),_&&N.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!y()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=o.current)==null?void 0:x.click()},100)}}),N},[g,m,t,S,_]);if(!d)return null;const L={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(hv,{...L.attach.props,disabled:e,onClick:T},a.createElement(J,{type:"add",color:e?E.themedColor.textDisabled:E.color.primary.main,size:20}),L.attach.descriptionNode),M.map(N=>a.createElement(mv,{key:N.type,type:"file",ref:N.inputRef,multiple:N.type==="image",onChange:A,accept:N.accept})),a.createElement(lt,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},M.map(N=>a.createElement(lt.ActionItem,{key:N.type,onClick:N.onSelect,icon:N.icon},N.label))))},fv=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=se(),{conversation:s}=re(),{rootElement:o}=le(),i=ut(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=iv({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Ae(),{files:g,addFiles:b,clearFiles:S}=ss(),_=rv(),{focusPolicy:p,disabled:y,disabledBy:A}=f.input,T=p==="preserve",M=p==="release",L=(()=>{if(!y)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(A){case"form_active":return r.FORM_PLACEHOLDER;case"ai_responding":return r.MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE;case"suggested_replies":return r.MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES;case"steward":return r.MESSAGE_INPUT__PLACE_HOLDER__STEWARD;case"system":return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED;case"reconnecting":return r.MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING;case"unavailable":case"conversation_closed":default:return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED}})();ug({onDropFiles:R=>{b(R)}}),nv({blurred:M,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),ov(m.channel,t,!y);const N=t.trim().length>0,x=g.length>0,O=!y&&(N||x),H={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},F=()=>{e.current&&(e.current.value="",e.current.style.height=""),S(),n("")},Y=()=>{var R;d(),(R=e.current)==null||R.focus()},{requestRestore:q,cancelRestore:k}=tv({elementRef:e,ready:T,onRestore:d}),G=R=>{k(),_(R)},P=()=>{k()},V=async R=>{try{await R(),P()}catch{G(e.current)}},me=async()=>{if(y)return;const R=t.trim();if(!R&&!g.length)return;const X=[...g];if(q(),F(),Y(),X.length===0){await V(()=>h.sendUserMessage({message:R}));return}if(X.length===1)await V(()=>h.sendFileMessage({message:R,file:X[0].file}));else{const ne=X.map(({file:oe})=>({file:oe}));await V(()=>h.sendMultipleFilesMessage({message:R,fileInfoList:ne}))}},Ie=R=>{const X=Array.from(R.clipboardData.files);X.length>0&&(R.preventDefault(),b(X))},j=R=>{R.key!=="Enter"||R.nativeEvent.isComposing||R.shiftKey||(R.preventDefault(),me())},K=R=>{if(y){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const X=Math.min(vh,e.current.scrollHeight);Wi<X&&(e.current.style.height=`${X}px`)}n(R.target.value)};return M?a.createElement(Uo,null,a.createElement(Ho,{disabled:!0}),a.createElement($o,null,a.createElement(Fo,null,a.createElement(Po,{rows:1,...H.input.props,disabled:!0,placeholder:L,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(Uo,{"data-message-composer":""},a.createElement(Ho,{disabled:y}),a.createElement($o,null,a.createElement(uv,null),a.createElement(Fo,null,a.createElement(Po,{ref:e,rows:1,...H.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:L,maxLength:5e3,$blocked:y,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:j,onChange:K,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:Ie}))),O&&a.createElement(qa,{...H.send.props,onClick:()=>me()},a.createElement(J,{type:"send",color:E.color.primary.main,size:20}),H.send.descriptionNode))},gv=C.default.div`padding:8px 16px;text-align:center;word-break:break-word;white-space:pre-wrap;line-height:1.43;letter-spacing:-0.2px;font-size:14px;font-weight:400;color:${E.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${Q.light`
454
454
  color: ${E.color.information.light};
455
455
  `};
456
456
  ${Q.dark`
457
457
  color: ${E.color.information.main};
458
458
  `};
459
459
  }
460
- `,lv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),uv=()=>{const{aiAgentInfo:e,userSession:t}=Oe(),{handlers:n}=ae(),{messageSource:r,channelSource:s}=Ae(),[o,i]=l.useState(null),c=Ur("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>st(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(cv,null,a.createElement(lv,{onClickLink:n.onClickLink},e.specialNotice))},dv=()=>a.createElement(mv,null,a.createElement(uv,null),a.createElement(Yb,null,a.createElement(av,null))),mv=C.default.div`z-index:0;border:none;width:100%;`,hv=()=>{var s;const{testerType:e}=Ha(),{channelSource:t}=Ae(),n=Fe(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(Vb,null):a.createElement(dv,null)},Va=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(fv,{...s},a.createElement(gv,null,n==="center"&&t&&a.createElement(pv,{$sideWidth:Math.max(c,d)},a.createElement(_v,null,t)),a.createElement(Ev,null,a.createElement(Cv,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(vv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(bv,{ref:i},r))))},fv=C.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${E.themedColor.textDisabled};`,gv=C.default.div`position:relative;height:56px;padding:11px 12px;`,pv=C.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,_v=C.default.div`max-width:100%;overflow:hidden;`,Ev=C.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Cv=C.default.div`flex-shrink:0;display:flex;align-items:center;`,bv=C.default.div`flex-shrink:0;display:flex;align-items:center;`,vv=C.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,Rt=(e=16)=>Jt()?e*1.5:e,yv=()=>{const{state:e}=ae(),{messenger:t}=re(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},Sv=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ae(),{channelSource:n}=Ae(),{conversation:r}=re(),s=n.channel,o=Rt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!Rr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(ct.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(it,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},Av=()=>{const{state:e,enableExpandButton:t}=ae(),{messenger:n}=re(),r=Rt();return t?a.createElement(it,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Tv=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Sr,null,t,a.createElement(Rv,{$position:n},a.createElement(Mv,{variant:"caption1"},e),a.createElement(Iv,{$position:n}))),Iv=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:E.themedColor.textHighEmphasis})),xv={top:U.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:U.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Sr=C.default.div`position:relative;`,Rv=C.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${gt.TOOLTIP};${({$position:e})=>xv[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Sr}:hover &,${Sr}:focus-within &{opacity:1;}`,Mv=C.default(H)`padding:6px 8px;background:${E.themedColor.textHighEmphasis};color:${E.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,wv=2e3,Ho=0,kv=1500,fn=Symbol("header-focus-status-pause"),Go="data-sb-header-focus-protected",Lv="[data-message-composer]",zo=new WeakMap,ar=e=>{const t=zo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return zo.set(e,n),n},cr=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},En=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},Ov=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),En(e)},Nv=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},Dv=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(Lv),!1),ss=()=>{const{setStatusPauseState:e}=ot(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+kv,o();const u=ar(e);cr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(fn,!0),En(u),u.maxPauseTimeout=setTimeout(()=>{Ov(u),e(fn,!1)},wv)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=ar(e),h=d instanceof HTMLElement&&Date.now()<=r.current;cr(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,_=g instanceof HTMLElement&&g.hasAttribute(Go);if(g===d||_||!Dv(g))return;const b=Nv(d);d.focus({preventScroll:!0}),b()},Ho)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(En(m),e(fn,!1))},Ho))},[o,e]);return l.useEffect(()=>()=>{const u=ar(e);n.current=!1,o(),cr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(En(u),e(fn,!1))},[o,e]),{[Go]:"true",onFocus:i,onBlur:c}},$v=()=>{const{logger:e}=ae(),{stringSet:t}=oe(),{channelSource:n}=Ae(),{conversation:r}=re(),s=n.channel,o=Rt(),i=Ur("handoff-button",s),c=!Rr(s)||rt(s),[u,d]=l.useState(!1),m=ss(),h=async()=>{d(!1);try{const g=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};if(!i)return null;const f={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(Tv,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(it,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(dt,{portalContainerId:ye.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ts,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},Fv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Pv=()=>{const{logger:e}=ae(),{stringSet:t}=oe(),{memoryInfo:n,sdkUser:r}=Oe(),{actions:s}=Ae(),{conversation:o}=re(),i=Rt(20),c=ss(),[u,d]=l.useState(null),[m,h]=l.useState(!1),f=l.useRef(!1);if(l.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const g=o.header.memoryIndicator(n.enabled),_=async b=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:b}),d(null)}catch(v){e.error("memoryIndicator.setUserMemoryState: error",v),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(Gv,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(J,{type:"memory",size:i,color:E.themedColor.textHighEmphasis}),a.createElement(zv,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(Uv,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:_}),a.createElement(Pn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},Uv=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=oe(),{colors:s}=U.useTheme(),o=l.useId(),i=l.useId(),c=vu(e),u=c==="consent",d={consent:{body:((h=e.consentDialog)==null?void 0:h.body)??"",negativeText:r.MEMORY__BUTTON_DONT_USE,positiveText:r.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:r.MEMORY__DESC_ON,negativeText:e.deleteOnOff?r.MEMORY__BUTTON_DISABLE_AND_DELETE:r.MEMORY__BUTTON_DISABLE,positiveText:r.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:r.MEMORY__DESC_OFF,negativeText:r.MEMORY__BUTTON_ENABLE,positiveText:r.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?r.MEMORY__DESC_ON:r.MEMORY__DESC_OFF,negativeText:void 0,positiveText:r.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[c],m=s.memoryDialog;return a.createElement(dt,{visible:!0,portalContainerId:ye.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(ts,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(Bv,null,d.body),descriptionId:i,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:u?"horizontal":"vertical-full-width",onCancel:d.onCancel,onConfirm:d.onConfirm,styles:{titleColor:m.titleText,positiveBackground:m.positiveBackground,positiveText:m.positiveText,positiveBorderColor:m.positiveBorderColor,negativeBackground:m.negativeBackground,negativeText:m.negativeText,negativeBorderColor:m.negativeBorderColor}}))},Bv=({children:e})=>{const{handlers:t}=ae();return a.createElement(Vv,null,a.createElement(Ht,{fallback:e},a.createElement(Fv,{onClickLink:t.onClickLink},e)))},Hv=U.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,Gv=C.default.button`${Hv};cursor:pointer;${xe}`,zv=C.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?E.themedColor.secondary:E.color.background300};box-shadow:0 0 0 2px ${E.color.background50};${Q.dark`
460
+ `,pv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),_v=()=>{const{aiAgentInfo:e,userSession:t}=Ne(),{handlers:n}=le(),{messageSource:r,channelSource:s}=Ae(),[o,i]=l.useState(null),c=Br("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>st(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(gv,null,a.createElement(pv,{onClickLink:n.onClickLink},e.specialNotice))},Ev=()=>a.createElement(Cv,null,a.createElement(_v,null),a.createElement(ev,null,a.createElement(fv,null))),Cv=C.default.div`z-index:0;border:none;width:100%;`,bv=()=>{var s;const{testerType:e}=za(),{channelSource:t}=Ae(),n=He(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(Zb,null):a.createElement(Ev,null)},Ka=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(vv,{...s},a.createElement(Sv,null,n==="center"&&t&&a.createElement(yv,{$sideWidth:Math.max(c,d)},a.createElement(Av,null,t)),a.createElement(Tv,null,a.createElement(Iv,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Rv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(xv,{ref:i},r))))},vv=C.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${E.themedColor.textDisabled};`,Sv=C.default.div`position:relative;height:56px;padding:11px 12px;`,yv=C.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,Av=C.default.div`max-width:100%;overflow:hidden;`,Tv=C.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Iv=C.default.div`flex-shrink:0;display:flex;align-items:center;`,xv=C.default.div`flex-shrink:0;display:flex;align-items:center;`,Rv=C.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,Rt=(e=16)=>Qt()?e*1.5:e,Mv=()=>{const{state:e}=le(),{messenger:t}=re(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},wv=()=>{const{enableCloseConversationButton:e,dispatcher:t}=le(),{channelSource:n}=Ae(),{conversation:r}=re(),s=n.channel,o=Rt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!Mr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(ct.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(it,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},kv=()=>{const{state:e,enableExpandButton:t}=le(),{messenger:n}=re(),r=Rt();return t?a.createElement(it,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Lv=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Ar,null,t,a.createElement(Nv,{$position:n},a.createElement($v,{variant:"caption1"},e),a.createElement(Ov,{$position:n}))),Ov=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:E.themedColor.textHighEmphasis})),Dv={top:U.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:U.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Ar=C.default.div`position:relative;`,Nv=C.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${gt.TOOLTIP};${({$position:e})=>Dv[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Ar}:hover &,${Ar}:focus-within &{opacity:1;}`,$v=C.default(B)`padding:6px 8px;background:${E.themedColor.textHighEmphasis};color:${E.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Fv=2e3,Go=0,Pv=1500,gn=Symbol("header-focus-status-pause"),zo="data-sb-header-focus-protected",Uv="[data-message-composer]",Vo=new WeakMap,cr=e=>{const t=Vo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return Vo.set(e,n),n},lr=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},bn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},Bv=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),bn(e)},Hv=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},Gv=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(Uv),!1),os=()=>{const{setStatusPauseState:e}=ot(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+Pv,o();const u=cr(e);lr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(gn,!0),bn(u),u.maxPauseTimeout=setTimeout(()=>{Bv(u),e(gn,!1)},Fv)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=cr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;lr(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,b=g instanceof HTMLElement&&g.hasAttribute(zo);if(g===d||b||!Gv(g))return;const S=Hv(d);d.focus({preventScroll:!0}),S()},Go)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(bn(m),e(gn,!1))},Go))},[o,e]);return l.useEffect(()=>()=>{const u=cr(e);n.current=!1,o(),lr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(bn(u),e(gn,!1))},[o,e]),{[zo]:"true",onFocus:i,onBlur:c}},zv=()=>{const{logger:e}=le(),{stringSet:t}=se(),{channelSource:n}=Ae(),{conversation:r}=re(),s=n.channel,o=Rt(),i=Br("handoff-button",s),c=!Mr(s)||rt(s),[u,d]=l.useState(!1),m=os(),h=async()=>{d(!1);try{const g=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};if(!i)return null;const f={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(Lv,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(it,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(dt,{portalContainerId:Se.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ns,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},Vv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),qv=()=>{const{logger:e}=le(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=Ne(),{actions:s}=Ae(),{conversation:o}=re(),i=Rt(20),c=os(),[u,d]=l.useState(null),[m,h]=l.useState(!1),f=l.useRef(!1);if(l.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const g=o.header.memoryIndicator(n.enabled),b=async S=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:S}),d(null)}catch(_){e.error("memoryIndicator.setUserMemoryState: error",_),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(jv,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(J,{type:"memory",size:i,color:E.themedColor.textHighEmphasis}),a.createElement(Xv,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(Kv,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:b}),a.createElement(Un,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},Kv=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=se(),{colors:s}=U.useTheme(),o=l.useId(),i=l.useId(),c=xu(e),u=c==="consent",d={consent:{body:((h=e.consentDialog)==null?void 0:h.body)??"",negativeText:r.MEMORY__BUTTON_DONT_USE,positiveText:r.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:r.MEMORY__DESC_ON,negativeText:e.deleteOnOff?r.MEMORY__BUTTON_DISABLE_AND_DELETE:r.MEMORY__BUTTON_DISABLE,positiveText:r.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:r.MEMORY__DESC_OFF,negativeText:r.MEMORY__BUTTON_ENABLE,positiveText:r.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?r.MEMORY__DESC_ON:r.MEMORY__DESC_OFF,negativeText:void 0,positiveText:r.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[c],m=s.memoryDialog;return a.createElement(dt,{visible:!0,portalContainerId:Se.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(ns,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(Wv,null,d.body),descriptionId:i,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:u?"horizontal":"vertical-full-width",onCancel:d.onCancel,onConfirm:d.onConfirm,styles:{titleColor:m.titleText,positiveBackground:m.positiveBackground,positiveText:m.positiveText,positiveBorderColor:m.positiveBorderColor,negativeBackground:m.negativeBackground,negativeText:m.negativeText,negativeBorderColor:m.negativeBorderColor}}))},Wv=({children:e})=>{const{handlers:t}=le();return a.createElement(Zv,null,a.createElement(Ht,{fallback:e},a.createElement(Vv,{onClickLink:t.onClickLink},e)))},Yv=U.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,jv=C.default.button`${Yv};cursor:pointer;${xe}`,Xv=C.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?E.themedColor.secondary:E.color.background300};box-shadow:0 0 0 2px ${E.color.background50};${Q.dark`
461
461
  box-shadow: 0 0 0 2px ${E.color.background500};
462
462
  `}
463
- `,Vv=C.default.div`color:${({theme:e})=>e.colors.memoryDialog.markdownBodyText};line-height:20px;word-break:break-word;&& a{color:${({theme:e})=>e.colors.memoryDialog.markdownLinkText};font-weight:inherit;text-decoration:underline;}`,qv=()=>{const{conversation:e}=re(),{onNavigateToConversationList:t}=Ae();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(it,{...n.menu.props,...Pi,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},qa=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Oe(),{fallbackIcon:s,url:o}=Br({channel:e,aiAgentInfo:r,userSession:n}),[i,c]=l.useState(),u=U.useTheme();return o&&o!==i?a.createElement(Aa,{src:o,size:t,"aria-hidden":"true",onImageError:c}):a.createElement(Kv,{"aria-hidden":"true",$size:t,$bgColor:u.colors.base.primary},a.createElement(J,{type:s,size:t*.55,color:u.colors.base.primaryContrastContent}))},Kv=C.default.div`width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;border-radius:50%;background-color:${({$bgColor:e})=>e};display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Yv=()=>{const{channelSource:e}=Ae(),{aiAgentInfo:t,userSession:n}=Oe(),{conversation:r}=re(),{config:s}=we(),{announcementsEnabled:o}=ot(),i=e.channel,c=Br({channel:i,userSession:n,aiAgentInfo:t}),u=s.conversation.header.avatarEnabled,d=ss(),m=fa({enabled:o,label:c.title}),h={title:r.header.title(c.title,{active:m.enabled,titleId:m.id,initialFocus:!1})};return a.createElement(Wv,null,u&&a.createElement(qa,{channel:i,size:34}),a.createElement(jv,{...h.title.props,...d},c.title))},Wv=C.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,jv=C.default(H).attrs({variant:"h2",color:E.themedColor.textHighEmphasis})`
463
+ `,Zv=C.default.div`color:${({theme:e})=>e.colors.memoryDialog.markdownBodyText};line-height:20px;word-break:break-word;&& a{color:${({theme:e})=>e.colors.memoryDialog.markdownLinkText};font-weight:inherit;text-decoration:underline;}`,Jv=()=>{const{conversation:e}=re(),{onNavigateToConversationList:t}=Ae();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(it,{...n.menu.props,...Bi,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Wa=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Ne(),{fallbackIcon:s,url:o}=Hr({channel:e,aiAgentInfo:r,userSession:n}),[i,c]=l.useState(),u=U.useTheme();return o&&o!==i?a.createElement(Ia,{src:o,size:t,"aria-hidden":"true",onImageError:c}):a.createElement(Qv,{"aria-hidden":"true",$size:t,$bgColor:u.colors.base.primary},a.createElement(J,{type:s,size:t*.55,color:u.colors.base.primaryContrastContent}))},Qv=C.default.div`width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;border-radius:50%;background-color:${({$bgColor:e})=>e};display:flex;align-items:center;justify-content:center;flex-shrink:0;`,eS=()=>{const{channelSource:e}=Ae(),{aiAgentInfo:t,userSession:n}=Ne(),{conversation:r}=re(),{config:s}=ke(),{announcementsEnabled:o}=ot(),i=e.channel,c=Hr({channel:i,userSession:n,aiAgentInfo:t}),u=s.conversation.header.avatarEnabled,d=os(),m=pa({enabled:o,label:c.title}),h={title:r.header.title(c.title,{active:m.enabled,titleId:m.id,initialFocus:!1})};return a.createElement(tS,null,u&&a.createElement(Wa,{channel:i,size:34}),a.createElement(nS,{...h.title.props,...d},c.title))},tS=C.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,nS=C.default(B).attrs({variant:"h2",color:E.themedColor.textHighEmphasis})`
464
464
  margin: 0;
465
465
  flex: 1;
466
466
  min-width: 0;
@@ -472,10 +472,10 @@
472
472
  &:focus {
473
473
  outline: none;
474
474
  }
475
- `,Xv=e=>{const{components:t}=Et.useContext();return a.createElement(Va,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Hi})},Zv=()=>{const{components:e}=Et.useContext();return a.createElement(e.MenuButton,null)},Jv=()=>{const{components:e}=Et.useContext();return a.createElement(e.Title,null)},Qv=()=>{const{components:e}=Et.useContext();return a.createElement(ty,null,a.createElement(e.MemoryIndicator,null),a.createElement(e.HandoffButton,null),a.createElement(e.ConversationCloseButton,null),a.createElement(e.ExpandButton,null),a.createElement(e.CloseButton,null))},Et=je({template:Xv,components:{StartArea:Zv,TitleArea:Jv,EndArea:Qv,MenuButton:qv,Title:Yv,MemoryIndicator:Pv,HandoffButton:$v,ConversationCloseButton:Sv,ExpandButton:Av,CloseButton:yv}}),ey=()=>{const{Template:e}=Et.useContext();return a.createElement(e,{titleAlign:"start"})},ty=C.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,os=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,announcementsEnabled:o=!0,conversationStatsEnabled:i=!0,initialFocusTarget:c,style:u,closedChannelUrl:d,onClearClosedChannelUrl:m})=>{const{Template:h}=Vn.useContext();return a.createElement(da,{onNavigateToConversationList:t,channelUrl:n??d,onClearChannelUrl:r??m,conversationStatsEnabled:i,shouldMarkAsRead:s},a.createElement(_r,null,a.createElement(_r.Consumer,null,f=>a.createElement(af,{announcementsEnabled:o},a.createElement(ny,{enabled:i}),a.createElement(ry,null),a.createElement(sy,{style:u,dragHandlers:f,initialFocusTarget:c},a.createElement(h,null)),e))))},ny=({enabled:e})=>(ag({enabled:e}),null),ry=()=>(Sg(),hg(),bg(),null),sy=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return ig(s,n),a.createElement(iy,{ref:s,style:e,...t},r)},oy=e=>{const{components:t}=Vn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},Vn=je({template:oy,components:{Header:ey,Body:Db,Footer:hv}}),iy=C.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Ka=be("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:ce}),ay=Ka.Provider,is=Ka.useContext,cy=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=Kr(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(ay,{value:s},e)},{Provider:ly,Context:uy,useContext:en}=be("ConversationList");function Ya({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=ce,children:s}){return a.createElement(zd,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(ly,{value:{...o,onOpenConversationView:r}},s))}const dy=e=>{const{announcementsEnabled:t}=is(),{listSource:n}=en(),r=Xi();ga(e,{enabled:t,ready:n.initialized,suppressed:r})},my=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=is(),{listSource:n}=en(),r=l.useRef(!1);l.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const s=n.channels.length,o=setTimeout(()=>{e({screen:"conversationList",conversationCount:s}),r.current=!0},0);return()=>clearTimeout(o)},[e,t,n.initialized])},hy=({channel:e})=>a.createElement(qa,{channel:e}),Ar=99,fy=e=>{var v,p;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=oe(),{userSession:o,aiAgentInfo:i}=Oe(),{conversationList:c}=re(),u=Br({channel:t,userSession:o,aiAgentInfo:i}),d=_u(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=Eu(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),h=t.unreadMessageCount,f=(v=t.lastMessage)!=null&&v.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=Fe(t)?r.CONVERSATION_LIST__ENDED:Ei(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),_=n?()=>n():void 0,b=c.item({agent:f,status:g,time:m,unreadCount:h,onActivate:_});return a.createElement(gy,{"data-testid":"sb-conversation-list-item",$clickable:!!_,...b.props},a.createElement(py,null,a.createElement(hy,{...e})),a.createElement(_y,null,a.createElement(Ey,null,(p=t.lastMessage)!=null&&p.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(ba,{variant:"subtitle1",color:E.themedColor.textHighEmphasis},d):a.createElement(H,{variant:"subtitle1",color:E.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(Cy,null,Fe(t)&&a.createElement(a.Fragment,null,a.createElement(H,{variant:"caption1",color:E.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(by,null)),a.createElement(H,{variant:"caption2",color:E.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(vy,{$count:h},a.createElement(H,{variant:"caption3",color:E.themedColor.textHighEmphasisInverse},h<=Ar?h:`${Ar}+`))),b.descriptionNode)},as=je({template:fy,components:{}}),gy=C.default.div`display:flex;flex-shrink:0;flex-direction:row;align-items:center;position:relative;width:100%;height:72px;box-sizing:border-box;gap:16px;cursor:${({$clickable:e})=>e?"pointer":"default"};`,py=C.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,_y=C.default.div`display:flex;flex-direction:row;align-items:center;flex:1;min-width:0;padding-inline-end:16px;height:100%;gap:8px;border-bottom:1px solid ${E.themedColor.textDisabled};`,Ey=C.default.div`display:flex;flex-direction:column;justify-content:center;flex:1;min-width:0;gap:4px;word-break:break-word;overflow-wrap:break-word;`,Cy=C.default.div`display:flex;align-items:center;gap:6px;`,by=C.default.div`width:2px;height:2px;border-radius:1px;background-color:${E.themedColor.textLowEmphasis};`,vy=C.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${E.themedColor.error};${({$count:e})=>e<=Ar&&U.css`
475
+ `,rS=e=>{const{components:t}=Et.useContext();return a.createElement(Ka,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:zi})},sS=()=>{const{components:e}=Et.useContext();return a.createElement(e.MenuButton,null)},oS=()=>{const{components:e}=Et.useContext();return a.createElement(e.Title,null)},iS=()=>{const{components:e}=Et.useContext();return a.createElement(cS,null,a.createElement(e.MemoryIndicator,null),a.createElement(e.HandoffButton,null),a.createElement(e.ConversationCloseButton,null),a.createElement(e.ExpandButton,null),a.createElement(e.CloseButton,null))},Et=je({template:rS,components:{StartArea:sS,TitleArea:oS,EndArea:iS,MenuButton:Jv,Title:eS,MemoryIndicator:qv,HandoffButton:zv,ConversationCloseButton:wv,ExpandButton:kv,CloseButton:Mv}}),aS=()=>{const{Template:e}=Et.useContext();return a.createElement(e,{titleAlign:"start"})},cS=C.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,is=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,announcementsEnabled:o=!0,conversationStatsEnabled:i=!0,initialFocusTarget:c,style:u,closedChannelUrl:d,onClearClosedChannelUrl:m})=>{const{Template:h}=qn.useContext();return a.createElement(ha,{onNavigateToConversationList:t,channelUrl:n??d,onClearChannelUrl:r??m,conversationStatsEnabled:i,shouldMarkAsRead:s},a.createElement(Er,null,a.createElement(Er.Consumer,null,f=>a.createElement(ff,{announcementsEnabled:o},a.createElement(lS,{enabled:i}),a.createElement(uS,null),a.createElement(dS,{style:u,dragHandlers:f,initialFocusTarget:c},a.createElement(h,null)),e))))},lS=({enabled:e})=>(fg({enabled:e}),null),uS=()=>(wg(),bg(),xg(),null),dS=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return hg(s,n),a.createElement(hS,{ref:s,style:e,...t},r)},mS=e=>{const{components:t}=qn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},qn=je({template:mS,components:{Header:aS,Body:Gb,Footer:bv}}),hS=C.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Ya=be("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:ue}),fS=Ya.Provider,as=Ya.useContext,gS=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=Wr(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(fS,{value:s},e)},{Provider:pS,Context:_S,useContext:tn}=be("ConversationList");function ja({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=ue,children:s}){return a.createElement(Xd,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(pS,{value:{...o,onOpenConversationView:r}},s))}const ES=e=>{const{announcementsEnabled:t}=as(),{listSource:n}=tn(),r=Ji();_a(e,{enabled:t,ready:n.initialized,suppressed:r})},CS=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=as(),{listSource:n}=tn(),r=l.useRef(!1);l.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const s=n.channels.length,o=setTimeout(()=>{e({screen:"conversationList",conversationCount:s}),r.current=!0},0);return()=>clearTimeout(o)},[e,t,n.initialized])},bS=({channel:e})=>a.createElement(Wa,{channel:e}),Tr=99,vS=e=>{var _,p;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=se(),{userSession:o,aiAgentInfo:i}=Ne(),{conversationList:c}=re(),u=Hr({channel:t,userSession:o,aiAgentInfo:i}),d=yu(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=Au(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),h=t.unreadMessageCount,f=(_=t.lastMessage)!=null&&_.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=He(t)?r.CONVERSATION_LIST__ENDED:bi(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),b=n?()=>n():void 0,S=c.item({agent:f,status:g,time:m,unreadCount:h,onActivate:b});return a.createElement(SS,{"data-testid":"sb-conversation-list-item",$clickable:!!b,...S.props},a.createElement(yS,null,a.createElement(bS,{...e})),a.createElement(AS,null,a.createElement(TS,null,(p=t.lastMessage)!=null&&p.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(Sa,{variant:"subtitle1",color:E.themedColor.textHighEmphasis},d):a.createElement(B,{variant:"subtitle1",color:E.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(IS,null,He(t)&&a.createElement(a.Fragment,null,a.createElement(B,{variant:"caption1",color:E.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(xS,null)),a.createElement(B,{variant:"caption2",color:E.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(RS,{$count:h},a.createElement(B,{variant:"caption3",color:E.themedColor.textHighEmphasisInverse},h<=Tr?h:`${Tr}+`))),S.descriptionNode)},cs=je({template:vS,components:{}}),SS=C.default.div`display:flex;flex-shrink:0;flex-direction:row;align-items:center;position:relative;width:100%;height:72px;box-sizing:border-box;gap:16px;cursor:${({$clickable:e})=>e?"pointer":"default"};`,yS=C.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,AS=C.default.div`display:flex;flex-direction:row;align-items:center;flex:1;min-width:0;padding-inline-end:16px;height:100%;gap:8px;border-bottom:1px solid ${E.themedColor.textDisabled};`,TS=C.default.div`display:flex;flex-direction:column;justify-content:center;flex:1;min-width:0;gap:4px;word-break:break-word;overflow-wrap:break-word;`,IS=C.default.div`display:flex;align-items:center;gap:6px;`,xS=C.default.div`width:2px;height:2px;border-radius:1px;background-color:${E.themedColor.textLowEmphasis};`,RS=C.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${E.themedColor.error};${({$count:e})=>e<=Tr&&U.css`
476
476
  width: 20px;
477
477
  `}
478
- `,yy=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=i=>{const c=i.target;c.scrollHeight-c.scrollTop-c.clientHeight<=2&&(n==null||n())};return a.createElement(Sy,{role:r,"aria-label":s,onScroll:i=>o(i)},e.map((i,c)=>{const u=t(i,c);if(r!=="list")return u;const d=l.isValidElement(u)&&u.key!=null?u.key:c;return a.createElement(Ay,{key:d,role:"listitem"},u)}))},Sy=C.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,Ay=C.default.div`flex-shrink:0;`,Ty=()=>{const{stringSet:e}=oe(),{listSource:t,onOpenConversationView:n}=en(),{Template:r}=as.useContext();return t.initialized?t.channels.length===0?a.createElement(Ut,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(yy,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:s=>{var o,i,c;return a.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,Fe(s)?"closed":"open"),channelUrl:s.url,title:(i=(o=s.conversation)==null?void 0:o.topics)==null?void 0:i.join(", "),lastMessageTimestamp:(c=s.lastMessage)==null?void 0:c.createdAt})},onEndReached:()=>{t.loadMore()}}):a.createElement(Ut,{type:"loading"})},Iy=()=>{const{stringSet:e}=oe(),{_aiAgentSDK:t}=we(),{language:n,countryCode:r,context:s}=ae(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Oe(),{onOpenConversationView:u}=en(),{conversationList:d}=re(),m=async()=>{var h;if(o.isMultipleActiveConversationsEnabled){const f=await c({aiAgentId:o.userId,language:n,country:r,context:s});(h=t.session)==null||h._updateActiveChannel({url:f,status:"open"}),u(f,"open",{initialFocusTarget:"messageInput"})}else{const f=await i();u(f,"open",{initialFocusTarget:"messageInput"})}};return a.createElement(xy,{...d.footer.button({onActivate:m}).props},a.createElement(Ry,{variant:"h1"},e.TALK_TO_AGENT))},xy=C.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,Ry=C.default(H)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,My=()=>{const{state:e}=ae(),{messenger:t}=re(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},wy=()=>{const{stringSet:e}=oe(),{announcementsEnabled:t}=is(),{conversationList:n}=re(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=fa({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(ky,{forwardedAs:"h2",variant:"h2",color:E.themedColor.textHighEmphasis,...o.title.props},r)},ky=C.default(H)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,Ly=e=>{const{components:t}=Mt.useContext();return a.createElement(Va,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Hi})},Oy=()=>null,Ny=()=>{const{components:e}=Mt.useContext();return a.createElement(e.Title,null)},Dy=()=>{const{components:e}=Mt.useContext();return a.createElement(e.CloseButton,null)},Mt=je({template:Ly,components:{StartArea:Oy,TitleArea:Ny,EndArea:Dy,Title:wy,CloseButton:My}}),$y=()=>{const{Template:e}=Mt.useContext();return a.createElement(e,{titleAlign:"start"})},Fy=()=>(my(),null),cs=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o=!0,style:i})=>{const{Template:c}=qn.useContext();return a.createElement(Ya,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(cy,{announcementsEnabled:s},a.createElement(Fy,null),a.createElement(Py,{style:i},a.createElement(c,null)),n))},Py=({style:e,children:t})=>{const n=l.useRef(null);return dy(n),a.createElement(By,{ref:n,style:e},t)},Uy=()=>{const{components:e}=qn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},qn=je({template:Uy,components:{Header:$y,Body:Ty,Footer:Iy}}),By=C.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Hy=U.css`:where(#${ye.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,Gy=[Hy,Oh,Nh],zy=(e,...t)=>U.createGlobalStyle(e,...Gy,...t),Vy=zy``,qy=pu(Vn,_t,xt,Hn,zn,qn,Et,as,Mt,Gn,Fn),Ky=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Wa({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){Qh(Ky?bh:"",t);const[f,g]=l.useState(null),_=l.useCallback(p=>{g(S=>S===p?S:p)},[]),b=m??f,v=a.createElement(U.StyleSheetManager,{target:t},a.createElement(Xh,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(Ah,{rootElement:t,boundaryElement:b},a.createElement(Yd,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(Lh,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(Wh,{icons:u},a.createElement(qy,null,a.createElement(yh,{entryElement:b,modalRootElement:h,rootElement:t},i),a.createElement(Vy,null))))))));return m?v:a.createElement("div",{ref:_,style:{display:"contents"}},v)}const Yy=()=>{const[e,t]=l.useState(null),[n,r]=l.useState(null),s=l.useCallback(i=>{t(c=>c===i?c:i)},[]),o=l.useCallback(i=>{r(c=>c===i?c:i)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},ls=l.forwardRef(function({rootElement:t=document.body,logLevel:n=le.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var v,p,S;Ft.level!==n&&(Ft.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=Yy();Jh("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const _=Yi(r),b=Wi.has(_)?_:Zt;return a.createElement("div",{ref:f,id:ye.ENTRY,lang:b,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(Wa,{logger:Ft,rootElement:t,appearance:(v=u.agentPreviewConfigs)==null?void 0:v.appearance,stringSet:u.stringSet,language:b,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(Of,{rootElement:t,language:r,logger:Ft,dispatcher:ja,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(p=u.agentPreviewConfigs)==null?void 0:p.forceCreateChannel,_agentVersion:(S=u.agentPreviewConfigs)==null?void 0:S.agentVersion,...u},a.createElement(Hf,{ref:d,userSessionInfo:s},a.createElement(Bb,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(sf,null,o))))),a.createElement("div",{ref:g,id:ye.MODAL_ROOT,dir:u.dir}))}),Ft=new ii(le.LogLevel.WARN),ja=new ri(Ft),{Provider:Wy,useContext:tn}=be("PageChildren"),Xa=({children:e})=>{const[t,n]=l.useState(()=>os),[r,s]=l.useState(null),[o,i]=l.useState(()=>cs),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(Wy,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},us=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":ye.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Za=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>a.createElement(Xr,null,a.createElement(jy,{isOpened:t,zIndex:n},e)),jy=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>{const{dir:r,rootElement:s}=ae(),o=ut(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Un();return $n(t,i,{nameReady:u}),l.useEffect(()=>{const d="sb-agent-block-scroll";return t?o.body.classList.add(d):o.body.classList.remove(d),()=>{o.body.classList.remove(d)}},[o,t]),a.createElement(Xy,{ref:i,id:ye.WINDOW,dir:r,...us(t,c),$visible:t,$zIndex:n},e)},Xy=C.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,Zy=48,Jy=2/3,Vo=12;function Ja({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:i,imageUrl:c,dir:u,animated:d=!0,backgroundColor:m,size:h=Zy,hasUnread:f=!1}){const g=Ia(),_=d&&!g,b=mr(m),v=Math.round(h*Jy);return a.createElement(tS,{dir:u,id:ye.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:_,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(nS,{$isOpened:n,$animated:_,$fillColor:b,$iconSize:v,$prefersReducedMotion:g},a.createElement(qo.Open,{url:c,isDefaultIcon:i==="default_icon",size:v})),a.createElement(rS,{$isOpened:n,$animated:_,$fillColor:b,$iconSize:v,$prefersReducedMotion:g},a.createElement(qo.Close,{size:v})),f&&a.createElement(sS,null),t)}const Qy=U.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,eS=U.css`img{width:100%;height:100%;object-fit:cover;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-drag:none;&[data-default-icon='true']{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;filter:${({$fillColor:e})=>e===Bt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Qa=U.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>U.css`
478
+ `,MS=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=i=>{const c=i.target;c.scrollHeight-c.scrollTop-c.clientHeight<=2&&(n==null||n())};return a.createElement(wS,{role:r,"aria-label":s,onScroll:i=>o(i)},e.map((i,c)=>{const u=t(i,c);if(r!=="list")return u;const d=l.isValidElement(u)&&u.key!=null?u.key:c;return a.createElement(kS,{key:d,role:"listitem"},u)}))},wS=C.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,kS=C.default.div`flex-shrink:0;`,LS=()=>{const{stringSet:e}=se(),{listSource:t,onOpenConversationView:n}=tn(),{Template:r}=cs.useContext();return t.initialized?t.channels.length===0?a.createElement(Ut,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(MS,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:s=>{var o,i,c;return a.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,He(s)?"closed":"open"),channelUrl:s.url,title:(i=(o=s.conversation)==null?void 0:o.topics)==null?void 0:i.join(", "),lastMessageTimestamp:(c=s.lastMessage)==null?void 0:c.createdAt})},onEndReached:()=>{t.loadMore()}}):a.createElement(Ut,{type:"loading"})},OS=()=>{const{stringSet:e}=se(),{_aiAgentSDK:t}=ke(),{language:n,countryCode:r,context:s}=le(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Ne(),{onOpenConversationView:u}=tn(),{conversationList:d}=re(),m=async()=>{var h;if(o.isMultipleActiveConversationsEnabled){const f=await c({aiAgentId:o.userId,language:n,country:r,context:s});(h=t.session)==null||h._updateActiveChannel({url:f,status:"open"}),u(f,"open",{initialFocusTarget:"messageInput"})}else{const f=await i();u(f,"open",{initialFocusTarget:"messageInput"})}};return a.createElement(DS,{...d.footer.button({onActivate:m}).props},a.createElement(NS,{variant:"h1"},e.TALK_TO_AGENT))},DS=C.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,NS=C.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,$S=()=>{const{state:e}=le(),{messenger:t}=re(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},FS=()=>{const{stringSet:e}=se(),{announcementsEnabled:t}=as(),{conversationList:n}=re(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=pa({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(PS,{forwardedAs:"h2",variant:"h2",color:E.themedColor.textHighEmphasis,...o.title.props},r)},PS=C.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,US=e=>{const{components:t}=Mt.useContext();return a.createElement(Ka,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:zi})},BS=()=>null,HS=()=>{const{components:e}=Mt.useContext();return a.createElement(e.Title,null)},GS=()=>{const{components:e}=Mt.useContext();return a.createElement(e.CloseButton,null)},Mt=je({template:US,components:{StartArea:BS,TitleArea:HS,EndArea:GS,Title:FS,CloseButton:$S}}),zS=()=>{const{Template:e}=Mt.useContext();return a.createElement(e,{titleAlign:"start"})},VS=()=>(CS(),null),ls=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o=!0,style:i})=>{const{Template:c}=Kn.useContext();return a.createElement(ja,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(gS,{announcementsEnabled:s},a.createElement(VS,null),a.createElement(qS,{style:i},a.createElement(c,null)),n))},qS=({style:e,children:t})=>{const n=l.useRef(null);return ES(n),a.createElement(WS,{ref:n,style:e},t)},KS=()=>{const{components:e}=Kn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},Kn=je({template:KS,components:{Header:zS,Body:LS,Footer:OS}}),WS=C.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,YS=U.css`:where(#${Se.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,jS=[YS,Bh,Hh],XS=(e,...t)=>U.createGlobalStyle(e,...jS,...t),ZS=XS``,JS=Su(qn,_t,xt,Gn,Vn,Kn,Et,cs,Mt,zn,Pn),QS=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Xa({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){af(QS?xh:"",t);const[f,g]=l.useState(null),b=l.useCallback(p=>{g(y=>y===p?y:p)},[]),S=m??f,_=a.createElement(U.StyleSheetManager,{target:t},a.createElement(rf,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(kh,{rootElement:t,boundaryElement:S},a.createElement(em,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(Uh,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(tf,{icons:u},a.createElement(JS,null,a.createElement(Mh,{entryElement:S,modalRootElement:h,rootElement:t},i),a.createElement(ZS,null))))))));return m?_:a.createElement("div",{ref:b,style:{display:"contents"}},_)}const ey=()=>{const[e,t]=l.useState(null),[n,r]=l.useState(null),s=l.useCallback(i=>{t(c=>c===i?c:i)},[]),o=l.useCallback(i=>{r(c=>c===i?c:i)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},us=l.forwardRef(function({rootElement:t=document.body,logLevel:n=ie.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var _,p,y;Ft.level!==n&&(Ft.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=ey();of("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const b=ji(r),S=Xi.has(b)?b:Jt;return a.createElement("div",{ref:f,id:Se.ENTRY,lang:S,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(Xa,{logger:Ft,rootElement:t,appearance:(_=u.agentPreviewConfigs)==null?void 0:_.appearance,stringSet:u.stringSet,language:S,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(Bf,{rootElement:t,language:r,logger:Ft,dispatcher:Za,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(p=u.agentPreviewConfigs)==null?void 0:p.forceCreateChannel,_agentVersion:(y=u.agentPreviewConfigs)==null?void 0:y.agentVersion,...u},a.createElement(Yf,{ref:d,userSessionInfo:s},a.createElement(Wb,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(mf,null,o))))),a.createElement("div",{ref:g,id:Se.MODAL_ROOT,dir:u.dir}))}),Ft=new ai(ie.LogLevel.WARN),Za=new si(Ft),{Provider:ty,useContext:nn}=be("PageChildren"),Ja=({children:e})=>{const[t,n]=l.useState(()=>is),[r,s]=l.useState(null),[o,i]=l.useState(()=>ls),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(ty,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},ds=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Se.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Qa=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>a.createElement(Zr,null,a.createElement(ny,{isOpened:t,zIndex:n},e)),ny=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>{const{dir:r,rootElement:s}=le(),o=ut(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Bn();return Fn(t,i,{nameReady:u}),l.useEffect(()=>{const d="sb-agent-block-scroll";return t?o.body.classList.add(d):o.body.classList.remove(d),()=>{o.body.classList.remove(d)}},[o,t]),a.createElement(ry,{ref:i,id:Se.WINDOW,dir:r,...ds(t,c),$visible:t,$zIndex:n},e)},ry=C.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,sy=48,oy=2/3,qo=12;function ec({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:i,imageUrl:c,dir:u,animated:d=!0,backgroundColor:m,size:h=sy,hasUnread:f=!1}){const g=Ra(),b=d&&!g,S=hr(m),_=Math.round(h*oy);return a.createElement(cy,{dir:u,id:Se.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:b,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(ly,{$isOpened:n,$animated:b,$fillColor:S,$iconSize:_,$prefersReducedMotion:g},a.createElement(Ko.Open,{url:c,isDefaultIcon:i==="default_icon",size:_})),a.createElement(uy,{$isOpened:n,$animated:b,$fillColor:S,$iconSize:_,$prefersReducedMotion:g},a.createElement(Ko.Close,{size:_})),f&&a.createElement(dy,null),t)}const iy=U.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,ay=U.css`img{width:100%;height:100%;object-fit:cover;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-drag:none;&[data-default-icon='true']{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;filter:${({$fillColor:e})=>e===Bt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,tc=U.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>U.css`
479
479
  ellipse,
480
480
  path {
481
481
  fill: ${e};
@@ -485,7 +485,7 @@
485
485
  }
486
486
  `}
487
487
  }
488
- `,tS=C.default.button`position:relative;padding:0;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;background:${({$backgroundColor:e})=>e};border-radius:50%;transition:${({$prefersReducedMotion:e})=>e?"none":"all 0.3s cubic-bezier(0.31, -0.105, 0.43, 1.4)"};border:none;display:flex;justify-content:center;align-items:center;box-shadow:0 16px 24px 2px rgba(33,33,33,0.12),0 6px 30px 5px rgba(33,33,33,0.08),0 6px 10px -5px rgba(33,33,33,0.04);${({$animated:e})=>e&&Qy}`,ec=C.default.span.attrs({"aria-hidden":"true"})`
488
+ `,cy=C.default.button`position:relative;padding:0;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;background:${({$backgroundColor:e})=>e};border-radius:50%;transition:${({$prefersReducedMotion:e})=>e?"none":"all 0.3s cubic-bezier(0.31, -0.105, 0.43, 1.4)"};border:none;display:flex;justify-content:center;align-items:center;box-shadow:0 16px 24px 2px rgba(33,33,33,0.12),0 6px 30px 5px rgba(33,33,33,0.08),0 6px 10px -5px rgba(33,33,33,0.04);${({$animated:e})=>e&&iy}`,nc=C.default.span.attrs({"aria-hidden":"true"})`
489
489
  position: absolute;
490
490
  width: 100%;
491
491
  height: 100%;
@@ -495,23 +495,23 @@
495
495
  display: flex;
496
496
  justify-content: center;
497
497
  align-items: center;
498
- `,nS=C.default(ec)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};opacity:${({$isOpened:e})=>e?0:1};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(-90deg) scale(0)":"rotate(0deg)")};${eS}${Qa}`,rS=C.default(ec)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};scale:${({$isOpened:e})=>e?1:0};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(0deg)":"rotate(-90deg)")};${Qa}`,sS=C.default.span.attrs({"aria-hidden":"true"})`
498
+ `,ly=C.default(nc)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};opacity:${({$isOpened:e})=>e?0:1};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(-90deg) scale(0)":"rotate(0deg)")};${ay}${tc}`,uy=C.default(nc)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};scale:${({$isOpened:e})=>e?1:0};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(0deg)":"rotate(-90deg)")};${tc}`,dy=C.default.span.attrs({"aria-hidden":"true"})`
499
499
  position: absolute;
500
500
  top: 1px;
501
501
  inset-inline-end: 1px;
502
- width: ${Vo}px;
503
- height: ${Vo}px;
502
+ width: ${qo}px;
503
+ height: ${qo}px;
504
504
  border-radius: 50%;
505
505
  background-color: ${E.themedColor.error};
506
- `,qo={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(J,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(J,{size:e,type:"chevron-down"})};function tc({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=U.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=ae(),{resolveElement:d}=Vr(),{launcher:m}=re(),{launcherInfo:h}=Oe(),f=i.launcher.unreadBadgeEnabled,g=Ti(),_=Im(o,{enabled:f,opened:u.opened,filter:g}),b=(r??n)==="ConversationList",v={launcher:m.button({isOpened:u.opened,opensConversationList:b})};Tm("launcher_toggle"),iS();const p=()=>{Me(()=>{const T=d(ye.WINDOW),M=T?sa(T):null;M==null||M.focus()})},S=()=>{Me(()=>{var T;(T=d(ye.LAUNCHER))==null||T.focus()})},A=()=>{const T=!u.opened;u.setOpened(T),T?p():S()};return a.createElement(Ja,{dir:c,className:e,isOpened:u.opened,onClick:A,type:h.type,imageUrl:h.imageUrl,backgroundColor:s.base.primary,size:t,hasUnread:f&&!u.opened&&_,...v.launcher.props},v.launcher.descriptionNode)}const oS=1e3*60;function iS(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ae(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===le.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),o(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function c(){o(),s.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},oS)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const nc=l.createContext(null);function ds(){const e=l.useContext(nc);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function rc({children:e}){const t=ds();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}const aS=U.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,cS=U.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,lS=U.css`animation-name:${aS};animation-duration:0.3s;animation-fill-mode:forwards;`,uS=U.css``,dS=U.css`animation-name:${cS};animation-duration:0.3s;animation-fill-mode:forwards;`,mS=U.css`visibility:hidden;`,hS=C.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return lS;case"entered":return uS;case"exiting":return dS;case"exited":return mS;default:return""}}}${({$active:e})=>e?U.css`
506
+ `,Ko={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(J,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(J,{size:e,type:"chevron-down"})};function rc({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=U.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=le(),{resolveElement:d}=qr(),{launcher:m}=re(),{launcherInfo:h}=Ne(),f=i.launcher.unreadBadgeEnabled,g=xi(),b=Om(o,{enabled:f,opened:u.opened,filter:g}),S=(r??n)==="ConversationList",_={launcher:m.button({isOpened:u.opened,opensConversationList:S})};Lm("launcher_toggle"),hy();const p=()=>{we(()=>{const T=d(Se.WINDOW),M=T?ia(T):null;M==null||M.focus()})},y=()=>{we(()=>{var T;(T=d(Se.LAUNCHER))==null||T.focus()})},A=()=>{const T=!u.opened;u.setOpened(T),T?p():y()};return a.createElement(ec,{dir:c,className:e,isOpened:u.opened,onClick:A,type:h.type,imageUrl:h.imageUrl,backgroundColor:s.base.primary,size:t,hasUnread:f&&!u.opened&&b,..._.launcher.props},_.launcher.descriptionNode)}const my=1e3*60;function hy(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=le(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===ie.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),o(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function c(){o(),s.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},my)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const sc=l.createContext(null);function ms(){const e=l.useContext(sc);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function oc({children:e}){const t=ms();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}const fy=U.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,gy=U.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,py=U.css`animation-name:${fy};animation-duration:0.3s;animation-fill-mode:forwards;`,_y=U.css``,Ey=U.css`animation-name:${gy};animation-duration:0.3s;animation-fill-mode:forwards;`,Cy=U.css`visibility:hidden;`,by=C.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return py;case"entered":return _y;case"exiting":return Ey;case"exited":return Cy;default:return""}}}${({$active:e})=>e?U.css`
507
507
  z-index: 999;
508
508
  `:U.css`z-index:1;pointer-events:none;`}
509
- `;function Cn({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((v,p)=>{r(S=>[...S,v]),h(S=>({...S,[v]:!0})),p!=null&&p.reset&&b(S=>({...S,[v]:(S[v]||0)+1})),g(S=>({...S,[v]:"entering"})),setTimeout(()=>{g(S=>({...S,[v]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(v=>{if(v.length<=1)return v;const p=v[v.length-1];return g(S=>({...S,[p]:"exiting"})),setTimeout(()=>{g(S=>({...S,[p]:"exited"})),r(S=>S.slice(0,-1))},300),v})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(v=>v.type===rc),[t]),d=l.useMemo(()=>{const v={};return u.forEach(p=>{const{id:S,lazy:A,children:T}=p.props;v[S]={lazy:A,element:typeof T=="function"?T(c):T}}),v},[u,c]),[m,h]=l.useState(()=>{const v={};return Object.entries(d).forEach(([p,{lazy:S}])=>{S===!1&&(v[p]=!0)}),v[e]=!0,v}),[f,g]=l.useState(()=>{const v={};return Object.keys(d).forEach(p=>{p===e?v[p]="entered":v[p]="exited"}),v}),[_,b]=l.useState({});return a.createElement(nc.Provider,{value:c},a.createElement(fS,null,Object.keys(d).map(v=>{var T;if(!m[v])return null;const p=f[v]||"exited",S=v===s,A=`${v}-${_[v]||0}`;return a.createElement(hS,{key:A,$transitionState:p,$active:S,"aria-hidden":S?void 0:!0,inert:S?void 0:!0},(T=d[v])==null?void 0:T.element)})))}const fS=C.default.div`position:relative;width:100%;height:100%;`;Cn.Screen=rc;const qe={conv:"conv",convList:"conv-list"},gS=e=>e===qe.convList?"ConversationList":"Conversation",pS=({isOpened:e,activeScreenId:t})=>e&&t===qe.conv,sc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:s})=>{const{conversationComponent:o,conversationChildren:i,conversationListComponent:c,conversationListChildren:u}=tn(),[d,m]=l.useState(),h=(()=>{switch(t){case"Conversation":return qe.conv;case"ConversationList":return qe.convList;default:return qe.conv}})(),f=a.createElement(a.Fragment,null,a.createElement(_S,{onOpenConversationView:(g,_)=>{r(_),m(void 0),g.navigate(qe.conv)}}),a.createElement(ES,{onActiveRouteChange:s}));return a.createElement(Cn,{initialId:h},a.createElement(Cn.Screen,{id:qe.conv},({navigation:g,activeScreenId:_})=>{const b=pS({isOpened:e,activeScreenId:_});return a.createElement(a.Fragment,null,f,a.createElement(o,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{m(void 0),g.navigate(qe.convList)},announcementsEnabled:b,conversationStatsEnabled:b,shouldMarkAsRead:b,initialFocusTarget:d},i))}),a.createElement(Cn.Screen,{id:qe.convList,lazy:!0},({navigation:g,activeScreenId:_})=>{const b=e&&_===qe.convList;return a.createElement(a.Fragment,null,f,a.createElement(c,{announcementsEnabled:b,conversationListStatsEnabled:b,onOpenConversationView:(v,p,S)=>{r(v),m(S==null?void 0:S.initialFocusTarget),g.navigate(qe.conv)}},u))}))},_S=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Oe(),{navigation:n}=ds();return t(({channel:r})=>{e(n,r.url)}),null},ES=({onActiveRouteChange:e})=>{const{activeScreenId:t}=ds();return l.useEffect(()=>{e==null||e(gS(t))},[t,e]),null},CS=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(Xr,null,a.createElement(bS,{isExpanded:e,isOpened:t,launcher:r},n)),bS=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=ae(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Un();return $n(t,o,{nameReady:c}),a.createElement(vS,null,a.createElement(yS,{ref:o,dir:s,id:ye.WINDOW,...us(t,i),$isExpanded:e,$isOpened:t},n),r)},vS=C.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,yS=C.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;transform:scale(0.15);opacity:0;transform-origin:right bottom;[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform-origin:left bottom;}${({$isOpened:e})=>e&&AS};${({$isExpanded:e})=>e&&SS};`,SS=U.css`width:743px;height:723px;`,AS=U.css`pointer-events:all;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;`,TS=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=Jt(),[o,i]=l.useState(t),[c,u]=l.useState(n.entryPoint??"Conversation"),d=s?Za:CS;return a.createElement(ls,{enableExpandButton:!s,ref:r,...n},a.createElement(ia,null,({state:m})=>a.createElement(Xa,null,a.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...s&&{zIndex:"auto"},launcher:a.createElement(tc,{entryPoint:n.entryPoint,activeRoute:c})},a.createElement(sc,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,onActiveRouteChange:u})),e)))}),{Provider:IS,useContext:ms}=be("FixedMessengerStyle");function oc(e,t,n,r=0){const{top:s,bottom:o,start:i,end:c}=n;let u="",d="";switch(e){case"start":d=`inset-inline-start: ${Ze(i)}`;break;case"end":d=`inset-inline-end: ${Ze(c)}`;break}switch(t){case"top":u=`top: calc(${Ze(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Ze(o)} + ${r}px)`;break}return U.css`${u};${d};`}function xS(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=ms();return a.createElement(RS,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const RS=C.default(tc)`position:fixed;z-index:${gt.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>oc(e,t,n)};`,MS=({isExpanded:e,isOpened:t,children:n})=>a.createElement(Xr,null,a.createElement(wS,{isExpanded:e,isOpened:t},n)),wS=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=ae(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=ms(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Un();return $n(t,u,{nameReady:m}),a.createElement(kS,{ref:u,dir:r,id:ye.WINDOW,...us(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},kS=C.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;position:fixed;pointer-events:none;visibility:hidden;${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>oc(e,t,n,r+12)};height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 150ms;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
509
+ `;function vn({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((_,p)=>{r(y=>[...y,_]),h(y=>({...y,[_]:!0})),p!=null&&p.reset&&S(y=>({...y,[_]:(y[_]||0)+1})),g(y=>({...y,[_]:"entering"})),setTimeout(()=>{g(y=>({...y,[_]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(_=>{if(_.length<=1)return _;const p=_[_.length-1];return g(y=>({...y,[p]:"exiting"})),setTimeout(()=>{g(y=>({...y,[p]:"exited"})),r(y=>y.slice(0,-1))},300),_})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(_=>_.type===oc),[t]),d=l.useMemo(()=>{const _={};return u.forEach(p=>{const{id:y,lazy:A,children:T}=p.props;_[y]={lazy:A,element:typeof T=="function"?T(c):T}}),_},[u,c]),[m,h]=l.useState(()=>{const _={};return Object.entries(d).forEach(([p,{lazy:y}])=>{y===!1&&(_[p]=!0)}),_[e]=!0,_}),[f,g]=l.useState(()=>{const _={};return Object.keys(d).forEach(p=>{p===e?_[p]="entered":_[p]="exited"}),_}),[b,S]=l.useState({});return a.createElement(sc.Provider,{value:c},a.createElement(vy,null,Object.keys(d).map(_=>{var T;if(!m[_])return null;const p=f[_]||"exited",y=_===s,A=`${_}-${b[_]||0}`;return a.createElement(by,{key:A,$transitionState:p,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(T=d[_])==null?void 0:T.element)})))}const vy=C.default.div`position:relative;width:100%;height:100%;`;vn.Screen=oc;const qe={conv:"conv",convList:"conv-list"},Sy=e=>e===qe.convList?"ConversationList":"Conversation",yy=({isOpened:e,activeScreenId:t})=>e&&t===qe.conv,ic=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:s})=>{const{conversationComponent:o,conversationChildren:i,conversationListComponent:c,conversationListChildren:u}=nn(),[d,m]=l.useState(),h=(()=>{switch(t){case"Conversation":return qe.conv;case"ConversationList":return qe.convList;default:return qe.conv}})(),f=a.createElement(a.Fragment,null,a.createElement(Ay,{onOpenConversationView:(g,b)=>{r(b),m(void 0),g.navigate(qe.conv)}}),a.createElement(Ty,{onActiveRouteChange:s}));return a.createElement(vn,{initialId:h},a.createElement(vn.Screen,{id:qe.conv},({navigation:g,activeScreenId:b})=>{const S=yy({isOpened:e,activeScreenId:b});return a.createElement(a.Fragment,null,f,a.createElement(o,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{m(void 0),g.navigate(qe.convList)},announcementsEnabled:S,conversationStatsEnabled:S,shouldMarkAsRead:S,initialFocusTarget:d},i))}),a.createElement(vn.Screen,{id:qe.convList,lazy:!0},({navigation:g,activeScreenId:b})=>{const S=e&&b===qe.convList;return a.createElement(a.Fragment,null,f,a.createElement(c,{announcementsEnabled:S,conversationListStatsEnabled:S,onOpenConversationView:(_,p,y)=>{r(_),m(y==null?void 0:y.initialFocusTarget),g.navigate(qe.conv)}},u))}))},Ay=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Ne(),{navigation:n}=ms();return t(({channel:r})=>{e(n,r.url)}),null},Ty=({onActiveRouteChange:e})=>{const{activeScreenId:t}=ms();return l.useEffect(()=>{e==null||e(Sy(t))},[t,e]),null},Iy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(Zr,null,a.createElement(xy,{isExpanded:e,isOpened:t,launcher:r},n)),xy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=le(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Bn();return Fn(t,o,{nameReady:c}),a.createElement(Ry,null,a.createElement(My,{ref:o,dir:s,id:Se.WINDOW,...ds(t,i),$isExpanded:e,$isOpened:t},n),r)},Ry=C.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,My=C.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;transform:scale(0.15);opacity:0;transform-origin:right bottom;[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform-origin:left bottom;}${({$isOpened:e})=>e&&ky};${({$isExpanded:e})=>e&&wy};`,wy=U.css`width:743px;height:723px;`,ky=U.css`pointer-events:all;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;`,Ly=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=Qt(),[o,i]=l.useState(t),[c,u]=l.useState(n.entryPoint??"Conversation"),d=s?Qa:Iy;return a.createElement(us,{enableExpandButton:!s,ref:r,...n},a.createElement(ca,null,({state:m})=>a.createElement(Ja,null,a.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...s&&{zIndex:"auto"},launcher:a.createElement(rc,{entryPoint:n.entryPoint,activeRoute:c})},a.createElement(ic,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,onActiveRouteChange:u})),e)))}),{Provider:Oy,useContext:hs}=be("FixedMessengerStyle");function ac(e,t,n,r=0){const{top:s,bottom:o,start:i,end:c}=n;let u="",d="";switch(e){case"start":d=`inset-inline-start: ${Ze(i)}`;break;case"end":d=`inset-inline-end: ${Ze(c)}`;break}switch(t){case"top":u=`top: calc(${Ze(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Ze(o)} + ${r}px)`;break}return U.css`${u};${d};`}function Dy(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=hs();return a.createElement(Ny,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const Ny=C.default(rc)`position:fixed;z-index:${gt.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>ac(e,t,n)};`,$y=({isExpanded:e,isOpened:t,children:n})=>a.createElement(Zr,null,a.createElement(Fy,{isExpanded:e,isOpened:t},n)),Fy=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=le(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=hs(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Bn();return Fn(t,u,{nameReady:m}),a.createElement(Py,{ref:u,dir:r,id:Se.WINDOW,...ds(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},Py=C.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;position:fixed;pointer-events:none;visibility:hidden;${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>ac(e,t,n,r+12)};height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 150ms;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
510
510
  [dir='rtl'] &:not([dir='ltr']),
511
511
  &[dir='rtl'] {
512
512
  transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
513
513
  }
514
514
 
515
- ${({$isOpened:e})=>e&&OS};
516
- ${({$isExpanded:e})=>e&&LS};
517
- `,LS=U.css`width:743px;height:723px;`,OS=U.css`z-index:${gt.WINDOW};pointer-events:all;visibility:visible;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 0s;`,ic={top:24,bottom:24,start:24,end:24},NS=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(n.entryPoint??"Conversation"),[u,d]=l.useState("end-bottom"),[m,h]=l.useState(ic),[f,g]=l.useState(48),_=Jt(),b=_?Za:MS,{horizontal:v,vertical:p}=l.useMemo(()=>{const[S,A]=u.split("-");return{horizontal:S==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[u]);return a.createElement(ls,{enableExpandButton:!_,ref:r,...n},a.createElement(ia,null,({state:S})=>a.createElement(IS,{value:{horizontal:v,vertical:p,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:g}},a.createElement(Xa,null,a.createElement(b,{isExpanded:S.expanded,isOpened:S.opened},a.createElement(sc,{isOpened:S.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,onActiveRouteChange:c})),a.createElement(xS,{entryPoint:n.entryPoint,activeRoute:i}),e))))}),DS=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=ms();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...ic,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(s=e.margin)==null?void 0:s.top,(o=e.margin)==null?void 0:o.bottom,(i=e.margin)==null?void 0:i.start,(c=e.margin)==null?void 0:c.end,e.launcherSize]),null},$S=({children:e})=>{const{setConversationChildren:t}=tn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},FS=({component:e})=>{const{setConversationComponent:t}=tn();return l.useLayoutEffect(()=>(t(e),()=>t(os)),[e,t]),null},PS=({children:e})=>{const{setConversationListChildren:t}=tn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},US=({component:e})=>{const{setConversationListComponent:t}=tn();return l.useLayoutEffect(()=>(t(e),()=>t(cs)),[e,t]),null},BS=Object.assign(NS,{Style:DS,Conversation:FS,ConversationChildren:$S,ConversationList:US,ConversationListChildren:PS}),HS=e=>{const{refreshActiveChannel:t}=Oe(),[n,r]=l.useState(!1),s=l.useRef(null),o=l.useRef(null);return l.useEffect(()=>{n&&t().then(()=>{var i;(i=s.current)==null||i.call(s),r(!1)}).catch(i=>{var c;(c=o.current)==null||c.call(o,i),r(!1)})},[n]),l.useCallback(()=>new Promise((i,c)=>{s.current=i,o.current=c,e().then(()=>r(!0)).catch(c)}),[e])};pi.set(le.SendbirdPlatform.JS,{deviceOSPlatform:Oc()?le.DeviceOsPlatform.MOBILE_WEB:le.DeviceOsPlatform.WEB,messengerVersion:gh,keyValueStorage:Eh(),networkStateAdapter:_h(),scheduleForegroundTask:ph});exports.ANCHOR_REL=zr;exports.AgentProviderContainer=ls;exports.AgentUIProviderContainer=Wa;exports.AnonymousSessionInfo=ur;exports.CSATType=Je;exports.Commands=ct;exports.ConnectionDelayLayout=Fn;exports.Conversation=os;exports.ConversationContext=eg;exports.ConversationContextProvider=da;exports.ConversationHeaderLayout=Et;exports.ConversationLayout=Vn;exports.ConversationList=cs;exports.ConversationListContext=uy;exports.ConversationListContextProvider=Ya;exports.ConversationListHeaderLayout=Mt;exports.ConversationListItemLayout=as;exports.ConversationListLayout=qn;exports.DefaultMessenger=TS;exports.DeskTicketPriority=Dr;exports.DeskTicketStatus=Nr;exports.FixedMessenger=BS;exports.ID_INCOMING=tt;exports.IncomingMessageLayout=_t;exports.LauncherBase=Ja;exports.LogLevel=wr;exports.ManualSessionInfo=ai;exports.MessageListUILayout=zn;exports.MessageLogs=Pa;exports.OutgoingMessageLayout=xt;exports.PlaceholderLayout=Gn;exports.SystemMessageLayout=Hn;exports.cssVars=E;exports.escapeMarkdownSyntax=kc;exports.flattenObject=Jl;exports.mapCommonStringsToReactFormat=Ki;exports.messengerDispatcher=ja;exports.noop=ce;exports.parseToMessageTemplate=fi;exports.parseToUITemplate=Xl;exports.pickColorByTheme=Zl;exports.replaceVariablesAsync=eu;exports.replaceVariablesSync=Ql;exports.useAIAgentContext=we;exports.useConversationContext=Ae;exports.useConversationListContext=en;exports.useLocalizationContext=oe;exports.useMessageTemplateFetchingContext=Kd;exports.useMessengerContext=ae;exports.useMessengerSessionContext=Oe;exports.useMessengerThemeContext=Ji;exports.useRefreshActiveChannel=HS;
515
+ ${({$isOpened:e})=>e&&By};
516
+ ${({$isExpanded:e})=>e&&Uy};
517
+ `,Uy=U.css`width:743px;height:723px;`,By=U.css`z-index:${gt.WINDOW};pointer-events:all;visibility:visible;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 0s;`,cc={top:24,bottom:24,start:24,end:24},Hy=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(n.entryPoint??"Conversation"),[u,d]=l.useState("end-bottom"),[m,h]=l.useState(cc),[f,g]=l.useState(48),b=Qt(),S=b?Qa:$y,{horizontal:_,vertical:p}=l.useMemo(()=>{const[y,A]=u.split("-");return{horizontal:y==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[u]);return a.createElement(us,{enableExpandButton:!b,ref:r,...n},a.createElement(ca,null,({state:y})=>a.createElement(Oy,{value:{horizontal:_,vertical:p,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:g}},a.createElement(Ja,null,a.createElement(S,{isExpanded:y.expanded,isOpened:y.opened},a.createElement(ic,{isOpened:y.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,onActiveRouteChange:c})),a.createElement(Dy,{entryPoint:n.entryPoint,activeRoute:i}),e))))}),Gy=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=hs();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...cc,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(s=e.margin)==null?void 0:s.top,(o=e.margin)==null?void 0:o.bottom,(i=e.margin)==null?void 0:i.start,(c=e.margin)==null?void 0:c.end,e.launcherSize]),null},zy=({children:e})=>{const{setConversationChildren:t}=nn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Vy=({component:e})=>{const{setConversationComponent:t}=nn();return l.useLayoutEffect(()=>(t(e),()=>t(is)),[e,t]),null},qy=({children:e})=>{const{setConversationListChildren:t}=nn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Ky=({component:e})=>{const{setConversationListComponent:t}=nn();return l.useLayoutEffect(()=>(t(e),()=>t(ls)),[e,t]),null},Wy=Object.assign(Hy,{Style:Gy,Conversation:Vy,ConversationChildren:zy,ConversationList:Ky,ConversationListChildren:qy}),Yy=e=>{const{refreshActiveChannel:t}=Ne(),[n,r]=l.useState(!1),s=l.useRef(null),o=l.useRef(null);return l.useEffect(()=>{n&&t().then(()=>{var i;(i=s.current)==null||i.call(s),r(!1)}).catch(i=>{var c;(c=o.current)==null||c.call(o,i),r(!1)})},[n]),l.useCallback(()=>new Promise((i,c)=>{s.current=i,o.current=c,e().then(()=>r(!0)).catch(c)}),[e])};Ei.set(ie.SendbirdPlatform.JS,{deviceOSPlatform:Nc()?ie.DeviceOsPlatform.MOBILE_WEB:ie.DeviceOsPlatform.WEB,messengerVersion:Sh,keyValueStorage:Th(),networkStateAdapter:Ah(),scheduleForegroundTask:yh});exports.ANCHOR_REL=Vr;exports.AgentProviderContainer=us;exports.AgentUIProviderContainer=Xa;exports.AnonymousSessionInfo=dr;exports.CSATType=Je;exports.Commands=ct;exports.ConnectionDelayLayout=Pn;exports.Conversation=is;exports.ConversationContext=ag;exports.ConversationContextProvider=ha;exports.ConversationHeaderLayout=Et;exports.ConversationLayout=qn;exports.ConversationList=ls;exports.ConversationListContext=_S;exports.ConversationListContextProvider=ja;exports.ConversationListHeaderLayout=Mt;exports.ConversationListItemLayout=cs;exports.ConversationListLayout=Kn;exports.DefaultMessenger=Ly;exports.DeskTicketPriority=$r;exports.DeskTicketStatus=Nr;exports.FixedMessenger=Wy;exports.ID_INCOMING=tt;exports.IncomingMessageLayout=_t;exports.LauncherBase=ec;exports.LogLevel=kr;exports.ManualSessionInfo=ci;exports.MessageListUILayout=Vn;exports.MessageLogs=Ba;exports.OutgoingMessageLayout=xt;exports.PlaceholderLayout=zn;exports.SystemMessageLayout=Gn;exports.cssVars=E;exports.escapeMarkdownSyntax=Oc;exports.flattenObject=eu;exports.mapCommonStringsToReactFormat=Yi;exports.messengerDispatcher=Za;exports.noop=ue;exports.parseToMessageTemplate=gi;exports.parseToUITemplate=Jl;exports.pickColorByTheme=Ql;exports.replaceVariablesAsync=nu;exports.replaceVariablesSync=tu;exports.useAIAgentContext=ke;exports.useConversationContext=Ae;exports.useConversationListContext=tn;exports.useLocalizationContext=se;exports.useMessageTemplateFetchingContext=Qd;exports.useMessengerContext=le;exports.useMessengerSessionContext=Ne;exports.useMessengerThemeContext=ea;exports.useRefreshActiveChannel=Yy;