@sendbird/ai-agent-messenger-react 1.36.0 → 1.38.0

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 nc=Object.defineProperty;var rc=(e,t,n)=>t in e?nc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>rc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ce=require("@sendbird/chat"),l=require("react"),H=require("styled-components"),ot=require("date-fns"),sc=require("date-fns/locale/en-US"),De=require("@sendbird/chat/message"),fe=require("@sendbird/chat/aiAgent"),oc=require("react-dom"),We=require("@sendbird/chat/groupChannel"),ic=require("date-fns/isSameDay"),ac=require("dompurify"),Ar=e=>e&&e.__esModule?e:{default:e};function cc(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 lc=Ar(Ce),a=cc(l),E=Ar(H),zo=Ar(ac),Vo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},uc=e=>{const t=Vo(e);return typeof t=="object"&&t!==null?t:{}},qo=e=>typeof e=="string"?uc(e):e??{},dc=e=>!!qo(e).stream,ms=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},Ko=e=>{const t=qo(e),n=ms(t.user_message_id)??ms(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},Ct="sb-agent",Yo="KEY_IMG_ASPECT_RATIO",ir="*/*",re={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 pn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(pn||{}),Ft=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Ft||{});const mc=e=>!!(e!=null&&e.cta_button),hc=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Wo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,fc=e=>{var t;return Wo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},gc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},He=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},In=e=>Object.defineProperties({},{hasMessageTemplate:He(()=>!!(e!=null&&e.message_template)),hasCTAButton:He(()=>mc(e)),hasChallenge:He(()=>!!(e!=null&&e.challenge)),isThinking:He(()=>!!(e!=null&&e.is_thinking)),hasCSAT:He(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:He(()=>gc(e)),hasCustomMessageTemplates:He(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:He(()=>Wo(e)),hasActiveForm:He(()=>fc(e)),hasSteward:He(()=>!!(e!=null&&e.steward)),hasCitations:He(()=>hc(e))}),pc=e=>{const t=In(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)},_c=e=>e===Ft.COMPLETED||e===Ft.CANCELED?e:Ft.IN_PROGRESS,Gn=e=>Xe(e)&&!jo(e),Xe=e=>!!e&&"sender"in e,Ec=e=>Xe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Cc=(e,t,n,r=!0)=>{if(!r||!Gn(e))return"single";const s=()=>{if(!Gn(t))return!1;const u=t.sender.userId===e.sender.userId,d=ot.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Gn(n))return!1;const u=n.sender.userId===e.sender.userId,d=ot.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},tt=(e,t)=>(()=>{var r;return Xe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Oe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>jo(e),isIncoming:(e,t)=>Xe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Xe(e)&&(e.sender.userId===t||e.sendingStatus===De.SendingStatus.PENDING)},Ve=e=>e.startsWith("image/"),zt=e=>e.startsWith("video/"),bc=e=>e.startsWith("audio/"),Xo=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Tr=(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"},Zo=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},vc=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return pc(t)},xn=e=>{switch(e){case"top":case"middle":return re.GAP_GROUPED;default:return re.GAP_UNGROUPED}},Sc=(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},yc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Ac=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Tc=e=>e.replace(/~~/g,"\\~\\~"),Ic=e=>{let t=e;return t=yc(t),t=Ac(t),t=Tc(t),t},xc=typeof navigator<"u"&&navigator.product==="ReactNative",hs=(e,t)=>{const n=r=>!t||t.length===0?!0:Xe(r)&&t.includes(r.sendingStatus);return xc?e.find(n):e.findLast(n)},Ie=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function he(){}function Rc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Mc(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 ke={isStreaming(e){return dc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(ke.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!tt(e,t))return!1;const n=Ko(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)}},zn=`@${Ct}`,wc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${zn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Mc(`${e}/${t}/${s}`);return`${zn}-udata/${o}`},anonUserSession:()=>`${zn}-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}}}}},Jo=(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},kc=()=>{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 Lc{constructor(t){S(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 Qo extends We.BaseChannelCollection{constructor(n,r){const s=new Lc(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:C,copilotConversationOnly:v,copilotSupportChannelUrl:p}=s.params,b={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:C,copilotConversationOnly:v,copilotSupportChannelUrl:p};return i.getMyGroupChannelChangeLogs(m,b,We.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});S(this,"_params");S(this,"_sdk");S(this,"_throttledOnChannelChanged");S(this,"_key");S(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${kc()}`,this._throttledOnChannelChanged=Jo(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:C,context:v}of m)h.delete(C.url),h.set(C.url,{channel:C,context:v});const f=new Map;for(const{channel:C,context:v}of h.values())f.has(v)||f.set(v,new Map),f.get(v).set(C.url,C);for(const[C,v]of f){const p=Array.from(v.values()),b=(g=this._sdk.currentUser)==null?void 0:g.userId,y=p.filter(T=>this.filter.match(T,b)),A=p.filter(T=>!this.filter.match(T,b)).map(T=>T.url);y.length>0&&this._base._addChannelsToView(y,C,!1),A.length>0&&this._removeChannels(A,C)}},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 ei{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=Oc(),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 Oc=()=>{let e=he,t=he;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var ze=(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))(ze||{});class Vt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const it={CloseConversation:e=>new Nc(e),MessengerSettingsUpdated:e=>new Dc(e),ActiveChannelUpdated:e=>new $c(e),AnonymousSessionTokenExpired:()=>new Pc,AuthTokenRefreshed:()=>new Fc};class Nc extends Vt{constructor(){super(...arguments);S(this,"type","conv.close")}}class Dc extends Vt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class $c extends Vt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Pc extends Vt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Fc extends Vt{constructor(){super(...arguments);S(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){S(this,"category","connection");this.userId=t}get data(){return qt({user_id:this.userId})}}class Uc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_connected")}}class Bc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_started")}}class Hc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_succeeded")}}class Gc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_failed")}}class zc extends Kt{constructor(){super(...arguments);S(this,"metricKey","connection_disconnected")}}class Vc{constructor(t){S(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 Uc(n):t==="reconnectStarted"?new Bc(n):t==="reconnectSucceeded"?new Hc(n):t==="reconnectFailed"?new Gc(n):new zc(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Ir{constructor(t,n){S(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class qc extends Ir{constructor(){super(...arguments);S(this,"metricKey","conversation_initialized")}}class Kc extends Ir{constructor(){super(...arguments);S(this,"metricKey","conversation_open")}}class Yc extends Ir{constructor(){super(...arguments);S(this,"metricKey","conversation_closed")}}class Wc{constructor(t){S(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 qc(t.url,n.id):s===fe.ConversationStatus.OPEN?new Kc(t.url,n.id):new Yc(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 ti=(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")},xr=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 et(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 jc(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!et(e):!1}function Xc(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function ni(e){return!!e&&e<=Date.now()}function Zc(e){return!e.title}function Jc(e,t){var n;if(e)return Zc(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 Rr{constructor(t,n){S(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return qt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Qc extends Rr{constructor(){super(...arguments);S(this,"metricKey","handoff_started")}}class el extends Rr{constructor(){super(...arguments);S(this,"metricKey","handoff_succeeded")}}class tl extends Rr{constructor(){super(...arguments);S(this,"metricKey","handoff_failed")}}class nl{constructor(t){S(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 Qc(t.url,r.id):o==="succeeded"?new el(t.url,r.id):new tl(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 rl{constructor(t){S(this,"category","message");S(this,"metricKey","incoming_message_received");S(this,"channelUrl");S(this,"messageId");S(this,"senderType");S(this,"createdAt");S(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 sl=(e,t)=>{const n=Xe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class ol{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 rl({channelUrl:t.url,messageId:n.messageId,senderType:sl(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!tt(t,this.getCurrentUserId())&&n!==null}}class il{constructor(t){S(this,"category","message");S(this,"metricKey");S(this,"channelUrl");S(this,"requestId");S(this,"messageId");S(this,"target");S(this,"sendingStatus");S(this,"createdAt");S(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 al=e=>{switch(e){case De.SendingStatus.PENDING:return"pending";case De.SendingStatus.SUCCEEDED:return"succeeded";case De.SendingStatus.FAILED:return"failed";case De.SendingStatus.SCHEDULED:return"scheduled";default:return}};class cl{constructor(t,n){S(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!tt(n,this.getCurrentUserId()))return;const r=al(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 il({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:et(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 ll{constructor(t){S(this,"id","aiagent_livemetric");S(this,"dispatch");S(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});S(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new Vc(this.emit),conversation:new Wc(this.emit),handoff:new nl(this.emit),incomingMessage:new ol(this.emit,n),outgoingMessage:new cl(this.emit,n)}}start(){const t=new Ce.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 Mr=(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))(Mr||{});class ri{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ct}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ct}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ct}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ct}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ct}/error]`,...t)}}class si{constructor({userId:t,authToken:n,sessionHandler:r}){S(this,"userId");S(this,"authToken");S(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class ar{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const ul=e=>({onSessionTokenRequired:t=>{t(null),e.send(it.AnonymousSessionTokenExpired())}}),wr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),dl="ai_agent:stats",ml="conversation_initial_render",hl="conversation_not_interactive_timeout",fl="recovery_not_interactive_timeout",gl="conversation_list_initial_render",pl="message_pending_stuck",_l="aiev_auth_expired_unhandled",El="user_perceived_response_time",Cl="stream_stalled",bl="ai_typing_indicator_absent_timeout",vl="rendered_content_unusable",Sl=800220;var z=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(z||{});const cr=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),oi=e=>typeof e=="object"&&e!==null,yl=e=>{if(oi(e))return typeof e.code=="number"?e.code:void 0},Al=e=>e instanceof Error?e.message:typeof e=="string"?e:oi(e)&&typeof e.message=="string"?e.message:"";class Ze{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=yl(t)??Sl,this.errorDescription=Al(t),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:performance.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:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=wr({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(dl,t)):!1}}class fs extends Ze{constructor(){super(...arguments);S(this,"reason");S(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return _l}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Rn{constructor(t){S(this,"commitCallback");this.commitCallback=t}}class It extends Rn{constructor(){super(...arguments);S(this,"records",new Map)}}class ii extends Rn{constructor(){super(...arguments);S(this,"activeSpan",null);S(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class ai{constructor(t,n){S(this,"stats");S(this,"visible");S(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const dt=(e,t)=>!(e&&t&&e!==t),lr=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&dt(n.measure.channelUrl,t))return!0;return!1},Mn=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class Tl extends Rn{onPayloadParseFailed(t){new fs().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new fs().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Il extends Ze{constructor(){super(...arguments);S(this,"channelUrl",null);S(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(z.PAGE_RENDER),this.timers.delete(z.PAGE_RENDER_FROM_CACHE),this.timers.delete(z.GET_CHANNEL),this.timers.delete(z.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return ml}buildPayload(){const n=this.getTimer(z.AUTH),r=this.getTimer(z.PAGE_RENDER),s=this.getTimer(z.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-cr(n,r),i=s.duration===null?null:s.duration-cr(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[z.AUTH]:n.duration,[z.GET_CHANNEL]:this.getTimer(z.GET_CHANNEL).duration,[z.GET_MESSAGES]:this.getTimer(z.GET_MESSAGES).duration,[z.PAGE_RENDER_FROM_CACHE]:i}})}}class xl extends ai{constructor(n,r,s){var o;super(n,s);S(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(z.PAGE_RENDER).startTimer(z.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(z.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(z.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(z.GET_CHANNEL).setError(r).stopTimer(z.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(z.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(z.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(z.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(z.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(z.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(z.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Rl extends ii{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Il().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(z.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(z.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(z.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new xl(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Ml extends Ze{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(z.PAGE_RENDER),this.timers.delete(z.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return gl}buildPayload(){const n=this.getTimer(z.AUTH),r=this.getTimer(z.PAGE_RENDER),s=this.getTimer(z.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-cr(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[z.AUTH]:n.duration,[z.GET_LIST]:s}})}}class wl extends ai{constructor(n,r){var s;super(n,r);S(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(z.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(z.PAGE_RENDER),this.stats.startTimer(z.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(z.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(z.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(z.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(z.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class kl extends ii{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Ml().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(z.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(z.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(z.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(z.AUTH),this.activeSpan=new wl(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Ll extends Ze{constructor(){super(...arguments);S(this,"phaseReached","auth");S(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return hl}buildPayload(){const n=this.getTimer(z.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class Ol extends It{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new Ll().setCommitCallback(this.commitCallback).startTimer(z.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(z.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Nl extends Ze{constructor(){super(...arguments);S(this,"requestId");S(this,"messageType");S(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return pl}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const Dl=5e3,gs=1e4;class $l extends It{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new Nl().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?gs:Dl;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),gs))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class Vn extends Ze{constructor(){super(...arguments);S(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return fl}buildPayload(){const n=this.getTimer(z.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class Pl extends It{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new Vn().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(z.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(z.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new Vn().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new Vn().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class Fl extends Ze{constructor(){super(...arguments);S(this,"messageId");S(this,"contentKind");S(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return vl}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const Ul=500;class Bl extends Rn{constructor(){super(...arguments);S(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;Mn(this.measure.committed,Ul),this.measure.committed.add(r),new Fl().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class Hl extends Ze{constructor(){super(...arguments);S(this,"durationMs");S(this,"messageId");S(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return Cl}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const ps=1e4,Et=5e3,Gl=500;class zl extends It{constructor(){super(...arguments);S(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,Et))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,Et)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,Et))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<Et){this.scheduleRenderStallCheck(n,r,Et-o);return}const i=performance.now()-s.lastRawAt;if(i>=Et&&s.deliveryTimer!==null){const c=ps-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),ps))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new Hl().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||Mn(this.emittedMessageChannels,Gl),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class Vl extends Ze{constructor(){super(...arguments);S(this,"beforeTpstAbsentMs");S(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return bl}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[z.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[z.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const _s=3e3,ql=3e4;class Kl extends It{constructor(){super(...arguments);S(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new Vl().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),ql),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{dt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{dt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!lr(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(Mn(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{dt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{dt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=_s&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=_s&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class Yl extends Ze{constructor(){super(...arguments);S(this,"ackToFirstChunkMs");S(this,"firstChunkToRenderMs");S(this,"isStreaming");S(this,"sendToAckMs");S(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return El}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[z.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[z.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[z.SEND_TO_ACK]:this.sendToAckMs}})}}const Wl=.15,jl=10,Xl=e=>e<=0?!1:e>=1?!0:Math.random()<e;class Zl extends It{constructor(n,r){super(n);S(this,"samplingRate");S(this,"pendingAIResponseByUserMessageId",new Map);S(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??Wl}startTurn(n){if(this.collectedCount>=jl||!Xl(this.samplingRate))return;this.collectedCount+=1;const r={stats:new Yl().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&lr(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!lr(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&dt(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&dt(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||(Mn(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function Jl(){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 Es={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},kr={conversation:{...Es,messageAlertSoundEnabled:!1,list:{...Es,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Cs=e=>e?{conversation:tu(e.conversation),launcher:Ql(e.launcher)}:kr,Ql=e=>bt(kr.launcher,e),eu=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},tu=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={...bt(t.list,c,n),deferredMarkdownElements:eu(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:bt(t.header,r),input:{camera:bt(t.input.camera,u),gallery:bt(t.input.gallery,d),fileEnabled:m},fileViewer:bt(t.fileViewer,o)}},bt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,wr(r));return n},nu=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}),ru=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),ur=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class su{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_initConversationRequests",new Map);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Jo(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 Ce.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})});S(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")});S(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)}});S(this,"_initConversationIfNeeded",t=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const n=this._initConversationRequests.get(t.url);if(n)return n;const r=t.initConversation({aiAgentId:this.aiAgentId}).then(()=>{}).catch(s=>{this._logger.warn("AIAgentEventManager: initConversation failed",s)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,r),r});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(ze.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(ze.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(ze.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(ze.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(ze.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(ze.AuthTokenRefreshed,t)}))}}class ou{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(it.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(it.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 ci=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)}},li=e=>JSON.parse(e),iu=e=>JSON.parse(e);function au(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function cu(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 lu({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,ci(c))},e)}async function uu({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,ci(c)),e)}var Lr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Lr||{});const ui=e=>typeof e=="object"&&e!==null,bs=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",du=e=>!ui(e)||!bs(e,"channel_url")||!bs(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},mu={1:du};function hu(e){if(!ui(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=mu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function fu(e,t,n,r){const s=lc.default.init({appId:e,modules:[new We.GroupChannelModule,new fe.AIAgentModule],localCacheEnabled:!0,options:new Ce.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:Ce.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function gu(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 pu=[400300,400301,400302,400310],_u=Lr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Eu=e=>`${_u}:${e}`;class Or{constructor(t,n,r,s,o){S(this,"chatSDK");S(this,"_aiAgentId");S(this,"_externalAuthTokenExpiredEventHandlerKey");S(this,"_logger");S(this,"_cache");S(this,"_statsTrackers");S(this,"_sessionHandler");S(this,"_aiEventHandlerRegistered",!1);S(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const o=new Ce.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}});S(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});S(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=hu(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)});S(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});S(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")});S(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));S(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));S(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));S(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});S(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});S(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});S(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)})}});S(this,"_isCacheRestrictedError",t=>pu.some(n=>t.code===n));S(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}=li(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=Eu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(gu(t.chatSDK),n=t.chatSDK):n=fu(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Or(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Cu=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},bu=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},en=new Map,di={set:(e,t)=>{en.set(e,t)},get:e=>{if(en.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=en.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=en.entries().next().value;return{platform:t[0],...t[1]}}};class vs extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);S(this,"status");S(this,"code");S(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||{}),mi=(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))(mi||{});const vu=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Su{constructor(t){S(this,"_appId");S(this,"_apiHost");S(this,"_logger");S(this,"_credential",null);S(this,"_authRefreshPromise",null);S(this,"_onDeskTokenRefreshRequired",async()=>!1);S(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)});S(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});S(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});S(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!vu(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)});S(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}});S(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))}:{}}));S(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));S(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));S(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));S(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new vs(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new vs(t.status,{})}});S(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}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class _n{constructor(t,n){S(this,"id");S(this,"title");S(this,"status");S(this,"agent");S(this,"priority");S(this,"group");S(this,"firstResponseTime");S(this,"issuedAt");S(this,"customFields");S(this,"_client");S(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 _n({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){S(this,"_logger");S(this,"_apiClient");S(this,"_onDeskTokenRefreshRequired");S(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);S(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}});S(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});S(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")});S(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return _n._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:wr({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 _n._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Su(t)}static init(t){return new $r(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Pr{constructor(){S(this,"authenticate",async t=>!1);S(this,"deauthenticate",()=>{});S(this,"refreshDeskAuthToken",async()=>!1);S(this,"setCustomerLanguage",async()=>{});S(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Pr}}function yu(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 Au=1440*60*1e3,Tu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function Qe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Iu(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const xu=e=>{const t={conversationInitialRender:new Rl(e),conversationNotInteractiveTimeout:new Ol(e),recoveryNotInteractiveTimeout:new Pl(e),conversationListInitialRender:new kl(e),aievAuthExpiredUnhandled:new Tl(e),messagePendingStuck:new $l(e),userPerceivedResponseTime:new Zl(e),streamStalled:new zl(e),typingIndicatorAbsentTimeout:new Kl(e),renderedContentUnusable:new Bl(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class En extends su{constructor(n){super();S(this,"appId");S(this,"aiAgentId");S(this,"_chatClient");S(this,"_deskClient");S(this,"_cache");S(this,"_logger");S(this,"_dispatcher");S(this,"_session",null);S(this,"language");S(this,"countryCode");S(this,"context");S(this,"queryParams");S(this,"_config");S(this,"_networkStateAdapter");S(this,"_scheduleForegroundTask");S(this,"_watchBackgrounded");S(this,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_liveMetricManager");S(this,"_operationQueue",Jl());S(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"))});S(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));S(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(it.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:v,session_token:p,expire_at:b}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:p,expireAt:b}),f={userId:v,authToken:p},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}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(it.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var v;return s.type==="anonymous"?ul(this._dispatcher):(v=s.userSessionCandidate)==null?void 0:v.sessionHandler})(),C=await this._chatClient.connect(f,g,v=>{var p;this._logger.debug("AIAgent: session token refreshed"),(p=this._session)==null||p._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{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:v})=>{var p;if(v===mi.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,2e3));const b=(p=this._session)==null?void 0:p.userSession.authToken;return b?await this._deskClient.refreshDeskAuthToken(b):!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 ou({sdkUser:C,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),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});S(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")}));S(this,"createConversation",async n=>{Qe(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});S(this,"searchConversation",async n=>{if(Qe(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)Iu(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});S(this,"closeConversation",async n=>{var s;Qe(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")});S(this,"createConversationListCollection",n=>new Qo(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{Qe(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??{}}});S(this,"updateContext",async(n,r)=>{Qe(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??{}}});S(this,"getContextObject",async n=>{Qe(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??{}}});S(this,"clearUserMemories",async(n={})=>{Qe(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")});S(this,"setUserMemoryState",async n=>{Qe(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"),ur(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(it.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),ur(i)});S(this,"refreshActiveChannel",async n=>{var c,u,d;Qe(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});S(this,"_getSessionCandidate",n=>n instanceof si?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof ar?{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});S(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Au<=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});S(this,"_getManualSessionInfo",n=>{if(!n||n instanceof ar)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=Cs(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=Cu(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&bu(n.foregroundStateAdapter),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 ll(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=di.get(n.platform),s=n.logger??new ri(n.logLevel??Mr.WARN),o=n.dispatcher??new ei(s),i=n.useMMKVStorage?yu(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=wc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=xu((C,v)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(C,v)});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=Tu?$r.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 En({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,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=Cs(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}get watchBackgrounded(){return this._watchBackgrounded}}const ve=(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 qe(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 Ru(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function Mu(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":wu(e,t)}function wu(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 ku(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ot.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):ot.isToday(s)?n.hoursAgo(ot.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Lu=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},tn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ss=(e,t)=>{const n=tn(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=Lu(e);return r?`#${tn(r[0])}${tn(r[1])}${tn(r[2])}${n}`:e},Ou=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Nu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Du=e=>e.length>0,$u=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ve(s.type)),r=e.some(s=>!Ve(s.type));return n&&r?Ve(t.type)?e.filter(s=>Ve(s.type)):[t]:r?[t]:e},ys=e=>e.length===0?"empty":e.every(t=>Ve(t.type))?"images":"non_images",Pu=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=$u(t),s=ys(e),o=ys(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}},yt=3,hi=6,Fu=e=>e%yt===0?yt:hi,Uu=({index:e,itemCount:t})=>{const n=t%yt,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:yt,c=o?e-s:e%yt,u=!r&&e>=t-yt;return{columnSpan:r?hi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},fi=ve("AIAgent"),Bu=fi.Provider,xe=fi.useContext;function Hu(e){const t=Gu(e);return a.createElement(Bu,{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 Gu(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=En.init(e);else{const o=zu(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=En.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 zu(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 le(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const wn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let Vu=0;function qu(){return l.useState(()=>`${Vu++}`)[0]}const mt=(e,t,n)=>{const r=l.useRef(t),o=qu();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var C;const g=r.current;(C=g[h])==null||C.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 Ku(e,t){return!e||!t?!0:e.url!==t.url}function Be(e){return e!=null&&"sendingStatus"in e}function Yu(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return Be(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Wu(e,t){return Yu(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function As(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const Cn={collection:{groupChannel:{defaultOrder:We.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Ts(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Is(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const ju=({...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=Xu(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=Be(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];Zu(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=>{Be(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{Be(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=>Wu(s,n));return t.value.clearBeforeAction?e.newMessageMap=Is(r,As):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Is(r,As)}),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&&(Be(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(Be(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Xu=e=>e.reduce((t,n)=>(Be(n)?(t[n.reqId]=n,n.sendingStatus===De.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Zu=(e,t,n=!1)=>{var r,s;if(!Be(e)||!Be(t))return!0;if(n&&e&&ke.isStreaming(e)&&ke.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===De.SendingStatus.SUCCEEDED?t.sendingStatus===De.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Ju=(e=Qu)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(ju,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(p,b,y,A)=>{i({type:"update_messages",value:{messages:p,clearBeforeAction:b,currentUserId:y,strictStreamingOrder:A}})},u=(p,b)=>{i({type:"delete_messages",value:{messageIds:p,reqIds:b}})},d=(p,b,y)=>{i({type:"update_new_messages",value:{messages:p,clearBeforeAction:b,currentUserId:y}})},m=(p,b)=>{i({type:"delete_new_messages",value:{messageIds:p,reqIds:b}})},h=p=>{i({type:"update_initialized",value:{status:p}})},f=p=>{i({type:"update_loading",value:{status:p}})},g=p=>{i({type:"update_refreshing",value:{status:p}})},C=Object.values(o),v=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:v,newMessages:C,updateNewMessages:d,deleteNewMessages:m}},xs=Math.floor(Number.MAX_SAFE_INTEGER/10);function Qu(e,t){let n=0,r=0;return Be(e)&&e.sendingStatus!=="succeeded"&&(n=xs),Be(t)&&t.sendingStatus!=="succeeded"&&(r=xs),e.createdAt+n-(t.createdAt+r)}const ed=(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 Rs(e){return e<Date.now()?Cn.collection.message.searchLimit:Cn.collection.message.defaultLimit}const td=(e,t,n={})=>{var Me,$;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=Rs(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=wn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:C,messages:v,newMessages:p,updateMessages:b,updateNewMessages:y,deleteNewMessages:A,deleteMessages:T,updateInitialized:R,updateLoading:N,updateRefreshing:k}=Ju(n==null?void 0:n.sortComparator),x=le(I=>{var w,O,G,J;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 Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(G=(O=r.current).markAsRead)==null||G.call(O,[s.current]);break}}catch(se){(J=o==null?void 0:o.warn)==null||J.call(o,"[useGroupChannelMessages/markAsReadBySource]",se)}}),D=le((I,w)=>{var O,G,J,se,Q;if(w.length>0)switch(I){case Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:{(G=(O=r.current).shouldCountNewMessages)!=null&&G.call(O)&&y(w,!1,(J=e.currentUser)==null?void 0:J.userId),(Q=(se=r.current).onMessagesReceived)==null||Q.call(se,w);break}}}),F=le(I=>{var w,O;(O=(w=r.current).onCollectionEvent)==null||O.call(w,I)}),U=le(async(I,w,O)=>new Promise((G,J)=>{var Ke,ut,st;h.current.instance&&h.current.instance.dispose(),x(),y([],!0,(Ke=e.currentUser)==null?void 0:Ke.userId);const se=()=>{var ne,ce;const{pendingMessages:de,failedMessages:be}=h.current.instance??{};Ts(de)&&b(de,!1,(ne=e.currentUser)==null?void 0:ne.userId),Ts(be)&&b(be,!1,(ce=e.currentUser)==null?void 0:ce.userId)},Q=ed(I,O,{...r.current,startingPoint:w});h.current={apiInitialized:!1,initialized:!1,instance:Q},Q.setMessageCollectionHandler({onMessagesAdded:(de,be,ne)=>{var ce;x(de.source),D(de.source,ne),b(ne,!1,(ce=e.currentUser)==null?void 0:ce.userId,u),F({kind:"messagesAdded",source:de.source,channelUrl:I.url,messages:ne})},onMessagesUpdated:(de,be,ne)=>{var ce,_e,Ee;x(de.source),D(de.source,ne),b(ne,!1,(ce=e.currentUser)==null?void 0:ce.userId,u),de.source===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Ee=(_e=r.current).onMessagesUpdated)==null||Ee.call(_e,ne)),F({kind:"messagesUpdated",source:de.source,channelUrl:I.url,messages:ne})},onMessagesDeleted:(de,be,ne,ce)=>{const _e=ce.map(Ae=>Ae.messageId),Ee=ce.filter(Be).map(Ae=>Ae.reqId);T(_e,Ee),A(_e,Ee),F({kind:"messagesDeleted",source:de.source,channelUrl:I.url,messages:ce})},onChannelDeleted:(de,be)=>{var ne,ce;(ce=(ne=r.current).onChannelDeleted)==null||ce.call(ne,be)},onChannelUpdated:(de,be)=>{var ne,ce;m(),(ce=(ne=r.current).onChannelUpdated)==null||ce.call(ne,be,de)},onHugeGapDetected:()=>{U(I,Number.MAX_SAFE_INTEGER,Cn.collection.message.defaultLimit)}});let pe=!1;(st=(ut=r.current).onCollectionInitializeStart)==null||st.call(ut),Q.initialize(We.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((de,be)=>{var ne,ce,_e,Ee,Ae;(ce=(ne=r.current).onCacheResult)==null||ce.call(ne,de,be??[],I.url),de?(e.isCacheEnabled&&((_e=o==null?void 0:o.error)==null||_e.call(o,"[useGroupChannelMessages/onCacheResult]",de)),pe=!0):be&&((Ee=o==null?void 0:o.debug)==null||Ee.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",be.length),b(Q.succeededMessages,!0,(Ae=e.currentUser)==null?void 0:Ae.userId),se(),be.length>0&&(h.current.initialized=!0,G())),F({kind:"initialized",source:"cache",channelUrl:I.url,messages:be??[],error:de})}).onApiResult((de,be)=>{var ne,ce,_e,Ee,Ae,ue,we;(ce=(ne=r.current).onApiResult)==null||ce.call(ne,de,be??[],I.url),h.current.initialized=!0,h.current.apiInitialized=!0,de?((_e=o==null?void 0:o.warn)==null||_e.call(o,"[useGroupChannelMessages/onApiResult]",de),pe?J(de):G()):be&&((Ee=o==null?void 0:o.debug)==null||Ee.call(o,"[useGroupChannelMessages/onApiResult]","message length:",be.length),b(Q.succeededMessages,!0,(Ae=e.currentUser)==null?void 0:Ae.userId),r.current.startingPoint||(we=(ue=r.current).onMessagesReceived)==null||we.call(ue,be),e.isCacheEnabled&&se(),G()),F({kind:"initialized",source:"api",channelUrl:I.url,messages:be??[],error:de})})}));mt(e,{onUserBanned(I,w){var O,G,J;I.isGroupChannel()&&!Ku(I,s.current)&&(w.userId===((O=e.currentUser)==null?void 0:O.userId)?(J=(G=r.current).onCurrentUserBanned)==null||J.call(G):m())}}),l.useLayoutEffect(()=>{const I=setTimeout(async()=>{e.currentUser&&s.current&&(R(!1),N(!0),await U(s.current,i,c),N(!1),R(!0))});return()=>clearTimeout(I)},[e,(Me=e.currentUser)==null?void 0:Me.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const q=le(async()=>{e.currentUser&&s.current&&(k(!0),await U(s.current,Number.MAX_SAFE_INTEGER,Cn.collection.message.defaultLimit),k(!1))}),K=le(async()=>{var w;const I=h.current.instance;if(I!=null&&I.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const O=await I.loadPrevious();b(O,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.prev=!1}}),L=le(()=>{const{initialized:I,instance:w}=h.current;return I&&w?w.hasPrevious:!1}),V=le(async()=>{var w;const I=h.current.instance;if(I!=null&&I.hasNext&&!d.current.next)try{d.current.next=!0;const O=await I.loadNext();b(O,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.next=!1}}),P=le(()=>{const{initialized:I,apiInitialized:w,instance:O}=h.current;return w&&I&&O?O.hasNext:!1}),Y=I=>{var w,O,G,J;!I||I.channelUrl!==((w=s.current)==null?void 0:w.url)||(b([I],!1,(O=e.currentUser)==null?void 0:O.userId),(J=(G=r.current).onOutgoingMessageStatusChanged)==null||J.call(G,I))},ge=le((I,w)=>{var O;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");return new Promise((G,J)=>{s.current.sendUserMessage(I).onPending(se=>{Y(se),w==null||w(se)}).onSucceeded(se=>{Y(se),G(se)}).onFailed((se,Q)=>{Y(Q),J(se)})})}),j=le((I,w)=>{var O;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");return new Promise((G,J)=>{s.current.sendFileMessage(I).onPending(se=>{Y(se),w==null||w(se)}).onSucceeded(se=>{Y(se),G(se)}).onFailed((se,Q)=>{Y(Q),J(se)})})}),W=le((I,w,O)=>{var G;if(!s.current||!s.current.url)throw(G=o==null?void 0:o.error)==null||G.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((J,se)=>{s.current.sendMultipleFilesMessage(I).onPending(Q=>{Y(Q),w==null||w(Q)}).onFileUploaded(Q=>{O==null||O(Q),m()}).onSucceeded(Q=>{Y(Q),J(Q)}).onFailed((Q,pe)=>{Y(pe),se(Q)})})}),X=le(async(I,w)=>{var G,J;if(!s.current||!s.current.url)throw(G=o==null?void 0:o.error)==null||G.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const O=await s.current.updateUserMessage(I,w);return O.channelUrl===s.current.url&&b([O],!1,(J=e.currentUser)==null?void 0:J.userId),O}),M=le(async(I,w)=>{var G,J;if(!s.current||!s.current.url)throw(G=o==null?void 0:o.error)==null||G.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const O=await s.current.updateFileMessage(I,w);return O.channelUrl===s.current.url&&b([O],!1,(J=e.currentUser)==null?void 0:J.userId),O}),Z=le(async(I,w,O)=>{var G;if(!s.current||!s.current.url)throw(G=o==null?void 0:o.error)==null||G.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((J,se)=>{let Q;I.isUserMessage()&&(Q=s.current.resendMessage(I)),I.isFileMessage()&&(Q=s.current.resendMessage(I)),I.isMultipleFilesMessage()&&(Q=s.current.resendMessage(I)),Q&&("onPending"in Q&&Q.onPending(pe=>{Y(pe),w==null||w(pe)}),"onFileUploaded"in Q&&Q.onFileUploaded(pe=>{O==null||O(pe),m()}),"onSucceeded"in Q&&Q.onSucceeded(pe=>{Y(pe),J(pe)}),"onFailed"in Q&&Q.onFailed((pe,Ke)=>{Y(Ke),se(pe)}))})}),ie=le(async I=>{var w,O,G,J;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((O=h.current.instance)==null?void 0:O.removeFailedMessage(I.reqId))}finally{T([],[I.reqId]),(J=(G=r.current).onLocalMessageDeleted)==null||J.call(G,I)}}),ye=le(()=>{var I;y([],!0,(I=e.currentUser)==null?void 0:I.userId)}),$e=le(async I=>{var w;if(e.currentUser&&s.current){const O=Rs(I);N(!0),b([],!0,(w=e.currentUser)==null?void 0:w.userId),await U(s.current,I,O),N(!1)}});return{initialized:f,loading:g,refreshing:C,messages:v,newMessages:p,resetNewMessages:ye,refresh:q,loadPrevious:K,hasPrevious:L,loadNext:V,hasNext:P,sendUserMessage:ge,sendFileMessage:j,sendMultipleFilesMessage:W,updateUserMessage:X,updateFileMessage:M,resendMessage:Z,deleteMessage:ie,resetWithStartingPoint:$e,_dangerous_reducer_updateMessages:b,_dangerous_reducer_deleteMessages:T}},nd=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,rd=(e,t,n)=>{const r=td(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!nd(o)),[r.messages]);return{...r,messages:s}},sd=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{n(t)})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},gi=sd(),od=({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(C=>r.current===C,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(C=>{c(C)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:C,conversationId:v})=>{i.current=!0,n.markChannelJoined(v,C)},[n]),h=l.useCallback(({channelUrl:C})=>{n.clearChannel(C),i.current=!1},[n]),f=l.useCallback(C=>{if(c(C.channelUrl)){if(!s.current){o.current=C;return}o.current=null,m(C)}},[c,m]),g=l.useCallback(C=>{if(c(C.channelUrl)){if(!s.current){o.current=C;return}o.current=null,h(C)}},[c,h]);return l.useEffect(()=>{if(t){const C=o.current;if(!C||(o.current=null,C.channelUrl!==e))return;"error"in C?h(C):m(C);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}},id=({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 pi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function ad(e){const t=pi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function cd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function ld(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 ud(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 nn(e,t,n){const[r,s,o]=ad(e),[i,c,u]=ld(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=ud(i,m,d);return cd([Math.round(h),Math.round(f),Math.round(g)])}function dd(e,t="light"){return{extraDark:nn(e,.6,1.2),dark:nn(e,.85,1.1),main:e,light:nn(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:nn(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function dr(e){const t=pi(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 md(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 hd=(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"}}),rn={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)"}},qn={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 Ms(e){const t=fd(e),n=gd(e,t),r=_d(n,e.colors,e.selectedTheme),s=Cd(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 fd({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===rn.primary.main?rn.primary:dd(n,e):rn.primary;return{...rn,primary:r,...t}}function gd({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??dr(o),c=n??Bt.DEFAULT_BOT_MSG_BG,u=r??dr(c);return(e==="light"?md:hd)(s,o,i,c,u)}function pd(e,t,n){return typeof e=="string"?e:e[t]??n}function _d(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]=pd(m,n,h)}}}return r}function Ed(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Cd({typography:e}){if(!e)return qn;const t={...qn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=qn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Ed(s,r,o)}}),t}const{Provider:bd,useContext:Fr}=ve("AIAgentTheme");function vd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Ms({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,C={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!C.primary&&(g!=null&&g.primary_color)&&(C.primary=g.primary_color,C.primaryContrast=g.primary_contrast_color),!C.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(C.botMessageBackground=g.bot_message_bg_color,C.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const v=Ms({selectedTheme:f,palette:t,typography:n,colors:r,...C});u(v),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(bd,{value:{theme:c,updateTheme:d}},o)}const Kn=25*1024*1024,ws=1,ks=new Set(["image/png","image/jpeg","image/jpg"]),Ls=new Set(["application/pdf"]),Sd={off:"off",always:"always",handed_off_only:"handed_off_only"},yd=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:ws,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Kn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:ks,supportedFileMimeTypes:Ls})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??ws,attachmentMode:Sd[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Kn,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)??ks),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Ls)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=Kn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?et(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 et(o);default:return!0}},get supportedMimeTypes(){return c()?[ir]:[...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}},Os=(...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:Ad,useContext:ht}=ve("AIAgentMessengerSession"),Td=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=xe(),{updateTheme:c}=Fr(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[C,v]=l.useState(null),[p,b]=l.useState(null),[y,A]=l.useState(null),[T,R]=l.useState(null),{updateBaseAttachmentRules:N,createAttachmentRules:k}=yd();l.useEffect(()=>{const U=r.onMessengerSettingsUpdated(({settings:L})=>{const{appearance:V,bot:P,launcher:Y,memory:ge}=L;c(V.selected_theme,V),b(nu(P)),A(ru(Y)),R(ge?ur(ge):null),N(L)}),q=r.onActiveChannelUpdated(({channelUrl:L,status:V,conversationStatus:P})=>{h({url:L,status:V,conversationStatus:P})}),K=r.onAuthTokenRefreshed(()=>{var V;const L=(V=r.session)==null?void 0:V.userSession.authToken;L&&v(P=>P?{...P,authToken:L}:null)});return()=>{U(),q(),K()}},[r,c,N]);const x=l.useCallback(async()=>{try{const U=await r.authenticate(e),q=r.session;return g(q.sdkUser),v(q.userSession),h(q.activeChannel),d(void 0),U}catch(U){throw g(null),v(null),h(void 0),d(U),U}},[r,e]),D=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),v(null),b(null),A(null),R(null)},[r]),F=l.useCallback(async()=>{if(!r.session){if(C)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!==(C==null?void 0:C.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,C]);return l.useImperativeHandle(n,()=>{const U=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:D,updateContext:async(...q)=>{const K=Os(...q);if(K.type==="active"){const P=await(await U()).updateContext(o,K.context);return kt(P)}const L=await s.aiAgent.updateContext(K.aiAgentId,K.channelUrl,K.context);return kt(L)},patchContext:async(...q)=>{const K=Os(...q);if(K.type==="active"){const P=await(await U()).patchContext(o,K.context);return kt(P)}const L=await s.aiAgent.patchContext(K.aiAgentId,K.channelUrl,K.context);return kt(L)},getContextObject:async()=>{const K=await(await U()).getContextObject(o);return kt(K)}}},[x,D,m,s,o,i]),a.createElement(Ad,{value:{sdkUser:f,userSessionInfo:e,userSession:C,activeChannel:m,setActiveChannel:h,refreshActiveChannel:F,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:u,aiAgentInfo:p,launcherInfo:y,memoryInfo:T,authenticate:x,deauthenticate:D,createAttachmentRules:k}},t)}),Id={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"},xd=e=>e.disabled?Id[e.disabledBy]==="ready":!0,Rd=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&&Ve(t)?"file_image":t&&zt(t)?"file_video":t&&bc(t)?"file_audio":"file_document"};let Ns=0;const Md=e=>(Ns+=1,`${e??"unknown"}:${Ns}`),vt=(e,t)=>e===void 0||t===e,_i=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Ei=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},wd=(e,t)=>{_i(e,t)},kd=(e,t)=>{Ei(e,t)},Ld=(e,t,n)=>{var o;if(!tt(e,n))return;const{hasResponseMetadata:r,...s}=Ko(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}))},Ds=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Xe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},Yn=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},Od=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=xe(),{aiAgentInfo:r}=ht(),s=l.useRef(!1),o=r==null?void 0:r.userId;mt(!!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])},Nd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(Yn(n,s),r.current=void 0);return}s&&s!==t&&(Yn(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(Yn(n,s),r.current=void 0)},[n])},Dd=({aiAgentUserId:e,statsEnabled: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&&vt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(_i(r,g),g.tracked=!0));const C=o.current;C&&f(C)&&(C.tracked||(Ei(r,C),C.tracked=!0))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&vt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(C=>Ds(C,r));return}t&&g.messages.forEach(C=>Ld(C,r,e))}},onCacheResult:(g,C,v)=>{if(!h(m)||!vt(n,v))return;const p={error:g,messages:C,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=p,t&&(wd(r,p),p.tracked=!0)},onApiResult:(g,C,v)=>{if(!h(m)||!vt(n,v))return;const p={error:g,messages:C,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=p,t&&(kd(r,p),p.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&vt(n,g.channelUrl)&&Ds(g,r)}}),[e,m,t,h,n,r])},$d=({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.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},Pd=({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(v=>u==null?void 0:u(v),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,C=v=>g()&&vt(f,v);try{const v=await c(p=>{if(!C(p.channelUrl)){u==null||u(p);return}m=p.reqId,n.messagePendingStuck.start({requestId:p.reqId,channelUrl:p.channelUrl,messageType:Rd(p),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(p)},p=>{!g()||m!==p||n.messagePendingStuck.markUploadProgress(p)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}catch(v){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}},[n])},Fd=({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=Md(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])},Ud=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ht();Od({activeChannelUrl:t,statsTrackers:r}),Nd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=Dd({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Pd({channelUrl:t,enabled:n,statsTrackers:r}),c=Fd({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},xt=()=>xe()._aiAgentSDK.statsTrackers,Bd=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=xt(),{watchBackgrounded:r}=xe()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();Ie(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},Yt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new Ce.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])},$s=()=>{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 Hd(e,t={}){const{shouldInitializeConversation:n=!0}=t,{chatSDK:r,logger:s,aiAgentId:o,_aiAgentSDK:i}=xe(),{sdkUser:c}=ht(),u=$s(),d=$s(),m=wn(),[h,f]=l.useState(void 0),[g,C]=l.useState(void 0),[v,p]=l.useState(!1),b=le(A=>{if(n&&A.isAIAgent&&!A.conversation){const T=d.next();p(!0),i.initConversationIfNeeded(A).finally(()=>{d.isCurrent(T)&&p(!1)})}});async function y(){var T,R,N,k,x,D;const A=u.next();if(!c){s.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(s.debug("useChannel.getChannel: start"),f(void 0),C(void 0),d.invalidate(),p(!1),e){(T=t.onFetchStart)==null||T.call(t,e);try{s.debug("useChannel.getChannel: get channel",e);const F=await r.groupChannel.getChannel(e);if(!u.isCurrent(A))return;b(F),f(F),(N=t.onFetchSuccess)==null||N.call(t,{channelUrl:F.url,conversationId:(R=F.conversation)==null?void 0:R.id}),F.url===((k=i.session)==null?void 0:k.activeChannel.url)&&i.session._updateActiveChannel({url:F.url,status:Fe(F)?"closed":"open",conversationStatus:(x=F.conversation)==null?void 0:x.status}),s.debug("useChannel.getChannel: fetched channel",F)}catch(F){if(!u.isCurrent(A))return;(D=t.onFetchError)==null||D.call(t,{channelUrl:e,error:F}),F instanceof Ce.SendbirdError&&C(F),s.error("useChannel.getChannel: error",F)}}}return l.useEffect(()=>(y(),()=>{u.invalidate()}),[r,c,e,o]),l.useEffect(()=>{n&&h&&b(h)},[n]),Yt(r,{async onReconnectSucceeded(){var R;if(!h){g&&await y();return}const A=u.current(),T=await h.refresh();!u.isCurrent(A)||h.url!==e||((R=t.onReconnectSucceeded)==null||R.call(t,h.url),b(T),f(T))}}),mt(r,{onChannelChanged:A=>{A.isGroupChannel()&&A.url===e&&(s.debug("useChannel.onChannelChanged: channel changed",A.url),f(A),m())}}),{channel:h,channelFetchError:g,getChannel:y,isInitializingConversation:v}}const Gd=new Set(["suggested_replies","steward","system"]),zd=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||!Gd.has(r)))return r},Vd=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=In(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},qd=()=>{const{chatSDK:e,networkStateAdapter:t}=xe(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Yt(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===Ce.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Kd=3e4,Yd=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&tt(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=Kd-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ci=e=>{const{chatSDK:t}=xe(),[n,r]=l.useState([]);return mt(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Wd=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Ci(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=tt(t,n)&&(ke.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},jd=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ht(),i=qd(),c=Wd({channel:e,lastMessage:hs(t,[De.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Yd({shouldApply:!!(e!=null&&e.isAIAgent)&&!et(e),isBlockedWhileAIResponding:c,lastMessage:hs(t,[De.SendingStatus.PENDING,De.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(jc(e))return d("handoff_pending");if(Vd(e))return d("form_active");const m=zd(e);return d(m||(c||u||r?"ai_responding":""))},Xd=()=>{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:Zd}=ve("AIAgentConversation");function Jd({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=he,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,shouldCountNewMessages:f=()=>!1,sortComparator:g}){var Me,$;const C=()=>d&&(x==null?void 0:x.markAsRead()),{_aiAgentSDK:v,chatSDK:p,logger:b,dispatcher:y}=xe(),A=xt(),T={channelUrl:t,enabled:m},R=od({...T,statsTracker:A.conversationNotInteractiveTimeout}),N=id({...T,scheduleForegroundTask:v.scheduleForegroundTask,statsTracker:A.recoveryNotInteractiveTimeout}),k=Bd(T),{channel:x,channelFetchError:D,getChannel:F,isInitializingConversation:U}=Hd(t,{shouldInitializeConversation:h,onFetchStart:I=>{R.onFetchStart(I),k.onGetChannelStart(I)},onFetchSuccess:I=>{R.onFetchSuccess(I),k.onGetChannelComplete(I)},onFetchError:I=>{R.onFetchError(I),k.onGetChannelError(I)},onReconnectSucceeded:N.onReconnectSucceeded}),q=x==null?void 0:x.url,K=Ud({requestedChannelUrl:t,activeChannelUrl:q,statsEnabled:m,statsTrackers:A}),L=rd(p,x,{replyType:De.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:f,logger:b,markAsRead:C,sortComparator:g,onChannelDeleted:n,onMessagesReceived:I=>r==null?void 0:r(I),onMessagesUpdated:I=>s==null?void 0:s(I),onCollectionInitializeStart:()=>{k.onCollectionInitializeStart()},onApiResult:(I,w,O)=>{k.onCollectionApiResult(I,O),K.messageCallbacks.onApiResult(I,w,O)},onCacheResult:(I,w,O)=>{k.onCollectionCacheResult(I,O),K.messageCallbacks.onCacheResult(I,w,O)},onCollectionEvent:I=>{K.messageCallbacks.onCollectionEvent(I),gi.publish(I)},onLocalMessageDeleted:I=>{K.messageCallbacks.onLocalMessageDeleted(I)},onOutgoingMessageStatusChanged:I=>{x&&v.liveMetricManager.track({type:"outgoingMessage",channel:x,message:I})}}),V=Xd(),P=jd({channel:x,messages:L.messages,isStreamAnimating:V.isAnimating,isInitializingConversation:U});$d({enabled:m,channelUrl:q,initialized:L.initialized,inputReady:xd(P),renderedSignal:L.messages,statsTrackers:A}),l.useEffect(()=>{C()},[d,x]);const Y=(Me=x==null?void 0:x.conversation)==null?void 0:Me.status;l.useEffect(()=>{Y&&(o==null||o(Y))},[Y,o]),l.useEffect(()=>{const I=async w=>{const O=typeof(w==null?void 0:w.channelUrl)=="string";x&&O&&w.channelUrl!==x.url||(b.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 y.subscribe(ze.ConversationClose,I),()=>{y.unsubscribe(ze.ConversationClose,I)}},[y,x,b,($=x==null?void 0:x.conversation)==null?void 0:$.status,i]);const ge=le(()=>L.loadPrevious()),j=le(()=>L.loadNext()),W=le(async I=>{try{await L.deleteMessage(I)}finally{I.sendingStatus!=="succeeded"&&K.messageCallbacks.onLocalMessageDeleted(I)}}),X=le(I=>I.isUserMessage()?K.runWithUserTurnStats(w=>K.runWithPendingStuckStats(O=>L.resendMessage(I,G=>{w(G.reqId),O(G)}),void 0)):K.runWithPendingStuckStats((w,O)=>L.resendMessage(I,w,O),void 0,{tracksUploadProgress:I.isMultipleFilesMessage()})),M=le(()=>L.resetNewMessages()),Z=le(async I=>{var O;if(((O=x==null?void 0:x.conversation)==null?void 0:O.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await K.runWithUserTurnStats(G=>K.runWithPendingStuckStats(J=>L.sendUserMessage(I,se=>{G(se.reqId),J(se)}),u));return u==null||u(w),w}),ie=le(async I=>{var O;if(((O=x==null?void 0:x.conversation)==null?void 0:O.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await K.runWithPendingStuckStats(G=>L.sendFileMessage(I,G),u);return u==null||u(w),w}),ye=le(async I=>{var O;if(((O=x==null?void 0:x.conversation)==null?void 0:O.status)===fe.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(I=await c(I));const w=await K.runWithPendingStuckStats((G,J)=>L.sendMultipleFilesMessage(I,G,J),u,{tracksUploadProgress:!0});return u==null||u(w),w}),$e={_statsEnabled:m,conversation:(x==null?void 0:x.conversation)??void 0,actions:{setUserMemoryState:v.setUserMemoryState},channelSource:{channel:x,error:D,refetch:()=>F(),closeConversation:async()=>{Fe(x)||await(x==null?void 0:x.closeConversation())}},messageSource:{messages:L.messages,newMessages:L.newMessages,initialized:L.initialized,loadPrevious:ge,loadNext:j,deleteMessage:W,resendMessage:X,resetNewMessages:M,sendUserMessage:Z,sendFileMessage:ie,sendMultipleFilesMessage:ye},state:{streamAnimation:V,input:P}};return a.createElement(Zd,{value:$e},e)}function Qd(e,t,n){var b,y,A,T,R,N,k,x,D,F;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=le(()=>{var U;return(U=n==null?void 0:n.onListRequestStart)==null?void 0:U.call(n)}),g=le(U=>{var q;return(q=n==null?void 0:n.onListRequestComplete)==null?void 0:q.call(n,U)}),C=l.useCallback(async U=>{f();try{await U.loadMore(),g()}catch(q){throw g(q),q}},[f,g]),v=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const U=new Qo(e,t);U.setConversationListCollectionHandler({onChannelsAdded:()=>{u(U.channels)},onChannelsUpdated:()=>{u(U.channels)},onChannelsDeleted:()=>{u(U.channels)}}),await C(U),u(U.channels),m(U),i(null)}catch(U){m(null),i(U)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(b=t.filter)==null?void 0:b.aiAgentChannelFilter,(A=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:A.join(),(R=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:R.join(),(N=t.filter)==null?void 0:N.deskChannelFilter,(x=(k=t.filter)==null?void 0:k.pinnedChannelUrls)==null?void 0:x.join(),(D=t.filter)==null?void 0:D.copilotConversationOnly,(F=t.filter)==null?void 0:F.copilotSupportChannelUrl,t.limit,C]),p=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(U){i(U)}},[d]);return Yt(e,{onConnected:()=>v()}),l.useEffect(()=>{v()},[v]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:p}}const bi=e=>{var s;const{aiAgentId:t,queryParams:n}=xe(),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}},em=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=xt(),{watchBackgrounded:n}=xe()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();Ie(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:tm}=ve("AIAgentConversationList");function nm({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=xe(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=bi(t),u=em({enabled:n}),d=Qd(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:f=>{u.onListRequestComplete(f)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(tm,{value:m},r)}function rm(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:sm,useContext:om}=ve("MessageTemplateFetching");function im({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 C=r.current[h];if(C)return C;f||i(h,{fetching:!0});const v=d(h).catch(p=>{throw f||i(h,{error:!0}),p}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=rm(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(sm,{value:u},e)}const am="remove_powered_by",Ur=(e,t)=>{var s,o;const{chatSDK:n}=xe(),{aiAgentInfo:r}=ht();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&&xr(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(am)),[i])}throw new Error("Unsupported feature")},cm={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"},lm={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}}},um={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}}},dm={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}}},mm={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}}},hm={text:lm,number:um,"single-select":dm,"multi-select":mm},fm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function vi(e){return hm[e.type]||fm}function Ps(e){return vi(e).getValueOrDefault(e)}function gm(e,t,n={}){const r={...cm,...n};return vi(e).validate(e,t,r)}const pm=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const v={};return e.fields.forEach(p=>{v[p.key]=Ps(p)}),v}),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 v={};let p=!1;e.fields.forEach(b=>{const y=Ps(b);JSON.stringify(c[b.key])!==JSON.stringify(y)&&(p=!0),v[b.key]=y}),p&&u(v)}},[d]);const m=(v,p)=>{u(b=>({...b,[v]:p})),i(b=>({...b,[v]:void 0}))},h=e.fields.map(v=>{var y,A,T;const p=c[v.key]??null,b={key:v.key,label:v.label,error:o[v.key],required:v.required};return v.type==="text"?{...b,type:"text",layout:v.layout,value:p,...v.placeholder&&{placeholder:v.placeholder},...((y=v.rules)==null?void 0:y.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...b,type:"number",layout:v.layout,value:p,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max)&&{max:v.rules.max}}:v.type==="single-select"?{...b,type:"single-select",layout:v.layout,value:p,options:v.options}:v.type==="multi-select"?{...b,type:"multi-select",layout:v.layout,value:p,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{...b,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(p=>p.key===v),updateFieldValue:m,submit:async()=>{const v={};let p=!1;for(const b of e.fields){const y=c[b.key]??null,A=gm(b,y,n);A.isValid||(v[b.key]=A.error,p=!0)}if(i(v),!p&&r){const b={};e.fields.forEach(y=>{b[y.key]=c[y.key]??null}),await r(b)}},cancel:async()=>{await(s==null?void 0:s())}}},_m=e=>{const{chatSDK:t,handlers:n,logger:r}=xe(),{aiAgentInfo:s}=ht(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!tt(m,s.userId))return;const f=m.messageId;if(ke.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=Vo(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 mt(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},Em=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},Si=e=>{const{aiAgentInfo:t}=ht(),n=Ci(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?Em(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Cm=(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},[])},bm=(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()}}},vm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=bm(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])},Sm=({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=ti(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?et(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Fs=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 ym=new Set(["free_text","single_choice"]),Am=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Fs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Fs({followUpItem:!1}),d=l.useMemo(()=>{var p;const g=o.csat,C=typeof g=="number",v=(p=e.follow_up)==null?void 0:p.find(b=>C?b.scores.includes(g):b.always_visible??!1);if(ym.has(v==null?void 0:v.response_type))return v},[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 C=typeof o.csat=="number",v=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(C&&v)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"}}},Tm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!je[n.type],o=!r&&typeof e!="number"&&ni(t),i=wn();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}},Wn=5,Nt=250,Im=50,Us=e=>Math.max(0,e-Im),dn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,xm=e=>e<1e3?{speed:Wn*.5,chunkSize:2}:e<2e3?{speed:Wn*.8,chunkSize:2}:{speed:Wn*.6,chunkSize:3},mn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Bs=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(mn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},yi=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!mn(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]==="["&&!mn(e,s),c=e[s]==="["&&!mn(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=Bs(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=Bs(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},Rm=({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,R=A&&e.deferLinks;return!T&&!R?y:yi(e.text.slice(0,y),{hideImages:T,hideLinks:R}).length},[e]),h=l.useCallback((y,A,T=!1)=>{r.current&&(y<=c.lastLength||!T&&A-c.lastReportedAt<Nt||(c.lastLength=y,c.lastReportedAt=A,d(y)))},[d,c]),f=l.useCallback((y,A,T=!1)=>{if(!r.current)return;const R=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&A-R<Nt||(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<Nt||(i.lastLength=y,i.lastReportedAt=A,s.current(y)))},[i]),C=l.useCallback((y,A,T)=>{const R=y>=A,N=T-i.lastReportedAt>=Nt;if(!R&&!N)return;const k=m(y);g(k,T,R)},[m,i,g]),v=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),p=l.useCallback(y=>{r.current&&(o.current!==null&&y<=o.current||(o.current=y,d(y)))},[d]),b=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 R=dn();h(A,R,!0),g(A,R,!0)},[u,g,h,e]);return{resetProgress:v,reportVisibleTextProgress:f,reportRenderedTextProgress:C,reportNonStreamingVisibleTextProgress:p,reportMarkdownRevealProgress:b}},Mm=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(()=>Us(t.length)),C=l.useRef(null),v=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,p=l.useRef({startCalled:!1,completeCalled:!1}).current,b=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:m,deferLinks:h,snapOnDisable:r}).current,y=le(()=>o==null?void 0:o()),A=le(()=>i==null?void 0:i()),T=le(()=>c==null?void 0:c()),{resetProgress:R,reportVisibleTextProgress:N,reportRenderedTextProgress:k,reportNonStreamingVisibleTextProgress:x,reportMarkdownRevealProgress:D}=Rm({trackedRef:b,onVisibleTextProgress:u,onRenderedTextProgress:d}),F=n,U=f<t.length,q=b.initialEnabled&&(F||U);l.useLayoutEffect(()=>{b.textLength=t.length,b.enabled=n,b.text=t,b.deferImages=m,b.deferLinks=h,b.snapOnDisable=r}),l.useLayoutEffect(()=>{if(b.initialEnabled){if(p.startCalled||(p.startCalled=!0,y()),!b.enabled&&b.snapOnDisable){g(t.length);const L=dn();N(t.length,L,!0),k(t.length,t.length,L);return}g(L=>t.length<L?t.length:L)}},[y,k,N,t]),l.useEffect(()=>{if(!b.initialEnabled)return;let L=Us(t.length);v.lastUpdate=0,v.startTime=0,v.lastProgressCall=0,R();const V=P=>{v.lastUpdate===0&&(v.lastUpdate=P,v.startTime=P,v.lastProgressCall=P,L>0&&N(L,P,!0));const Y=b.textLength;!b.enabled&&b.snapOnDisable&&L<Y&&(L=Y,g(L),N(L,P,!0),k(L,Y,P));const ge=P-v.lastUpdate,j=P-v.startTime,{speed:W,chunkSize:X}=xm(j),M=W*X;ge>=M&&L<Y&&(L=Math.min(L+X,Y),g(L),N(L,P,L>=Y),k(L,Y,P),v.lastUpdate=P),P-v.lastProgressCall>=Nt&&(v.lastProgressCall=P,A()),(L<Y||b.enabled)&&(C.current=requestAnimationFrame(V))};return C.current=requestAnimationFrame(V),()=>{C.current&&cancelAnimationFrame(C.current),p.startCalled&&!p.completeCalled&&(p.completeCalled=!0,T())}},[T,A,k,N,R]),l.useEffect(()=>{b.initialEnabled&&(n||t.length>0)||(x(t.length),k(t.length,t.length,dn()))},[n,d,u,x,k,t.length,b]),l.useEffect(()=>{const L=b.initialEnabled&&p.startCalled,V=!n,P=f>=t.length;L&&V&&P&&!p.completeCalled&&(p.completeCalled=!0,T())},[n,f,T,t.length]);const K=l.useMemo(()=>{const L=b.initialEnabled?t.slice(0,f):t,V=q&&m,P=q&&h;return!V&&!P?L:yi(L,{hideImages:V,hideLinks:P})},[t,f,m,h,q]);return l.useEffect(()=>{!b.initialEnabled||q||N(f,dn(),!0)},[f,q,N]),l.useEffect(()=>{D({displayedLength:f,streamTextLength:K.length})},[f,D,K.length]),{streamText:K,isAnimating:q}},Hs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},wm=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),km=(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}},Lm=()=>{const{chatSDK:e}=xe(),[t,n]=l.useState(Hs),r=()=>n(Hs);return Yt(e,{onConnectionDelayed:s=>{s>0?n(wm(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>km(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},Om=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Nm=(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)}},Dm=({enabled:e=!0}={})=>{const t=xt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=ke.isStreaming(n),c=In(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!vc(n)&&!ke.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,C=!1;const v={};return(f||m)&&(v.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!C&&(C=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(v.onRenderedTextProgress=p=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:p})}),u&&(v.onMessageTemplateError=p=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:p})}),d&&(v.onFormRenderError=p=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:p})}),v},[e,t])},$m=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},jn=5e3,Pm=({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()?performance.now()-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(performance.now()-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=performance.now()-jn):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Fm=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=xt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Um=(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===Ce.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]),Yt(e,{onConnected:c,onReconnectSucceeded:c}),s},At=e=>e.replace(/\s+/g," ").trim(),Bm="Code block",Ai=e=>`A11Y_INLINE_CODE_${e}`,Ti=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}},Ii=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}},Hm=e=>{const{blockquotePrefix:t,content:n}=Ti(e),{content:r}=Ii(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}},Gm=(e,t)=>{const{blockquotePrefix:n,content:r}=Ti(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=Ii(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)},zm=(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},Vm=(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},qm=(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},Km=e=>{let t=0,n="";for(;t<e.length;){const r=zm(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Vm(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&bn(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]==="!"&&!bn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=qm(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},xi=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Ym=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return xi(n,r,i)?t:`${n}${r}`}),Wm=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),jm=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Xm=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 xi(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Zm=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Jm=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},Gs=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))},zs=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},Qm=e=>{const t=e.split(`
2
- `),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=zs(s);if(i.length>0&&o&&Gs(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=zs(c);if(u.length===0||Gs(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
3
- `)},eh=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),th=(e,t)=>{const n=e.split(`
4
- `),r=[];let s=0;for(;s<n.length;){const o=n[s],i=Hm(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(Gm(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
- `)},bn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},nh=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||bn(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]==="`"&&!bn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=Ai(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Ri=(e,{codeBlockPlaceholder:t=Bm}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
7
- `);if(!n)return;const r=[];let s=n;s=th(s,t),s=Jm(s);const o=nh(s);s=o.text,r.push(...o.inlineCodes),s=Km(s),s=Ym(s),s=Wm(s),s=jm(s),s=Xm(s),s=Qm(s),s=eh(s),s=Zm(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Ai(c),r[c]);return At(s)||void 0},rh=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ve(r)?t.image:zt(r)?t.video:Xo({name:n,mimeType:r})?t.pdf(n):t.document(n)},vn=e=>(e==null?void 0:e.trim())||"",sh=e=>(e?At(e):void 0)||void 0,Vs=30,oh=e=>e.length>Vs?`${e.slice(0,Vs)}…`:e,ih=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=oh(At(n)),c=[t,i].filter(Boolean).join(", ");return o(At(e),At(c),r,s)},Mi=e=>({text:vn(e),format:"plain"}),ah=e=>({text:vn(e),format:"markdown"}),Xn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=vn(e);return r&&r!==vn(n)?ah(r):Mi(t)},Dt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Ri(t,{codeBlockPlaceholder:s}):sh(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},wi=(e,t)=>Ri(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),ch=(...e)=>At(e.filter(Boolean).join(", "))||void 0,qs=(e,t,n,r)=>{if(!t||t===n)return e;const s=wi(t,r);return s?ch(e,s):e},lh=(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=rh({name:c,mimeType:e.type},t);return qs(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 qs(h,n,d,t.codeBlockPlaceholder)}return wi(n,t.codeBlockPlaceholder)},uh=(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,D,F)=>({text:x,ignoreSuppression:D,queueOrder:f++,dedupeKey:F}),C=()=>{const x=c[0]??null,D=i;return x&&D?D.queueOrder<x.queueOrder?(i=null,D):c.shift()??null:x?c.shift()??null:D!==null?(i=null,D):null},v=()=>{for(;;){const x=C();if(!x)return null;if(!(!x.ignoreSuppression&&(r!=null&&r())))return x}},p=x=>{u=x.text,d=x.dedupeKey??null,h=!0,e(x.text),m=setTimeout(()=>{m=null,h=!1;const D=v();D&&p(D)},n)},b=x=>{u=x.text,d=x.dedupeKey??null,e(x.text)},y=(x,D,F,U)=>D!=null&&U!=null?D===U:D==null&&U==null?x!=null&&x===F:!1,A=(x,D,F)=>{if(!x||!D&&(r!=null&&r()))return;const U=F==null?void 0:F.dedupeKey;if(!(h&&y(x,U,u,d)))if(h){if(((F==null?void 0:F.mode)??"latestOnly")==="ordered"){const K=c[c.length-1];if(K&&y(x,U,K.text,K.dedupeKey))return;c.push(g(x,D,U)),c.length>o&&c.shift();return}i=g(x,D,U)}else i=null,p(g(x,D,U))};return{announce:(x,D)=>{A(x,!1,D)},announceIgnoringSuppression:(x,D)=>{A(x,!0,D)},flush:()=>{const x=[];let D=C();for(;D!==null;)x.push(D),D=C();if(m!==null&&(clearTimeout(m),m=null),h=!1,x.length!==0)for(const F of x)b(F)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},dh=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},mh=(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(". "),hh=(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}},fh=(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}},gh=(e,t)=>!t||!Xe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),ph=(e,t)=>Oe.isAdmin(e)?Oe.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,_h=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Eh=e=>e===Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED,Ch=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",bh=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},vh=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Sh=({intent:e,strings:t})=>({label:bh(e,t),hint:vh(e,t)}),yh="1.36.0",Ue="sb-agent",Se={ENTRY:`${Ue}-entry`,MODAL_ROOT:`${Ue}-modal-root`,WINDOW:`${Ue}-window`,LAUNCHER:`${Ue}-launcher`,WINDOW_TITLE:`${Ue}-window-title`},ki="data-sb-initial-focus",Li="true",Ah=`[${ki}="${Li}"]`,Oi={[ki]:Li},Hr="data-sb-focus-trap-sentinel",Th="true",Ni="data-sb-initial-focus-header",Di="true",Ih=`[${Ni}="${Di}"]`,$i={[Ni]:Di},Pi="data-sb-message-input",Fi="true",xh=`textarea[${Pi}="${Fi}"]:not(:disabled)`,Rh={[Pi]:Fi},Ui=1e3,sn=2147483647,ft={MODAL:sn-1,TOOLTIP:sn-2,WINDOW:sn-3,LAUNCHER:sn-4},Bi=36,Mh=100,wh=yh,Gr="noopener noreferrer nofollow",kh=()=>typeof document>"u"||document.visibilityState==="visible",mr=()=>typeof document<"u"&&document.visibilityState==="hidden",Ks=()=>mr()?"backgrounded":"foregrounded",Lh={getState:Ks,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(Ks());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function Oh(){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 on={};function Nh(){return{get:e=>{try{return localStorage.getItem(e)}catch{return on[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{on[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete on[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(on).filter(t=>t.startsWith(e))}}}}const Dh={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}`}},hr={language:"en",strings:Dh,dateLocale:sc.enUS},Hi=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}),Gi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Wt},Wt="en",zi=new Set([Wt,"ko","es","pt","fr","hi","it","de","tr","ja"]),$h='@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:Ph,useContext:zr}=ve("AgentUIElementResolver"),Fh=({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(Ph,{value:s},r)};function ct(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Ys=()=>{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:Uh,useContext:Vr}=ve("EscapeDismissStack"),Ws=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Bh=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Ys()),s.current||(s.current=Ys());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??ct(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Ws(m);return}i.dismissTopmost()&&Ws(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(Uh,{value:c},n)},Vi=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Hh=(e,t)=>{const{register:n}=Vr();Vi(e,t,n)},Gh=(e,t)=>{const{registerShellDismissHandler:n}=Vr();Vi(e,t,n)},qi=()=>{const{subscribe:e,getOpenCount:t}=Vr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},zh=(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=Hi(hr.strings),Vh={...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"},Sn={language:hr.language,dateLocale:hr.dateLocale,stringSet:Vh},qh=Object.freeze(Object.defineProperty({__proto__:null,default:Sn},Symbol.toStringTag,{value:"Module"})),fr=new Map([[Wt,Sn]]);async function Kh(e){const t=fr.get(e);if(t)return t;try{if(zi.has(e)){const{default:n}=await zh(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>qh),"./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 fr.set(e,n),n}return Sn}catch{return Sn}}const{Provider:Yh,useContext:ae}=ve("Localization"),Wh=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(fr.get(Wt));return l.useEffect(()=>{const c=t??Gi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Kh(c).then(i))},[e,t,n]),a.createElement(Yh,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>ot.format(c,u,{locale:o.dateLocale,...d})}},s)},yn="data-sb-agent-theme",Xs=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${yn}='${e}'] & { ${r} }`},te={light:Xs("light"),dark:Xs("dark")},jh=H.css(({theme:e})=>{const{palette:t}=e;return`
1
+ "use strict";var hc=Object.defineProperty;var fc=(e,t,n)=>t in e?hc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var b=(e,t,n)=>fc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ce=require("@sendbird/chat"),l=require("react"),U=require("styled-components"),ut=require("date-fns"),gc=require("date-fns/locale/en-US"),Le=require("@sendbird/chat/message"),he=require("@sendbird/chat/aiAgent"),pc=require("react-dom"),Qe=require("@sendbird/chat/groupChannel"),_c=require("date-fns/isSameDay"),Ec=require("dompurify"),Or=e=>e&&e.__esModule?e:{default:e};function Cc(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 bc=Or(Ce),a=Cc(l),_=Or(U),Wo=Or(Ec),jo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},vc=e=>{const t=jo(e);return typeof t=="object"&&t!==null?t:{}},Xo=e=>typeof e=="string"?vc(e):e??{},Sc=e=>!!Xo(e).stream,Cs=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},Zo=e=>{const t=Xo(e),n=Cs(t.user_message_id)??Cs(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},St="sb-agent",Jo="KEY_IMG_ASPECT_RATIO",fr="*/*",oe={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 vn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(vn||{}),Gt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Gt||{});const yc=e=>!!(e!=null&&e.cta_button),Ac=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Qo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,Tc=e=>{var t;return Qo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},Ic=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Ke=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},Wt=e=>Object.defineProperties({},{hasMessageTemplate:Ke(()=>!!(e!=null&&e.message_template)),hasCTAButton:Ke(()=>yc(e)),hasChallenge:Ke(()=>!!(e!=null&&e.challenge)),isThinking:Ke(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Ke(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Ke(()=>Ic(e)),hasCustomMessageTemplates:Ke(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Ke(()=>Qo(e)),hasActiveForm:Ke(()=>Tc(e)),hasSteward:Ke(()=>!!(e!=null&&e.steward)),hasCitations:Ke(()=>Ac(e))}),xc=e=>{const t=Wt(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},ei=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Rc=e=>e===Gt.COMPLETED||e===Gt.CANCELED?e:Gt.IN_PROGRESS,Wn=e=>tt(e)&&!ei(e),tt=e=>!!e&&"sender"in e,Mc=(e,{aiAgentInfo:t,members:n})=>t&&nt(e,t.userId)?t:(n==null?void 0:n.find(r=>r.userId===e.sender.userId))??e.sender,wc=e=>tt(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),kc=(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=ut.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Wn(n))return!1;const u=n.sender.userId===e.sender.userId,d=ut.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},nt=(e,t)=>(()=>{var r;return tt(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Me={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>ei(e),isIncoming:(e,t)=>tt(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>tt(e)&&(e.sender.userId===t||e.sendingStatus===Le.SendingStatus.PENDING)},We=e=>e.startsWith("image/"),jt=e=>e.startsWith("video/"),Lc=e=>e.startsWith("audio/"),ti=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Nr=(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"},ni=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},Oc=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return xc(t)},kn=e=>{switch(e){case"top":case"middle":return oe.GAP_GROUPED;default:return oe.GAP_UNGROUPED}},Nc=(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},Dc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),$c=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Pc=e=>e.replace(/~~/g,"\\~\\~"),Fc=e=>{let t=e;return t=Dc(t),t=$c(t),t=Pc(t),t},Uc=typeof navigator<"u"&&navigator.product==="ReactNative",gr=(e,t)=>{const n=r=>!t||t.length===0?!0:tt(r)&&t.includes(r.sendingStatus);return Uc?e.find(n):e.findLast(n)},Bc=(e,t)=>{const n=gr(e,[Le.SendingStatus.SUCCEEDED]);return n&&Me.isIncoming(n,t)?n:void 0},Ie=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function me(){}function Hc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Gc(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 we={isStreaming(e){return Sc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(we.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!nt(e,t))return!1;const n=Zo(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)}},jn=`@${St}`,zc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${jn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Gc(`${e}/${t}/${s}`);return`${jn}-udata/${o}`},anonUserSession:()=>`${jn}-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}}}}},ri=(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},Vc=()=>{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 qc{constructor(t){b(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??he.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[he.ConversationStatus.OPEN,he.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??he.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===he.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!==he.DeskChannelFilter.EXCLUDE:!1}}class si extends Qe.BaseChannelCollection{constructor(n,r){const s=new qc(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=Qe.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:p,copilotConversationOnly:v,copilotSupportChannelUrl:S}=s.params,C={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:p,copilotConversationOnly:v,copilotSupportChannelUrl:S};return i.getMyGroupChannelChangeLogs(m,C,Qe.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});b(this,"_params");b(this,"_sdk");b(this,"_throttledOnChannelChanged");b(this,"_key");b(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Vc()}`,this._throttledOnChannelChanged=ri(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:p,context:v}of m)h.delete(p.url),h.set(p.url,{channel:p,context:v});const f=new Map;for(const{channel:p,context:v}of h.values())f.has(v)||f.set(v,new Map),f.get(v).set(p.url,p);for(const[p,v]of f){const S=Array.from(v.values()),C=(g=this._sdk.currentUser)==null?void 0:g.userId,A=S.filter(T=>this.filter.match(T,C)),y=S.filter(T=>!this.filter.match(T,C)).map(T=>T.url);A.length>0&&this._base._addChannelsToView(A,p,!1),y.length>0&&this._removeChannels(y,p)}},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 oi{constructor(t){b(this,"subscribers",{});this.logger=t}async send(t){const n=Kc(),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 Kc=()=>{let e=me,t=me;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Be=(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.NudgeMessageReceived="nudge.message.received",e))(Be||{});class wt{constructor(t={}){b(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const at={CloseConversation:e=>new Yc(e),MessengerSettingsUpdated:e=>new Wc(e),ActiveChannelUpdated:e=>new jc(e),AnonymousSessionTokenExpired:()=>new Xc,AuthTokenRefreshed:()=>new Zc,NudgeMessageReceived:e=>new Jc(e)};class Yc extends wt{constructor(){super(...arguments);b(this,"type","conv.close")}}class Wc extends wt{constructor(){super(...arguments);b(this,"type","messenger.settings.updated")}}class jc extends wt{constructor(){super(...arguments);b(this,"type","active.channel.updated")}}class Xc extends wt{constructor(){super(...arguments);b(this,"type","anon.token.expired")}}class Zc extends wt{constructor(){super(...arguments);b(this,"type","auth.token.refreshed")}}class Jc extends wt{constructor(){super(...arguments);b(this,"type","nudge.message.received")}}const Xt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class Zt{constructor(t){b(this,"category","connection");this.userId=t}get data(){return Xt({user_id:this.userId})}}class Qc extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_connected")}}class el extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_reconnect_started")}}class tl extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_reconnect_succeeded")}}class nl extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_reconnect_failed")}}class rl extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_disconnected")}}class sl{constructor(t){b(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 Qc(n):t==="reconnectStarted"?new el(n):t==="reconnectSucceeded"?new tl(n):t==="reconnectFailed"?new nl(n):new rl(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Dr{constructor(t,n){b(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return Xt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class ol extends Dr{constructor(){super(...arguments);b(this,"metricKey","conversation_initialized")}}class il extends Dr{constructor(){super(...arguments);b(this,"metricKey","conversation_open")}}class al extends Dr{constructor(){super(...arguments);b(this,"metricKey","conversation_closed")}}class cl{constructor(t){b(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===he.ConversationStatus.INITIALIZED?new ol(t.url,n.id):s===he.ConversationStatus.OPEN?new il(t.url,n.id):new al(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===he.ConversationStatus.INITIALIZED?t===void 0:n===he.ConversationStatus.OPEN?t===he.ConversationStatus.INITIALIZED:t===he.ConversationStatus.OPEN}}const ii=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},De=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===he.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},$r=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===he.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function ct(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 ll(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!ct(e):!1}function ul(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function ai(e){return!!e&&e<=Date.now()}function dl(e){return!e.title}function ml(e,t){var n;if(e)return dl(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 Pr{constructor(t,n){b(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return Xt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class hl extends Pr{constructor(){super(...arguments);b(this,"metricKey","handoff_started")}}class fl extends Pr{constructor(){super(...arguments);b(this,"metricKey","handoff_succeeded")}}class gl extends Pr{constructor(){super(...arguments);b(this,"metricKey","handoff_failed")}}class pl{constructor(t){b(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 hl(t.url,r.id):o==="succeeded"?new fl(t.url,r.id):new gl(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(De(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 _l{constructor(t){b(this,"category","message");b(this,"metricKey","incoming_message_received");b(this,"channelUrl");b(this,"messageId");b(this,"senderType");b(this,"createdAt");b(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 Xt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const El=(e,t)=>{const n=tt(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class Cl{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 _l({channelUrl:t.url,messageId:n.messageId,senderType:El(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!nt(t,this.getCurrentUserId())&&n!==null}}class bl{constructor(t){b(this,"category","message");b(this,"metricKey");b(this,"channelUrl");b(this,"requestId");b(this,"messageId");b(this,"target");b(this,"sendingStatus");b(this,"createdAt");b(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 Xt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const vl=e=>{switch(e){case Le.SendingStatus.PENDING:return"pending";case Le.SendingStatus.SUCCEEDED:return"succeeded";case Le.SendingStatus.FAILED:return"failed";case Le.SendingStatus.SCHEDULED:return"scheduled";default:return}};class Sl{constructor(t,n){b(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!nt(n,this.getCurrentUserId()))return;const r=vl(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 bl({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:ct(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 yl{constructor(t){b(this,"id","aiagent_livemetric");b(this,"dispatch");b(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});b(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new sl(this.emit),conversation:new cl(this.emit),handoff:new pl(this.emit),incomingMessage:new Cl(this.emit,n),outgoingMessage:new Sl(this.emit,n)}}start(){const t=new Ce.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 Qe.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 Fr=(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))(Fr||{});class ci{constructor(t){b(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${St}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${St}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${St}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${St}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${St}/error]`,...t)}}class li{constructor({userId:t,authToken:n,sessionHandler:r}){b(this,"userId");b(this,"authToken");b(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class pr{constructor(){b(this,"userId");b(this,"authToken");b(this,"sessionHandler")}}const Al=e=>({onSessionTokenRequired:t=>{t(null),e.send(at.AnonymousSessionTokenExpired())}}),Ur=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),Tl="ai_agent:stats",Il="conversation_initial_render",xl="conversation_not_interactive_timeout",Rl="recovery_not_interactive_timeout",Ml="conversation_list_initial_render",wl="message_pending_stuck",kl="aiev_auth_expired_unhandled",Ll="user_perceived_response_time",Ol="stream_stalled",Nl="ai_typing_indicator_absent_timeout",Dl="rendered_content_unusable",$l=800220;var j=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(j||{});const _r=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),ui=e=>typeof e=="object"&&e!==null,Pl=e=>{if(ui(e))return typeof e.code=="number"?e.code:void 0},Fl=e=>e instanceof Error?e.message:typeof e=="string"?e:ui(e)&&typeof e.message=="string"?e.message:"";class rt{constructor(){b(this,"timers",new Map);b(this,"committed",!1);b(this,"commitCallback",null);b(this,"conversationId",null);b(this,"errorCode",null);b(this,"errorDescription",null);b(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=Pl(t)??$l,this.errorDescription=Fl(t),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:performance.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:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=Ur({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(Tl,t)):!1}}class bs extends rt{constructor(){super(...arguments);b(this,"reason");b(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return kl}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Ln{constructor(t){b(this,"commitCallback");this.commitCallback=t}}class kt extends Ln{constructor(){super(...arguments);b(this,"records",new Map)}}class di extends Ln{constructor(){super(...arguments);b(this,"activeSpan",null);b(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class mi{constructor(t,n){b(this,"stats");b(this,"visible");b(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const gt=(e,t)=>!(e&&t&&e!==t),Er=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&gt(n.measure.channelUrl,t))return!0;return!1},On=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class Ul extends Ln{onPayloadParseFailed(t){new bs().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new bs().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Bl extends rt{constructor(){super(...arguments);b(this,"channelUrl",null);b(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(j.PAGE_RENDER),this.timers.delete(j.PAGE_RENDER_FROM_CACHE),this.timers.delete(j.GET_CHANNEL),this.timers.delete(j.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Il}buildPayload(){const n=this.getTimer(j.AUTH),r=this.getTimer(j.PAGE_RENDER),s=this.getTimer(j.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-_r(n,r),i=s.duration===null?null:s.duration-_r(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[j.AUTH]:n.duration,[j.GET_CHANNEL]:this.getTimer(j.GET_CHANNEL).duration,[j.GET_MESSAGES]:this.getTimer(j.GET_MESSAGES).duration,[j.PAGE_RENDER_FROM_CACHE]:i}})}}class Hl extends mi{constructor(n,r,s){var o;super(n,s);b(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(j.PAGE_RENDER).startTimer(j.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(j.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(j.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(j.GET_CHANNEL).setError(r).stopTimer(j.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(j.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(j.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(j.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(j.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(j.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(j.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Gl extends di{constructor(){super(...arguments);b(this,"stats",null);b(this,"authState","idle");b(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Bl().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(j.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(j.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(j.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new Hl(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class zl extends rt{constructor(){super(...arguments);b(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(j.PAGE_RENDER),this.timers.delete(j.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Ml}buildPayload(){const n=this.getTimer(j.AUTH),r=this.getTimer(j.PAGE_RENDER),s=this.getTimer(j.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-_r(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[j.AUTH]:n.duration,[j.GET_LIST]:s}})}}class Vl extends mi{constructor(n,r){var s;super(n,r);b(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(j.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(j.PAGE_RENDER),this.stats.startTimer(j.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(j.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(j.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(j.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(j.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class ql extends di{constructor(){super(...arguments);b(this,"stats",null);b(this,"authState","idle");b(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new zl().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(j.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(j.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(j.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(j.AUTH),this.activeSpan=new Vl(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Kl extends rt{constructor(){super(...arguments);b(this,"phaseReached","auth");b(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return xl}buildPayload(){const n=this.getTimer(j.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class Yl extends kt{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new Kl().setCommitCallback(this.commitCallback).startTimer(j.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(j.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Wl extends rt{constructor(){super(...arguments);b(this,"requestId");b(this,"messageType");b(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return wl}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const jl=5e3,vs=1e4;class Xl extends kt{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new Wl().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?vs:jl;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),vs))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class Xn extends rt{constructor(){super(...arguments);b(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return Rl}buildPayload(){const n=this.getTimer(j.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class Zl extends kt{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new Xn().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(j.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(j.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new Xn().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new Xn().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class Jl extends rt{constructor(){super(...arguments);b(this,"messageId");b(this,"contentKind");b(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return Dl}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const Ql=500;class eu extends Ln{constructor(){super(...arguments);b(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;On(this.measure.committed,Ql),this.measure.committed.add(r),new Jl().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class tu extends rt{constructor(){super(...arguments);b(this,"durationMs");b(this,"messageId");b(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return Ol}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const Ss=1e4,vt=5e3,nu=500;class ru extends kt{constructor(){super(...arguments);b(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,vt))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,vt)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,vt))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<vt){this.scheduleRenderStallCheck(n,r,vt-o);return}const i=performance.now()-s.lastRawAt;if(i>=vt&&s.deliveryTimer!==null){const c=Ss-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),Ss))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new tu().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||On(this.emittedMessageChannels,nu),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class su extends rt{constructor(){super(...arguments);b(this,"beforeTpstAbsentMs");b(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return Nl}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[j.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[j.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const ys=3e3,ou=3e4;class iu extends kt{constructor(){super(...arguments);b(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new su().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),ou),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{gt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{gt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!Er(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(On(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{gt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{gt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=ys&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=ys&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class au extends rt{constructor(){super(...arguments);b(this,"ackToFirstChunkMs");b(this,"firstChunkToRenderMs");b(this,"isStreaming");b(this,"sendToAckMs");b(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return Ll}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[j.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[j.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[j.SEND_TO_ACK]:this.sendToAckMs}})}}const cu=.15,lu=10,uu=e=>e<=0?!1:e>=1?!0:Math.random()<e;class du extends kt{constructor(n,r){super(n);b(this,"samplingRate");b(this,"pendingAIResponseByUserMessageId",new Map);b(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??cu}startTurn(n){if(this.collectedCount>=lu||!uu(this.samplingRate))return;this.collectedCount+=1;const r={stats:new au().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&Er(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!Er(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&gt(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&gt(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||(On(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function mu(){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 As={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},Br={conversation:{...As,messageAlertSoundEnabled:!1,list:{...As,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Ts=e=>e?{conversation:gu(e.conversation),launcher:hu(e.launcher)}:Br,hu=e=>yt(Br.launcher,e),fu=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},gu=e=>{const t=Br.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={...yt(t.list,c,n),deferredMarkdownElements:fu(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:yt(t.header,r),input:{camera:yt(t.input.camera,u),gallery:yt(t.input.gallery,d),fileEnabled:m},fileViewer:yt(t.fileViewer,o)}},yt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,Ur(r));return n},pu=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}),_u=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Cr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Eu{constructor(){b(this,"_channelHandlerId",null);b(this,"_connectionHandlerId",null);b(this,"_initConversationRequests",new Map);b(this,"_handleActiveChannelChangedThrottled",null);b(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ri(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:De(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 Qe.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 Ce.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})});b(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")});b(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:De(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)}});b(this,"_initConversationIfNeeded",(t,n)=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const r=this._initConversationRequests.get(t.url);if(r)return r;const s=t.initConversation({aiAgentId:this.aiAgentId,initialUserMessage:n==null?void 0:n.initialUserMessage}).then(()=>{}).catch(o=>{this._logger.warn("AIAgentEventManager: initConversation failed",o)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,s),s});b(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Be.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Be.MessengerSettingsUpdated,t)}));b(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Be.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Be.ActiveChannelUpdated,t)}));b(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Be.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Be.AuthTokenRefreshed,t)}));b(this,"onNudgeMessageReceived",t=>(this._dispatcher.subscribe(Be.NudgeMessageReceived,t),()=>{this._dispatcher.unsubscribe(Be.NudgeMessageReceived,t)}))}}class Cu{constructor(t){b(this,"_sdkUser");b(this,"_userSession");b(this,"_dispatcher");b(this,"_activeChannel");b(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(at.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});b(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(at.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),bu=e=>JSON.parse(e);function vu(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Su(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 yu({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 Au({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 Hr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Hr||{});const gi=e=>typeof e=="object"&&e!==null,Zn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Tu=e=>!gi(e)||!Zn(e,"channel_url")||!Zn(e,"ai_agent_id")||!Zn(e,"cpa_key")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id,cpaKey:e.cpa_key},Iu={1:Tu};function xu(e){if(!gi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Iu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Ru(e,t,n,r){const s=bc.default.init({appId:e,modules:[new Qe.GroupChannelModule,new he.AIAgentModule],localCacheEnabled:!0,options:new Ce.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:Ce.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Mu(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 wu=[400300,400301,400302,400310],ku=Hr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Lu=e=>`${ku}:${e}`;class Gr{constructor(t,n,r,s,o){b(this,"chatSDK");b(this,"_aiAgentId");b(this,"_externalAuthTokenExpiredEventHandlerKey");b(this,"_logger");b(this,"_cache");b(this,"_statsTrackers");b(this,"_sessionHandler");b(this,"_aiEventHandlerRegistered",!1);b(this,"connect",async(t,n,r,s,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const i=new Ce.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(i)}this._registerAIEventHandler();try{await this.chatSDK.connect(t.userId,t.authToken);const[,i]=await Promise.allSettled([this._syncTemplatesIfNeeded(),o?this.submitCPAAuthorizationCodes(o):Promise.resolve()]);return o&&(i.status==="fulfilled"?this._logger.debug("ChatClient.connect: CPA authorization codes submitted",i.value):this._logger.error("ChatClient.connect: CPA authorization code submission failed",i.reason)),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(i){const c=i;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(c))this._logger.warn("ChatClient.connect","offline connect restricted",c.message,c.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(u=>this._logger.warn("ChatClient.connect","clear cached-data failure",u));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",c.message,c.code),this.dispose(),c}});b(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});b(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=xu(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Hr.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)});b(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});b(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")});b(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));b(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));b(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));b(this,"requestNudgeMessage",async t=>this.chatSDK.aiAgent.requestNudgeMessage(t));b(this,"submitCPAAuthorizationCodes",async({aiAgentId:t,authCodes:n})=>this.chatSDK.aiAgent.submitCustomerProvidedAuthCodes({aiAgentId:t,authorizationCodes:n}));b(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});b(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});b(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});b(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)})}});b(this,"_isCacheRestrictedError",t=>wu.some(n=>t.code===n));b(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=Lu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Mu(t.chatSDK),n=t.chatSDK):n=Ru(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Gr(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Ou=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},Nu=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},an=new Map,pi={set:(e,t)=>{an.set(e,t)},get:e=>{if(an.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=an.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=an.entries().next().value;return{platform:t[0],...t[1]}}};class Is extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);b(this,"status");b(this,"code");b(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var zr=(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))(zr||{}),Vr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Vr||{}),_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 Du=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class $u{constructor(t){b(this,"_appId");b(this,"_apiHost");b(this,"_logger");b(this,"_credential",null);b(this,"_authRefreshPromise",null);b(this,"_onDeskTokenRefreshRequired",async()=>!1);b(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)});b(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});b(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});b(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Du(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)});b(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}});b(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))}:{}}));b(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));b(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));b(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));b(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Is(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Is(t.status,{})}});b(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}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class Sn{constructor(t,n){b(this,"id");b(this,"title");b(this,"status");b(this,"agent");b(this,"priority");b(this,"group");b(this,"firstResponseTime");b(this,"issuedAt");b(this,"customFields");b(this,"_client");b(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 Sn({id:t.id,title:t.channelName??null,status:t.status2??zr.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??Vr.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 qr{constructor(t){b(this,"_logger");b(this,"_apiClient");b(this,"_onDeskTokenRefreshRequired");b(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);b(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}});b(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});b(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")});b(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return Sn._fromResponse(n,this)});b(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Ur({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 Sn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new $u(t)}static init(t){return new qr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Kr{constructor(){b(this,"authenticate",async t=>!1);b(this,"deauthenticate",()=>{});b(this,"refreshDeskAuthToken",async()=>!1);b(this,"setCustomerLanguage",async()=>{});b(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Kr}}function Pu(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 Fu=1440*60*1e3,Uu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function Ye(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 Hu=e=>{const t={conversationInitialRender:new Gl(e),conversationNotInteractiveTimeout:new Yl(e),recoveryNotInteractiveTimeout:new Zl(e),conversationListInitialRender:new ql(e),aievAuthExpiredUnhandled:new Ul(e),messagePendingStuck:new Xl(e),userPerceivedResponseTime:new du(e),streamStalled:new ru(e),typingIndicatorAbsentTimeout:new iu(e),renderedContentUnusable:new eu(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class yn extends Eu{constructor(n){super();b(this,"appId");b(this,"aiAgentId");b(this,"_chatClient");b(this,"_deskClient");b(this,"_cache");b(this,"_logger");b(this,"_dispatcher");b(this,"_session",null);b(this,"language");b(this,"countryCode");b(this,"context");b(this,"cpaAuthorizationCodes");b(this,"queryParams");b(this,"_config");b(this,"_networkStateAdapter");b(this,"_scheduleForegroundTask");b(this,"_watchBackgrounded");b(this,"_forceCreateChannel");b(this,"_agentVersion");b(this,"_statsTrackers");b(this,"_liveMetricManager");b(this,"_operationQueue",mu());b(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"))});b(this,"initConversationIfNeeded",(n,r)=>this._initConversationIfNeeded(n,r));b(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(at.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:v,session_token:S,expire_at:C}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:S,expireAt:C}),f={userId:v,authToken:S},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}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(at.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var v;return s.type==="anonymous"?Al(this._dispatcher):(v=s.userSessionCandidate)==null?void 0:v.sessionHandler})(),p=await this._chatClient.connect(f,g,v=>{var S;this._logger.debug("AIAgent: session token refreshed"),(S=this._session)==null||S._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()},this.cpaAuthorizationCodes?{aiAgentId:this.aiAgentId,authCodes:this.cpaAuthorizationCodes}:void 0);return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var S;if(v===_i.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const C=(S=this._session)==null?void 0:S.userSession.authToken;return C?await this._deskClient.refreshDeskAuthToken(C):!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 Cu({sdkUser:p,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),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});b(this,"submitCPAAuthorizationCodes",async n=>{Ye(this._session),this._logger.debug("AIAgent.submitCPAAuthorizationCodes: start");const r=await this._chatClient.submitCPAAuthorizationCodes({aiAgentId:this.aiAgentId,authCodes:n});return this._logger.debug("AIAgent.submitCPAAuthorizationCodes: end",r),r});b(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")}));b(this,"createConversation",async n=>{Ye(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});b(this,"searchConversation",async n=>{if(Ye(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:he.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});b(this,"closeConversation",async n=>{var s;Ye(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===he.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:he.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});b(this,"createConversationListCollection",n=>new si(this.chatSDK,n??{}));b(this,"patchContext",async(n,r)=>{Ye(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??{}}});b(this,"updateContext",async(n,r)=>{Ye(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??{}}});b(this,"getContextObject",async n=>{Ye(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??{}}});b(this,"requestNudgeMessage",async n=>{Ye(this._session);const r=this._session;this._logger.debug("AIAgent.requestNudgeMessage: start",n);const s=await this._chatClient.requestNudgeMessage({aiAgentId:this.aiAgentId,key:n.key,context:n.context,language:this.language});if(this._logger.debug("AIAgent.requestNudgeMessage: end",s),this._session!==r){this._logger.debug("AIAgent.requestNudgeMessage: session changed during request, discarding stale nudge");return}s.status!=="ok"||!s.payload.message||this._dispatcher.send(at.NudgeMessageReceived({message:s.payload.message,callbackUserMessage:s.payload.callback_user_message??void 0}))});b(this,"clearUserMemories",async(n={})=>{Ye(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")});b(this,"setUserMemoryState",async n=>{Ye(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"),Cr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(at.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),Cr(i)});b(this,"refreshActiveChannel",async n=>{var c,u,d;Ye(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});b(this,"_getSessionCandidate",n=>n instanceof li?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof pr?{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});b(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Fu<=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});b(this,"_getManualSessionInfo",n=>{if(!n||n instanceof pr)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.cpaAuthorizationCodes=n.cpaAuthorizationCodes,this._config=Ts(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=Ou(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&Nu(n.foregroundStateAdapter),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 yl(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=pi.get(n.platform),s=n.logger??new ci(n.logLevel??Fr.WARN),o=n.dispatcher??new oi(s),i=n.useMMKVStorage?Pu(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=zc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=Hu((p,v)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,v)});d=Gr.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=Uu?qr.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Kr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new yn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,cpaAuthorizationCodes:n.cpaAuthorizationCodes,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,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=Ts(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}get watchBackgrounded(){return this._watchBackgrounded}}const ve=(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 Gu(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function zu(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Vu(e,t)}function Vu(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 qu(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ut.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):ut.isToday(s)?n.hoursAgo(ut.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Ku=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},cn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),xs=(e,t)=>{const n=cn(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=Ku(e);return r?`#${cn(r[0])}${cn(r[1])}${cn(r[2])}${n}`:e},Yu=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Wu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",ju=e=>e.length>0,Xu=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},Rs=e=>e.length===0?"empty":e.every(t=>We(t.type))?"images":"non_images",Zu=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Xu(t),s=Rs(e),o=Rs(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}},It=3,Ei=6,Ju=e=>e%It===0?It:Ei,Qu=({index:e,itemCount:t})=>{const n=t%It,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:It,c=o?e-s:e%It,u=!r&&e>=t-It;return{columnSpan:r?Ei/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},Ci=ve("AIAgent"),ed=Ci.Provider,ye=Ci.useContext;function td(e){const t=nd(e);return a.createElement(ed,{value:{_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,cpaAuthorizationCodes:t.cpaAuthorizationCodes,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}},e.children)}function nd(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=yn.init(e);else{const o=rd(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=yn.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.cpaAuthorizationCodes=e.cpaAuthorizationCodes,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function rd(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 ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Nn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let sd=0;function od(){return l.useState(()=>`${sd++}`)[0]}const pt=(e,t,n)=>{const r=l.useRef(t),o=od();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var p;const g=r.current;(p=g[h])==null||p.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new Qe.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function id(e,t){return!e||!t?!0:e.url!==t.url}function Ve(e){return e!=null&&"sendingStatus"in e}function ad(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return Ve(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function cd(e,t){return ad(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 An={collection:{groupChannel:{defaultOrder:Qe.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 ld=({...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=ud(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=Ve(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];dd(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=>{Ve(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{Ve(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=>cd(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&&(Ve(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(Ve(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},ud=e=>e.reduce((t,n)=>(Ve(n)?(t[n.reqId]=n,n.sendingStatus===Le.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),dd=(e,t,n=!1)=>{var r,s;if(!Ve(e)||!Ve(t))return!0;if(n&&e&&we.isStreaming(e)&&we.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===Le.SendingStatus.SUCCEEDED?t.sendingStatus===Le.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},md=(e=hd)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(ld,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(S,C,A,y)=>{i({type:"update_messages",value:{messages:S,clearBeforeAction:C,currentUserId:A,strictStreamingOrder:y}})},u=(S,C)=>{i({type:"delete_messages",value:{messageIds:S,reqIds:C}})},d=(S,C,A)=>{i({type:"update_new_messages",value:{messages:S,clearBeforeAction:C,currentUserId:A}})},m=(S,C)=>{i({type:"delete_new_messages",value:{messageIds:S,reqIds:C}})},h=S=>{i({type:"update_initialized",value:{status:S}})},f=S=>{i({type:"update_loading",value:{status:S}})},g=S=>{i({type:"update_refreshing",value:{status:S}})},p=Object.values(o),v=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:v,newMessages:p,updateNewMessages:d,deleteNewMessages:m}},Ls=Math.floor(Number.MAX_SAFE_INTEGER/10);function hd(e,t){let n=0,r=0;return Ve(e)&&e.sendingStatus!=="succeeded"&&(n=Ls),Ve(t)&&t.sendingStatus!=="succeeded"&&(r=Ls),e.createdAt+n-(t.createdAt+r)}const fd=(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 Qe.MessageFilter(r)})};function Os(e){return e<Date.now()?An.collection.message.searchLimit:An.collection.message.defaultLimit}const gd=(e,t,n={})=>{var Te,$;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=Nn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:p,messages:v,newMessages:S,updateMessages:C,updateNewMessages:A,deleteNewMessages:y,deleteMessages:T,updateInitialized:I,updateLoading:N,updateRefreshing:O}=md(n==null?void 0:n.sortComparator),k=ce(M=>{var x,L,P,X;if(!s.current||!s.current.url)return(x=o==null?void 0:o.error)==null?void 0:x.call(o,"[useGroupChannelMessages] channel is required");try{switch(M){case Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(P=(L=r.current).markAsRead)==null||P.call(L,[s.current]);break}}catch(se){(X=o==null?void 0:o.warn)==null||X.call(o,"[useGroupChannelMessages/markAsReadBySource]",se)}}),R=ce((M,x)=>{var L,P,X,se,Z;if(x.length>0)switch(M){case Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:{(P=(L=r.current).shouldCountNewMessages)!=null&&P.call(L)&&A(x,!1,(X=e.currentUser)==null?void 0:X.userId),(Z=(se=r.current).onMessagesReceived)==null||Z.call(se,x);break}}}),F=ce(M=>{var x,L;(L=(x=r.current).onCollectionEvent)==null||L.call(x,M)}),D=ce(async(M,x,L)=>new Promise((P,X)=>{var Xe,it,sn;h.current.instance&&h.current.instance.dispose(),k(),A([],!0,(Xe=e.currentUser)==null?void 0:Xe.userId);const se=()=>{var ge,pe;const{pendingMessages:le,failedMessages:fe}=h.current.instance??{};ws(le)&&C(le,!1,(ge=e.currentUser)==null?void 0:ge.userId),ws(fe)&&C(fe,!1,(pe=e.currentUser)==null?void 0:pe.userId)},Z=fd(M,L,{...r.current,startingPoint:x});h.current={apiInitialized:!1,initialized:!1,instance:Z},Z.setMessageCollectionHandler({onMessagesAdded:(le,fe,ge)=>{var pe;k(le.source),R(le.source,ge),C(ge,!1,(pe=e.currentUser)==null?void 0:pe.userId,u),F({kind:"messagesAdded",source:le.source,channelUrl:M.url,messages:ge})},onMessagesUpdated:(le,fe,ge)=>{var pe,Fe,Ue;k(le.source),R(le.source,ge),C(ge,!1,(pe=e.currentUser)==null?void 0:pe.userId,u),le.source===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Ue=(Fe=r.current).onMessagesUpdated)==null||Ue.call(Fe,ge)),F({kind:"messagesUpdated",source:le.source,channelUrl:M.url,messages:ge})},onMessagesDeleted:(le,fe,ge,pe)=>{const Fe=pe.map(Ee=>Ee.messageId),Ue=pe.filter(Ve).map(Ee=>Ee.reqId);T(Fe,Ue),y(Fe,Ue),F({kind:"messagesDeleted",source:le.source,channelUrl:M.url,messages:pe})},onChannelDeleted:(le,fe)=>{var ge,pe;(pe=(ge=r.current).onChannelDeleted)==null||pe.call(ge,fe)},onChannelUpdated:(le,fe)=>{var ge,pe;m(),(pe=(ge=r.current).onChannelUpdated)==null||pe.call(ge,fe,le)},onHugeGapDetected:()=>{D(M,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit)}});let be=!1;(sn=(it=r.current).onCollectionInitializeStart)==null||sn.call(it),Z.initialize(Qe.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((le,fe)=>{var ge,pe,Fe,Ue,Ee;(pe=(ge=r.current).onCacheResult)==null||pe.call(ge,le,fe??[],M.url),le?(e.isCacheEnabled&&((Fe=o==null?void 0:o.error)==null||Fe.call(o,"[useGroupChannelMessages/onCacheResult]",le)),be=!0):fe&&((Ue=o==null?void 0:o.debug)==null||Ue.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",fe.length),C(Z.succeededMessages,!0,(Ee=e.currentUser)==null?void 0:Ee.userId),se(),fe.length>0&&(h.current.initialized=!0,P())),F({kind:"initialized",source:"cache",channelUrl:M.url,messages:fe??[],error:le})}).onApiResult((le,fe)=>{var ge,pe,Fe,Ue,Ee,Ze,Ne;(pe=(ge=r.current).onApiResult)==null||pe.call(ge,le,fe??[],M.url),h.current.initialized=!0,h.current.apiInitialized=!0,le?((Fe=o==null?void 0:o.warn)==null||Fe.call(o,"[useGroupChannelMessages/onApiResult]",le),be?X(le):P()):fe&&((Ue=o==null?void 0:o.debug)==null||Ue.call(o,"[useGroupChannelMessages/onApiResult]","message length:",fe.length),C(Z.succeededMessages,!0,(Ee=e.currentUser)==null?void 0:Ee.userId),r.current.startingPoint||(Ne=(Ze=r.current).onMessagesReceived)==null||Ne.call(Ze,fe),e.isCacheEnabled&&se(),P()),F({kind:"initialized",source:"api",channelUrl:M.url,messages:fe??[],error:le})})}));pt(e,{onUserBanned(M,x){var L,P,X;M.isGroupChannel()&&!id(M,s.current)&&(x.userId===((L=e.currentUser)==null?void 0:L.userId)?(X=(P=r.current).onCurrentUserBanned)==null||X.call(P):m())}}),l.useLayoutEffect(()=>{const M=setTimeout(async()=>{e.currentUser&&s.current&&(I(!1),N(!0),await D(s.current,i,c),N(!1),I(!0))});return()=>clearTimeout(M)},[e,(Te=e.currentUser)==null?void 0:Te.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const Q=ce(async()=>{e.currentUser&&s.current&&(O(!0),await D(s.current,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit),O(!1))}),re=ce(async()=>{var x;const M=h.current.instance;if(M!=null&&M.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const L=await M.loadPrevious();C(L,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.prev=!1}}),G=ce(()=>{const{initialized:M,instance:x}=h.current;return M&&x?x.hasPrevious:!1}),H=ce(async()=>{var x;const M=h.current.instance;if(M!=null&&M.hasNext&&!d.current.next)try{d.current.next=!0;const L=await M.loadNext();C(L,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.next=!1}}),q=ce(()=>{const{initialized:M,apiInitialized:x,instance:L}=h.current;return x&&M&&L?L.hasNext:!1}),J=M=>{var x,L,P,X;!M||M.channelUrl!==((x=s.current)==null?void 0:x.url)||(C([M],!1,(L=e.currentUser)==null?void 0:L.userId),(X=(P=r.current).onOutgoingMessageStatusChanged)==null||X.call(P,M))},K=ce((M,x)=>{var L;if(!s.current||!s.current.url)throw(L=o==null?void 0:o.error)==null||L.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((P,X)=>{s.current.sendUserMessage(M).onPending(se=>{J(se),x==null||x(se)}).onSucceeded(se=>{J(se),P(se)}).onFailed((se,Z)=>{J(Z),X(se)})})}),z=ce((M,x)=>{var L;if(!s.current||!s.current.url)throw(L=o==null?void 0:o.error)==null||L.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((P,X)=>{s.current.sendFileMessage(M).onPending(se=>{J(se),x==null||x(se)}).onSucceeded(se=>{J(se),P(se)}).onFailed((se,Z)=>{J(Z),X(se)})})}),Y=ce((M,x,L)=>{var P;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((X,se)=>{s.current.sendMultipleFilesMessage(M).onPending(Z=>{J(Z),x==null||x(Z)}).onFileUploaded(Z=>{L==null||L(Z),m()}).onSucceeded(Z=>{J(Z),X(Z)}).onFailed((Z,be)=>{J(be),se(Z)})})}),W=ce(async(M,x)=>{var P,X;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const L=await s.current.updateUserMessage(M,x);return L.channelUrl===s.current.url&&C([L],!1,(X=e.currentUser)==null?void 0:X.userId),L}),V=ce(async(M,x)=>{var P,X;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const L=await s.current.updateFileMessage(M,x);return L.channelUrl===s.current.url&&C([L],!1,(X=e.currentUser)==null?void 0:X.userId),L}),ee=ce(async(M,x,L)=>{var P;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((X,se)=>{let Z;M.isUserMessage()&&(Z=s.current.resendMessage(M)),M.isFileMessage()&&(Z=s.current.resendMessage(M)),M.isMultipleFilesMessage()&&(Z=s.current.resendMessage(M)),Z&&("onPending"in Z&&Z.onPending(be=>{J(be),x==null||x(be)}),"onFileUploaded"in Z&&Z.onFileUploaded(be=>{L==null||L(be),m()}),"onSucceeded"in Z&&Z.onSucceeded(be=>{J(be),X(be)}),"onFailed"in Z&&Z.onFailed((be,Xe)=>{J(Xe),se(be)}))})}),w=ce(async M=>{var x,L,P,X;if(!s.current||!s.current.url)throw(x=o==null?void 0:o.error)==null||x.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(M.sendingStatus==="succeeded")M.isUserMessage()&&await s.current.deleteMessage(M),M.isFileMessage()&&await s.current.deleteMessage(M),M.isMultipleFilesMessage()&&await s.current.deleteMessage(M);else try{await((L=h.current.instance)==null?void 0:L.removeFailedMessage(M.reqId))}finally{T([],[M.reqId]),(X=(P=r.current).onLocalMessageDeleted)==null||X.call(P,M)}}),_e=ce(()=>{var M;A([],!0,(M=e.currentUser)==null?void 0:M.userId)}),Re=ce(async M=>{var x;if(e.currentUser&&s.current){const L=Os(M);N(!0),C([],!0,(x=e.currentUser)==null?void 0:x.userId),await D(s.current,M,L),N(!1)}});return{initialized:f,loading:g,refreshing:p,messages:v,newMessages:S,resetNewMessages:_e,refresh:Q,loadPrevious:re,hasPrevious:G,loadNext:H,hasNext:q,sendUserMessage:K,sendFileMessage:z,sendMultipleFilesMessage:Y,updateUserMessage:W,updateFileMessage:V,resendMessage:ee,deleteMessage:w,resetWithStartingPoint:Re,_dangerous_reducer_updateMessages:C,_dangerous_reducer_deleteMessages:T}},pd=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,_d=(e,t,n)=>{const r=gd(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!pd(o)),[r.messages]);return{...r,messages:s}},Ed=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{n(t)})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},bi=Ed(),Cd=({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(p=>r.current===p,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(p=>{c(p)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:p,conversationId:v})=>{i.current=!0,n.markChannelJoined(v,p)},[n]),h=l.useCallback(({channelUrl:p})=>{n.clearChannel(p),i.current=!1},[n]),f=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,m(p)}},[c,m]),g=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,h(p)}},[c,h]);return l.useEffect(()=>{if(t){const p=o.current;if(!p||(o.current=null,p.channelUrl!==e))return;"error"in p?h(p):m(p);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}},bd=({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}},qt={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 vd(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 Sd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function yd(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 Ad(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 ln(e,t,n){const[r,s,o]=vd(e),[i,c,u]=yd(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=Ad(i,m,d);return Sd([Math.round(h),Math.round(f),Math.round(g)])}function Td(e,t="light"){return{extraDark:ln(e,.6,1.2),dark:ln(e,.85,1.1),main:e,light:ln(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:ln(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function br(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?qt.BLACK:qt.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},conversation:{headerProfileSkeleton: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 xd=(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},conversation:{headerProfileSkeleton: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"}}),un={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 Ns(e){const t=Rd(e),n=Md(e,t),r=kd(n,e.colors,e.selectedTheme),s=Od(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 Rd({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===un.primary.main?un.primary:Td(n,e):un.primary;return{...un,primary:r,...t}}function Md({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??br(o),c=n??qt.DEFAULT_BOT_MSG_BG,u=r??br(c);return(e==="light"?Id:xd)(s,o,i,c,u)}function wd(e,t,n){return typeof e=="string"?e:e[t]??n}function kd(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]=wd(m,n,h)}}}return r}function Ld(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Od({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]=Ld(s,r,o)}}),t}const{Provider:Nd,useContext:Yr}=ve("AIAgentTheme");function Dd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Ns({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,p={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!p.primary&&(g!=null&&g.primary_color)&&(p.primary=g.primary_color,p.primaryContrast=g.primary_contrast_color),!p.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(p.botMessageBackground=g.bot_message_bg_color,p.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const v=Ns({selectedTheme:f,palette:t,typography:n,colors:r,...p});u(v),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(Nd,{value:{theme:c,updateTheme:d}},o)}const Qn=25*1024*1024,Ds=1,$s=new Set(["image/png","image/jpeg","image/jpg"]),Ps=new Set(["application/pdf"]),$d={off:"off",always:"always",handed_off_only:"handed_off_only"},Pd=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:Ds,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Qn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:$s,supportedFileMimeTypes:Ps})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Ds,attachmentMode:$d[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Qn,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)??Ps)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=Qn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?ct(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 ct(o);default:return!0}},get supportedMimeTypes(){return c()?[fr]:[...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)")},$t=e=>({...e,context:e.context??{}}),{Provider:Fd,useContext:ht}=ve("AIAgentMessengerSession"),Ud=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=ye(),{updateTheme:c}=Yr(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[p,v]=l.useState(null),[S,C]=l.useState(null),[A,y]=l.useState(null),[T,I]=l.useState(null),{updateBaseAttachmentRules:N,createAttachmentRules:O}=Pd();l.useEffect(()=>{const D=r.onMessengerSettingsUpdated(({settings:G})=>{const{appearance:H,bot:q,launcher:J,memory:K}=G;c(H.selected_theme,H),C(pu(q)),y(_u(J)),I(K?Cr(K):null),N(G)}),Q=r.onActiveChannelUpdated(({channelUrl:G,status:H,conversationStatus:q})=>{h({url:G,status:H,conversationStatus:q})}),re=r.onAuthTokenRefreshed(()=>{var H;const G=(H=r.session)==null?void 0:H.userSession.authToken;G&&v(q=>q?{...q,authToken:G}:null)});return()=>{D(),Q(),re()}},[r,c,N]);const k=l.useCallback(async()=>{try{const D=await r.authenticate(e),Q=r.session;return g(Q.sdkUser),v(Q.userSession),h(Q.activeChannel),d(void 0),D}catch(D){throw g(null),v(null),h(void 0),d(D),D}},[r,e]),R=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),v(null),C(null),y(null),I(null)},[r]),F=l.useCallback(async()=>{if(!r.session){if(p)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!==(p==null?void 0:p.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,p]);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:k,deauthenticate:R,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,updateContext:async(...Q)=>{const re=Fs(...Q);if(re.type==="active"){const q=await(await D()).updateContext(o,re.context);return $t(q)}const G=await s.aiAgent.updateContext(re.aiAgentId,re.channelUrl,re.context);return $t(G)},patchContext:async(...Q)=>{const re=Fs(...Q);if(re.type==="active"){const q=await(await D()).patchContext(o,re.context);return $t(q)}const G=await s.aiAgent.patchContext(re.aiAgentId,re.channelUrl,re.context);return $t(G)},getContextObject:async()=>{const re=await(await D()).getContextObject(o);return $t(re)},requestNudgeMessage:Q=>r.requestNudgeMessage(Q)}},[k,R,m,s,o,i,r]),a.createElement(Fd,{value:{sdkUser:f,userSessionInfo:e,userSession:p,activeChannel:m,setActiveChannel:h,refreshActiveChannel:F,createConversation:r.createConversation,searchConversation:r.searchConversation,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,connectionError:u,aiAgentInfo:S,launcherInfo:A,memoryInfo:T,authenticate:k,deauthenticate:R,createAttachmentRules:O}},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"},Hd=e=>e.disabled?Bd[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&&We(t)?"file_image":t&&jt(t)?"file_video":t&&Lc(t)?"file_audio":"file_document"};let Us=0;const zd=e=>(Us+=1,`${e??"unknown"}:${Us}`),At=(e,t)=>e===void 0||t===e,Si=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},yi=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},Vd=(e,t)=>{Si(e,t)},qd=(e,t)=>{yi(e,t)},Kd=(e,t,n)=>{var o;if(!nt(e,n))return;const{hasResponseMetadata:r,...s}=Zo(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=tt(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},er=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},Yd=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=ye(),{aiAgentInfo:r}=ht(),s=l.useRef(!1),o=r==null?void 0:r.userId;pt(!!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])},Wd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(er(n,s),r.current=void 0);return}s&&s!==t&&(er(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(er(n,s),r.current=void 0)},[n])},jd=({aiAgentUserId:e,statsEnabled: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&&At(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(Si(r,g),g.tracked=!0));const p=o.current;p&&f(p)&&(p.tracked||(yi(r,p),p.tracked=!0))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&At(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(p=>Bs(p,r));return}t&&g.messages.forEach(p=>Kd(p,r,e))}},onCacheResult:(g,p,v)=>{if(!h(m)||!At(n,v))return;const S={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=S,t&&(Vd(r,S),S.tracked=!0)},onApiResult:(g,p,v)=>{if(!h(m)||!At(n,v))return;const S={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=S,t&&(qd(r,S),S.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&At(n,g.channelUrl)&&Bs(g,r)}}),[e,m,t,h,n,r])},Xd=({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.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},Zd=({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(v=>u==null?void 0:u(v),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,p=v=>g()&&At(f,v);try{const v=await c(S=>{if(!p(S.channelUrl)){u==null||u(S);return}m=S.reqId,n.messagePendingStuck.start({requestId:S.reqId,channelUrl:S.channelUrl,messageType:Gd(S),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(S)},S=>{!g()||m!==S||n.messagePendingStuck.markUploadProgress(S)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}catch(v){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}},[n])},Jd=({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=zd(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])},Qd=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ht();Yd({activeChannelUrl:t,statsTrackers:r}),Wd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=jd({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Zd({channelUrl:t,enabled:n,statsTrackers:r}),c=Jd({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},Lt=()=>ye()._aiAgentSDK.statsTrackers,em=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=Lt(),{watchBackgrounded:r}=ye()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();Ie(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},Jt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new Ce.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 tm(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=ye(),{sdkUser:u}=ht(),d=Hs(),m=Hs(),h=Nn(),[f,g]=l.useState(void 0),[p,v]=l.useState(void 0),[S,C]=l.useState(!1),A=ce(T=>{if(n&&T.isAIAgent&&!T.conversation){const I=m.next();C(!0),c.initConversationIfNeeded(T,{initialUserMessage:r}).finally(()=>{m.isCurrent(I)&&C(!1)})}});async function y(){var I,N,O,k,R,F;const T=d.next();if(!u){o.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(o.debug("useChannel.getChannel: start"),g(void 0),v(void 0),m.invalidate(),C(!1),e){(I=t.onFetchStart)==null||I.call(t,e);try{o.debug("useChannel.getChannel: get channel",e);const D=await s.groupChannel.getChannel(e);if(!d.isCurrent(T))return;A(D),g(D),(O=t.onFetchSuccess)==null||O.call(t,{channelUrl:D.url,conversationId:(N=D.conversation)==null?void 0:N.id}),D.url===((k=c.session)==null?void 0:k.activeChannel.url)&&c.session._updateActiveChannel({url:D.url,status:De(D)?"closed":"open",conversationStatus:(R=D.conversation)==null?void 0:R.status}),o.debug("useChannel.getChannel: fetched channel",D)}catch(D){if(!d.isCurrent(T))return;(F=t.onFetchError)==null||F.call(t,{channelUrl:e,error:D}),D instanceof Ce.SendbirdError&&v(D),o.error("useChannel.getChannel: error",D)}}}return l.useEffect(()=>(y(),()=>{d.invalidate()}),[s,u,e,i]),l.useEffect(()=>{n&&f&&A(f)},[n]),Jt(s,{async onReconnectSucceeded(){var N;if(!f){p&&await y();return}const T=d.current(),I=await f.refresh();!d.isCurrent(T)||f.url!==e||((N=t.onReconnectSucceeded)==null||N.call(t,f.url),A(I),g(I))}}),pt(s,{onChannelChanged:T=>{T.isGroupChannel()&&T.url===e&&(o.debug("useChannel.onChannelChanged: channel changed",T.url),g(T),h())}}),{channel:f,channelFetchError:p,getChannel:y,isInitializingConversation:S}}const nm=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)return;const s=Wt(n);switch(r){case"suggested_replies":return s.hasSuggestedReplies?r:void 0;case"steward":return s.hasSteward?r:void 0;case"system":return r;default:return}},rm=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=Wt(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},sm=()=>{const{chatSDK:e,networkStateAdapter:t}=ye(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Jt(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===Ce.ConnectionState.OPEN?"connected":o)})},[t,e]),n},om=3e4,im=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&nt(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=om-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ai=e=>{const{chatSDK:t}=ye(),[n,r]=l.useState([]);return pt(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},am=({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=nt(t,n)&&(we.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},cm=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ht(),i=sm(),c=am({channel:e,lastMessage:gr(t,[Le.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=im({shouldApply:!!(e!=null&&e.isAIAgent)&&!ct(e),isBlockedWhileAIResponding:c,lastMessage:gr(t,[Le.SendingStatus.PENDING,Le.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(De(e))return d("conversation_closed");if(ll(e))return d("handoff_pending");if(rm(e))return d("form_active");const m=nm(e);return d(m||(c||u||r?"ai_responding":""))},lm=()=>{const[e,t]=l.useState(new Set),[n,r]=l.useState(new Map),s=l.useCallback(m=>{t(h=>{if(h.has(m))return h;const f=new Set(h);return f.add(m),f})},[]),o=l.useCallback(m=>{t(h=>{if(!h.has(m))return h;const f=new Set(h);return f.delete(m),f})},[]),i=l.useCallback((m,h)=>{r(f=>{const g=new Map(f);return g.set(m,h),g})},[]),c=l.useCallback(m=>{r(h=>{if(!h.has(m))return h;const f=new Map(h);return f.delete(m),f})},[]),u=l.useCallback(m=>n.has(m),[n]),d=n.values().next().value;return{isAnimating:e.size>0,start:s,stop:o,isHolding:u,heldTypingInfo:d,holdStart:i,holdStop:c}},{Provider:um}=ve("AIAgentConversation");function dm({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=me,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,initialUserMessage:f,shouldCountNewMessages:g=()=>!1,sortComparator:p}){var $,M;const v=()=>d&&(R==null?void 0:R.markAsRead()),{_aiAgentSDK:S,chatSDK:C,logger:A,dispatcher:y}=ye(),T=Lt(),I={channelUrl:t,enabled:m},N=Cd({...I,statsTracker:T.conversationNotInteractiveTimeout}),O=bd({...I,scheduleForegroundTask:S.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),k=em(I),{channel:R,channelFetchError:F,getChannel:D,isInitializingConversation:Q}=tm(t,{shouldInitializeConversation:h,initialUserMessage:f,onFetchStart:x=>{N.onFetchStart(x),k.onGetChannelStart(x)},onFetchSuccess:x=>{N.onFetchSuccess(x),k.onGetChannelComplete(x)},onFetchError:x=>{N.onFetchError(x),k.onGetChannelError(x)},onReconnectSucceeded:O.onReconnectSucceeded}),re=R==null?void 0:R.url,G=Qd({requestedChannelUrl:t,activeChannelUrl:re,statsEnabled:m,statsTrackers:T}),H=_d(C,R,{replyType:Le.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:g,logger:A,markAsRead:v,sortComparator:p,onChannelDeleted:n,onMessagesReceived:x=>r==null?void 0:r(x),onMessagesUpdated:x=>s==null?void 0:s(x),onCollectionInitializeStart:()=>{k.onCollectionInitializeStart()},onApiResult:(x,L,P)=>{k.onCollectionApiResult(x,P),G.messageCallbacks.onApiResult(x,L,P)},onCacheResult:(x,L,P)=>{k.onCollectionCacheResult(x,P),G.messageCallbacks.onCacheResult(x,L,P)},onCollectionEvent:x=>{G.messageCallbacks.onCollectionEvent(x),bi.publish(x)},onLocalMessageDeleted:x=>{G.messageCallbacks.onLocalMessageDeleted(x)},onOutgoingMessageStatusChanged:x=>{R&&S.liveMetricManager.track({type:"outgoingMessage",channel:R,message:x})}}),q=lm(),J=cm({channel:R,messages:H.messages,isStreamAnimating:q.isAnimating,isInitializingConversation:Q});Xd({enabled:m,channelUrl:re,initialized:H.initialized,inputReady:Hd(J),renderedSignal:H.messages,statsTrackers:T}),l.useEffect(()=>{v()},[d,R]);const K=($=R==null?void 0:R.conversation)==null?void 0:$.status;l.useEffect(()=>{K&&(o==null||o(K))},[K,o]),l.useEffect(()=>{const x=async L=>{const P=typeof(L==null?void 0:L.channelUrl)=="string";R&&P&&L.channelUrl!==R.url||(A.debug("conversation.dispatcher: try to close conversation",R),R!=null&&R.conversation&&R.conversation.status===he.ConversationStatus.OPEN&&(await R.closeConversation(),i==null||i()))};return y.subscribe(Be.ConversationClose,x),()=>{y.unsubscribe(Be.ConversationClose,x)}},[y,R,A,(M=R==null?void 0:R.conversation)==null?void 0:M.status,i]);const z=ce(()=>H.loadPrevious()),Y=ce(()=>H.loadNext()),W=ce(async x=>{try{await H.deleteMessage(x)}finally{x.sendingStatus!=="succeeded"&&G.messageCallbacks.onLocalMessageDeleted(x)}}),V=ce(x=>x.isUserMessage()?G.runWithUserTurnStats(L=>G.runWithPendingStuckStats(P=>H.resendMessage(x,X=>{L(X.reqId),P(X)}),void 0)):G.runWithPendingStuckStats((L,P)=>H.resendMessage(x,L,P),void 0,{tracksUploadProgress:x.isMultipleFilesMessage()})),ee=ce(()=>H.resetNewMessages()),w=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithUserTurnStats(X=>G.runWithPendingStuckStats(se=>H.sendUserMessage(x,Z=>{X(Z.reqId),se(Z)}),u));return u==null||u(L),L}),_e=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithPendingStuckStats(X=>H.sendFileMessage(x,X),u);return u==null||u(L),L}),Re=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithPendingStuckStats((X,se)=>H.sendMultipleFilesMessage(x,X,se),u,{tracksUploadProgress:!0});return u==null||u(L),L}),Te={_statsEnabled:m,conversation:(R==null?void 0:R.conversation)??void 0,actions:{setUserMemoryState:S.setUserMemoryState},channelSource:{channel:R,error:F,refetch:()=>D(),closeConversation:async()=>{De(R)||await(R==null?void 0:R.closeConversation())}},messageSource:{messages:H.messages,newMessages:H.newMessages,initialized:H.initialized,loadPrevious:z,loadNext:Y,deleteMessage:W,resendMessage:V,resetNewMessages:ee,sendUserMessage:w,sendFileMessage:_e,sendMultipleFilesMessage:Re},state:{streamAnimation:q,input:J}};return a.createElement(um,{value:Te},e)}function mm(e,t,n){var C,A,y,T,I,N,O,k,R,F;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(D=>{var Q;return(Q=n==null?void 0:n.onListRequestComplete)==null?void 0:Q.call(n,D)}),p=l.useCallback(async D=>{f();try{await D.loadMore(),g()}catch(Q){throw g(Q),Q}},[f,g]),v=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const D=new si(e,t);D.setConversationListCollectionHandler({onChannelsAdded:()=>{u(D.channels)},onChannelsUpdated:()=>{u(D.channels)},onChannelsDeleted:()=>{u(D.channels)}}),await p(D),u(D.channels),m(D),i(null)}catch(D){m(null),i(D)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(C=t.filter)==null?void 0:C.aiAgentChannelFilter,(y=(A=t.filter)==null?void 0:A.aiAgentConversationStatusFilter)==null?void 0:y.join(),(I=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:I.join(),(N=t.filter)==null?void 0:N.deskChannelFilter,(k=(O=t.filter)==null?void 0:O.pinnedChannelUrls)==null?void 0:k.join(),(R=t.filter)==null?void 0:R.copilotConversationOnly,(F=t.filter)==null?void 0:F.copilotSupportChannelUrl,t.limit,p]),S=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(D){i(D)}},[d]);return Jt(e,{onConnected:()=>v()}),l.useEffect(()=>{v()},[v]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:S}}const Ti=e=>{var s;const{aiAgentId:t,queryParams:n}=ye(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[he.ConversationStatus.CLOSED,he.ConversationStatus.OPEN],...r,...e}},hm=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=Lt(),{watchBackgrounded:n}=ye()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();Ie(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:fm}=ve("AIAgentConversationList");function gm({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=ye(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=Ti(t),u=hm({enabled:n}),d=mm(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:f=>{u.onListRequestComplete(f)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(fm,{value:m},r)}function pm(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:_m,useContext:Em}=ve("MessageTemplateFetching");function Cm({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 p=r.current[h];if(p)return p;f||i(h,{fetching:!0});const v=d(h).catch(S=>{throw f||i(h,{error:!0}),S}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=pm(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(_m,{value:u},e)}const bm="remove_powered_by",Wr=(e,t)=>{var s,o;const{chatSDK:n}=ye(),{aiAgentInfo:r}=ht();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&&$r(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(bm)),[i])}throw new Error("Unsupported feature")},vm={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"},Sm={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}}},ym={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}}},Am={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}}},Tm={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}}},Im={text:Sm,number:ym,"single-select":Am,"multi-select":Tm},xm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ii(e){return Im[e.type]||xm}function Gs(e){return Ii(e).getValueOrDefault(e)}function Rm(e,t,n={}){const r={...vm,...n};return Ii(e).validate(e,t,r)}const Mm=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const v={};return e.fields.forEach(S=>{v[S.key]=Gs(S)}),v}),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 v={};let S=!1;e.fields.forEach(C=>{const A=Gs(C);JSON.stringify(c[C.key])!==JSON.stringify(A)&&(S=!0),v[C.key]=A}),S&&u(v)}},[d]);const m=(v,S)=>{u(C=>({...C,[v]:S})),i(C=>({...C,[v]:void 0}))},h=e.fields.map(v=>{var A,y,T;const S=c[v.key]??null,C={key:v.key,label:v.label,error:o[v.key],required:v.required};return v.type==="text"?{...C,type:"text",layout:v.layout,value:S,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...C,type:"number",layout:v.layout,value:S,...v.placeholder&&{placeholder:v.placeholder},...((y=v.rules)==null?void 0:y.max)&&{max:v.rules.max}}:v.type==="single-select"?{...C,type:"single-select",layout:v.layout,value:S,options:v.options}:v.type==="multi-select"?{...C,type:"multi-select",layout:v.layout,value:S,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{...C,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(S=>S.key===v),updateFieldValue:m,submit:async()=>{const v={};let S=!1;for(const C of e.fields){const A=c[C.key]??null,y=Rm(C,A,n);y.isValid||(v[C.key]=y.error,S=!0)}if(i(v),!S&&r){const C={};e.fields.forEach(A=>{C[A.key]=c[A.key]??null}),await r(C)}},cancel:async()=>{await(s==null?void 0:s())}}},wm=({isMessengerOpened:e,onConversationStarted:t})=>{const{_aiAgentSDK:n,aiAgentId:r,language:s,countryCode:o,context:i}=ye(),{createConversation:c,userSession:u}=ht(),[d,m]=l.useState(null),h=u==null?void 0:u.userId;l.useEffect(()=>{if(m(null),!(e||!h))return n.onNudgeMessageReceived(v=>m(S=>({seq:((S==null?void 0:S.seq)??0)+1,response:v})))},[n,e,h]);const f=()=>m(null),g=l.useRef(!1),p=async()=>{var S;if(!d||g.current)return;g.current=!0,m(null);const v=n.session;try{const C=await c({aiAgentId:r,language:s,country:o,context:i});if(n.session!==v)return;(S=n.session)==null||S._updateActiveChannel({url:C,status:"open"}),t({channelUrl:C,initialUserMessage:d.response.callbackUserMessage})}finally{g.current=!1}};return{nudgeMessage:e?null:(d==null?void 0:d.response)??null,nudgeMessageKey:(d==null?void 0:d.seq)??0,dismissNudgeMessage:f,startNudgeConversation:p}},km=e=>{const{chatSDK:t,handlers:n,logger:r}=ye(),{aiAgentInfo:s}=ht(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!nt(m,s.userId))return;const f=m.messageId;if(we.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=jo(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 pt(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},Lm=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}=ht(),n=Ai(e);if(De(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Lm(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Om=250,Nm=(e,t)=>{var i;const[n,r]=l.useState(!1),s=l.useRef(e),o=l.useRef(void 0);return e!==null?(s.current=e,n||(o.current=t==null?void 0:t.messageId,r(!0))):n&&t!==void 0&&t.sender.userId===((i=s.current)==null?void 0:i.user.userId)&&t.messageId!==o.current&&r(!1),l.useEffect(()=>{if(!n||e!==null)return;const c=setTimeout(()=>r(!1),Om);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},Dm=(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},[])},$m=(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()}}},Pm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=$m(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])},Fm=({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])},jr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:void 0,url:void 0,title:""};const r=ii(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?ct(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 et=(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))(et||{});const Um=new Set(["free_text","single_choice"]),Bm=({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 S;const g=o.csat,p=typeof g=="number",v=(S=e.follow_up)==null?void 0:S.find(C=>p?C.scores.includes(g):C.always_visible??!1);if(Um.has(v==null?void 0:v.response_type))return v},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===et.AI_AGENT_CSAT_5||t===et.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===et.AI_AGENT_CSAT_5_WITH_CRE){const p=typeof o.csat=="number",v=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(p&&v)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"}}},Hm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!et[n.type],o=!r&&typeof e!="number"&&ai(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}},tr=5,Ut=250,Ri=50,Gm=1500,nr=e=>Math.max(0,e-Ri),_n=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,zm=(e,t)=>{const n=e&&t.length<=Ri,r=l.useRef(n&&t.length>0?t:null),[s,o]=l.useState(()=>!n),i=r.current!==null&&t!==r.current,c=!n||i;return l.useEffect(()=>{if(s)return;const u=()=>{r.current=null,o(!0)};if(c){u();return}if(r.current===null&&t.length>0&&(r.current=t),r.current===null)return;const d=setTimeout(u,Gm);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},Vm=e=>e<1e3?{speed:tr*.5,chunkSize:2}:e<2e3?{speed:tr*.8,chunkSize:2}:{speed:tr*.6,chunkSize:3},En=(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(En(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Mi=(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=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},qm=({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(A=>{var y;(y=r.current)==null||y.call(r,A)},[]),m=l.useCallback(A=>{const y=e.initialEnabled&&(e.enabled||A<e.textLength),T=y&&e.deferImages,I=y&&e.deferLinks;return!T&&!I?A:Mi(e.text.slice(0,A),{hideImages:T,hideLinks:I}).length},[e]),h=l.useCallback((A,y,T=!1)=>{r.current&&(A<=c.lastLength||!T&&y-c.lastReportedAt<Ut||(c.lastLength=A,c.lastReportedAt=y,d(A)))},[d,c]),f=l.useCallback((A,y,T=!1)=>{if(!r.current)return;const I=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&y-I<Ut||(c.lastCheckedAt=y,h(m(A),y,!0))},[m,h,c]),g=l.useCallback((A,y,T=!1)=>{s.current&&(A<=i.lastLength||!T&&y-i.lastReportedAt<Ut||(i.lastLength=A,i.lastReportedAt=y,s.current(A)))},[i]),p=l.useCallback((A,y,T)=>{const I=A>=y,N=T-i.lastReportedAt>=Ut;if(!I&&!N)return;const O=m(A);g(O,T,I)},[m,i,g]),v=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),S=l.useCallback(A=>{r.current&&(o.current!==null&&A<=o.current||(o.current=A,d(A)))},[d]),C=l.useCallback(({displayedLength:A,streamTextLength:y})=>{const T=u.current;if(u.current={displayedLength:A,streamTextLength:y},!e.initialEnabled||!T||A>T.displayedLength||y<=T.streamTextLength)return;const I=_n();h(y,I,!0),g(y,I,!0)},[u,g,h,e]);return{resetProgress:v,reportVisibleTextProgress:f,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:S,reportMarkdownRevealProgress:C}},Km=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onAnimationHoldChange:u,onVisibleTextProgress:d,onRenderedTextProgress:m}=e,h=zm(n,t),f=s.includes("image"),g=s.includes("link"),[p,v]=l.useState(()=>n?h?0:nr(t.length):t.length),S=l.useRef(null),C=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,A=l.useRef({startCalled:!1,completeCalled:!1}).current,y=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:f,deferLinks:g,snapOnDisable:r,isGatingStreamingStart:h}).current,T=ce(()=>o==null?void 0:o()),I=ce(()=>i==null?void 0:i()),N=ce(()=>c==null?void 0:c()),O=ce(K=>u==null?void 0:u(K)),{resetProgress:k,reportVisibleTextProgress:R,reportRenderedTextProgress:F,reportNonStreamingVisibleTextProgress:D,reportMarkdownRevealProgress:Q}=qm({trackedRef:y,onVisibleTextProgress:d,onRenderedTextProgress:m}),re=n,G=p<t.length,H=y.initialEnabled&&(re||G);l.useLayoutEffect(()=>{y.textLength=t.length,y.enabled=n,y.text=t,y.deferImages=f,y.deferLinks=g,y.snapOnDisable=r,y.isGatingStreamingStart=h}),l.useLayoutEffect(()=>{if(y.initialEnabled){if(A.startCalled||(A.startCalled=!0,T()),!y.enabled&&y.snapOnDisable){v(t.length);const K=_n();R(t.length,K,!0),F(t.length,t.length,K);return}v(K=>t.length<K?t.length:K)}},[T,F,R,t]),l.useEffect(()=>{if(!y.initialEnabled)return;let K=h?0:nr(t.length),z=h;C.lastUpdate=0,C.startTime=0,C.lastProgressCall=0,k();const Y=W=>{C.lastUpdate===0&&(C.lastUpdate=W,C.startTime=W,C.lastProgressCall=W,K>0&&R(K,W,!0));const V=y.textLength;z&&!y.isGatingStreamingStart&&(K=nr(V),v(K),K>0&&R(K,W,!0),C.lastUpdate=W,z=!1),!y.enabled&&y.snapOnDisable&&K<V&&(K=V,v(K),R(K,W,!0),F(K,V,W));const ee=W-C.lastUpdate,w=W-C.startTime,{speed:_e,chunkSize:Re}=Vm(w),Te=_e*Re;!y.isGatingStreamingStart&&ee>=Te&&K<V&&(K=Math.min(K+Re,V),v(K),R(K,W,K>=V),F(K,V,W),C.lastUpdate=W),W-C.lastProgressCall>=Ut&&(C.lastProgressCall=W,I()),(K<V||y.enabled)&&(S.current=requestAnimationFrame(Y))};return S.current=requestAnimationFrame(Y),()=>{S.current&&cancelAnimationFrame(S.current),A.startCalled&&!A.completeCalled&&(A.completeCalled=!0,N())}},[N,I,F,R,k]),l.useEffect(()=>{y.initialEnabled&&(n||t.length>0)||(D(t.length),F(t.length,t.length,_n()))},[n,m,d,D,F,t.length,y]),l.useEffect(()=>{const K=y.initialEnabled&&A.startCalled,z=!n,Y=p>=t.length;K&&z&&Y&&!A.completeCalled&&(A.completeCalled=!0,N())},[n,p,N,t.length]);const q=l.useMemo(()=>{let K=t;y.initialEnabled&&(K=h?"":t.slice(0,p));const z=H&&f,Y=H&&g;return!z&&!Y?K:Mi(K,{hideImages:z,hideLinks:Y})},[t,p,f,g,H,h]);l.useEffect(()=>{!y.initialEnabled||H||R(p,_n(),!0)},[p,H,R]),l.useEffect(()=>{Q({displayedLength:p,streamTextLength:q.length})},[p,Q,q.length]);const J=q.length===0&&H;return l.useLayoutEffect(()=>(O(J),()=>O(!1)),[O,J]),{streamText:q,isAnimating:H,isHolding:J}},qs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Ym=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Wm=(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}},jm=()=>{const{chatSDK:e}=ye(),[t,n]=l.useState(qs),r=()=>n(qs);return Jt(e,{onConnectionDelayed:s=>{s>0?n(Ym(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Wm(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")}`},Zm=(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)}},Jm=({enabled:e=!0}={})=>{const t=Lt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=we.isStreaming(n),c=Wt(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!Oc(n)&&!we.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,p=!1;const v={};return(f||m)&&(v.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!p&&(p=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(v.onRenderedTextProgress=S=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:S})}),u&&(v.onMessageTemplateError=S=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:S})}),d&&(v.onFormRenderError=S=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:S})}),v},[e,t])},Qm=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},rr=5e3,eh=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=Lt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-rr: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(performance.now()-u.current<rr){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=performance.now()-rr):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},th=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=Lt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},nh=(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===Ce.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]),Jt(e,{onConnected:c,onReconnectSucceeded:c}),s},Rt=e=>e.replace(/\s+/g," ").trim(),rh="Code block",wi=e=>`A11Y_INLINE_CODE_${e}`,ki=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}},Li=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}},sh=e=>{const{blockquotePrefix:t,content:n}=ki(e),{content:r}=Li(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}},oh=(e,t)=>{const{blockquotePrefix:n,content:r}=ki(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=Li(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)},ih=(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},ah=(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},ch=(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},lh=e=>{let t=0,n="";for(;t<e.length;){const r=ih(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=ah(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=ch(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Oi=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},uh=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Oi(n,r,i)?t:`${n}${r}`}),dh=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),mh=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),hh=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 Oi(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},fh=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),gh=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},ph=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
+ `)},_h=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Eh=(e,t)=>{const n=e.split(`
4
+ `),r=[];let s=0;for(;s<n.length;){const o=n[s],i=sh(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(oh(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},Ch=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+=wi(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Ni=(e,{codeBlockPlaceholder:t=rh}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
7
+ `);if(!n)return;const r=[];let s=n;s=Eh(s,t),s=gh(s);const o=Ch(s);s=o.text,r.push(...o.inlineCodes),s=lh(s),s=uh(s),s=dh(s),s=mh(s),s=hh(s),s=ph(s),s=_h(s),s=fh(s);for(let c=0;c<r.length;c++)s=s.replaceAll(wi(c),r[c]);return Rt(s)||void 0},bh=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return We(r)?t.image:jt(r)?t.video:ti({name:n,mimeType:r})?t.pdf(n):t.document(n)},In=e=>(e==null?void 0:e.trim())||"",vh=e=>(e?Rt(e):void 0)||void 0,Ws=30,Sh=e=>e.length>Ws?`${e.slice(0,Ws)}…`:e,yh=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=Sh(Rt(n)),c=[t,i].filter(Boolean).join(", ");return o(Rt(e),Rt(c),r,s)},Di=e=>({text:In(e),format:"plain"}),Ah=e=>({text:In(e),format:"markdown"}),sr=({markdownText:e,plainText:t,comparisonText:n})=>{const r=In(e);return r&&r!==In(n)?Ah(r):Di(t)},zt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Ni(t,{codeBlockPlaceholder:s}):vh(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},$i=(e,t)=>Ni(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Th=(...e)=>Rt(e.filter(Boolean).join(", "))||void 0,js=(e,t,n,r)=>{if(!t||t===n)return e;const s=$i(t,r);return s?Th(e,s):e},Ih=(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=bh({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 $i(n,t.codeBlockPlaceholder)},xh=(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=(k,R,F)=>({text:k,ignoreSuppression:R,queueOrder:f++,dedupeKey:F}),p=()=>{const k=c[0]??null,R=i;return k&&R?R.queueOrder<k.queueOrder?(i=null,R):c.shift()??null:k?c.shift()??null:R!==null?(i=null,R):null},v=()=>{for(;;){const k=p();if(!k)return null;if(!(!k.ignoreSuppression&&(r!=null&&r())))return k}},S=k=>{u=k.text,d=k.dedupeKey??null,h=!0,e(k.text),m=setTimeout(()=>{m=null,h=!1;const R=v();R&&S(R)},n)},C=k=>{u=k.text,d=k.dedupeKey??null,e(k.text)},A=(k,R,F,D)=>R!=null&&D!=null?R===D:R==null&&D==null?k!=null&&k===F:!1,y=(k,R,F)=>{if(!k||!R&&(r!=null&&r()))return;const D=F==null?void 0:F.dedupeKey;if(!(h&&A(k,D,u,d)))if(h){if(((F==null?void 0:F.mode)??"latestOnly")==="ordered"){const re=c[c.length-1];if(re&&A(k,D,re.text,re.dedupeKey))return;c.push(g(k,R,D)),c.length>o&&c.shift();return}i=g(k,R,D)}else i=null,S(g(k,R,D))};return{announce:(k,R)=>{y(k,!1,R)},announceIgnoringSuppression:(k,R)=>{y(k,!0,R)},flush:()=>{const k=[];let R=p();for(;R!==null;)k.push(R),R=p();if(m!==null&&(clearTimeout(m),m=null),h=!1,k.length!==0)for(const F of k)C(F)},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"}},Mh=(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(". "),wh=(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}},kh=(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}},Lh=(e,t)=>!t||!tt(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Oh=(e,t)=>Me.isAdmin(e)?Me.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,Dh=e=>e===Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED,$h=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Ph=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Fh=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Uh=({intent:e,strings:t})=>({label:Ph(e,t),hint:Fh(e,t)}),Bh="1.38.0",He="sb-agent",Se={ENTRY:`${He}-entry`,MODAL_ROOT:`${He}-modal-root`,WINDOW:`${He}-window`,LAUNCHER:`${He}-launcher`,WINDOW_TITLE:`${He}-window-title`},Pi="data-sb-initial-focus",Fi="true",Hh=`[${Pi}="${Fi}"]`,Ui={[Pi]:Fi},Xr="data-sb-focus-trap-sentinel",Gh="true",Bi="data-sb-initial-focus-header",Hi="true",zh=`[${Bi}="${Hi}"]`,Gi={[Bi]:Hi},zi="data-sb-message-input",Vi="true",Vh=`textarea[${zi}="${Vi}"]:not(:disabled)`,qh={[zi]:Vi},qi=1e3,dn=2147483647,_t={MODAL:dn-1,TOOLTIP:dn-2,WINDOW:dn-3,LAUNCHER:dn-4},Ki=36,Kh=100,Yh=Bh,Zr="noopener noreferrer nofollow",Wh=()=>typeof document>"u"||document.visibilityState==="visible",vr=()=>typeof document<"u"&&document.visibilityState==="hidden",Xs=()=>vr()?"backgrounded":"foregrounded",jh={getState:Xs,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(Xs());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function Xh(){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 mn={};function Zh(){return{get:e=>{try{return localStorage.getItem(e)}catch{return mn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{mn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete mn[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(mn).filter(t=>t.startsWith(e))}}}}const Jh={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_dismiss_nudge_message:"Dismiss message",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}`}},Sr={language:"en",strings:Jh,dateLocale:gc.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_DISMISS_NUDGE_MESSAGE:e.conversation.a11y_dismiss_nudge_message,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}),Wi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Qt},Qt="en",ji=new Set([Qt,"ko","es","pt","fr","hi","it","de","tr","ja"]),Qh='@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:ef,useContext:Jr}=ve("AgentUIElementResolver"),tf=({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(ef,{value:s},r)};function mt(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:nf,useContext:Qr}=ve("EscapeDismissStack"),Js=e=>{e.stopPropagation(),e.stopImmediatePropagation()},rf=({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??mt(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(nf,{value:c},n)},Xi=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},sf=(e,t)=>{const{register:n}=Qr();Xi(e,t,n)},of=(e,t)=>{const{registerShellDismissHandler:n}=Qr();Xi(e,t,n)},Zi=()=>{const{subscribe:e,getOpenCount:t}=Qr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},af=(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(Sr.strings),cf={...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"},xn={language:Sr.language,dateLocale:Sr.dateLocale,stringSet:cf},lf=Object.freeze(Object.defineProperty({__proto__:null,default:xn},Symbol.toStringTag,{value:"Module"})),yr=new Map([[Qt,xn]]);async function uf(e){const t=yr.get(e);if(t)return t;try{if(ji.has(e)){const{default:n}=await af(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/CIjjIGUs.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>lf),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/B9JzuCyz.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/BQ8EaWkc.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/Cr2LxvlJ.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/C2Oi-KA4.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/LFX2h7v2.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/CKr98WbE.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/C3VEshQr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/C116E0pr.cjs"))}),`./languages/${e}.ts`,3);return yr.set(e,n),n}return xn}catch{return xn}}const{Provider:df,useContext:ie}=ve("Localization"),mf=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(yr.get(Qt));return l.useEffect(()=>{const c=t??Wi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),uf(c).then(i))},[e,t,n]),a.createElement(df,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>ut.format(c,u,{locale:o.dateLocale,...d})}},s)},Rn="data-sb-agent-theme",eo=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Rn}='${e}'] & { ${r} }`},ne={light:eo("light"),dark:eo("dark")},hf=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,9 +53,9 @@
53
53
  --sendbird-overlay-dark: ${t.overlay.dark};
54
54
  --sendbird-overlay-light: ${t.overlay.light};
55
55
  }
56
- `}),Xh=H.css`[${yn}='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);}[${yn}='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);}`,_={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 Ye=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Zh=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"})),Jh=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"})),Qh=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"})),ef=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"})),tf=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"})),nf=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),rf={close:Zh,send:tf,menu:ef,expand:Qh,collapse:Jh,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")))},sf=e=>({size:t=24,color:n=_.color.primary.main,flipInRtl:r=!1})=>a.createElement(af,{$size:t,$color:n,$rtlFlip:r},a.createElement(Ht,{errorFallback:a.createElement(cf,null)},a.createElement(e,null))),Ki=Object.fromEntries(Object.entries(rf).map(([e,t])=>[e,sf(t)])),of=H.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,af=E.default.span.attrs({"aria-hidden":"true"})`
57
- width: ${({$size:e})=>Ye(e)};
58
- height: ${({$size:e})=>Ye(e)};
56
+ `}),ff=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 Kt 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 Je=e=>{const t=e;return typeof t=="number"?`${t}px`:t},gf=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"})),pf=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"})),_f=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"})),Ef=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"})),Cf=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"})),bf=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),vf={close:gf,send:Cf,menu:Ef,expand:_f,collapse:pf,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")))},Sf=e=>({size:t=24,color:n=E.color.primary.main,flipInRtl:r=!1})=>a.createElement(Af,{$size:t,$color:n,$rtlFlip:r},a.createElement(Kt,{errorFallback:a.createElement(Tf,null)},a.createElement(e,null))),Ji=Object.fromEntries(Object.entries(vf).map(([e,t])=>[e,Sf(t)])),yf=U.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Af=_.default.span.attrs({"aria-hidden":"true"})`
57
+ width: ${({$size:e})=>Je(e)};
58
+ height: ${({$size:e})=>Je(e)};
59
59
  display: inline-block;
60
60
 
61
61
  svg {
@@ -74,25 +74,25 @@
74
74
  stroke-linejoin: round;
75
75
  }
76
76
 
77
- ${({$rtlFlip:e})=>e&&of};
78
- `,cf=()=>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:lf,useContext:uf}=ve("MessengerIcon",{icons:Ki}),df=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:Ou(Ki,e)}),[e]);return a.createElement(lf,{value:n},t)},{Provider:mf,useContext:Yi}=ve("MessengerTheme");function hf(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(vd,{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(ff,{...e}))}function ff({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Fr();return l.useLayoutEffect(()=>{e.setAttribute(yn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(H.ThemeProvider,{theme:n},a.createElement(mf,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const gf=(e,t)=>{l.useEffect(()=>{const n=ct(t)instanceof ShadowRoot,r=ct(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])},pf=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=ct(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])},_f=80,Ef=()=>{const{stringSet:e}=ae(),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},Wi=ve("AriaLiveRegion",{announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,flush:he,setSuppressionState:he}),Cf=Wi.Provider,qr=Wi.useContext,bf={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},vf=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(he),s=Ef(),[o]=l.useState(()=>uh(g=>{r.current(g)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=g=>{const C=t.current;C&&(C.textContent="",requestAnimationFrame(()=>{C.textContent=g}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(g=>{const C=mh(g,s.current);i(C)},[i]),d=l.useCallback((g,C)=>{const v=hh(g,s.current),p=(C==null?void 0:C.mode)??dh(g.event);i(v,{mode:p,dedupeKey:C==null?void 0:C.dedupeKey})},[i]),m=l.useCallback((g,C)=>{const v=fh(g,s.current);o.announceIgnoringSuppression(v),C&&setTimeout(()=>{C.focus()},_f)},[o]),h=l.useCallback((g,C)=>{if(C){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(Cf,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:bf}))},ji=ve("ConversationAnnouncements",{announcementsEnabled:!0,announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,setIsSuppressed:he,setStatusPauseState:he,flush:he}),Sf=ji.Provider,nt=ji.useContext,yf=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=qr(),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(R=>{i(),s(R.params,R.options)})},[s,t,f,i]),C=l.useCallback((T,R)=>{if(R){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),v=l.useCallback(T=>{t&&n(T)},[n,t]),p=l.useCallback(T=>{t&&r(T)},[r,t]),b=l.useCallback((T,R)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:R});return}s(T,R)}},[s,t]),y=l.useCallback((T,R)=>{t&&o(T,R)},[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:v,announceScreenEntry:p,announceStatus:b,announceError:y,setIsSuppressed:h,setStatusPauseState:C,flush:i}),[t,i,v,y,p,b,h,C]);return a.createElement(Sf,{value:A},e)},kn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),Xi=`${kn}, [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(Hr)&&Tt(n))return n;return null},Zi=e=>{let t=null,n=null;for(const r of e.querySelectorAll(kn))r.hasAttribute(Hr)||Tt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Ji=(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,Af=(e,t,n)=>Ji(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),Kr=e=>Gt(e,Ah),Qi=e=>Kr(e)??Gt(e,kn),Tf=e=>{const t=Kr(e);if(t)return t;const n=e.querySelector(Ih);return(n?Gt(n,Xi):null)??Gt(e,kn)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(Rf,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),Zs=new WeakMap,If=(e,t)=>{let n=Zs.get(t);n||(n=new Map,Zs.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=H.css`font-size:${Ye(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
77
+ ${({$rtlFlip:e})=>e&&yf};
78
+ `,Tf=()=>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:If,useContext:xf}=ve("MessengerIcon",{icons:Ji}),Rf=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:Yu(Ji,e)}),[e]);return a.createElement(If,{value:n},t)},{Provider:Mf,useContext:Qi}=ve("MessengerTheme");function wf(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(Dd,{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(kf,{...e}))}function kf({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Yr();return l.useLayoutEffect(()=>{e.setAttribute(Rn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(U.ThemeProvider,{theme:n},a.createElement(Mf,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Lf=(e,t)=>{l.useEffect(()=>{const n=mt(t)instanceof ShadowRoot,r=mt(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])},Of=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=mt(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])},Nf=80,Df=()=>{const{stringSet:e}=ie(),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},ea=ve("AriaLiveRegion",{announce:me,announceScreenEntry:me,announceStatus:me,announceError:me,flush:me,setSuppressionState:me}),$f=ea.Provider,es=ea.useContext,Pf={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Ff=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(me),s=Df(),[o]=l.useState(()=>xh(g=>{r.current(g)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=g=>{const p=t.current;p&&(p.textContent="",requestAnimationFrame(()=>{p.textContent=g}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(g=>{const p=Mh(g,s.current);i(p)},[i]),d=l.useCallback((g,p)=>{const v=wh(g,s.current),S=(p==null?void 0:p.mode)??Rh(g.event);i(v,{mode:S,dedupeKey:p==null?void 0:p.dedupeKey})},[i]),m=l.useCallback((g,p)=>{const v=kh(g,s.current);o.announceIgnoringSuppression(v),p&&setTimeout(()=>{p.focus()},Nf)},[o]),h=l.useCallback((g,p)=>{if(p){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($f,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:Pf}))},ta=ve("ConversationAnnouncements",{announcementsEnabled:!0,announce:me,announceScreenEntry:me,announceStatus:me,announceError:me,setIsSuppressed:me,setStatusPauseState:me,flush:me}),Uf=ta.Provider,lt=ta.useContext,Bf=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=es(),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(I=>{i(),s(I.params,I.options)})},[s,t,f,i]),p=l.useCallback((T,I)=>{if(I){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),v=l.useCallback(T=>{t&&n(T)},[n,t]),S=l.useCallback(T=>{t&&r(T)},[r,t]),C=l.useCallback((T,I)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:I});return}s(T,I)}},[s,t]),A=l.useCallback((T,I)=>{t&&o(T,I)},[o,t]);l.useLayoutEffect(()=>(t||(f(),c(m.current,!1)),()=>{f(),c(m.current,!1)}),[t,f,c]);const y=l.useMemo(()=>({announcementsEnabled:t,announce:v,announceScreenEntry:S,announceStatus:C,announceError:A,setIsSuppressed:h,setStatusPauseState:p,flush:i}),[t,i,v,A,S,C,h,p]);return a.createElement(Uf,{value:y},e)},Dn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),na=`${Dn}, [tabindex="-1"]`,Mt=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},Yt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(Xr)&&Mt(n))return n;return null},ra=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Dn))r.hasAttribute(Xr)||Mt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},sa=(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,Hf=(e,t,n)=>sa(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),ts=e=>Yt(e,Hh),oa=e=>ts(e)??Yt(e,Dn),Gf=e=>{const t=ts(e);if(t)return t;const n=e.querySelector(zh);return(n?Yt(n,na):null)??Yt(e,Dn)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(qf,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),to=new WeakMap,zf=(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:${Je(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},xf=e=>e?H.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Rf=E.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>If(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>xf(e)}`;async function Yr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const gr='[role="dialog"][aria-modal="true"]',Mf=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(gr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(gr);return r&&r!==e&&n.add(r),n},wf=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(gr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Tt(n)),kf=e=>{const t=Qi(e)??e;t===e&&ea(e),t.focus()},ea=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Lf=(e,t)=>{const n=Zi(e);if(!n){ea(e),e.focus();return}n[t].focus()},Js=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Hr,Th),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Lf(e,t)),n},Of=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(Zi(t)||(e.preventDefault(),t.focus())))},Ln=(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=Mf(i,u);return()=>{u&&Ie(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!Ji(c,m)&&m.matches(Xi)&&Tt(m)||wf(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,kf(o)};if(n)return Ie(c),()=>{i=!0};const u=setTimeout(()=>Ie(c),Ui);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=Js(o,"last"),c=Js(o,"first"),u=d=>Of(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])},lt=({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}=zr();return Ln(n,d),Hh(n,o?r:he),n?oc.createPortal(a.createElement(Nf,{onClick:o?r:void 0,style:e},a.createElement(Df,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Nf=E.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${_.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${ft.MODAL};`,Df=E.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:${ft.MODAL};`,$f=({id:e,children:t})=>a.createElement(Pf,{id:e},t),Pf=E.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;`,Qs=(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?{}:Oi}:n},Ff=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement($f,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},eo=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ve(t??"")?r.A11Y_FILE_IMAGE(e):zt(t??"")?r.A11Y_FILE_VIDEO(e):Xo({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},Uf=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},$t=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Uf(e)}),Bf=({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()},to=(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:Bf({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},oe=()=>{const{stringSet:e}=ae(),t=Ff(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ve(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":eo(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=Sh({intent:Ch({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:Qs(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,...Rh},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?eo({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 b;const C=c.trim()||c,v=e.A11Y_HINT_SELECT_RATING,p=t(v,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...to(u,d,m,h,f,y=>g(y+1)),...p.props,"aria-label":((b=e.A11Y_CSAT_RATING_LABEL)==null?void 0:b.call(e,i,C))??`${i} / ${h} — ${C}`},descriptionNode:p.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:{...to(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:Qs(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,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const f=ih({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":f},descriptionNode:null};const g=e.A11Y_HINT_OPEN_CONVERSATION,C=t(g,"cli");return{props:{...$t({onActivate:h}),...C.props,"aria-label":f},descriptionNode:C.node}}}}},Hf=({title:e,description:t,highlightedText:n})=>{const r=Nm(t,n);return a.createElement(zf,null,a.createElement(Vf,null,a.createElement(B,{as:"div",variant:"h1",color:_.themedColor.textHighEmphasis},e),t&&a.createElement(qf,null,a.createElement(B,{as:"div",variant:"body3",color:_.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(Kf,null,r.highlightedText):null,r.afterText))))},Gf=()=>{const{components:e}=On.useContext(),{stringSet:t}=ae(),{messenger:n}=oe(),r=Lm(),s=r.showDescription?Om(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(lt,{portalContainerId:Se.WINDOW,visible:r.visible,onClose:he,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},On=qe({template:Gf,components:{Dialog:Hf}}),zf=E.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Vf=E.default.div`display:flex;flex-direction:column;`,qf=E.default.div`margin-top:16px;`,Kf=E.default.strong`font-weight:700;`,Yf=({url:e})=>Yr(e),{Provider:Wf,Consumer:ta,useContext:me}=ve("Messenger");function jf({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}=zr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Gh(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const p=g.current&&!m.opened;if(g.current=m.opened,!p)return;const b=ct(o.rootElement),y=h(Se.WINDOW);let A=!1;return Ie(()=>{var T;A||Af(b,b.activeElement,y)&&((T=h(Se.LAUNCHER))==null||T.focus())}),()=>{A=!0}},[m.opened,o.rootElement,h]);const{Template:C}=On.useContext(),v=l.useMemo(()=>{var p;return{...o.handlers,onClickLink:((p=o.handlers)==null?void 0:p.onClickLink)??Yf}},[o.handlers]);return a.createElement(Hu,{...o},p=>a.createElement(Wf,{value:{...o,...p,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(C,null),e))}const na=/iPad|iPhone|iPod/.test(navigator.userAgent),Xf=/Android/.test(navigator.userAgent),jt=e=>na||Xf;let Lt=null,Zn=null;const Zf=(e,t=5e3)=>{Lt&&(clearInterval(Lt),clearTimeout(Zn));const n=document.title;Lt=setInterval(()=>{document.title=document.title===e?n:e},750),Zn=setTimeout(()=>{clearInterval(Lt),Lt=null,Zn=null,document.title=n},t)},ra=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Re=H.css`&:focus-visible{outline:2px solid ${_.themedColor.primary};outline-offset:2px;}`,no=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Nn=({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??no(t)??no(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,C=()=>{c(),Ie(()=>o==null?void 0:o())},v=()=>{c(),Ie(()=>i==null?void 0:i())};return a.createElement(lt,{portalContainerId:Se.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(Jf,null,a.createElement(Qf,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:_.themedColor.textHighEmphasis},t)),n&&a.createElement(eg,{id:m},a.createElement(B,{variant:"body3",color:_.themedColor.textMidEmphasis},n))),a.createElement(tg,null,s&&a.createElement(ro,{onClick:v},a.createElement(B,{variant:"button",color:_.themedColor.textHighEmphasis},s)),a.createElement(ro,{onClick:C},a.createElement(B,{variant:"button",color:_.themedColor.primary},r)))))},Jf=E.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};`,Qf=E.default.div`margin-bottom:16px;`,eg=E.default.div`margin-top:16px;`,tg=E.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ro=E.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Re}`,{Provider:ng,useContext:Ne}=ve("MessengerSession"),rg=l.forwardRef(function({children:e,...t},n){return a.createElement(Td,{ref:n,...t},r=>a.createElement(sg,{...r},e))}),sg=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=me(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:C,launcherInfo:v}=t,[p,b]=l.useState(!1),y=l.useRef(null);mt(n,{async onUserJoined(T,R){var k,x,D,F;T.conversation&&T.conversation.type===fe.ConversationType.PROACTIVE&&R.userId===((k=n.currentUser)==null?void 0:k.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(D=m.session)==null||D._updateActiveChannel({url:T.url,status:"open",conversationStatus:(x=T.conversation)==null?void 0:x.status}),c.setOpened(!0),og({sound:document.hidden||!c.opened}),(F=y.current)==null||F.call(y,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!jt()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var R;r.error("messengerSession: failed to initialize",T),(R=u==null?void 0:u.onInitializeFailed)==null||R.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>b(!0);return d.subscribe(ze.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(ze.AnonymousSessionTokenExpired,T)},[d]);const A=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!C||!v?null:a.createElement(ng,{value:{...t,userSession:g,aiAgentInfo:{...C,...i==null?void 0:i.bot},launcherInfo:{...v,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>y.current=T}},e,a.createElement(Nn,{visible:p,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:he}))};function og({sound:e}){Zf("🔔You have received a new message"),e&&ra()}const An=`@${Ue}-focused-channel`,sa=`${Date.now()}-${Math.random().toString(36).slice(2)}`,ig=()=>{try{const e=localStorage.getItem(An);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},so=e=>{try{localStorage.setItem(An,JSON.stringify({channelUrl:e,tabId:sa}))}catch{}},oo=()=>{try{const e=localStorage.getItem(An);if(!e)return;JSON.parse(e).tabId===sa&&localStorage.removeItem(An)}catch{}},ag=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>so(e),r=()=>oo();return document.hasFocus()&&so(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),oo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||ig()===e}),cg=e=>{const{config:t,chatSDK:n}=me(),{sdkUser:r}=Ne(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=ag(e,s);mt(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Xe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&ra()}})};function lg(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 ug(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await lg(e.file);return new De.MessageMetaArray({key:Yo,value:[t,n]})}}const dg=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=me(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await ug(s),i={...s,metaArrays:o?[o]:void 0},c=mg(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===De.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===De.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},mg=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,Jn=St-40,{Provider:hg,useContext:oa}=ve("ConversationScroll"),io={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Qn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),ao=e=>Array.from(e.querySelectorAll(`#${Ue}-message-item`));function fg({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(io),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[C,v]=l.useState(!1),[p,b]=l.useState(!0),y=$=>{const I=Qn($);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()},[]),R=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),N=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},k=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(I=>{c.current.shouldUpdate=!1;const{contentHeight:w,contentSnapshotHeight:O,shouldRecalc:G}=c.current,J=$.clientHeight;if(O>w)return I;const se=x($,{messageType:"outgoing"});let Q=0;if(se){const pe=se.message.offsetTop-Jn+J;Q=Math.max(0,pe-w)}else{const pe=w-O,Ke=J-Jn;Q=Math.max(0,pe-Ke)}return I===0||Q!==I||G?(c.current.shouldRecalc=!1,Q):I})},x=l.useCallback(($,I)=>{const{messageType:w="all"}=I??{},O=ao($);let G=O;w==="outgoing"&&(G=O.filter(ut=>ut.getAttribute("data-layout-id")==="outgoingmessage"));const J=G[G.length-1];if(!J)return null;const se=$.getBoundingClientRect(),Q=J.getBoundingClientRect(),pe=$.scrollTop+(Q.top-se.top),Ke=pe+J.offsetHeight;return{message:J,scrollTop:pe,lastMessageBottom:Ke}},[]),D=l.useCallback(()=>{const $=r.current;if(!$||R!=="fixed")return;const I=x($);c.current.contentHeight=(I==null?void 0:I.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&N(),i.current.programmatic?o.current.distanceFromBottom=Qn($):y($),k()},[R,x]),F=l.useCallback(()=>{T(),A(),c.current=io,d(0),h(0),b(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),U=l.useCallback(($=!0)=>{const I=o.current.distanceFromBottom>St;if(i.current.awayByUser=!1,h(0),!I){Ie(()=>{const w=r.current;w&&!i.current.awayByUser&&w.scrollTo({top:w.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,b(!1),A()),Ie(()=>{const w=r.current;if(!w){i.current.programmatic=!1,b(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,y(w),b(!0);return}const O=()=>{if(r.current!==w){i.current.programmatic=!1,r.current&&y(r.current),b(!0);return}i.current.programmatic=!1,y(w),b(!0)};if($&&!i.current.reconcileTimer){const G=setTimeout(O,500);i.current.reconcileTimer=G,w.addEventListener("scrollend",()=>{clearTimeout(G),i.current.reconcileTimer=null,O()},{once:!0})}w.scrollTo({top:w.scrollHeight,behavior:$?"smooth":"auto"}),$||O()})},[]),q=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){y($);return}U(!1)}},[U]),K=l.useCallback(()=>{const $=r.current,I=s.current;if(!$||!I.resize)return;const w=new Set(ao($));for(const O of I.resizeTargets)w.has(O)||(I.resize.unobserve(O),I.resizeTargets.delete(O));for(const O of w)I.resizeTargets.has(O)||(I.resize.observe(O),I.resizeTargets.add(O))},[]),L=l.useCallback($=>{T();const I=s.current;typeof ResizeObserver<"u"&&(I.resize=new ResizeObserver(q),K());const w=new MutationObserver(()=>{K(),q()});I.mutation=w,w.observe($,{childList:!0})},[T,q,K]),V=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,R!=="fixed"){L($);return}F(),c.current.viewport=$.clientHeight;const I=new MutationObserver(()=>{D()});s.current.mutation=I,I.observe($,{childList:!0,subtree:!0})},[T,R,D,F,L]),P=l.useCallback(()=>{const $=r.current;if(!$)return;const I=x($,{messageType:"outgoing"});I&&($.scrollTo({top:I.message.offsetTop-Jn,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[x]),Y=($,I,w)=>{const O=Qn($);if(w&&O>St){i.current.programmatic=!1,i.current.awayByUser=!0,A(),y($),b(!0),o.current.prevScrollTop=I;return}o.current.distanceFromBottom=O},ge=($,I,w)=>{const G=y($)<=St;I&&!G&&(i.current.awayByUser=!0,A()),w&&G&&(i.current.awayByUser=!1)},j=$=>{const{scrollTop:I}=$.currentTarget,w=o.current.prevScrollTop;i.current.programmatic?Y($.currentTarget,I,I<w):ge($.currentTarget,I<w,I>w),o.current.prevScrollTop=I},W=l.useCallback(()=>{R==="fixed"&&(v(!0),N())},[R]),X=l.useCallback(()=>{R==="fixed"?setTimeout(()=>P(),300):U()},[R,P]),M=l.useCallback($=>{i.current.streaming=$,R==="fixed"?N():i.current.awayByUser||U()},[R,U]),Z=l.useCallback($=>{g($),$&&(d(0),R==="fixed"&&T())},[T,R]),ie=l.useCallback($=>{R==="auto"&&$&&!i.current.awayByUser&&U()},[R,U]),$e=!(m<=St)&&!C,Me=l.useCallback(()=>o.current.distanceFromBottom>St,[]);return a.createElement(hg,{value:{ref:V,state:{bottomSpace:u,isAwayFromBottom:$e,isScrollPositionReconciled:p,shouldCountNewMessages:Me},props:{onScroll:j},actions:{scrollToBottom:U,onBeforeMessageSend:W,onAfterMessageSend:X,onStreamingUpdate:M,onConversationClosed:Z,onTypingIndicatorUpdate:ie}}},n)}const{Provider:gg,Context:pg,useContext:Te}=ve("Conversation"),_g=({children:e})=>{var s;const{channelSource:t}=Te(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=_m(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)},Eg=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,children:i})=>{const{activeChannel:c,refreshActiveChannel:u}=Ne(),d=oa(),m=e||(c==null?void 0:c.url);cg(m);const{onBeforeSendMessage:h,onAfterSendMessage:f}=dg({onScrollAfterSendMessage:()=>{d.actions.onAfterMessageSend()}}),g=l.useCallback(b=>(d.actions.onBeforeMessageSend(),h(b)),[d.actions,h]),C=l.useCallback(b=>{const y=b.some(A=>ke.isStreaming(A));d.actions.onStreamingUpdate(y)},[d.actions.onStreamingUpdate]),v=l.useCallback(b=>{d.actions.onConversationClosed(b===fe.ConversationStatus.CLOSED)},[d.actions.onConversationClosed]),p=l.useCallback(async()=>{await u(),e&&(t==null||t())},[u,e,t]);return a.createElement(Jd,{key:m,channelUrl:m,onBeforeSendMessage:g,onAfterSendMessage:f,onMessagesUpdated:C,onMessagesReceived:C,onChannelDeleted:p,onConversationStatusChanged:v,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,shouldCountNewMessages:d.state.shouldCountNewMessages},b=>a.createElement(gg,{value:{...b,scrollSource:d,goToActiveConversation:p,onNavigateToConversationList:n}},a.createElement(_g,null,i)))},ia=({children:e,...t})=>{const{config:n}=xe(),{agentPreviewConfigs:r}=me(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(fg,{scrollMode:s,messageStackDirection:o},a.createElement(Eg,{...t},e))},Wr=l.createContext({onDrop:he,subscribe:()=>he}),pr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(Wr.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)},Cg=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(Wr);l.useEffect(()=>t(e),[e])};pr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(Wr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const aa=ve("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>he,registerWindowTitlePending:()=>he}),bg=aa.Provider,ca=aa.useContext,co=()=>{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]},jr=({children:e})=>{const[t,n]=co(),[r,s]=co(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(bg,{value:i},e)},Dn=ca,la=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=ca(),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}},vg=(e,t)=>{const r=(t?Gt(e,t):null)??Tf(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},ua=(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=Kr(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,vg(e.current,s))};if(r)return Ie(d),()=>{u=!0};const m=setTimeout(()=>Ie(d),Ui);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},Sg=(e,t)=>{const{announcementsEnabled:n}=nt(),{channelSource:r}=Te(),{isWindowNameReady:s}=Dn(),o=qi(),i=r.channel!=null||r.error!=null;ua(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?xh:void 0,suppressed:o})},yg=()=>{var s;const{_statsEnabled:e,channelSource:t}=Te(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(mr()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Pm({channelUrl:n,enabled:e,isInitiallyBackgrounded:mr,isForegrounded:kh,subscribeToForegroundState:r})},Ag=e=>Ve(e)||zt(e);function Tg(e,t){return e.filter(n=>ke.isWelcomeMessage(n,t))}const da=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!ke.isWelcomeMessage(r,n):!0),Ig=[],ma=()=>{var C,v,p,b,y,A;const{agentPreviewConfigs:e={},aiAgentId:t}=me(),{aiAgentInfo:n,userSession:r}=Ne(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Te(),u=e.welcomeMessages??Ig,d=l.useMemo(()=>da(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=et(s.channel),h=(v=(C=ti(s.channel,r.userId))==null?void 0:C.nickname)==null?void 0:v.trim(),f=m?(b=(p=s.channel)==null?void 0:p.name)==null?void 0:b.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:Fe(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},xg=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=nt(),{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=>Oe.isAdmin(f)&&Oe.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])},Rg=()=>{const e=ma();xg(e)},Mg=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}),lo=(e,t,n=ot.format)=>{const r=lh(e,Mg(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}},wg={senderName:!0,body:!0,time:!0},kg=Object.keys(wg),Lg=(e,t)=>kg.every(n=>e[n]===t[n]),uo=2e3,mo=400,_r=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]},ha=e=>{if(!Oe.isAdmin(e)||!Oe.isCSAT(e))return null;const t=_h(e);return t?`csat:${t}`:null},Og=e=>{const t=new Set;for(const n of e){const r=ha(n);r&&t.add(r)}return t},Ng=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&_r(r).some(s=>t.includes(s)))return r}},er=(e,t)=>e.some(n=>t.includes(n)),ho=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,tr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Dg=()=>{const{announceStatus:e,announcementsEnabled:t}=nt(),{stringSet:n,format:r}=ae(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,currentUserId:g}=ma(),{outgoingMessageStates:C,outgoingMessageStatusSignature:v}=l.useMemo(()=>{if(!g)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const j=o.flatMap(W=>{const X=gh(W,g);return!X||!("sendingStatus"in W)?[]:[{key:X,sendingStatus:W.sendingStatus}]});return{outgoingMessageStates:j,outgoingMessageStatusSignature:j.map(({key:W,sendingStatus:X})=>`${W}:${X}`).join(",")}},[g,o]),p=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:tr(C)}),b=l.useRef({messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),y=l.useRef([]),A=l.useRef(null),T=l.useRef([]),R=l.useRef(new Set),N=l.useRef(new Set),k=l.useRef(!1),x=l.useRef(s);b.current={messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const D=()=>b.current.isStreamAnimating||b.current.inputDisabledBy==="ai_responding",F=()=>{A.current!=null&&(clearTimeout(A.current),A.current=null)},U=(j,W,X)=>{const M=X==null?void 0:X.replaceableForMs;if(j.length===0||!M)return;const Z=Date.now();T.current=[...T.current.filter(({replaceableUntil:ie})=>ie>Z),{eventKeys:j,parts:W,replaceableUntil:Z+M}]},q=()=>y.current.length>0,K=()=>{y.current=[]},L=()=>{const[j,...W]=y.current;if(!j)return!1;y.current=W;const{eventKeys:X,parts:M,dedupeKey:Z}=j,ie=Me=>{U(X,Me,{replaceableForMs:X.length>0?uo:void 0}),e({event:"newMessage",...Me},Z?{dedupeKey:Z}:void 0)};if(X.length===0)return ie(M),!0;const ye=b.current,$e=Ng(ye.messages,X);if($e){const Me=lo($e,ye.stringSet,ye.format);return ie(Me),!0}return ie(M),!0},V=()=>{for(F();L(););},P=(j=uo)=>{F(),A.current=setTimeout(()=>{if(A.current=null,D())return;const W=ho(),[X]=y.current;if(!X)return;if(X.focusTarget!==W){y.current=[{...X,focusTarget:W},...y.current.slice(1)],P(mo);return}L()&&q()&&P(mo)},j)},Y=(j,W,X)=>{const M={eventKeys:W,parts:j,focusTarget:ho(),dedupeKey:X?X.dedupeKey??void 0:W[0]},Z=W.length===0?-1:y.current.findIndex(({eventKeys:ie})=>er(ie,W));Z>=0?y.current=y.current.map((ie,ye)=>ye===Z?{...M,dedupeKey:X?M.dedupeKey:ie.dedupeKey}:ie):y.current=[...y.current,M],P()},ge=(j,W,X)=>{if(j!=="messagesUpdated"||W.length===0)return!1;const M=Date.now(),Z=T.current.find(ie=>ie.replaceableUntil>M&&er(ie.eventKeys,W));return Z?!Lg(X,Z.parts):!1};l.useEffect(()=>{const j=x.current!==s;(!t||!d||j)&&(k.current=!1,N.current.clear(),K(),T.current=[],R.current.clear(),F(),j&&(x.current=s),!t||!d)||k.current||(k.current=!0,x.current=s,p.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:tr(C)},R.current=new Set(o.flatMap(W=>{if(!ke.isStreaming(W))return[];const X="sender"in W?W.sender:void 0;return(X==null?void 0:X.userId)===b.current.currentUserId?[]:_r(W)})),N.current=Og(o))},[e,t,s,d,m,i,c,v]),l.useEffect(()=>{const j=(W,X)=>{const M=b.current,Z=_r(W),ie=ha(W);if(ie!=null){if(N.current.has(ie))return;N.current.add(ie),e({event:"csatDisplayed"});return}if(ke.isStreaming(W)){Z.forEach(G=>{R.current.add(G)});return}const ye=Z.filter(G=>R.current.has(G)),$e=X==="messagesUpdated"&&ye.length>0;$e&&ye.forEach(G=>{R.current.delete(G)});const Me=X==="messagesUpdated"&&y.current.some(({eventKeys:G})=>er(G,Z)),$=lo(W,M.stringSet,M.format),I=ge(X,Z,$);if(!$e&&X!=="messagesAdded"&&!Me&&!I)return;const w=I?{dedupeKey:null}:void 0;if($e||D()||Me){Y($,[...new Set([...ye,...Z])],w);return}if(I){Y($,Z,w);return}q()&&V();const O=Z[0];e({event:"newMessage",...$},O?{dedupeKey:O}:void 0)};return gi.subscribe(W=>{if(!k.current||W.channelUrl!==s||W.kind==="initialized"||W.kind==="messagesDeleted"||!Eh(W.source))return;const X=b.current.currentUserId;for(const M of W.messages)M&&ph(M,X)&&j(M,W.kind)})},[e,s]),l.useEffect(()=>{k.current&&(D()||q()&&P())},[h,f]),l.useEffect(()=>()=>{F()},[]),l.useEffect(()=>{if(!k.current)return;const j=p.current,W=j.outgoingMessageStatuses;j.outgoingMessageStatuses=tr(C),C.some(({key:M,sendingStatus:Z})=>{const ie=W.get(M);return ie!==void 0&&ie!=="failed"&&Z==="failed"})&&e({event:"sendFailed"})},[e,v]),l.useEffect(()=>{if(!k.current)return;const j=p.current;i&&!j.isClosed&&e({event:"conversationClosed"}),j.isClosed=i},[e,i]),l.useEffect(()=>{if(!k.current)return;const j=p.current;c&&!j.isHandedOff&&e({event:"agentConnected",agentName:u}),j.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!k.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])},$g=()=>{const{channelSource:e}=Te(),t=Si(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Pg=e=>{const{announceStatus:t,announcementsEnabled:n}=nt();vm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Fg=()=>{const e=$g();Pg(e)},ee=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=uf(),o=s[e];return a.createElement(Ug,{className:n},a.createElement(o,{size:t,color:r??_.color.primary.main,flipInRtl:nf.has(e)}))},Ug=E.default.span.attrs({"aria-hidden":"true"})`
80
+ `;return n.set(e,o),o},Vf=e=>e?U.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",qf=_.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>zf(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Vf(e)}`;async function ns(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const Ar='[role="dialog"][aria-modal="true"]',Kf=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Ar)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(Ar);return r&&r!==e&&n.add(r),n},Yf=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Ar)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Mt(n)),Wf=e=>{const t=oa(e)??e;t===e&&ia(e),t.focus()},ia=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},jf=(e,t)=>{const n=ra(e);if(!n){ia(e),e.focus();return}n[t].focus()},no=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Xr,Gh),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>jf(e,t)),n},Xf=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ra(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=Kf(i,u);return()=>{u&&Ie(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!sa(c,m)&&m.matches(na)&&Mt(m)||Yf(i,d)||!u.isConnected||!Mt(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)&&Mt(m)){s.current=!0;return}s.current=!0,Wf(o)};if(n)return Ie(c),()=>{i=!0};const u=setTimeout(()=>Ie(c),qi);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=>Xf(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])},ft=({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}=Jr();return $n(n,d),sf(n,o?r:me),n?pc.createPortal(a.createElement(Zf,{onClick:o?r:void 0,style:e},a.createElement(Jf,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Zf=_.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:${_t.MODAL};`,Jf=_.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:${_t.MODAL};`,Qf=({id:e,children:t})=>a.createElement(eg,{id:e},t),eg=_.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?{}:Ui}:n},tg=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(Qf,{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):jt(t??"")?r.A11Y_FILE_VIDEO(e):ti({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},ng=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Bt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:ng(e)}),rg=({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:rg({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ae=()=>{const{stringSet:e}=ie(),t=tg(),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=Uh({intent:$h({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,...qh},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})},messageList:{item:({label:i,holding:c})=>c?{props:{"aria-hidden":!0},descriptionNode:null}:{props:{role:"listitem",tabIndex:-1,"aria-label":i},descriptionNode:null},typingItem:i=>({props:{role:"listitem",tabIndex:-1,"aria-label":zt({sender:i,message:e.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER})},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:{...Bt({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:{...Bt({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 C;const p=c.trim()||c,v=e.A11Y_HINT_SELECT_RATING,S=t(v,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...oo(u,d,m,h,f,A=>g(A+1)),...S.props,"aria-label":((C=e.A11Y_CSAT_RATING_LABEL)==null?void 0:C.call(e,i,p))??`${i} / ${h} — ${p}`},descriptionNode:S.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:{...Bt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const f=yh({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":f},descriptionNode:null};const g=e.A11Y_HINT_OPEN_CONVERSATION,p=t(g,"cli");return{props:{...Bt({onActivate:h}),...p.props,"aria-label":f},descriptionNode:p.node}}}}},sg=({title:e,description:t,highlightedText:n})=>{const r=Zm(t,n);return a.createElement(ig,null,a.createElement(ag,null,a.createElement(B,{as:"div",variant:"h1",color:E.themedColor.textHighEmphasis},e),t&&a.createElement(cg,null,a.createElement(B,{as:"div",variant:"body3",color:E.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(lg,null,r.highlightedText):null,r.afterText))))},og=()=>{const{components:e}=Pn.useContext(),{stringSet:t}=ie(),{messenger:n}=ae(),r=jm(),s=r.showDescription?Xm(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(ft,{portalContainerId:Se.WINDOW,visible:r.visible,onClose:me,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Pn=je({template:og,components:{Dialog:sg}}),ig=_.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,ag=_.default.div`display:flex;flex-direction:column;`,cg=_.default.div`margin-top:16px;`,lg=_.default.strong`font-weight:700;`,ug=({url:e})=>ns(e),{Provider:dg,Consumer:aa,useContext:ue}=ve("Messenger");function mg({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}=Jr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);of(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const S=g.current&&!m.opened;if(g.current=m.opened,!S)return;const C=mt(o.rootElement),A=h(Se.WINDOW);let y=!1;return Ie(()=>{var T;y||Hf(C,C.activeElement,A)&&((T=h(Se.LAUNCHER))==null||T.focus())}),()=>{y=!0}},[m.opened,o.rootElement,h]);const{Template:p}=Pn.useContext(),v=l.useMemo(()=>{var S;return{...o.handlers,onClickLink:((S=o.handlers)==null?void 0:S.onClickLink)??ug}},[o.handlers]);return a.createElement(td,{...o},S=>a.createElement(dg,{value:{...o,...S,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(p,null),e))}const ca=/iPad|iPhone|iPod/.test(navigator.userAgent),hg=/Android/.test(navigator.userAgent),en=e=>ca||hg;let Pt=null,or=null;const fg=(e,t=5e3)=>{Pt&&(clearInterval(Pt),clearTimeout(or));const n=document.title;Pt=setInterval(()=>{document.title=document.title===e?n:e},750),or=setTimeout(()=>{clearInterval(Pt),Pt=null,or=null,document.title=n},t)},la=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},ua="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)",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)},Fn=({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,p=()=>{c(),Ie(()=>o==null?void 0:o())},v=()=>{c(),Ie(()=>i==null?void 0:i())};return a.createElement(ft,{portalContainerId:Se.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(gg,null,a.createElement(pg,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:E.themedColor.textHighEmphasis},t)),n&&a.createElement(_g,{id:m},a.createElement(B,{variant:"body3",color:E.themedColor.textMidEmphasis},n))),a.createElement(Eg,null,s&&a.createElement(ao,{onClick:v},a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},s)),a.createElement(ao,{onClick:p},a.createElement(B,{variant:"button",color:E.themedColor.primary},r)))))},gg=_.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};`,pg=_.default.div`margin-bottom:16px;`,_g=_.default.div`margin-top:16px;`,Eg=_.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ao=_.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:Cg,useContext:Oe}=ve("MessengerSession"),bg=l.forwardRef(function({children:e,...t},n){return a.createElement(Ud,{ref:n,...t},r=>a.createElement(vg,{...r},e))}),vg=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=ue(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:p,launcherInfo:v}=t,[S,C]=l.useState(!1),A=l.useRef(null);pt(n,{async onUserJoined(T,I){var O,k,R,F;T.conversation&&T.conversation.type===he.ConversationType.PROACTIVE&&I.userId===((O=n.currentUser)==null?void 0:O.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(R=m.session)==null||R._updateActiveChannel({url:T.url,status:"open",conversationStatus:(k=T.conversation)==null?void 0:k.status}),c.setOpened(!0),Sg({sound:document.hidden||!c.opened}),(F=A.current)==null||F.call(A,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!en()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var I;r.error("messengerSession: failed to initialize",T),(I=u==null?void 0:u.onInitializeFailed)==null||I.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>C(!0);return d.subscribe(Be.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Be.AnonymousSessionTokenExpired,T)},[d]);const y=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!p||!v?null:a.createElement(Cg,{value:{...t,userSession:g,aiAgentInfo:{...p,...i==null?void 0:i.bot},launcherInfo:{...v,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>A.current=T}},e,a.createElement(Fn,{visible:S,title:"Session timed out",description:"Start a new conversation.",onConfirm:y,onClose:me}))};function Sg({sound:e}){fg("🔔You have received a new message"),e&&la()}const Mn=`@${He}-focused-channel`,da=`${Date.now()}-${Math.random().toString(36).slice(2)}`,yg=()=>{try{const e=localStorage.getItem(Mn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},co=e=>{try{localStorage.setItem(Mn,JSON.stringify({channelUrl:e,tabId:da}))}catch{}},lo=()=>{try{const e=localStorage.getItem(Mn);if(!e)return;JSON.parse(e).tabId===da&&localStorage.removeItem(Mn)}catch{}},Ag=(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()||yg()===e}),Tg=e=>{const{config:t,chatSDK:n}=ue(),{sdkUser:r}=Oe(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=Ag(e,s);pt(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(tt(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&la()}})};function Ig(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 xg(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Ig(e.file);return new Le.MessageMetaArray({key:Jo,value:[t,n]})}}const Rg=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ue(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await xg(s),i={...s,metaArrays:o?[o]:void 0},c=Mg(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===Le.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Le.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Mg=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},Tt=50,ir=Tt-40,{Provider:wg,useContext:ma}=ve("ConversationScroll"),uo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},ar=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),mo=e=>Array.from(e.querySelectorAll(`#${He}-message-item`));function kg({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),[p,v]=l.useState(!1),[S,C]=l.useState(!0),A=$=>{const M=ar($);return o.current.distanceFromBottom=M,h(M),M},y=()=>{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()},[]),I=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),N=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},O=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(M=>{c.current.shouldUpdate=!1;const{contentHeight:x,contentSnapshotHeight:L,shouldRecalc:P}=c.current,X=$.clientHeight;if(L>x)return M;const se=k($,{messageType:"outgoing"});let Z=0;if(se){const be=se.message.offsetTop-ir+X;Z=Math.max(0,be-x)}else{const be=x-L,Xe=X-ir;Z=Math.max(0,be-Xe)}return M===0||Z!==M||P?(c.current.shouldRecalc=!1,Z):M})},k=l.useCallback(($,M)=>{const{messageType:x="all"}=M??{},L=mo($);let P=L;x==="outgoing"&&(P=L.filter(it=>it.getAttribute("data-layout-id")==="outgoingmessage"));const X=P[P.length-1];if(!X)return null;const se=$.getBoundingClientRect(),Z=X.getBoundingClientRect(),be=$.scrollTop+(Z.top-se.top),Xe=be+X.offsetHeight;return{message:X,scrollTop:be,lastMessageBottom:Xe}},[]),R=l.useCallback(()=>{const $=r.current;if(!$||I!=="fixed")return;const M=k($);c.current.contentHeight=(M==null?void 0:M.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&N(),i.current.programmatic?o.current.distanceFromBottom=ar($):A($),O()},[I,k]),F=l.useCallback(()=>{T(),y(),c.current=uo,d(0),h(0),C(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),D=l.useCallback(($=!0)=>{const M=o.current.distanceFromBottom>Tt;if(i.current.awayByUser=!1,h(0),!M){Ie(()=>{const x=r.current;x&&!i.current.awayByUser&&x.scrollTo({top:x.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,C(!1),y()),Ie(()=>{const x=r.current;if(!x){i.current.programmatic=!1,C(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,A(x),C(!0);return}const L=()=>{if(r.current!==x){i.current.programmatic=!1,r.current&&A(r.current),C(!0);return}i.current.programmatic=!1,A(x),C(!0)};if($&&!i.current.reconcileTimer){const P=setTimeout(L,500);i.current.reconcileTimer=P,x.addEventListener("scrollend",()=>{clearTimeout(P),i.current.reconcileTimer=null,L()},{once:!0})}x.scrollTo({top:x.scrollHeight,behavior:$?"smooth":"auto"}),$||L()})},[]),Q=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){A($);return}D(!1)}},[D]),re=l.useCallback(()=>{const $=r.current,M=s.current;if(!$||!M.resize)return;const x=new Set(mo($));for(const L of M.resizeTargets)x.has(L)||(M.resize.unobserve(L),M.resizeTargets.delete(L));for(const L of x)M.resizeTargets.has(L)||(M.resize.observe(L),M.resizeTargets.add(L))},[]),G=l.useCallback($=>{T();const M=s.current;typeof ResizeObserver<"u"&&(M.resize=new ResizeObserver(Q),re());const x=new MutationObserver(()=>{re(),Q()});M.mutation=x,x.observe($,{childList:!0})},[T,Q,re]),H=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,I!=="fixed"){G($);return}F(),c.current.viewport=$.clientHeight;const M=new MutationObserver(()=>{R()});s.current.mutation=M,M.observe($,{childList:!0,subtree:!0})},[T,I,R,F,G]),q=l.useCallback(()=>{const $=r.current;if(!$)return;const M=k($,{messageType:"outgoing"});M&&($.scrollTo({top:M.message.offsetTop-ir,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[k]),J=($,M,x)=>{const L=ar($);if(x&&L>Tt){i.current.programmatic=!1,i.current.awayByUser=!0,y(),A($),C(!0),o.current.prevScrollTop=M;return}o.current.distanceFromBottom=L},K=($,M,x)=>{const P=A($)<=Tt;M&&!P&&(i.current.awayByUser=!0,y()),x&&P&&(i.current.awayByUser=!1)},z=$=>{const{scrollTop:M}=$.currentTarget,x=o.current.prevScrollTop;i.current.programmatic?J($.currentTarget,M,M<x):K($.currentTarget,M<x,M>x),o.current.prevScrollTop=M},Y=l.useCallback(()=>{I==="fixed"&&(v(!0),N())},[I]),W=l.useCallback(()=>{I==="fixed"?setTimeout(()=>q(),300):D()},[I,q]),V=l.useCallback($=>{i.current.streaming=$,I==="fixed"?N():i.current.awayByUser||D()},[I,D]),ee=l.useCallback($=>{g($),$&&(d(0),I==="fixed"&&T())},[T,I]),w=l.useCallback($=>{I==="auto"&&$&&!i.current.awayByUser&&D()},[I,D]),Re=!(m<=Tt)&&!p,Te=l.useCallback(()=>o.current.distanceFromBottom>Tt,[]);return a.createElement(wg,{value:{ref:H,state:{bottomSpace:u,isAwayFromBottom:Re,isScrollPositionReconciled:S,shouldCountNewMessages:Te},props:{onScroll:z},actions:{scrollToBottom:D,onBeforeMessageSend:Y,onAfterMessageSend:W,onStreamingUpdate:V,onConversationClosed:ee,onTypingIndicatorUpdate:w}}},n)}const{Provider:Lg,Context:Og,useContext:Ae}=ve("Conversation"),Ng=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=km(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)},Dg=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,children:c})=>{const{activeChannel:u,refreshActiveChannel:d}=Oe(),m=ma(),h=e||(u==null?void 0:u.url);Tg(h);const{onBeforeSendMessage:f,onAfterSendMessage:g}=Rg({onScrollAfterSendMessage:()=>{m.actions.onAfterMessageSend()}}),p=l.useCallback(A=>(m.actions.onBeforeMessageSend(),f(A)),[m.actions,f]),v=l.useCallback(A=>{const y=A.some(T=>we.isStreaming(T));m.actions.onStreamingUpdate(y)},[m.actions.onStreamingUpdate]),S=l.useCallback(A=>{m.actions.onConversationClosed(A===he.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),C=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(dm,{key:h,channelUrl:h,onBeforeSendMessage:p,onAfterSendMessage:g,onMessagesUpdated:v,onMessagesReceived:v,onChannelDeleted:C,onConversationStatusChanged:S,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,shouldCountNewMessages:m.state.shouldCountNewMessages},A=>a.createElement(Lg,{value:{...A,scrollSource:m,goToActiveConversation:C,onNavigateToConversationList:n}},a.createElement(Ng,null,c)))},ha=({children:e,...t})=>{const{config:n}=ye(),{agentPreviewConfigs:r}=ue(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(kg,{scrollMode:s,messageStackDirection:o},a.createElement(Dg,{...t},e))},rs=l.createContext({onDrop:me,subscribe:()=>me}),Tr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(rs.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)},$g=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(rs);l.useEffect(()=>t(e),[e])};Tr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(rs);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const fa=ve("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>me,registerWindowTitlePending:()=>me}),Pg=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]},ss=({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(Pg,{value:i},e)},Un=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}},Fg=(e,t)=>{const r=(t?Yt(e,t):null)??Gf(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=ts(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,Fg(e.current,s))};if(r)return Ie(d),()=>{u=!0};const m=setTimeout(()=>Ie(d),qi);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},Ug=(e,t)=>{const{announcementsEnabled:n}=lt(),{channelSource:r}=Ae(),{isWindowNameReady:s}=Un(),o=Zi(),i=r.channel!=null||r.error!=null;_a(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?Vh:void 0,suppressed:o})},Bg=()=>{var s;const{_statsEnabled:e,channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(vr()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);eh({channelUrl:n,enabled:e,isInitiallyBackgrounded:vr,isForegrounded:Wh,subscribeToForegroundState:r})},Hg=e=>We(e)||jt(e);function Gg(e,t){return e.filter(n=>we.isWelcomeMessage(n,t))}const Ea=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!we.isWelcomeMessage(r,n):!0),zg=[],Ca=()=>{var p,v,S,C,A,y;const{agentPreviewConfigs:e={},aiAgentId:t}=ue(),{aiAgentInfo:n,userSession:r}=Oe(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ae(),u=e.welcomeMessages??zg,d=l.useMemo(()=>Ea(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=ct(s.channel),h=(v=(p=ii(s.channel,r.userId))==null?void 0:p.nickname)==null?void 0:v.trim(),f=m?(C=(S=s.channel)==null?void 0:S.name)==null?void 0:C.trim():(A=n==null?void 0:n.nickname)==null?void 0:A.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(y=s.channel)==null?void 0:y.url,agentName:g,isClosed:De(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},Vg=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=lt(),{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=>Me.isAdmin(f)&&Me.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])},qg=()=>{const e=Ca();Vg(e)},Kg=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=ut.format)=>{const r=Ih(e,Kg(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}},Yg={senderName:!0,body:!0,time:!0},Wg=Object.keys(Yg),jg=(e,t)=>Wg.every(n=>e[n]===t[n]),go=2e3,po=400,Ir=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(!Me.isAdmin(e)||!Me.isCSAT(e))return null;const t=Nh(e);return t?`csat:${t}`:null},Xg=e=>{const t=new Set;for(const n of e){const r=ba(n);r&&t.add(r)}return t},Zg=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Ir(r).some(s=>t.includes(s)))return r}},cr=(e,t)=>e.some(n=>t.includes(n)),_o=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,lr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Jg=()=>{const{announceStatus:e,announcementsEnabled:t}=lt(),{stringSet:n,format:r}=ie(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,currentUserId:g}=Ca(),{outgoingMessageStates:p,outgoingMessageStatusSignature:v}=l.useMemo(()=>{if(!g)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const z=o.flatMap(Y=>{const W=Lh(Y,g);return!W||!("sendingStatus"in Y)?[]:[{key:W,sendingStatus:Y.sendingStatus}]});return{outgoingMessageStates:z,outgoingMessageStatusSignature:z.map(({key:Y,sendingStatus:W})=>`${Y}:${W}`).join(",")}},[g,o]),S=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:lr(p)}),C=l.useRef({messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),y=l.useRef(null),T=l.useRef([]),I=l.useRef(new Set),N=l.useRef(new Set),O=l.useRef(!1),k=l.useRef(s);C.current={messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const R=()=>C.current.isStreamAnimating||C.current.inputDisabledBy==="ai_responding",F=()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},D=(z,Y,W)=>{const V=W==null?void 0:W.replaceableForMs;if(z.length===0||!V)return;const ee=Date.now();T.current=[...T.current.filter(({replaceableUntil:w})=>w>ee),{eventKeys:z,parts:Y,replaceableUntil:ee+V}]},Q=()=>A.current.length>0,re=()=>{A.current=[]},G=()=>{const[z,...Y]=A.current;if(!z)return!1;A.current=Y;const{eventKeys:W,parts:V,dedupeKey:ee}=z,w=Te=>{D(W,Te,{replaceableForMs:W.length>0?go:void 0}),e({event:"newMessage",...Te},ee?{dedupeKey:ee}:void 0)};if(W.length===0)return w(V),!0;const _e=C.current,Re=Zg(_e.messages,W);if(Re){const Te=fo(Re,_e.stringSet,_e.format);return w(Te),!0}return w(V),!0},H=()=>{for(F();G(););},q=(z=go)=>{F(),y.current=setTimeout(()=>{if(y.current=null,R())return;const Y=_o(),[W]=A.current;if(!W)return;if(W.focusTarget!==Y){A.current=[{...W,focusTarget:Y},...A.current.slice(1)],q(po);return}G()&&Q()&&q(po)},z)},J=(z,Y,W)=>{const V={eventKeys:Y,parts:z,focusTarget:_o(),dedupeKey:W?W.dedupeKey??void 0:Y[0]},ee=Y.length===0?-1:A.current.findIndex(({eventKeys:w})=>cr(w,Y));ee>=0?A.current=A.current.map((w,_e)=>_e===ee?{...V,dedupeKey:W?V.dedupeKey:w.dedupeKey}:w):A.current=[...A.current,V],q()},K=(z,Y,W)=>{if(z!=="messagesUpdated"||Y.length===0)return!1;const V=Date.now(),ee=T.current.find(w=>w.replaceableUntil>V&&cr(w.eventKeys,Y));return ee?!jg(W,ee.parts):!1};l.useEffect(()=>{const z=k.current!==s;(!t||!d||z)&&(O.current=!1,N.current.clear(),re(),T.current=[],I.current.clear(),F(),z&&(k.current=s),!t||!d)||O.current||(O.current=!0,k.current=s,S.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:lr(p)},I.current=new Set(o.flatMap(Y=>{if(!we.isStreaming(Y))return[];const W="sender"in Y?Y.sender:void 0;return(W==null?void 0:W.userId)===C.current.currentUserId?[]:Ir(Y)})),N.current=Xg(o))},[e,t,s,d,m,i,c,v]),l.useEffect(()=>{const z=(Y,W)=>{const V=C.current,ee=Ir(Y),w=ba(Y);if(w!=null){if(N.current.has(w))return;N.current.add(w),e({event:"csatDisplayed"});return}if(we.isStreaming(Y)){ee.forEach(P=>{I.current.add(P)});return}const _e=ee.filter(P=>I.current.has(P)),Re=W==="messagesUpdated"&&_e.length>0;Re&&_e.forEach(P=>{I.current.delete(P)});const Te=W==="messagesUpdated"&&A.current.some(({eventKeys:P})=>cr(P,ee)),$=fo(Y,V.stringSet,V.format),M=K(W,ee,$);if(!Re&&W!=="messagesAdded"&&!Te&&!M)return;const x=M?{dedupeKey:null}:void 0;if(Re||R()||Te){J($,[...new Set([..._e,...ee])],x);return}if(M){J($,ee,x);return}Q()&&H();const L=ee[0];e({event:"newMessage",...$},L?{dedupeKey:L}:void 0)};return bi.subscribe(Y=>{if(!O.current||Y.channelUrl!==s||Y.kind==="initialized"||Y.kind==="messagesDeleted"||!Dh(Y.source))return;const W=C.current.currentUserId;for(const V of Y.messages)V&&Oh(V,W)&&z(V,Y.kind)})},[e,s]),l.useEffect(()=>{O.current&&(R()||Q()&&q())},[h,f]),l.useEffect(()=>()=>{F()},[]),l.useEffect(()=>{if(!O.current)return;const z=S.current,Y=z.outgoingMessageStatuses;z.outgoingMessageStatuses=lr(p),p.some(({key:V,sendingStatus:ee})=>{const w=Y.get(V);return w!==void 0&&w!=="failed"&&ee==="failed"})&&e({event:"sendFailed"})},[e,v]),l.useEffect(()=>{if(!O.current)return;const z=S.current;i&&!z.isClosed&&e({event:"conversationClosed"}),z.isClosed=i},[e,i]),l.useEffect(()=>{if(!O.current)return;const z=S.current;c&&!z.isHandedOff&&e({event:"agentConnected",agentName:u}),z.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!O.current)return;const z=S.current;m&&h!=="ai_responding"&&(!z.inputDisabled||z.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),z.inputDisabled=m,z.inputDisabledBy=h},[e,m,h])},Qg=()=>{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}},ep=e=>{const{announceStatus:t,announcementsEnabled:n}=lt();Pm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},tp=()=>{const e=Qg();ep(e)},te=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=xf(),o=s[e];return a.createElement(np,{className:n},a.createElement(o,{size:t,color:r??E.color.primary.main,flipInRtl:bf.has(e)}))},np=_.default.span.attrs({"aria-hidden":"true"})`
81
81
  display: inline-flex;
82
82
  &:focus {
83
83
  outline: none;
84
84
  }
85
- `,Bg=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(lt,{portalContainerId:Se.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Vg,null,n)),Hg=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(Gg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(zg,null,a.createElement(ee,{type:n,size:24,color:_.themedColor.primary})),s),at=Object.assign(Bg,{ActionItem:Hg}),Gg=E.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?_.themedColor.error:_.themedColor.textHighEmphasis};${Re}`,zg=E.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Vg=E.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};`,fo=40,go=.9,qg="[data-message-listitem]",Kg='input, textarea, select, [role="textbox"], [contenteditable="true"]',Yg=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*go;case"PageUp":return t.clientHeight*-go;case"ArrowDown":return n?fo:void 0;case"ArrowUp":return n?fo*-1:void 0;default:return}},Wg=({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(qg),i=Yg({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]),jg="[data-message-listitem]",Xg=e=>Math.min(Math.max(0,e),1),Zg=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(jg),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},Jg=({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 b=t.current;b&&(u.current==="top"&&(b.scrollTop=b.scrollHeight-m.current,Jg({list:b,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(b.scrollTop=d.current),u.current=void 0)},[t,r]);const C=l.useCallback(async b=>{const y=t.current;if(!y||(i==null||i(b),m.current=y.scrollHeight-y.scrollTop,d.current=y.scrollTop,c.current))return;const A=y.clientHeight*Xg(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]),v=l.useCallback(b=>{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,C(b);return}f.current=null,C(b)},[C,t]),p=l.useCallback(b=>{const y=t.current;y&&(f.current=b,g.current=null,y.scrollTop=b,y.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:v,syncScrollPosition:p}},ep=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:C,onLoadNext:v,loadThreshold:p=.05,onScroll:b=he,depsForResetScrollPositionToBottom:y,stackDirection:A="top",bottomSpacerHeight:T=0,"aria-label":R}=t,N=l.useRef(null),k=l.useCallback(U=>{N.current=U,n&&(typeof n=="function"?n(U):n.current=U)},[n]),{handleScroll:x,syncScrollPosition:D}=Qg({depsForResetScrollPositionToBottom:y,listRef:N,loadThreshold:p,messagesLength:r.length,onLoadNext:v,onLoadPrev:C,onScroll:b}),F=Wg({listRef:N,syncScrollPosition:D});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(tp,{id:"infinite-list-container"},a.createElement(np,{id:"infinite-list-inner",ref:k,onScroll:x,onKeyDown:F,role:"list","aria-label":R,tabIndex:0},A==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((U,q)=>s({message:U,index:q})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(rp,{id:"infinite-list-overlay-container"},a.createElement(sp,{id:"infinite-list-overlay"},g)))}),tp=E.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,np=E.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${_.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,rp=E.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,sp=E.default.div`pointer-events:auto;`,rt=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?_.themedColor.textDisabled:_.themedColor.textHighEmphasis;return a.createElement(op,{as:e,disabled:s,...i},a.createElement(ee,{type:t,size:n,color:r??c}),o)},op=E.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Re}&:disabled{cursor:not-allowed;}`,gt=({className:e,children:t,size:n=26})=>a.createElement(ip,{className:e,$size:n},t??a.createElement(ee,{type:"spinner",size:n})),ip=E.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ye(e)};height:${({$size:e})=>Ye(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,ap=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=ae(),{config:m}=me(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,C=h>1,v=(f==null?void 0:f.type)||"",p=Ve(v),b=zt(v),y=!Ag(v);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const A=l.useCallback(()=>{s>0&&(o(R=>R-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(R=>R+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const R=N=>{N.key==="ArrowLeft"?A():N.key==="ArrowRight"&&T()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[r,A,T]),!r||!f?null:a.createElement(lt,{onClose:n,visible:r,portalContainerId:Se.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(cp,null,a.createElement(lp,null,a.createElement(up,null,a.createElement(dp,null,a.createElement(B,{variant:"button",maxTextLines:1,color:_.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(B,{variant:"caption2",color:_.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(mp,{type:"close",size:18,color:_.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(hp,null,C&&a.createElement(po,{$position:"left",type:"chevron-right",size:22,color:_.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(fp,{onClick:R=>R.currentTarget===R.target&&n()},p&&a.createElement(a.Fragment,null,!i&&a.createElement(gp,null,a.createElement(gt,{size:32},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(pp,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),b&&a.createElement(_p,{controls:!0},a.createElement("source",{src:f.url,type:v})),y&&a.createElement(Ep,null,a.createElement(B,{variant:"h1",color:_.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),C&&a.createElement(po,{$position:"right",type:"chevron-right",size:22,color:_.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(Cp,null,C&&a.createElement(B,{variant:"body2",color:_.color.ondark.textHighEmphasis},s+1,"/",h),g&&!y&&a.createElement(bp,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:_.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},cp=E.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${_.themedColor.bg_50_600};`,lp=E.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:${_.color.overlay.dark};`,up=E.default.div`flex:1;min-width:0;padding-right:8px;`,dp=E.default.div`display:flex;flex-direction:column;gap:2px;`,mp=E.default(rt)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,$n=E.default.div`display:flex;align-items:center;justify-content:center;`,hp=E.default($n)`flex:1;min-height:0;position:relative;`,fp=E.default($n)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,gp=E.default($n)`position:absolute;inset:0;pointer-events:none;`,pp=E.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;`,_p=E.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Ep=E.default($n)`flex-direction:column;gap:16px;`,po=E.default(rt)`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:${_.color.overlay.dark};&:disabled{opacity:0.3;}`,Cp=E.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:${_.color.overlay.dark};`,bp=E.default(rt)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,vp=.75,fa=6,Sp=fa*2;let Er=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Er=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const yp=e=>Er?Array.from(Er.segment(e),t=>t.segment):[...e],Ap=e=>{const t=Math.floor(e.length*vp),n=Math.max(0,e.length-fa);return Math.max(t,n)},_o=(e,t="")=>{if(e.length<Sp)return{start:e+t,end:""};const n=yp(e),r=Ap(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Tp=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return _o(t);const s=t.slice(0,n),o=t.slice(n);return _o(s,o)},ga=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>Tp(e),[e]);return r?a.createElement(Ip,null,a.createElement(xp,{...t},n),a.createElement(Rp,{...t},r)):a.createElement(B,{...t},n)},Ip=E.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,xp=E.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,Rp=E.default(B)`flex-shrink:0;white-space:nowrap;`,Xr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=H.useTheme(),{conversation:u}=oe(),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(Mp,{...d.props,$clickable:!!o},a.createElement(kp,{$bgColor:s??c.base.primary},a.createElement(ee,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(Lp,null,a.createElement(ga,{variant:"button",color:_.themedColor.textHighEmphasis},e),a.createElement(B,{color:_.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},Mp=E.default.div`border:none;border-radius:12px;gap:8px;width:${re.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${_.themedColor.textDisabled};background-color:${_.themedColor.bg_50_600};${({$clickable:e})=>e&&wp}`,wp=H.css`cursor:pointer;${Re}&:hover{background-color:${_.themedColor.bg_100_500};}`,kp=E.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Lp=E.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Op({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Np,null,a.createElement(Xr,{name:e.name,mimeType:e.type,type:Tr(e.name,e.type),onClick:r}),t)}const Np=E.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Je=`${Ue}-incoming-msg`,Dp=`${Ue}-marked-text`;function $p({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=oe(),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(Up,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(Bp,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${Je}-media-body`,...c.props};return a.createElement(Pp,null,a.createElement(Fp,{...d},u(),c.descriptionNode),r)}return null}const Pp=E.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Fp=E.default.div`width:${re.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${te.light`
86
- background-color: ${_.color.background100};
85
+ `,rp=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(ft,{portalContainerId:Se.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(ap,null,n)),sp=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(op,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(ip,null,a.createElement(te,{type:n,size:24,color:E.themedColor.primary})),s),dt=Object.assign(rp,{ActionItem:sp}),op=_.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}`,ip=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,ap=_.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,cp="[data-message-listitem]",lp='input, textarea, select, [role="textbox"], [contenteditable="true"]',up=({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}},dp=({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(lp))return;const o=s===r||s.matches(cp),i=up({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]),mp="[data-message-listitem]",hp=e=>Math.min(Math.max(0,e),1),fp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(mp),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},gp=({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})},pp=({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 C=t.current;C&&(u.current==="top"&&(C.scrollTop=C.scrollHeight-m.current,gp({list:C,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(C.scrollTop=d.current),u.current=void 0)},[t,r]);const p=l.useCallback(async C=>{const A=t.current;if(!A||(i==null||i(C),m.current=A.scrollHeight-A.scrollTop,d.current=A.scrollTop,c.current))return;const y=A.clientHeight*hp(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=fp(A),await o(),c.current=!1;return}if(A.scrollHeight-A.scrollTop-A.clientHeight<=y){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),v=l.useCallback(C=>{const A=t.current;if(!A)return;const y=g.current;if(y!=null){if(y===A.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===A.scrollTop){f.current=null,g.current=A.scrollTop,p(C);return}f.current=null,p(C)},[p,t]),S=l.useCallback(C=>{const A=t.current;A&&(f.current=C,g.current=null,A.scrollTop=C,A.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:v,syncScrollPosition:S}},_p=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:p,onLoadNext:v,loadThreshold:S=.05,onScroll:C=me,depsForResetScrollPositionToBottom:A,stackDirection:y="top",bottomSpacerHeight:T=0,"aria-label":I}=t,N=l.useRef(null),O=l.useCallback(D=>{N.current=D,n&&(typeof n=="function"?n(D):n.current=D)},[n]),{handleScroll:k,syncScrollPosition:R}=pp({depsForResetScrollPositionToBottom:A,listRef:N,loadThreshold:S,messagesLength:r.length,onLoadNext:v,onLoadPrev:p,onScroll:C}),F=dp({listRef:N,syncScrollPosition:R});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(Ep,{id:"infinite-list-container"},a.createElement(Cp,{id:"infinite-list-inner",ref:O,onScroll:k,onKeyDown:F,role:"list","aria-label":I,tabIndex:0},y==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((D,Q)=>s({message:D,index:Q})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(bp,{id:"infinite-list-overlay-container"},a.createElement(vp,{id:"infinite-list-overlay"},g)))}),Ep=_.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Cp=_.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;}`,bp=_.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,vp=_.default.div`pointer-events:auto;`,st=({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(Sp,{as:e,disabled:s,...i},a.createElement(te,{type:t,size:n,color:r??c}),o)},Sp=_.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,Et=({className:e,children:t,size:n=26})=>a.createElement(yp,{className:e,$size:n},t??a.createElement(te,{type:"spinner",size:n})),yp=_.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Je(e)};height:${({$size:e})=>Je(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Ap=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=ie(),{config:m}=ue(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,p=h>1,v=(f==null?void 0:f.type)||"",S=We(v),C=jt(v),A=!Hg(v);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const y=l.useCallback(()=>{s>0&&(o(I=>I-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(I=>I+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const I=N=>{N.key==="ArrowLeft"?y():N.key==="ArrowRight"&&T()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[r,y,T]),!r||!f?null:a.createElement(ft,{onClose:n,visible:r,portalContainerId:Se.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(Tp,null,a.createElement(Ip,null,a.createElement(xp,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(Mp,{type:"close",size:18,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(wp,null,p&&a.createElement(bo,{$position:"left",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:y,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(kp,{onClick:I=>I.currentTarget===I.target&&n()},S&&a.createElement(a.Fragment,null,!i&&a.createElement(Lp,null,a.createElement(Et,{size:32},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(Op,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),C&&a.createElement(Np,{controls:!0},a.createElement("source",{src:f.url,type:v})),A&&a.createElement(Dp,null,a.createElement(B,{variant:"h1",color:E.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&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($p,null,p&&a.createElement(B,{variant:"body2",color:E.color.ondark.textHighEmphasis},s+1,"/",h),g&&!A&&a.createElement(Pp,{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}))))},Tp=_.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};`,Ip=_.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};`,xp=_.default.div`flex:1;min-width:0;padding-right:8px;`,Rp=_.default.div`display:flex;flex-direction:column;gap:2px;`,Mp=_.default(st)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Bn=_.default.div`display:flex;align-items:center;justify-content:center;`,wp=_.default(Bn)`flex:1;min-height:0;position:relative;`,kp=_.default(Bn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,Lp=_.default(Bn)`position:absolute;inset:0;pointer-events:none;`,Op=_.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=_.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Dp=_.default(Bn)`flex-direction:column;gap:16px;`,bo=_.default(st)`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;}`,$p=_.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};`,Pp=_.default(st)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,Fp=.75,va=6,Up=va*2;let xr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(xr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Bp=e=>xr?Array.from(xr.segment(e),t=>t.segment):[...e],Hp=e=>{const t=Math.floor(e.length*Fp),n=Math.max(0,e.length-va);return Math.max(t,n)},vo=(e,t="")=>{if(e.length<Up)return{start:e+t,end:""};const n=Bp(e),r=Hp(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Gp=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(()=>Gp(e),[e]);return r?a.createElement(zp,null,a.createElement(Vp,{...t},n),a.createElement(qp,{...t},r)):a.createElement(B,{...t},n)},zp=_.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,Vp=_.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,qp=_.default(B)`flex-shrink:0;white-space:nowrap;`,os=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=U.useTheme(),{conversation:u}=ae(),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(Kp,{...d.props,$clickable:!!o},a.createElement(Wp,{$bgColor:s??c.base.primary},a.createElement(te,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(jp,null,a.createElement(Sa,{variant:"button",color:E.themedColor.textHighEmphasis},e),a.createElement(B,{color:E.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},Kp=_.default.div`border:none;border-radius:12px;gap:8px;width:${oe.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&&Yp}`,Yp=U.css`cursor:pointer;${xe}&:hover{background-color:${E.themedColor.bg_100_500};}`,Wp=_.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,jp=_.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Xp({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Zp,null,a.createElement(os,{name:e.name,mimeType:e.type,type:Nr(e.name,e.type),onClick:r}),t)}const Zp=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${oe.GAP_GROUPED}px;`,ot=`${He}-incoming-msg`,Jp=`${He}-marked-text`;function Qp({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=ae(),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(n_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(r_,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${ot}-media-body`,...c.props};return a.createElement(e_,null,a.createElement(t_,{...d},u(),c.descriptionNode),r)}return null}const e_=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${oe.GAP_GROUPED}px;`,t_=_.default.div`width:${oe.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${ne.light`
86
+ background-color: ${E.color.background100};
87
87
  `}
88
- ${te.dark`
89
- background-color: ${_.color.background400};
88
+ ${ne.dark`
89
+ background-color: ${E.color.background400};
90
90
  `}
91
- `,Up=E.default.img`width:100%;height:100%;object-fit:cover;`,Bp=E.default.video`width:100%;height:100%;object-fit:cover;`,pa=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=oe(),s=e.length;if(s===0)return null;const o=Fu(s),i=!!n&&!t;return a.createElement(Gp,{$width:re.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=Uu({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(zp,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(Hp,{src:c.url,alt:c.name||""}),t&&a.createElement(Vp,null),g.descriptionNode)}))},Hp=({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(qp,null,a.createElement(gt,{size:20},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(Kp,null,a.createElement(ee,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(Yp,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},Gp=E.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,zp=E.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${te.light`
92
- background-color: ${_.color.background100};
91
+ `,n_=_.default.img`width:100%;height:100%;object-fit:cover;`,r_=_.default.video`width:100%;height:100%;object-fit:cover;`,ya=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=ae(),s=e.length;if(s===0)return null;const o=Ju(s),i=!!n&&!t;return a.createElement(o_,{$width:oe.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=Qu({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(i_,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(s_,{src:c.url,alt:c.name||""}),t&&a.createElement(a_,null),g.descriptionNode)}))},s_=({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(c_,null,a.createElement(Et,{size:20},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(l_,null,a.createElement(te,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(u_,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},o_=_.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,i_=_.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${ne.light`
92
+ background-color: ${E.color.background100};
93
93
  `}
94
- ${te.dark`
95
- background-color: ${_.color.background400};
94
+ ${ne.dark`
95
+ background-color: ${E.color.background400};
96
96
  `}
97
97
  ${e=>e.$itemSpan&&e.$itemSpan>1&&`
98
98
  grid-column: span ${e.$itemSpan};
@@ -100,7 +100,7 @@
100
100
  `}
101
101
 
102
102
  &:focus-visible {
103
- outline: 2px solid ${_.color.primary.main};
103
+ outline: 2px solid ${E.color.primary.main};
104
104
  outline-offset: -2px;
105
105
  }
106
106
 
@@ -111,19 +111,19 @@
111
111
  }
112
112
  `}
113
113
  }
114
- `,Vp=E.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${_.color.overlay.dark};pointer-events:none;`,_a=E.default.div`display:flex;align-items:center;justify-content:center;`,qp=E.default(_a)`position:absolute;inset:0;`,Kp=E.default(_a)`position:absolute;inset:0;${te.light`
115
- background-color: ${_.color.background200};
114
+ `,a_=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${E.color.overlay.dark};pointer-events:none;`,Aa=_.default.div`display:flex;align-items:center;justify-content:center;`,c_=_.default(Aa)`position:absolute;inset:0;`,l_=_.default(Aa)`position:absolute;inset:0;${ne.light`
115
+ background-color: ${E.color.background200};
116
116
  `}
117
- ${te.dark`
118
- background-color: ${_.color.background500};
117
+ ${ne.dark`
118
+ background-color: ${E.color.background500};
119
119
  `}
120
- `,Yp=E.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Wp=({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(jp,null,a.createElement(pa,{images:e,onClickImage:s}),t)},jp=E.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Xp="✱",Ea=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Xp}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${Dp} aria-label="masked-text">${o}</span>`:n)},Zp=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),Eo=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)}}},Jp=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),Co=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??re.BODY_MAX_WIDTH,n=l.useMemo(()=>Sc(e.message,Ea),[e.message]),r={id:`${Je}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor};return n.length===0?e.children?a.createElement(bo,{...r},e.children):null:a.createElement(bo,{...r},n.map((i,c)=>i.type==="text"?a.createElement(vo,{key:c,variant:"body3"},a.createElement(Ht,{fallback:i.value},a.createElement(Jp,{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"?Co?a.createElement(Ht,{key:c,fallback:a.createElement(vo,{variant:"body3"},i.value)},a.createElement(Co,{code:i.value,language:i.language})):a.createElement(e_,{key:c},a.createElement("code",null,i.value)):null),e.children)}const bo=E.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);border-radius:12px;overflow:hidden;padding:12px 0;${({theme:e,$color:t,$bgColor:n})=>H.css`
120
+ `,u_=_.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,d_=({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(m_,null,a.createElement(ya,{images:e,onClickImage:s}),t)},m_=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${oe.GAP_GROUPED}px;`,h_="✱",Ta=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${h_}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${Jp} aria-label="masked-text">${o}</span>`:n)},f_=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)}}},g_=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 p_(e){var s,o;const t=e.maxBodyWidth??oe.BODY_MAX_WIDTH,n=l.useMemo(()=>Nc(e.message,Ta),[e.message]),r={id:`${ot}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor};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(Kt,{fallback:i.value},a.createElement(g_,{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(Kt,{key:c,fallback:a.createElement(To,{variant:"body3"},i.value)},a.createElement(yo,{code:i.value,language:i.language})):a.createElement(__,{key:c},a.createElement("code",null,i.value)):null),e.children)}const Ao=_.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);border-radius:12px;overflow:hidden;padding:12px 0;${({theme:e,$color:t,$bgColor:n})=>U.css`
121
121
  color: ${t||e.colors.messageIncoming.text};
122
122
  background-color: ${n||e.colors.messageIncoming.background};
123
123
  `}
124
124
  transition: max-width 0.3s;
125
125
  overflow-wrap: break-word;
126
- `,vo=E.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,e_=E.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 Ca({id:e,src:t,size:n=56,onClick:r,onImageError:s,style:o,...i}){const[c,u]=l.useState();return a.createElement(t_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ye(n),style:o,...i},t&&t!==c?a.createElement(n_,{src:t,alt:"",onError:()=>{u(t),s==null||s(t)}}):a.createElement(ee,{type:"user",size:n}))}const t_=E.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:${_.themedColor.bg_100_500};&:focus{outline:none;}${Re}`,n_=E.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,r_=({sender:e,isBotMessage:t})=>{const n=`${Je}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(s_,{id:n},a.createElement(ee,{type:"delight",size:"100%"})):a.createElement(Ca,{id:n,size:re.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},s_=E.default.div`flex-shrink:0;width:${re.AVATAR_SIZE}px;height:${re.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;}}`,o_=({sender:e})=>a.createElement(i_,{id:`${Je}-sender-name`,variant:"caption1",color:_.themedColor.textMidEmphasis},e.nickname),i_=E.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;`,a_=({createdAt:e})=>{const{stringSet:t,format:n}=ae();return e?a.createElement(B,{id:`${Je}-sent-time`,variant:"caption4",color:_.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},ba="(prefers-reduced-motion: reduce)",c_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(ba).matches,va=()=>{const[e,t]=l.useState(c_);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(ba);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},l_=({thinkingMessage:e,customStyle:t})=>{const n=va();return e?a.createElement(m_,{$prefersReducedMotion:n},a.createElement(h_,null,e),!n&&a.createElement(f_,null)):a.createElement(u_,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(d_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},u_=E.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};`,d_=E.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;}`,m_=E.default.div.attrs({id:`${Je}-typing-indicator`})`
126
+ `,To=_.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,__=_.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,onImageLoad:o,style:i,backgroundColor:c,...u}){const[d,m]=l.useState();return a.createElement(E_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Je(n),$backgroundColor:c,style:i,...u},t&&t!==d?a.createElement(C_,{src:t,alt:"",onLoad:()=>o==null?void 0:o(t),onError:()=>{m(t),s==null||s(t)}}):a.createElement(te,{type:"user",size:n}))}const E_=_.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=>e.$backgroundColor??E.themedColor.bg_100_500};&:focus{outline:none;}${xe}`,C_=_.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,b_=({sender:e,isBotMessage:t})=>{const n=`${ot}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(v_,{id:n},a.createElement(te,{type:"delight",size:"100%"})):a.createElement(Ia,{id:n,size:oe.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},v_=_.default.div`flex-shrink:0;width:${oe.AVATAR_SIZE}px;height:${oe.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;}}`,S_=({sender:e})=>a.createElement(y_,{id:`${ot}-sender-name`,variant:"caption1",color:E.themedColor.textMidEmphasis},e.nickname),y_=_.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;`,A_=({createdAt:e})=>{const{stringSet:t,format:n}=ie();return e?a.createElement(B,{id:`${ot}-sent-time`,variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},xa="(prefers-reduced-motion: reduce)",T_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(xa).matches,Ra=()=>{const[e,t]=l.useState(T_);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},I_=({thinkingMessage:e,customStyle:t})=>{const n=Ra();return e?a.createElement(M_,{$prefersReducedMotion:n},a.createElement(w_,null,e),!n&&a.createElement(k_,null)):a.createElement(x_,{$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})))},x_=_.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_=_.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;}`,M_=_.default.div.attrs({id:`${ot}-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
- `,h_=E.default(B).attrs({variant:"body3"})`
138
+ `,w_=_.default(B).attrs({variant:"body3"})`
139
139
  white-space: pre-wrap;
140
140
  word-break: break-word;
141
- color: ${_.themedColor.textHighEmphasis};
142
- `,f_=E.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=Ss(e.colors.base.background,.5),n=Ss(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
143
- `,g_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Yr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(p_,{id:`${Je}-ext-cta-button`,onClick:r},a.createElement(__,{variant:"button"},n.label))},p_=E.default.button.attrs({type:"button"})`
141
+ color: ${E.themedColor.textHighEmphasis};
142
+ `,k_=_.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=xs(e.colors.base.background,.5),n=xs(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
143
+ `,L_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>ns(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(O_,{id:`${ot}-ext-cta-button`,onClick:r},a.createElement(N_,{variant:"button"},n.label))},O_=_.default.button.attrs({type:"button"})`
144
144
  all: unset;
145
145
  display: flex;
146
146
  width: 100%;
@@ -150,14 +150,14 @@
150
150
  cursor: pointer;
151
151
  border-radius: 6px;
152
152
  padding: 8px;
153
- color: ${_.themedColor.textHighEmphasis};
154
- background-color: ${_.color.background50};
155
- ${te.dark`
156
- background-color: ${_.color.ondark.textDisabled};
153
+ color: ${E.themedColor.textHighEmphasis};
154
+ background-color: ${E.color.background50};
155
+ ${ne.dark`
156
+ background-color: ${E.color.ondark.textDisabled};
157
157
  `}
158
158
 
159
- ${Re}
160
- `,__=E.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,E_=e=>a.createElement(a.Fragment,null),C_=({extendedMessagePayload:e,onClickCitation:t=n=>Yr(n.link)})=>{const{stringSet:n}=ae(),{theme:r}=Fr(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(b_,{id:`${Je}-ext-citation`},a.createElement(v_,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(S_,null,s.map((o,i)=>a.createElement(A_,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(ee,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(y_,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},b_=E.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,v_=E.default(B)`opacity:0.5;`,S_=E.default.div`display:flex;flex-direction:column;gap:8px;`,y_=E.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,A_=E.default.button.attrs({type:"button"})`
159
+ ${xe}
160
+ `,N_=_.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,D_=e=>a.createElement(a.Fragment,null),$_=({extendedMessagePayload:e,onClickCitation:t=n=>ns(n.link)})=>{const{stringSet:n}=ie(),{theme:r}=Yr(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(P_,{id:`${ot}-ext-citation`},a.createElement(F_,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(U_,null,s.map((o,i)=>a.createElement(H_,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(te,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(B_,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},P_=_.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,F_=_.default(B)`opacity:0.5;`,U_=_.default.div`display:flex;flex-direction:column;gap:8px;`,B_=_.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,H_=_.default.button.attrs({type:"button"})`
161
161
  background: none;
162
162
  border: none;
163
163
  padding: 0;
@@ -172,127 +172,127 @@
172
172
  &:hover {
173
173
  opacity: 0.5;
174
174
  }
175
- `,T_=e=>a.createElement(a.Fragment,null),Cr=e=>`${e}-filled`,I_=e=>e==="good"?fe.AIAgentMessageFeedbackRating.GOOD:fe.AIAgentMessageFeedbackRating.BAD,Zr=H.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,an={good:{onlight:_.color.secondary.dark,ondark:_.color.secondary.light},bad:{onlight:_.color.error.dark,ondark:_.color.error.light}},x_={good:_.themedColor.secondary,bad:_.themedColor.error},Sa=e=>H.css`color:${an[e].onlight};border-color:${an[e].onlight};${te.dark`
176
- color: ${an[e].ondark};
177
- border-color: ${an[e].ondark};
175
+ `,G_=e=>a.createElement(a.Fragment,null),Rr=e=>`${e}-filled`,z_=e=>e==="good"?he.AIAgentMessageFeedbackRating.GOOD:he.AIAgentMessageFeedbackRating.BAD,is=U.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,hn={good:{onlight:E.color.secondary.dark,ondark:E.color.secondary.light},bad:{onlight:E.color.error.dark,ondark:E.color.error.light}},V_={good:E.themedColor.secondary,bad:E.themedColor.error},Ma=e=>U.css`color:${hn[e].onlight};border-color:${hn[e].onlight};${ne.dark`
176
+ color: ${hn[e].ondark};
177
+ border-color: ${hn[e].ondark};
178
178
  `}
179
- `,R_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=ae(),{conversation:u}=oe(),{rootElement:d}=Yi(),m=ct(d),[h,f]=l.useState(r),[g,C]=l.useState(s),[v,p]=l.useState(!1),b=l.useRef(!1),y=h??r??"good",A=u.feedback;l.useLayoutEffect(()=>{e?(f(r),C(s)):(f(void 0),C(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const k=D=>{const F=D;F.metaKey||F.altKey||F.ctrlKey||(b.current=!0)},x=()=>{b.current=!1,p(!1)};return m.addEventListener("keydown",k),m.addEventListener("pointerdown",x),()=>{m.removeEventListener("keydown",k),m.removeEventListener("pointerdown",x)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},R=()=>{t()};if(!e)return null;const N={feedback:A.container()};return a.createElement(lt,{portalContainerId:Se.WINDOW,visible:e,onClose:R,"aria-label":c.FEEDBACK_TITLE},a.createElement(M_,null,a.createElement(w_,null,a.createElement(B,{variant:"h2",color:_.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(k_,null,a.createElement(L_,{...N.feedback.props},["good","bad"].map(k=>{const x=h===k,D=k==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,F=A.button(k,x);return a.createElement(l.Fragment,{key:k},a.createElement(O_,{type:"button",$selected:x,$rating:k,...F.props,onClick:()=>f(k),"data-sb-initial-focus":k===y?"true":void 0},a.createElement(ee,{type:x?Cr(k):k,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},D)),F.descriptionNode)}),N.feedback.descriptionNode),i&&a.createElement(N_,null,a.createElement(B,{variant:"caption3",color:_.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(D_,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:k=>C(k.target.value),onFocus:()=>p(b.current),onBlur:()=>p(!1),maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),a.createElement($_,null,a.createElement(P_,{onClick:R},a.createElement(B,{variant:"button",color:_.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(F_,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},M_=E.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,w_=E.default.div`padding:24px;`,k_=E.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,L_=E.default.div`display:flex;gap:4px;`,O_=E.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${_.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:${_.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Sa(t)}${Zr}`,N_=E.default.label`display:flex;flex-direction:column;gap:6px;`,D_=E.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${_.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${_.themedColor.textHighEmphasis};background-color:${_.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${_.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&H.css`
180
- outline: 2px solid ${_.themedColor.primary};
179
+ `,q_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=ie(),{conversation:u}=ae(),{rootElement:d}=Qi(),m=mt(d),[h,f]=l.useState(r),[g,p]=l.useState(s),[v,S]=l.useState(!1),C=l.useRef(!1),A=h??r??"good",y=u.feedback;l.useLayoutEffect(()=>{e?(f(r),p(s)):(f(void 0),p(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const O=R=>{const F=R;F.metaKey||F.altKey||F.ctrlKey||(C.current=!0)},k=()=>{C.current=!1,S(!1)};return m.addEventListener("keydown",O),m.addEventListener("pointerdown",k),()=>{m.removeEventListener("keydown",O),m.removeEventListener("pointerdown",k)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},I=()=>{t()};if(!e)return null;const N={feedback:y.container()};return a.createElement(ft,{portalContainerId:Se.WINDOW,visible:e,onClose:I,"aria-label":c.FEEDBACK_TITLE},a.createElement(K_,null,a.createElement(Y_,null,a.createElement(B,{variant:"h2",color:E.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(W_,null,a.createElement(j_,{...N.feedback.props},["good","bad"].map(O=>{const k=h===O,R=O==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,F=y.button(O,k);return a.createElement(l.Fragment,{key:O},a.createElement(X_,{type:"button",$selected:k,$rating:O,...F.props,onClick:()=>f(O),"data-sb-initial-focus":O===A?"true":void 0},a.createElement(te,{type:k?Rr(O):O,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},R)),F.descriptionNode)}),N.feedback.descriptionNode),i&&a.createElement(Z_,null,a.createElement(B,{variant:"caption3",color:E.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(J_,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:O=>p(O.target.value),onFocus:()=>S(C.current),onBlur:()=>S(!1),maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),a.createElement(Q_,null,a.createElement(eE,{onClick:I},a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(tE,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},K_=_.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,Y_=_.default.div`padding:24px;`,W_=_.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,j_=_.default.div`display:flex;gap:4px;`,X_=_.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)}${is}`,Z_=_.default.label`display:flex;flex-direction:column;gap:6px;`,J_=_.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
+ outline: 2px solid ${E.themedColor.primary};
181
181
  outline-offset: 2px;
182
182
  `}
183
- `,$_=E.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,ya=E.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;`,P_=E.default(ya)`background-color:transparent;${Zr}`,F_=E.default(ya)`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};}`,U_=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=ae(),{conversation:u}=oe(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,C]=l.useState(void 0),[v,p]=l.useState(""),b=l.useRef(null),y=l.useRef(null),A=l.useRef(null),T=l.useRef(!1),R=u.feedback,N=o==null?void 0:o.feedback,k=(N==null?void 0:N.rating)??"none";if(k!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const D=P=>{P&&Ie(()=>{const Y=P==="good"?b.current:y.current;Y==null||Y.focus()})},F=({restoreTrigger:P=!0}={})=>{f(!1),P&&D(A.current)},U=P=>{k==="none"?(C(P),p(""),m(!0)):(A.current=P,f(!0))},q=()=>{i==null||i(null),F()},K=()=>{T.current=!0,F({restoreTrigger:!1}),C(N==null?void 0:N.rating),p((N==null?void 0:N.comment)??""),m(!0)},L=P=>{T.current=!1,i==null||i(P),m(!1),D(A.current)},V=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&k!=="none"?a.createElement(So,{role:"presentation",$horizontal:!0},a.createElement(B_,null,a.createElement(ee,{type:Cr(k),size:12,color:x_[k]})),(N==null?void 0:N.comment)&&a.createElement(yo,{variant:"caption2",style:{lineHeight:"16px"}},N.comment)):a.createElement(a.Fragment,null,a.createElement(So,{role:"presentation"},a.createElement(H_,{role:"presentation"},["good","bad"].map(P=>{const Y=k===P,ge=R.button(P,Y);return a.createElement(l.Fragment,{key:P},a.createElement(G_,{$selected:Y,$rating:P,ref:P==="good"?b:y,...ge.props,onClick:()=>U(P)},a.createElement(ee,{type:Y?Cr(P):P,size:14,color:"currentColor"})),ge.descriptionNode)})),k!=="none"&&(N==null?void 0:N.comment)&&a.createElement(yo,{variant:"caption2"},N.comment)),a.createElement(at,{visible:h,onClose:F,...R.optionsBottomSheet().props},a.createElement(at.ActionItem,{onClick:K,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(at.ActionItem,{onClick:q,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(R_,{visible:d,onClose:V,isEdit:k!=="none",initialRating:g,initialComment:v,onSubmit:L,isCommentEnabled:s}))},So=E.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:${re.BODY_MAX_WIDTH}px;`,B_=E.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,H_=E.default.div`display:flex;gap:2px;`,G_=E.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:${_.themedColor.textMidEmphasis};border:1px solid ${_.color.background200};background-color:transparent;${te.dark`
184
- border: 1px solid ${_.color.background400};
183
+ `,Q_=_.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,wa=_.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;`,eE=_.default(wa)`background-color:transparent;${is}`,tE=_.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};}`,nE=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=ie(),{conversation:u}=ae(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,p]=l.useState(void 0),[v,S]=l.useState(""),C=l.useRef(null),A=l.useRef(null),y=l.useRef(null),T=l.useRef(!1),I=u.feedback,N=o==null?void 0:o.feedback,O=(N==null?void 0:N.rating)??"none";if(O!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const R=q=>{q&&Ie(()=>{const J=q==="good"?C.current:A.current;J==null||J.focus()})},F=({restoreTrigger:q=!0}={})=>{f(!1),q&&R(y.current)},D=q=>{O==="none"?(p(q),S(""),m(!0)):(y.current=q,f(!0))},Q=()=>{i==null||i(null),F()},re=()=>{T.current=!0,F({restoreTrigger:!1}),p(N==null?void 0:N.rating),S((N==null?void 0:N.comment)??""),m(!0)},G=q=>{T.current=!1,i==null||i(q),m(!1),R(y.current)},H=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&O!=="none"?a.createElement(Io,{role:"presentation",$horizontal:!0},a.createElement(rE,null,a.createElement(te,{type:Rr(O),size:12,color:V_[O]})),(N==null?void 0:N.comment)&&a.createElement(xo,{variant:"caption2",style:{lineHeight:"16px"}},N.comment)):a.createElement(a.Fragment,null,a.createElement(Io,{role:"presentation"},a.createElement(sE,{role:"presentation"},["good","bad"].map(q=>{const J=O===q,K=I.button(q,J);return a.createElement(l.Fragment,{key:q},a.createElement(oE,{$selected:J,$rating:q,ref:q==="good"?C:A,...K.props,onClick:()=>D(q)},a.createElement(te,{type:J?Rr(q):q,size:14,color:"currentColor"})),K.descriptionNode)})),O!=="none"&&(N==null?void 0:N.comment)&&a.createElement(xo,{variant:"caption2"},N.comment)),a.createElement(dt,{visible:h,onClose:F,...I.optionsBottomSheet().props},a.createElement(dt.ActionItem,{onClick:re,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(dt.ActionItem,{onClick:Q,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(q_,{visible:d,onClose:H,isEdit:O!=="none",initialRating:g,initialComment:v,onSubmit:G,isCommentEnabled:s}))},Io=_.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:${oe.BODY_MAX_WIDTH}px;`,rE=_.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,sE=_.default.div`display:flex;gap:2px;`,oE=_.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;${ne.dark`
184
+ border: 1px solid ${E.color.background400};
185
185
  `}
186
186
 
187
- ${({$selected:e,$rating:t})=>e&&Sa(t)}
187
+ ${({$selected:e,$rating:t})=>e&&Ma(t)}
188
188
 
189
- ${Zr}
190
- `,yo=E.default(B)`color:${_.themedColor.textMidEmphasis};${te.dark`
191
- color: ${_.themedColor.textHighEmphasis};
189
+ ${is}
190
+ `,xo=_.default(B)`color:${E.themedColor.textMidEmphasis};${ne.dark`
191
+ color: ${E.themedColor.textHighEmphasis};
192
192
  `}
193
- `,Jr=H.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;${Re}&:disabled{cursor:not-allowed;}`,Ao=E.default.button`${Jr};background-color:${_.themedColor.primary};color:${_.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,z_=E.default.button`${Jr};color:${_.themedColor.primary};${te.light`
194
- background-color: ${_.color.background50};
193
+ `,as=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=_.default.button`${as};background-color:${E.themedColor.primary};color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,iE=_.default.button`${as};color:${E.themedColor.primary};${ne.light`
194
+ background-color: ${E.color.background50};
195
195
  `};
196
- ${te.dark`
197
- background-color: ${_.color.background700};
196
+ ${ne.dark`
197
+ background-color: ${E.color.background700};
198
198
  `};
199
199
 
200
200
  &:hover:not(:disabled) {
201
201
  opacity: 0.9;
202
202
  }
203
- `,V_=E.default.button`${Jr};background-color:transparent;color:${_.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,q_=e=>{switch(e){case"primary":return Ao;case"secondary":return z_;case"clear":return V_;default:return Ao}},K_=E.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);}}`,Y_=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return _.themedColor.textHighEmphasisInverse;case"secondary":return _.themedColor.primary;case"clear":return _.themedColor.textHighEmphasis;default:return _.themedColor.textHighEmphasisInverse}},u=q_(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(K_,null,a.createElement(ee,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},W_=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(B,{variant:"caption4",color:_.themedColor.error,className:t,style:n,id:r,role:s},e),j_=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=ae();return a.createElement(B,{id:e,variant:"caption3",color:_.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:_.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},X_=({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,""),C=g.split("."),p=C.length>1?C[0]+"."+C.slice(1).join("").replace(/\./g,""):g;if(h.target.value=p,p===""||p==="-")t==null||t(null);else{const b=Number(p);if(!isNaN(b)){if(c!==void 0&&b>c)return;t==null||t(b)}}},m=e==null?"":String(e);return a.createElement(tE,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},Z_=H.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;${Re}&::placeholder{color:${_.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,J_=H.css`color:${_.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${te.light`
204
- background-color: ${_.color.ondark.textMidEmphasis};
203
+ `,aE=_.default.button`${as};background-color:transparent;color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,cE=e=>{switch(e){case"primary":return Ro;case"secondary":return iE;case"clear":return aE;default:return Ro}},lE=_.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);}}`,uE=({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=cE(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(lE,null,a.createElement(te,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},dE=({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),mE=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=ie();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})`))},hE=({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,""),p=g.split("."),S=p.length>1?p[0]+"."+p.slice(1).join("").replace(/\./g,""):g;if(h.target.value=S,S===""||S==="-")t==null||t(null);else{const C=Number(S);if(!isNaN(C)){if(c!==void 0&&C>c)return;t==null||t(C)}}},m=e==null?"":String(e);return a.createElement(EE,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},fE=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;}`,gE=U.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
204
+ background-color: ${E.color.ondark.textMidEmphasis};
205
205
  `}
206
- ${te.dark`
207
- background-color: ${_.color.onlight.textLowEmphasis};
206
+ ${ne.dark`
207
+ background-color: ${E.color.onlight.textLowEmphasis};
208
208
  `}
209
209
 
210
210
  &::placeholder {
211
- color: ${_.themedColor.textLowEmphasis};
211
+ color: ${E.themedColor.textLowEmphasis};
212
212
  }
213
- `,Q_=H.css`border:1px solid ${_.themedColor.error};color:${_.themedColor.textHighEmphasis};${te.light`
214
- background-color: ${_.color.background50};
213
+ `,pE=U.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${ne.light`
214
+ background-color: ${E.color.background50};
215
215
  `}
216
- ${te.dark`
217
- background-color: ${_.color.onlight.textLowEmphasis};
216
+ ${ne.dark`
217
+ background-color: ${E.color.onlight.textLowEmphasis};
218
218
  `}
219
- `,eE=H.css`border:1px solid ${_.themedColor.textDisabled};color:${_.themedColor.textHighEmphasis};${te.light`
220
- background-color: ${_.color.background50};
219
+ `,_E=U.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${ne.light`
220
+ background-color: ${E.color.background50};
221
221
  `}
222
- ${te.dark`
223
- background-color: ${_.color.onlight.textLowEmphasis};
222
+ ${ne.dark`
223
+ background-color: ${E.color.onlight.textLowEmphasis};
224
224
  `}
225
225
 
226
226
  &:focus {
227
- border-color: ${_.themedColor.primary};
227
+ border-color: ${E.themedColor.primary};
228
228
  }
229
- `,tE=E.default.input`${Z_}${({$error:e,$submitted:t})=>t?J_:e?Q_:eE}`,nE=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))}}}},Aa=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=oe(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=nE(e),m=t.some(h=>u.includes(h.value));return a.createElement(sE,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,f)=>{const g=u.includes(h.value),C=o?`${o}, ${h.label}`:h.label;return a.createElement(dE,{key:h.value,type:"button",$active:g,$submitted:n,$error:r,...(c?i.form.multiSelectOption(C,g,n):i.form.singleSelectOption(C,g,n,f,t.length,m,v=>{const p=t[v];p&&d(p.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:rE(g,n)},h.label))}))},rE=(e,t)=>t?e?_.themedColor.textHighEmphasis:_.themedColor.textDisabled:e?_.themedColor.primary:_.themedColor.textMidEmphasis,sE=E.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,oE=H.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,iE=H.css`cursor:default;background-color:${_.color.ondark.textMidEmphasis};color:${_.themedColor.textHighEmphasis};${te.dark`
229
+ `,EE=_.default.input`${fE}${({$error:e,$submitted:t})=>t?gE:e?pE:_E}`,CE=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}=ae(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=CE(e),m=t.some(h=>u.includes(h.value));return a.createElement(vE,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,f)=>{const g=u.includes(h.value),p=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(p,g,n):i.form.singleSelectOption(p,g,n,f,t.length,m,v=>{const S=t[v];S&&d(S.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:bE(g,n)},h.label))}))},bE=(e,t)=>t?e?E.themedColor.textHighEmphasis:E.themedColor.textDisabled:e?E.themedColor.primary:E.themedColor.textMidEmphasis,vE=_.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,SE=U.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,yE=U.css`cursor:default;background-color:${E.color.ondark.textMidEmphasis};color:${E.themedColor.textHighEmphasis};${ne.dark`
230
230
  background-color: transparent;
231
231
  border: 1px solid white;
232
232
  color: white;
233
233
  `}
234
- `,aE=H.css`cursor:default;${te.light`
235
- background-color: ${_.color.ondark.textMidEmphasis};
236
- color: ${_.themedColor.textDisabled};
234
+ `,AE=U.css`cursor:default;${ne.light`
235
+ background-color: ${E.color.ondark.textMidEmphasis};
236
+ color: ${E.themedColor.textDisabled};
237
237
  `}
238
- ${te.dark`
239
- background-color: ${_.color.onlight.textLowEmphasis};
240
- border: 1px solid ${_.color.onlight.textLowEmphasis};
241
- color: ${_.themedColor.textDisabled};
238
+ ${ne.dark`
239
+ background-color: ${E.color.onlight.textLowEmphasis};
240
+ border: 1px solid ${E.color.onlight.textLowEmphasis};
241
+ color: ${E.themedColor.textDisabled};
242
242
  `}
243
- `,cE=H.css`cursor:pointer;border:1px solid ${_.themedColor.primary};${te.light`
244
- background-color: ${_.color.background50};
245
- color: ${_.themedColor.primary};
243
+ `,TE=U.css`cursor:pointer;border:1px solid ${E.themedColor.primary};${ne.light`
244
+ background-color: ${E.color.background50};
245
+ color: ${E.themedColor.primary};
246
246
  `}
247
- ${te.dark`
248
- background-color: ${_.color.onlight.textLowEmphasis};
249
- color: ${_.themedColor.primary};
247
+ ${ne.dark`
248
+ background-color: ${E.color.onlight.textLowEmphasis};
249
+ color: ${E.themedColor.primary};
250
250
  `}
251
- `,lE=H.css`cursor:pointer;border:1px solid ${_.themedColor.textDisabled};${te.light`
252
- background-color: ${_.color.background50};
253
- color: ${_.themedColor.textMidEmphasis};
251
+ `,IE=U.css`cursor:pointer;border:1px solid ${E.themedColor.textDisabled};${ne.light`
252
+ background-color: ${E.color.background50};
253
+ color: ${E.themedColor.textMidEmphasis};
254
254
  `}
255
- ${te.dark`
256
- background-color: ${_.color.onlight.textLowEmphasis};
257
- color: ${_.themedColor.textMidEmphasis};
255
+ ${ne.dark`
256
+ background-color: ${E.color.onlight.textLowEmphasis};
257
+ color: ${E.themedColor.textMidEmphasis};
258
258
  `}
259
- `,uE=H.css`border-color:${_.themedColor.error}!important;`,dE=E.default.button`${oE}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?iE:aE;const r=e?cE:lE;return n?H.css`
260
- ${r} ${uE}
259
+ `,xE=U.css`border-color:${E.themedColor.error}!important;`,RE=_.default.button`${SE}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?yE:AE;const r=e?TE:IE;return n?U.css`
260
+ ${r} ${xE}
261
261
  `:r}}
262
- `,mE=e=>a.createElement(Aa,{...e,multiple:!1}),hE=e=>a.createElement(Aa,{...e,multiple:!0}),fE=E.default.div`width:100%;height:1px;background-color:${_.themedColor.textDisabled};`,gE=({className:e})=>a.createElement(fE,{className:e}),pE=({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 C=g.target.value;d&&C.length>d||n==null||n(C)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(EE,{...f}):a.createElement(_E,{...f})},Ta=H.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;${Re}&::placeholder{color:${_.themedColor.textLowEmphasis};}`,Ia=H.css`color:${_.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${te.light`
263
- background-color: ${_.color.ondark.textMidEmphasis};
262
+ `,ME=e=>a.createElement(ka,{...e,multiple:!1}),wE=e=>a.createElement(ka,{...e,multiple:!0}),kE=_.default.div`width:100%;height:1px;background-color:${E.themedColor.textDisabled};`,LE=({className:e})=>a.createElement(kE,{className:e}),OE=({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 p=g.target.value;d&&p.length>d||n==null||n(p)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(DE,{...f}):a.createElement(NE,{...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;${ne.light`
263
+ background-color: ${E.color.ondark.textMidEmphasis};
264
264
  `}
265
- ${te.dark`
266
- background-color: ${_.color.onlight.textLowEmphasis};
265
+ ${ne.dark`
266
+ background-color: ${E.color.onlight.textLowEmphasis};
267
267
  `}
268
268
 
269
269
  &::placeholder {
270
- color: ${_.themedColor.textLowEmphasis};
270
+ color: ${E.themedColor.textLowEmphasis};
271
271
  }
272
- `,xa=H.css`border:1px solid ${_.themedColor.error};color:${_.themedColor.textHighEmphasis};${te.light`
273
- background-color: ${_.color.background50};
272
+ `,Na=U.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${ne.light`
273
+ background-color: ${E.color.background50};
274
274
  `}
275
- ${te.dark`
276
- background-color: ${_.color.onlight.textLowEmphasis};
275
+ ${ne.dark`
276
+ background-color: ${E.color.onlight.textLowEmphasis};
277
277
  `}
278
- `,Ra=H.css`border:1px solid ${_.themedColor.textDisabled};color:${_.themedColor.textHighEmphasis};${te.light`
279
- background-color: ${_.color.background50};
278
+ `,Da=U.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${ne.light`
279
+ background-color: ${E.color.background50};
280
280
  `}
281
- ${te.dark`
282
- background-color: ${_.color.onlight.textLowEmphasis};
281
+ ${ne.dark`
282
+ background-color: ${E.color.onlight.textLowEmphasis};
283
283
  `}
284
284
 
285
285
  &:focus {
286
- border-color: ${_.themedColor.primary};
286
+ border-color: ${E.themedColor.primary};
287
287
  }
288
- `,_E=E.default.input`${Ta};height:36px;${({$error:e,$submitted:t})=>t?Ia:e?xa:Ra}`,EE=E.default.textarea`${Ta};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Ia:e?xa:Ra}`,CE=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:_.themedColor.textHighEmphasis,className:t,style:n},e),Le={Title:CE,Label:j_,ErrorLabel:W_,Separator:gE,Button:Y_,TextInput:pE,NumberInput:X_,SingleSelect:mE,MultiSelect:hE},bE=1,vE=new Set(["text","number","single-select","multi-select"]),Ma=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,SE=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Ma||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},yE=e=>{var b,y;const t=(b=e.extendedMessagePayload)==null?void 0:b.form;if(SE({messageForm:t,onError:(y=e.statsCallbacks)==null?void 0:y.onFormRenderError}),!Ma)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=ae(),{conversation:r}=oe(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=pm(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",C=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}))}},v=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}))}},p=l.useMemo(()=>{const A=()=>t.version>bE,T=()=>t.fields.some(R=>!vE.has(R.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:p.visible?a.createElement(l.Fragment,null,a.createElement(To,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(Le.Title,null,t.title),a.createElement(AE,null,d.map(A=>a.createElement(TE,{key:A.key},a.createElement(Le.Label,{style:{marginBottom:"6px"},required:A.required},A.label),A.type==="text"&&a.createElement(Le.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(Le.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(Le.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(Le.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(Le.ErrorLabel,{style:{marginTop:"4px"}},A.error)))),a.createElement(Le.Separator,null),a.createElement(IE,null,a.createElement(Le.Button,{variant:g?"clear":"primary",...r.form.button(g?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:C,disabled:g||s.canceling,loading:s.submitting},g?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&a.createElement(Le.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(Nn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(To,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},p.reason),p.cancelable&&a.createElement(Le.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,loading:s.canceling},n.BUTTON__CANCEL))},To=E.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>H.css`
288
+ `,NE=_.default.input`${La};height:36px;${({$error:e,$submitted:t})=>t?Oa:e?Na:Da}`,DE=_.default.textarea`${La};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Oa:e?Na:Da}`,$E=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis,className:t,style:n},e),ke={Title:$E,Label:mE,ErrorLabel:dE,Separator:LE,Button:uE,TextInput:OE,NumberInput:hE,SingleSelect:ME,MultiSelect:wE},PE=1,FE=new Set(["text","number","single-select","multi-select"]),$a=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,UE=({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])},BE=e=>{var C,A;const t=(C=e.extendedMessagePayload)==null?void 0:C.form;if(UE({messageForm:t,onError:(A=e.statsCallbacks)==null?void 0:A.onFormRenderError}),!$a)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=ie(),{conversation:r}=ae(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=Mm(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:y=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:y})},onCancel:()=>{var y;return(y=e.onCancelForm)==null?void 0:y.call(e,{key:t.key})}}),g=u==="submitted",p=async()=>{o(y=>({...y,submitting:!0}));try{await m()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,submitting:!1}))}},v=async()=>{o(y=>({...y,canceling:!0}));try{await h()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,canceling:!1}))}},S=l.useMemo(()=>{const y=()=>t.version>PE,T=()=>t.fields.some(I=>!FE.has(I.type));return y()||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:S.visible?a.createElement(l.Fragment,null,a.createElement(Mo,{$maxWidth:e.maxBodyWidth??oe.BODY_MAX_WIDTH},a.createElement(ke.Title,null,t.title),a.createElement(HE,null,d.map(y=>a.createElement(GE,{key:y.key},a.createElement(ke.Label,{style:{marginBottom:"6px"},required:y.required},y.label),y.type==="text"&&a.createElement(ke.TextInput,{value:y.value||"",placeholder:y.placeholder,onChange:T=>f(y.key,T),disabled:g,error:!!y.error,submitted:g,variant:y.layout==="multiline"?"multi-line":"single-line",maxLength:y.maxLength,...r.form.textInput(y.label,y.required??!1,g).props}),y.type==="number"&&a.createElement(ke.NumberInput,{value:y.value||null,placeholder:y.placeholder,onChange:T=>f(y.key,T),disabled:g,error:!!y.error,submitted:g,max:y.max,...r.form.numberInput(y.label,y.required??!1,g).props}),y.type==="single-select"&&a.createElement(ke.SingleSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||"",onChange:T=>f(y.key,T),submitted:g,groupLabel:y.label}),y.type==="multi-select"&&a.createElement(ke.MultiSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||[],onChange:T=>f(y.key,T),submitted:g,maxSelect:y.maxSelect,groupLabel:y.label}),y.error&&a.createElement(ke.ErrorLabel,{style:{marginTop:"4px"}},y.error)))),a.createElement(ke.Separator,null),a.createElement(zE,null,a.createElement(ke.Button,{variant:g?"clear":"primary",...r.form.button(g?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:p,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:v,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(Fn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Mo,{$maxWidth:e.maxBodyWidth??oe.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},S.reason),S.cancelable&&a.createElement(ke.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,loading:s.canceling},n.BUTTON__CANCEL))},Mo=_.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
- `,AE=E.default.div`display:flex;flex-direction:column;gap:12px;`,TE=E.default.div`display:flex;flex-direction:column;`,IE=E.default.div`display:flex;flex-direction:column;gap:8px;`,xE=e=>a.createElement(a.Fragment,null),br=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,RE=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(br||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},ME=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return RE({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),br?a.createElement(Ht,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(br,{...e})):null},wE=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=oe(),[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(kE,{id:`${Je}-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(LE,{$type:n,...h.props,onClick:()=>u(d)},a.createElement(OE,{variant:"body3"},d)),h.descriptionNode)}))},kE=E.default.div`margin:16px 0;padding:0 ${re.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?NE:DE};`,LE=E.default.button.attrs({type:"button"})`
295
+ `,HE=_.default.div`display:flex;flex-direction:column;gap:12px;`,GE=_.default.div`display:flex;flex-direction:column;`,zE=_.default.div`display:flex;flex-direction:column;gap:8px;`,VE=e=>a.createElement(a.Fragment,null),Mr=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,qE=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Mr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},KE=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return qE({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),Mr?a.createElement(Kt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(Mr,{...e})):null},YE=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=ae(),[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(WE,{id:`${ot}-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(jE,{$type:n,...h.props,onClick:()=>u(d)},a.createElement(XE,{variant:"body3"},d)),h.descriptionNode)}))},WE=_.default.div`margin:16px 0;padding:0 ${oe.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?ZE:JE};`,jE=_.default.button.attrs({type:"button"})`
296
296
  all: unset;
297
297
  box-sizing: border-box;
298
298
  padding: 8px 12px;
@@ -302,84 +302,84 @@
302
302
  border-radius: 20px / clamp(20px, 5%, 100px);
303
303
  cursor: pointer;
304
304
  word-break: break-word;
305
- color: ${_.color.primary.main};
306
- border: 1px solid ${_.color.primary.main};
307
- background-color: ${_.themedColor.bg_50_600};
305
+ color: ${E.color.primary.main};
306
+ border: 1px solid ${E.color.primary.main};
307
+ background-color: ${E.themedColor.bg_50_600};
308
308
 
309
309
  &:hover {
310
- background-color: ${_.themedColor.bg_100_500};
310
+ background-color: ${E.themedColor.bg_100_500};
311
311
  }
312
312
 
313
- ${Re}
313
+ ${xe}
314
314
 
315
- ${({$type:e,theme:t})=>H.css`${e==="vertical"?$E:PE};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
316
- `,OE=E.default(B)`color:inherit;`,NE=H.css`flex-direction:column;align-items:flex-end;`,DE=H.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,$E=H.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,PE=H.css`white-space:nowrap;`,FE=e=>{const{components:t}=pt.useContext(),{stringSet:n}=ae(),r=Zo(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})},UE=e=>{var A,T,R,N,k;const{components:t}=pt.useContext(),{streamText:n,isAnimating:r}=Mm({text:e.message,enabled:e.isStreaming,snapOnDisable:((A=e.extendedMessagePayload)==null?void 0:A.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onVisibleTextProgress:(T=e.statsCallbacks)==null?void 0:T.onVisibleTextProgress,onRenderedTextProgress:(R=e.statsCallbacks)==null?void 0:R.onRenderedTextProgress}),s={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},o=!!s.isTyping,i=!!s.isSenderAvatarVisible,c=In(s.extendedMessagePayload),u=c.hasCTAButton,d=c.hasChallenge,m=c.hasCitations,h=c.hasForm,f=c.hasMessageTemplate,g=!!s.createdAt,C=u||m,v=s.groupType==="top"||s.groupType==="single",p=s.groupType==="bottom"||s.groupType==="single",b=i?re.AVATAR_SIZE:0,y=C&&a.createElement(l.Fragment,null,u&&a.createElement(HE,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...s})),m&&a.createElement(t.Citation,{...s}));return a.createElement(BE,{$marginBottom:o?0:xn(s.groupType)},v&&a.createElement(GE,null,i&&a.createElement(t.SenderAvatar,{...s}),a.createElement(t.SenderName,{...s})),a.createElement(VE,null,a.createElement(nr,{$extraStartPadding:b},o?a.createElement(t.TypingIndicator,{...s}):a.createElement(t.MessageBody,{...s},y)),f&&a.createElement(Io,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??a.createElement(nr,{$extraStartPadding:b},a.createElement(t.MessageBody,{...s,messageType:"user",message:((k=(N=s.extendedMessagePayload)==null?void 0:N.message_template)==null?void 0:k.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??a.createElement(nr,{$extraStartPadding:b},a.createElement(t.TypingIndicator,{...s}))})),a.createElement(t.CustomMessageTemplate,{...s}),d&&a.createElement(t.Challenge,{...s}),h&&a.createElement(Io,{$extraStartPadding:b},a.createElement(t.Form,{...s}))),a.createElement(t.MessageLogs,{...s}),p&&g&&a.createElement(zE,{$extraStartPadding:b+8},a.createElement(t.SentTime,{...s})),a.createElement(l.Fragment,null,!o&&a.createElement(Xt,{$extraStartPadding:b+8},a.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...s})))},pt=qe({template:UE,components:{SenderName:o_,SenderAvatar:r_,SentTime:a_,MessageBody:FE,TextMessageBody:Qp,MediaMessageBody:$p,FileMessageBody:Op,MultipleFilesMessageBody:Wp,TypingIndicator:l_,SuggestedReplies:wE,MessageTemplate:ME,CustomMessageTemplate:T_,Challenge:E_,CTAButton:g_,Citation:C_,Form:yE,Feedback:U_,MessageLogs:xE}}),BE=E.default.div.attrs({role:"presentation"})`
315
+ ${({$type:e,theme:t})=>U.css`${e==="vertical"?QE:eC};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
316
+ `,XE=_.default(B)`color:inherit;`,ZE=U.css`flex-direction:column;align-items:flex-end;`,JE=U.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,QE=U.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,eC=U.css`white-space:nowrap;`,tC=e=>{const{components:t}=Ct.useContext(),{stringSet:n}=ie(),r=ni(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})},nC=e=>{var T,I,N,O,k;const{components:t}=Ct.useContext(),{streamText:n,isAnimating:r,isHolding:s}=Km({text:e.message,enabled:e.isStreaming,snapOnDisable:((T=e.extendedMessagePayload)==null?void 0:T.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onAnimationHoldChange:e.onStreamAnimationHoldChange,onVisibleTextProgress:(I=e.statsCallbacks)==null?void 0:I.onVisibleTextProgress,onRenderedTextProgress:(N=e.statsCallbacks)==null?void 0:N.onRenderedTextProgress});if(s)return null;const o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},i=!!o.isTyping,c=!!o.isSenderAvatarVisible,u=Wt(o.extendedMessagePayload),d=u.hasCTAButton,m=u.hasChallenge,h=u.hasCitations,f=u.hasForm,g=u.hasMessageTemplate,p=!!o.createdAt,v=d||h,S=o.groupType==="top"||o.groupType==="single",C=o.groupType==="bottom"||o.groupType==="single",A=c?oe.AVATAR_SIZE:0,y=v&&a.createElement(l.Fragment,null,d&&a.createElement(sC,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...o})),h&&a.createElement(t.Citation,{...o}));return a.createElement(rC,{$marginBottom:i?0:kn(o.groupType)},S&&a.createElement(oC,null,c&&a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(aC,null,a.createElement(ur,{$extraStartPadding:A},i?a.createElement(t.TypingIndicator,{...o}):a.createElement(t.MessageBody,{...o},y)),g&&a.createElement(wo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(ur,{$extraStartPadding:A},a.createElement(t.MessageBody,{...o,messageType:"user",message:((k=(O=o.extendedMessagePayload)==null?void 0:O.message_template)==null?void 0:k.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??a.createElement(ur,{$extraStartPadding:A},a.createElement(t.TypingIndicator,{...o}))})),a.createElement(t.CustomMessageTemplate,{...o}),m&&a.createElement(t.Challenge,{...o}),f&&a.createElement(wo,{$extraStartPadding:A},a.createElement(t.Form,{...o}))),a.createElement(t.MessageLogs,{...o}),C&&p&&a.createElement(iC,{$extraStartPadding:A+8},a.createElement(t.SentTime,{...o})),a.createElement(l.Fragment,null,!i&&a.createElement(tn,{$extraStartPadding:A+8},a.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},Ct=je({template:nC,components:{SenderName:S_,SenderAvatar:b_,SentTime:A_,MessageBody:tC,TextMessageBody:p_,MediaMessageBody:Qp,FileMessageBody:Xp,MultipleFilesMessageBody:d_,TypingIndicator:I_,SuggestedReplies:YE,MessageTemplate:KE,CustomMessageTemplate:G_,Challenge:D_,CTAButton:L_,Citation:$_,Form:BE,Feedback:nE,MessageLogs:VE}}),rC=_.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
- `,Xt=E.default.div.attrs({role:"presentation"})`
321
+ `,tn=_.default.div.attrs({role:"presentation"})`
322
322
  display: flex;
323
323
  align-self: stretch;
324
324
  justify-content: flex-start;
325
- ${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
325
+ ${({$startPadding:e=oe.HORIZONTAL_PADDING,$endPadding:t=oe.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
326
326
  padding-inline: ${e+n}px ${t}px;
327
327
  `}
328
- `,HE=E.default.div.attrs({role:"presentation"})`
328
+ `,sC=_.default.div.attrs({role:"presentation"})`
329
329
  display: flex;
330
330
  flex-direction: column;
331
331
  min-width: 0;
332
- ${({$marginTop:e=0,$paddingInline:t=0})=>H.css`margin-top:${e}px;padding-inline:${t}px;`}
333
- `,GE=E.default(Xt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,nr=E.default(Xt)`display:flex;`,zE=E.default(Xt)`margin-top:${re.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Io=E.default(Xt).attrs({role:"presentation"})`
332
+ ${({$marginTop:e=0,$paddingInline:t=0})=>U.css`margin-top:${e}px;padding-inline:${t}px;`}
333
+ `,oC=_.default(tn)`display:flex;flex-direction:row;align-items:center;gap:8px;`,ur=_.default(tn)`display:flex;`,iC=_.default(tn)`margin-top:${oe.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,wo=_.default(tn).attrs({role:"presentation"})`
334
334
  display: flex;
335
- ${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
335
+ ${({$startPadding:e=oe.HORIZONTAL_PADDING,$endPadding:t=oe.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
336
336
  padding-inline: ${e+n}px ${t}px;
337
337
  `}
338
- `,VE=E.default.div.attrs({role:"presentation"})`
338
+ `,aC=_.default.div.attrs({role:"presentation"})`
339
339
  display: flex;
340
340
  flex-direction: column;
341
341
  min-width: 0;
342
342
  max-width: 100%;
343
- gap: ${re.GAP_GROUPED}px;
344
- `;function qE({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(KE,null,a.createElement(Xr,{name:e.name,mimeType:e.type,type:Tr(e.name,e.type),onClick:s}),t)}const KE=E.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`;function YE({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=oe(),{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}),C={...g.props,$ratio:c,$clickable:!!f};return a.createElement(WE,null,a.createElement(jE,{...C},!m&&a.createElement(gt,{size:26},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement(XE,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const WE=E.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,jE=E.default.div`width:${re.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;${te.light`
345
- background-color: ${_.color.background100};
343
+ gap: ${oe.GAP_GROUPED}px;
344
+ `;function cC({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(lC,null,a.createElement(os,{name:e.name,mimeType:e.type,type:Nr(e.name,e.type),onClick:s}),t)}const lC=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${oe.GAP_GROUPED}px;`;function uC({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=ae(),{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}),p={...g.props,$ratio:c,$clickable:!!f};return a.createElement(dC,null,a.createElement(mC,{...p},!m&&a.createElement(Et,{size:26},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement(hC,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const dC=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${oe.GAP_GROUPED}px;`,mC=_.default.div`width:${oe.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;${ne.light`
345
+ background-color: ${E.color.background100};
346
346
  `}
347
- ${te.dark`
348
- background-color: ${_.color.background400};
347
+ ${ne.dark`
348
+ background-color: ${E.color.background400};
349
349
  `}
350
- `,XE=E.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;`,ZE=({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(JE,null,a.createElement(pa,{images:i,isPending:c,onClickImage:d}),o)},JE=E.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`;function QE(e){var n,r;const t=l.useMemo(()=>{const s=Zp(Ea(e.message));return zo.default.sanitize(s)},[e.message]);return a.createElement(eC,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(tC,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const eC=E.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>H.css`
350
+ `,hC=_.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;`,fC=({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(gC,null,a.createElement(ya,{images:i,isPending:c,onClickImage:d}),o)},gC=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${oe.GAP_GROUPED}px;`;function pC(e){var n,r;const t=l.useMemo(()=>{const s=f_(Ta(e.message));return Wo.default.sanitize(s)},[e.message]);return a.createElement(_C,{$maxWidth:e.maxBodyWidth??oe.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(EC,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const _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`
351
351
  color: ${t||e.colors.messageOutgoing.text};
352
352
  background-color: ${n||e.colors.messageOutgoing.background};
353
353
  `}
354
354
  padding: 12px 0;
355
355
  transition: max-width 0.3s;
356
356
  overflow-wrap: break-word;
357
- `,tC=E.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,nC=({sendingStatus:e})=>{const t=H.useTheme();switch(e){case"pending":return a.createElement(rC,{size:16},a.createElement(ee,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(ee,{type:"error",color:_.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(ee,{type:"done",color:_.themedColor.secondary,size:16}))}},rC=E.default(gt)`margin-bottom:2px;width:16px;height:16px;`,sC=({createdAt:e})=>{const{stringSet:t,format:n}=ae();return e?a.createElement(B,{variant:"caption4",color:_.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},oC=e=>{const{components:t}=Rt.useContext(),{stringSet:n}=ae(),r=()=>{const i=Zo(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())},iC=e=>a.createElement(a.Fragment,null),aC=e=>{const{components:t}=Rt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(cC,{$marginBottom:xn(e.groupType)},a.createElement(lC,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(uC,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Rt=qe({template:aC,components:{SendingStatus:nC,SentTime:sC,MessageBody:oC,TextMessageBody:QE,MediaMessageBody:YE,FileMessageBody:qE,MultipleFilesMessageBody:ZE,MessageLogs:iC}}),cC=E.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
358
- `,wa=E.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
359
- `,lC=E.default(wa)``,uC=E.default(wa)`margin-top:${re.BODY_TIME_GAP}px;`,dC=e=>e.messageType!=="admin"?null:a.createElement(mC,null,a.createElement(B,{variant:"caption2",color:_.themedColor.textMidEmphasis},hC(zo.default.sanitize(e.message),e.onClickLink))),mC=E.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${re.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,hC=(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:Gr,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]}},fC=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,ka=({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(fC({direction:f,currentIndex:h,totalCount:e.length}))}})}},gC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},pC=({event:e,onClick:t,onArrowNavigate:n})=>{if(_C(e))return;const r=gC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},_C=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Qr=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?_.themedColor.primary:r?_.themedColor.textDisabled:_.themedColor.textLowEmphasis,m=t?_.themedColor.textHighEmphasis:r?_.themedColor.textLowEmphasis:_.themedColor.textHighEmphasis;return a.createElement(bC,{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=>pC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(EC,{"aria-hidden":"true"},a.createElement(ee,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(CC,{"aria-hidden":"true",variant:o,color:m},n))});Qr.displayName="Radio";const EC=E.default.div`width:20px;height:20px;`,CC=E.default(B)`line-height:20px;word-break:break-word;`,bC=E.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Re}&[aria-disabled='false']{cursor:pointer;}`,vC=({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=ka({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(SC,null,a.createElement(Le.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(yC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(Qr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},SC=E.default.div`display:flex;flex-direction:column;gap:8px;`,yC=E.default.div`display:flex;flex-direction:column;gap:8px;`,AC=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=ae(),{conversation:i}=oe(),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=ka({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(TC,null,a.createElement(Le.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Le.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(IC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(Qr,{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(xC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},TC=E.default.div`display:flex;flex-direction:column;gap:8px;`,IC=E.default.div`display:flex;flex-direction:column;gap:8px;`,xC=E.default(Le.ErrorLabel)``,RC=({value:e,selected:t})=>a.createElement(MC,{$selected:t,"aria-hidden":"true"},wC[e-1]),MC=E.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,wC=[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)"}))))],kC=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=oe(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(OC,null,a.createElement(B,{variant:"caption3",color:_.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(NC,{...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(DC,{key:d,type:"button",...g.props},a.createElement(LC,{value:m,selected:s||h,src:u}),!!c&&a.createElement(B,{"aria-hidden":"true",color:h?_.themedColor.textHighEmphasis:_.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},LC=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(RC,{value:e,selected:n}):a.createElement(PC,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement($C,null,o)},OC=E.default.div`display:flex;flex-direction:column;gap:8px;`,NC=E.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,DC=E.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;${Re}&:not(:disabled):hover span{color:${_.themedColor.textHighEmphasis};}`,$C=E.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${_.color.background200};${te.dark`
360
- background-color: ${_.color.background500};
357
+ `,EC=_.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,CC=({sendingStatus:e})=>{const t=U.useTheme();switch(e){case"pending":return a.createElement(bC,{size:16},a.createElement(te,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"error",color:E.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"done",color:E.themedColor.secondary,size:16}))}},bC=_.default(Et)`margin-bottom:2px;width:16px;height:16px;`,vC=({createdAt:e})=>{const{stringSet:t,format:n}=ie();return e?a.createElement(B,{variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},SC=e=>{const{components:t}=Ot.useContext(),{stringSet:n}=ie(),r=()=>{const i=ni(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?Bt({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())},yC=e=>a.createElement(a.Fragment,null),AC=e=>{const{components:t}=Ot.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(TC,{$marginBottom:kn(e.groupType)},a.createElement(IC,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(xC,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Ot=je({template:AC,components:{SendingStatus:CC,SentTime:vC,MessageBody:SC,TextMessageBody:pC,MediaMessageBody:uC,FileMessageBody:cC,MultipleFilesMessageBody:fC,MessageLogs:yC}}),TC=_.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
358
+ `,Pa=_.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=oe.HORIZONTAL_PADDING,$endPadding:t=oe.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
359
+ `,IC=_.default(Pa)``,xC=_.default(Pa)`margin-top:${oe.BODY_TIME_GAP}px;`,RC=e=>e.messageType!=="admin"?null:a.createElement(MC,null,a.createElement(B,{variant:"caption2",color:E.themedColor.textMidEmphasis},wC(Wo.default.sanitize(e.message),e.onClickLink))),MC=_.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${oe.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,wC=(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]}},kC=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Fa=({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(kC({direction:f,currentIndex:h,totalCount:e.length}))}})}},LC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},OC=({event:e,onClick:t,onArrowNavigate:n})=>{if(NC(e))return;const r=LC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},NC=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",cs=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(PC,{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=>OC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(DC,{"aria-hidden":"true"},a.createElement(te,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement($C,{"aria-hidden":"true",variant:o,color:m},n))});cs.displayName="Radio";const DC=_.default.div`width:20px;height:20px;`,$C=_.default(B)`line-height:20px;word-break:break-word;`,PC=_.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=Fa({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(UC,null,a.createElement(ke.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(BC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(cs,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},UC=_.default.div`display:flex;flex-direction:column;gap:8px;`,BC=_.default.div`display:flex;flex-direction:column;gap:8px;`,HC=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=ie(),{conversation:i}=ae(),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=Fa({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(GC,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(zC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(cs,{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(VC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},GC=_.default.div`display:flex;flex-direction:column;gap:8px;`,zC=_.default.div`display:flex;flex-direction:column;gap:8px;`,VC=_.default(ke.ErrorLabel)``,qC=({value:e,selected:t})=>a.createElement(KC,{$selected:t,"aria-hidden":"true"},YC[e-1]),KC=_.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)"}))))],WC=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=ae(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(XC,null,a.createElement(B,{variant:"caption3",color:E.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(ZC,{...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(JC,{key:d,type:"button",...g.props},a.createElement(jC,{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)})))},jC=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(qC,{value:e,selected:n}):a.createElement(eb,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(QC,null,o)},XC=_.default.div`display:flex;flex-direction:column;gap:8px;`,ZC=_.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,JC=_.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};}`,QC=_.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${E.color.background200};${ne.dark`
360
+ background-color: ${E.color.background500};
361
361
  `}
362
362
  }
363
- `,PC=E.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,FC=({csatPayload:e})=>a.createElement(B,{variant:"button",color:_.themedColor.textHighEmphasis},e.title),rr=({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}=Am({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(UC,null,a.createElement(FC,{...g}),t===je.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(vC,{...g,defaultValue:o,value:i.isResolved,onChange:C=>c({isResolved:C})}),a.createElement(kC,{...g,value:i.csat,onChange:C=>c({csat:C})}),m&&a.createElement(AC,{...g,followUpItem:m,value:i.csatReason,onChange:C=>{c({csatReason:C}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Le.Separator,null),n({state:h,params:i,validateParams:f})))},UC=E.default.div`display:flex;flex-direction:column;gap:12px;`,BC=e=>{const{stringSet:t}=ae();return Jc(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})},HC=()=>{const{stringSet:e}=ae();return a.createElement(B,{variant:"body2",color:_.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},GC=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Ie(e)},[]),t),zC=e=>{const{conversation:t}=oe();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=wn(),m=BC(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,C]=l.useState(!1),v=l.useRef(!1),p=l.useCallback(()=>{Ie(()=>{var R;return(R=f.current)==null?void 0:R.focus()})},[]),{isExpiredNow:b,isRenderableCSAT:y}=Tm({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(Sm({csat:o,csatPayload:m,isRenderableCSAT:y,isExpiredNow:b,announceStatus:e.announceStatus,onSubmittedAnnounced:p}),!y||!m)return null;const A=()=>{var N;const R=(N=h.current)==null?void 0:N.querySelector('[aria-invalid="true"]');return R?R.getAttribute("role")==="radiogroup"?R.querySelector('[role="radio"]'):R:null},T=m.type===je.AI_AGENT_CSAT_5||m.type===je.AI_AGENT_CSAT_5_WITH_CRE||m.type===je.HELPDESK_CSAT_5?rr:()=>null;return a.createElement(VC,{ref:h},!o&&b?a.createElement(HC,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:R,params:N,validateParams:k})=>R==="submitted"?a.createElement(KC,{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(GC,{onMount:s},a.createElement(qC,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(v.current)return;const x=ni(c);if(!x&&k()){v.current=!0,C(!0);try{await r(N)}catch(D){throw v.current=!1,C(!1),D}}else d(),x||Ie(()=>{var D;(D=e.announceError)==null||D.call(e,{type:"csatFormError"},A())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},VC=E.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,qC=E.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;${Re}&:hover{background-color:${_.color.primary.dark};}`,KC=E.default.div`width:100%;box-sizing:border-box;color:${_.themedColor.textHighEmphasis};background-color:${_.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${te.dark`
364
- background-color: ${_.color.onlight.textDisabled};
363
+ `,eb=_.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,tb=({csatPayload:e})=>a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},e.title),dr=({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}=Bm({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(nb,null,a.createElement(tb,{...g}),t===et.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(FC,{...g,defaultValue:o,value:i.isResolved,onChange:p=>c({isResolved:p})}),a.createElement(WC,{...g,value:i.csat,onChange:p=>c({csat:p})}),m&&a.createElement(HC,{...g,followUpItem:m,value:i.csatReason,onChange:p=>{c({csatReason:p}),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})))},nb=_.default.div`display:flex;flex-direction:column;gap:12px;`,rb=e=>{const{stringSet:t}=ie();return ml(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})},sb=()=>{const{stringSet:e}=ie();return a.createElement(B,{variant:"body2",color:E.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},ob=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Ie(e)},[]),t),ib=e=>{const{conversation:t}=ae();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=rb(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,p]=l.useState(!1),v=l.useRef(!1),S=l.useCallback(()=>{Ie(()=>{var I;return(I=f.current)==null?void 0:I.focus()})},[]),{isExpiredNow:C,isRenderableCSAT:A}=Hm({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(Fm({csat:o,csatPayload:m,isRenderableCSAT:A,isExpiredNow:C,announceStatus:e.announceStatus,onSubmittedAnnounced:S}),!A||!m)return null;const y=()=>{var N;const I=(N=h.current)==null?void 0:N.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},T=m.type===et.AI_AGENT_CSAT_5||m.type===et.AI_AGENT_CSAT_5_WITH_CRE||m.type===et.HELPDESK_CSAT_5?dr:()=>null;return a.createElement(ab,{ref:h},!o&&C?a.createElement(sb,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:I,params:N,validateParams:O})=>I==="submitted"?a.createElement(lb,{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(ob,{onMount:s},a.createElement(cb,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(v.current)return;const k=ai(c);if(!k&&O()){v.current=!0,p(!0);try{await r(N)}catch(R){throw v.current=!1,p(!1),R}}else d(),k||Ie(()=>{var R;(R=e.announceError)==null||R.call(e,{type:"csatFormError"},y())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},ab=_.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,cb=_.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};}`,lb=_.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;${ne.dark`
364
+ background-color: ${E.color.onlight.textDisabled};
365
365
  `}
366
- `,YC=e=>{const{components:t}=Pn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(WC,{$marginBottom:xn(e.groupType)},n)},Pn=qe({template:YC,components:{AdminMessage:dC,CSATMessage:zC}}),WC=E.default.div`padding-inline:${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,es=({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(QC,{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)??_.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(eb,{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)??_.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(jC,null,a.createElement(XC,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??_.themedColor.textHighEmphasis},e)),a.createElement(ZC,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??_.themedColor.textMidEmphasis},n)),a.createElement(JC,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},jC=E.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,XC=E.default.div`padding:24px 24px 16px;`,ZC=E.default.div`padding-inline:24px;`,JC=E.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;`,QC=E.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;}`,eb=E.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??_.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,cn=16,tb=({status:e})=>e===pn.COMPLETED?a.createElement(ee,{type:"done-circle",size:cn,color:_.themedColor.textHighEmphasis}):e===pn.CANCELED?a.createElement(ee,{type:"stop-circle",size:cn,color:_.themedColor.textLowEmphasis}):a.createElement(gt,{size:cn},a.createElement(ee,{type:"spinner",size:cn,color:_.themedColor.textHighEmphasis})),La=24,nb=8,rb=40,sb=({task:e,isFirst:t,isLast:n})=>a.createElement(ob,{role:"listitem"},a.createElement(ib,null,a.createElement(xo,{$hidden:t}),a.createElement(ab,null,a.createElement(tb,{status:e.status})),a.createElement(xo,{$hidden:n})),a.createElement(cb,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===pn.CANCELED?_.themedColor.textLowEmphasis:_.themedColor.textHighEmphasis},e.user_facing_title))),ob=E.default.div`display:flex;gap:4px;`,ib=E.default.div`display:flex;flex-direction:column;align-items:center;width:${La}px;flex-shrink:0;`,xo=E.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${_.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,ab=E.default.div`display:flex;height:${La}px;align-items:center;justify-content:center;`,cb=E.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${rb}px;padding-block:${nb}px;`,lb=({steward:e,onCancelSteward:t})=>{const{logger:n}=me(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=_c(e.status);return a.createElement(ub,{$marginBottom:xn("single")},a.createElement(db,null,a.createElement(mb,null,a.createElement(hb,null,a.createElement(B,{as:"div",variant:"caption1",color:_.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(B,{as:"div",variant:"caption4",color:_.themedColor.textLowEmphasis},e.description)),c&&a.createElement(_b,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(ee,{type:"stop",size:16,color:o?_.themedColor.textDisabled:_.themedColor.textHighEmphasis}))),a.createElement(fb,null),e.tasks.length===0?u!==Ft.IN_PROGRESS?null:a.createElement(pb,null,a.createElement(gt,{size:16},a.createElement(ee,{type:"spinner",size:16,color:_.themedColor.textHighEmphasis}))):a.createElement(gb,{role:"list"},e.tasks.map((d,m)=>a.createElement(sb,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(lt,{portalContainerId:Se.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(es,{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)}}})))},ub=E.default.div`display:flex;flex-direction:column;margin:0 ${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
367
- `,db=E.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${_.themedColor.bg_300_500};background-color:${_.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,mb=E.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,hb=E.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,fb=E.default.div`height:1px;margin-block:12px;background-color:${_.themedColor.bg_200_400};`,gb=E.default.div`display:flex;flex-direction:column;`,pb=E.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,_b=E.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:${_.themedColor.textHighEmphasis};background-color:${_.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,Eb=({className:e,label:t,onClick:n})=>{const{colors:r}=H.useTheme(),{conversation:s}=oe(),o={newMessages:s.newMessagesButton()};return a.createElement(Cb,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(ee,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},Cb=E.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;}${Re}`,ts=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(vb,{className:n},t&&a.createElement(ee,{type:t,size:e,color:_.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:_.themedColor.textMidEmphasis},r),s),bb=E.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,vb=E.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,Sb=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(ts,{icon:t,label:e,...r},n&&a.createElement(yb,{onClick:n.onClick,label:n.label??"Retry"})),yb=({label:e,onClick:t})=>{const{conversation:n}=oe();return a.createElement(Ab,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(ee,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:_.color.primary.main},e))},Ab=E.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Re}`,Tb=({iconSize:e=48,className:t})=>a.createElement(gt,{size:e,className:t}),Ib=({label:e="No channels",icon:t="chat",...n})=>a.createElement(ts,{icon:t,label:e,...n}),xb=({label:e="No messages",icon:t="message",...n})=>a.createElement(ts,{icon:t,label:e,...n}),Rb=e=>{const{components:t}=Fn.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(bb,null,n)},Fn=qe({template:Rb,components:{Loading:Tb,Error:Sb,NoChannels:Ib,NoMessages:xb}}),Ut=e=>{const{Template:t}=Fn.useContext();return a.createElement(t,{...e})},Mb=[0,150,450];function wb({enabled:e}){const{state:t,actions:n}=oa(),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=Mb.map(c=>setTimeout(()=>{Ie(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const kb=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=ae();return a.createElement(Lb,{id:`${Ue}-date-separator`,role:n,style:r,className:e},a.createElement(B,{variant:"caption4",color:_.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},Lb=E.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Ob=({className:e,style:t,onClick:n})=>{const{conversation:r}=oe(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(Nb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(ee,{size:24,type:"chevron-down",color:_.color.primary.main}),s.scrollToBottom.descriptionNode??null)},Nb=E.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);${te.light`
368
- background-color: ${_.color.background50};
366
+ `,ub=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(db,{$marginBottom:kn(e.groupType)},n)},Hn=je({template:ub,components:{AdminMessage:RC,CSATMessage:ib}}),db=_.default.div`padding-inline:${oe.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,ls=({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(pb,{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(_b,{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(mb,null,a.createElement(hb,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??E.themedColor.textHighEmphasis},e)),a.createElement(fb,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??E.themedColor.textMidEmphasis},n)),a.createElement(gb,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},mb=_.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,hb=_.default.div`padding:24px 24px 16px;`,fb=_.default.div`padding-inline:24px;`,gb=_.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;`,pb=_.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;}`,_b=_.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;}`,fn=16,Eb=({status:e})=>e===vn.COMPLETED?a.createElement(te,{type:"done-circle",size:fn,color:E.themedColor.textHighEmphasis}):e===vn.CANCELED?a.createElement(te,{type:"stop-circle",size:fn,color:E.themedColor.textLowEmphasis}):a.createElement(Et,{size:fn},a.createElement(te,{type:"spinner",size:fn,color:E.themedColor.textHighEmphasis})),Ua=24,Cb=8,bb=40,vb=({task:e,isFirst:t,isLast:n})=>a.createElement(Sb,{role:"listitem"},a.createElement(yb,null,a.createElement(ko,{$hidden:t}),a.createElement(Ab,null,a.createElement(Eb,{status:e.status})),a.createElement(ko,{$hidden:n})),a.createElement(Tb,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===vn.CANCELED?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis},e.user_facing_title))),Sb=_.default.div`display:flex;gap:4px;`,yb=_.default.div`display:flex;flex-direction:column;align-items:center;width:${Ua}px;flex-shrink:0;`,ko=_.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 );`,Ab=_.default.div`display:flex;height:${Ua}px;align-items:center;justify-content:center;`,Tb=_.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${bb}px;padding-block:${Cb}px;`,Ib=({steward:e,onCancelSteward:t})=>{const{logger:n}=ue(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=Rc(e.status);return a.createElement(xb,{$marginBottom:kn("single")},a.createElement(Rb,null,a.createElement(Mb,null,a.createElement(wb,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(Nb,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(te,{type:"stop",size:16,color:o?E.themedColor.textDisabled:E.themedColor.textHighEmphasis}))),a.createElement(kb,null),e.tasks.length===0?u!==Gt.IN_PROGRESS?null:a.createElement(Ob,null,a.createElement(Et,{size:16},a.createElement(te,{type:"spinner",size:16,color:E.themedColor.textHighEmphasis}))):a.createElement(Lb,{role:"list"},e.tasks.map((d,m)=>a.createElement(vb,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(ft,{portalContainerId:Se.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(ls,{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)}}})))},xb=_.default.div`display:flex;flex-direction:column;margin:0 ${oe.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
367
+ `,Rb=_.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);`,Mb=_.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,wb=_.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,kb=_.default.div`height:1px;margin-block:12px;background-color:${E.themedColor.bg_200_400};`,Lb=_.default.div`display:flex;flex-direction:column;`,Ob=_.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,Nb=_.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}=ae(),o={newMessages:s.newMessagesButton()};return a.createElement($b,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(te,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},$b=_.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}`,us=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(Fb,{className:n},t&&a.createElement(te,{type:t,size:e,color:E.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:E.themedColor.textMidEmphasis},r),s),Pb=_.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,Fb=_.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,Ub=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(us,{icon:t,label:e,...r},n&&a.createElement(Bb,{onClick:n.onClick,label:n.label??"Retry"})),Bb=({label:e,onClick:t})=>{const{conversation:n}=ae();return a.createElement(Hb,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(te,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:E.color.primary.main},e))},Hb=_.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${xe}`,Gb=({iconSize:e=48,className:t})=>a.createElement(Et,{size:e,className:t}),zb=({label:e="No channels",icon:t="chat",...n})=>a.createElement(us,{icon:t,label:e,...n}),Vb=({label:e="No messages",icon:t="message",...n})=>a.createElement(us,{icon:t,label:e,...n}),qb=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(Pb,null,n)},Gn=je({template:qb,components:{Loading:Gb,Error:Ub,NoChannels:zb,NoMessages:Vb}}),Vt=e=>{const{Template:t}=Gn.useContext();return a.createElement(t,{...e})},Kb=[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=Kb.map(c=>setTimeout(()=>{Ie(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const Wb=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=ie();return a.createElement(jb,{id:`${He}-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)))},jb=_.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Xb=({className:e,style:t,onClick:n})=>{const{conversation:r}=ae(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(Zb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(te,{size:24,type:"chevron-down",color:E.color.primary.main}),s.scrollToBottom.descriptionNode??null)},Zb=_.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);${ne.light`
368
+ background-color: ${E.color.background50};
369
369
  &:hover {
370
- background-color: ${_.color.background100};
370
+ background-color: ${E.color.background100};
371
371
  }
372
372
  &:active {
373
- background-color: ${_.color.background200};
373
+ background-color: ${E.color.background200};
374
374
  }
375
375
  `}
376
- ${te.dark`
377
- background-color: ${_.color.background400};
376
+ ${ne.dark`
377
+ background-color: ${E.color.background400};
378
378
  &:hover {
379
- background-color: ${_.color.background500};
379
+ background-color: ${E.color.background500};
380
380
  }
381
381
  &:active {
382
- background-color: ${_.color.background700};
382
+ background-color: ${E.color.background700};
383
383
  }
384
384
  `}
385
385
 
@@ -387,45 +387,45 @@
387
387
  outline: none;
388
388
  }
389
389
 
390
- ${Re}
391
- `,Db=()=>null,Un=qe({template:Db,components:{DateSeparator:kb,ScrollToBottomButton:Ob}}),$b=()=>{const{stringSet:e,format:t}=ae(),{agentPreviewConfigs:n={},aiAgentId:r}=me(),{aiAgentInfo:s}=Ne(),{messageSource:o}=Te(),{Template:i}=pt.useContext(),{components:c}=Un.useContext(),u=n.welcomeMessages??[],d=o.messages,m=Tg(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:da(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!ot.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,C)=>{const v=C===u.length-1,p=m.length!==d.length,b=u.length===1?"single":C===0?"top":v||p?"bottom":"middle",y=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:C,role:"listitem",tabIndex:-1,"aria-label":Dt({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:b,createdAt:y,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!p,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{o.sendUserMessage({message:A})}}))}))}},Pb=()=>{const{messageSource:e,scrollSource:t}=Te();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Ro="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",Fb=({style:e})=>{const{stringSet:t}=ae(),{handlers:n}=me(),{conversation:r}=oe();return Ur("powered-by")?a.createElement(Ub,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Bb,{variant:"caption2",forwardedAs:"a",href:Ro,...r.poweredByLink().props,rel:Gr,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:Ro})}},"Sendbird")):null},Ub=E.default(B)`color:${_.themedColor.textLowEmphasis};text-align:center;`,Bb=E.default(B)`color:${_.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,Hb=()=>{var c;const{stringSet:e}=ae(),{conversation:t}=oe(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Te(),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(Gb,null,a.createElement(zb,{variant:"button",color:_.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},Gb=E.default.div`display:flex;justify-content:center;margin-bottom:16px;`,zb=E.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${_.color.background50};border:1px solid ${_.color.onlight.textDisabled};${te.dark`
392
- background-color: ${_.color.background700};
393
- border-color: ${_.color.ondark.textLowEmphasis};
390
+ ${xe}
391
+ `,Jb=()=>null,zn=je({template:Jb,components:{DateSeparator:Wb,ScrollToBottomButton:Xb}}),Qb=()=>{const{stringSet:e,format:t}=ie(),{agentPreviewConfigs:n={},aiAgentId:r}=ue(),{aiAgentInfo:s}=Oe(),{messageSource:o}=Ae(),{Template:i}=Ct.useContext(),{components:c}=zn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=Gg(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&&!ut.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,p)=>{const v=p===u.length-1,S=m.length!==d.length,C=u.length===1?"single":p===0?"top":v||S?"bottom":"middle",A=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:p,role:"listitem",tabIndex:-1,"aria-label":zt({sender:(s==null?void 0:s.nickname)||"",message:g.message,messageFormat:"markdown",time:t(A,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:C,createdAt:A,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!S,isBotMessage:!0,onClickSuggestedReply:async({reply:y})=>{o.sendUserMessage({message:y})}}))}))}},ev=()=>{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",tv=({style:e})=>{const{stringSet:t}=ie(),{handlers:n}=ue(),{conversation:r}=ae();return Wr("powered-by")?a.createElement(nv,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(rv,{variant:"caption2",forwardedAs:"a",href:Lo,...r.poweredByLink().props,rel:Zr,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:Lo})}},"Sendbird")):null},nv=_.default(B)`color:${E.themedColor.textLowEmphasis};text-align:center;`,rv=_.default(B)`color:${E.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,sv=()=>{var c;const{stringSet:e}=ie(),{conversation:t}=ae(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Ae(),o=De(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(ov,null,a.createElement(iv,{variant:"button",color:E.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},ov=_.default.div`display:flex;justify-content:center;margin-bottom:16px;`,iv=_.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};${ne.dark`
392
+ background-color: ${E.color.background700};
393
+ border-color: ${E.color.ondark.textLowEmphasis};
394
394
  `}
395
- `,Vb=({statsCallbacks:e,...t})=>($m(e),a.createElement(lb,{...t})),qb=(e,t,n)=>t&&ke.isWelcomeMessage(e,n)&&ke.isWelcomeMessage(t,n)?!1:!ic.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Kb=()=>{var X;const{Template:e}=Rt.useContext(),{Template:t}=pt.useContext(),{Template:n}=Pn.useContext(),{components:r}=Un.useContext(),{stringSet:s,format:o}=ae(),{announceError:i,announceStatus:c}=nt(),{file:u}=oe().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:C}=me(),{userSession:v,aiAgentInfo:p,connectionError:b}=Ne(),{_statsEnabled:y,conversation:A,channelSource:T,messageSource:R,scrollSource:N,state:{input:k,streamAnimation:x}}=Te(),{filteredMessages:D,shouldShowOriginalDate:F,renderAgentPreviewWelcomeMessages:U}=$b(),q=Si(T.channel),K=Dm({enabled:y}),[L,V]=l.useState(null),[P,Y]=l.useState(null);l.useEffect(()=>{N.actions.onTypingIndicatorUpdate(!!q)},[!!q,N.actions.onTypingIndicatorUpdate]),Pb(),wb({enabled:R.initialized&&R.messages.length>0});const ge=(M,Z=!1)=>{var ie;return Z?p:((ie=T.channel)==null?void 0:ie.members.find(ye=>ye.userId===M.sender.userId))??M.sender},j=M=>{if(M.sendingStatus==="failed"&&!k.disabled)return()=>Y(M)},W=({message:M,index:Z})=>{const ie=Ec(M),ye=D[Z-1],$e=D[Z+1],Me=D[D.length-1],$=M===Me,I=tt(M,p.userId),w=!(p.isUserFeedbackEnabled&&I&&!ke.isWelcomeMessage(M)),O=Cc(M,ye,$e,w),G=qb(M,ye,p.userId)&&F(Z),J=ne=>{V({files:ne.files.map(ce=>({...ce,timestamp:M.createdAt})),index:ne.index})},se=ne=>{J({files:[ne],index:0})},Q=G?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:M.createdAt}):null,pe={data:M.data,maxBodyWidth:C.expanded?re.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:M.extendedMessagePayload,createdAt:M.createdAt,groupType:O,onClickMedia:se,onClickMediaFiles:J,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:ne=>g.onClickLink({url:ne.link}),onClickLink:g.onClickLink},Ke=()=>{if(Oe.isOutgoing(M,v.userId))return"outgoingmessage";if(Oe.isIncoming(M,v.userId))return"incomingmessage"},ut=M.createdAt!=null&&M.createdAt!==0?o(M.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,st=(()=>{var ce,_e,Ee,Ae,ue,we;const ne=(ce=M.message)==null?void 0:ce.trim();if(M.isFileMessage()){const Pe=((_e=M.name)==null?void 0:_e.trim())||"";return Xn({markdownText:ne,comparisonText:Pe,plainText:u.label(Pe,M.type)})}if(M.isMultipleFilesMessage()){const Pe=((ue=(Ae=(Ee=M.fileInfoList)==null?void 0:Ee[0])==null?void 0:Ae.fileName)==null?void 0:ue.trim())||"",Qt=((we=M.fileInfoList)==null?void 0:we.length)??0;return Xn({markdownText:ne,comparisonText:Pe,plainText:Qt>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Qt):""})}return ne?Xn({markdownText:ne}):Mi("")})(),de=(()=>{if(Oe.isAdmin(M))return Dt({message:st.text,messageFormat:st.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isOutgoing(M,v.userId))return Dt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:st.text,messageFormat:"plain",time:ut,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isIncoming(M,v.userId))return Dt({sender:ge(M,I).nickname,message:st.text,messageFormat:st.format,time:ut,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),be=(()=>{var ne,ce;if(Oe.isAdmin(M))return Oe.isCSAT(M)?A?a.createElement(n,{...pe,...A,isResolvedWhenDeterminedByUser:Xc(A),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async _e=>{var Ee;await((Ee=T.channel)==null?void 0:Ee.submitCSAT(_e))},onScrollToBottom:()=>N.actions.scrollToBottom()}):null:a.createElement(n,{...pe,messageType:"admin",message:M.message});if(Oe.isSteward(M)){const _e=K({message:M,isBotMessage:I,aiAgentUserId:p.userId});return a.createElement(Vb,{steward:M.extendedMessagePayload.steward,statsCallbacks:_e,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:M.channelUrl,messageId:M.messageId})}})}if(Oe.isOutgoing(M,v.userId)){const _e={...pe,message:M.message,sender:ge(M),sendingStatus:M.sendingStatus,onClickFailedMessage:j(M)};if(M.isUserMessage())return a.createElement(e,{messageType:"user",..._e});if(M.isFileMessage()){const[Ee,Ae]=((ne=M.metaArrays.find(ue=>ue.key===Yo))==null?void 0:ne.value)??[];return a.createElement(e,{messageType:"file",file:M,metadata:{aspectRatio:Ee&&Ae?`${Ee}/${Ae}`:"1/1",localFile:(ce=M.messageParams)==null?void 0:ce.file},..._e})}if(M.isMultipleFilesMessage()){const{files:Ee,metadata:Ae}=Eo(M);return a.createElement(e,{messageType:"multipleFiles",files:Ee,metadata:Ae,..._e})}}if(Oe.isIncoming(M,v.userId)){const _e=ke.isStreaming(M),Ee=K({message:M,isBotMessage:I,aiAgentUserId:p.userId}),Ae={...pe,statsCallbacks:Ee,sender:ge(M,I),message:M.message,suggestedRepliesVisible:$,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:I,isStreaming:_e,isHandedOff:et(T.channel),isConversationClosed:Fe(T.channel),isFeedbackEnabled:p.isUserFeedbackEnabled,isFeedbackCommentEnabled:p.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:ue})=>{R.sendUserMessage({message:ue})},onRequestMessageTemplate:async ue=>{const{template:we}=await f.aiAgent.getMessageTemplate(ue);return m.template.set(ue,we),we},onGetCachedMessageTemplate:ue=>m.template.get(ue),onHandleTemplateInternalAction:ue=>{if(ue.type==="internal"&&ue.internalData){const{method:we,payload:Pe}=ue.internalData;we==="message.send"&&(Pe!=null&&Pe.message)&&R.sendUserMessage({message:Pe.message})}},onFeedbackUpdate:ue=>{const we={messageId:M.messageId,channelUrl:M.channelUrl};if(!ue)return f.aiAgent.deleteMessageFeedback(we);const Pe={...we,rating:I_(ue.rating),comment:ue.comment};return ke.hasFeedback(M)?f.aiAgent.updateMessageFeedback(Pe):f.aiAgent.createMessageFeedback(Pe)},onSubmitForm:({key:ue,data:we})=>f.aiAgent.submitForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:ue,formData:we}),onCancelForm:({key:ue})=>f.aiAgent.cancelForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:ue}),onSendChallengeAction:({key:ue,requestId:we,action:Pe,data:Qt})=>f.aiAgent.sendChallengeAction({channelUrl:M.channelUrl,key:ue,requestId:we,action:Pe,data:Qt}),onStreamAnimationStart:()=>{x.start(M.messageId)},onStreamAnimationProgress:()=>{N.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{x.stop(M.messageId),N.actions.onStreamingUpdate(!1)}};if(M.isUserMessage())return a.createElement(t,{messageType:"user",...Ae});if(M.isFileMessage())return a.createElement(t,{messageType:"file",file:M,...Ae});if(M.isMultipleFilesMessage()){const{files:ue}=Eo(M);return a.createElement(t,{messageType:"multipleFiles",files:ue,...Ae})}}})();return a.createElement(l.Fragment,{key:ie},Q,a.createElement("div",{id:`${Ue}-message-item`,role:"listitem",tabIndex:-1,"aria-label":de,"data-message-listitem":"","data-layout-id":Ke()},be))};return a.createElement(Yb,{id:`${Ue}-message-list`},a.createElement(ep,{ref:N.ref,onScroll:N.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:D,renderMessage:W,onLoadPrev:R.loadPrevious,onLoadNext:R.loadNext,depsForResetScrollPositionToBottom:[R.initialized,R.messages.length!==0],bottomSpacerHeight:N.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!R.initialized||!T.channel,empty:D.length===0&&!q,error:!!(b||T.error),LoadingComponent:a.createElement(Ut,{type:"loading"}),EmptyComponent:(()=>{const M=U();return M?a.createElement("div",{style:{width:"100%"}},M):a.createElement(Ut,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Ut,{type:"error",label:(b==null?void 0:b.message)??((X=T.error)==null?void 0:X.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Fb,{style:{marginTop:16}}),U()),messageBottomArea:a.createElement(a.Fragment,null,q&&a.createElement("div",{id:`${Ue}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:q.user.nickname,message:s.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:D.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:q.isBot,sender:q.user,thinkingMessage:q.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(Hb,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&N.state.isAwayFromBottom&&R.newMessages.length>0&&a.createElement(Wb,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(R.newMessages),onClick:()=>N.actions.scrollToBottom()}),N.state.isAwayFromBottom&&R.newMessages.length===0&&!q&&a.createElement(r.ScrollToBottomButton,{onClick:()=>N.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),L&&a.createElement(ap,{files:L.files,initialIndex:L.index,onClose:()=>V(null),visible:!0}),P&&a.createElement(at,{visible:!0,onClose:()=>Y(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(at.ActionItem,{onClick:()=>{R.resendMessage(P),Y(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(at.ActionItem,{destructive:!0,onClick:()=>{R.deleteMessage(P),Y(null)}},s.FAILED_MESSAGE_REMOVE)))},Yb=E.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Wb=E.default(Eb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,jb=()=>a.createElement(Kb,null),Mo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Oa=({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=C=>C.default,style:g={}})=>{const{iconColor:C="#000000",textColor:v="#000000",highlightColor:p=Bt.DEFAULT_PRIMARY}=g;return a.createElement(wo,null,m,e&&a.createElement(wo,null,a.createElement(Tn,null,a.createElement(Ot,null,a.createElement(ee,{size:16,type:"actionbook",color:C})),a.createElement(ln,{$clickable:!!o,$highlightColor:p,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(b=>a.createElement(hn,{key:b.key},a.createElement(Ot,null,a.createElement(ee,{size:16,type:"function",color:C})),a.createElement(Tn,null,a.createElement(ln,{$clickable:!!i,$highlightColor:p,variant:"body2",color:v,onClick:()=>i==null?void 0:i(b),maxTextLines:1},b.name),c&&a.createElement(Xb,{role:"button",onClick:()=>c==null?void 0:c(b)},a.createElement(B,{variant:"body2",color:p},"View details"),a.createElement(ee,{type:"chevron-right",size:16,color:p}))))),n==null?void 0:n.map(b=>a.createElement(hn,{key:b.id},a.createElement(Ot,null,f({default:a.createElement(ee,{size:16,type:Mo[b.source_type]??Mo.snippet,color:C}),sourceType:b.source_type})),a.createElement(ln,{$clickable:!!u,$highlightColor:p,variant:"body2",color:v,onClick:()=>u==null?void 0:u(b),maxTextLines:1},b.preview_title))),r==null?void 0:r.map(b=>a.createElement(hn,{key:b.key},a.createElement(Ot,null,a.createElement(ee,{size:16,type:"template",color:C})),a.createElement(ln,{$clickable:!!d,$highlightColor:p,variant:"body2",color:v,onClick:()=>d==null?void 0:d(b),maxTextLines:1},b.name))),!!(s!=null&&s.length)&&a.createElement(Zb,null,a.createElement(Ot,null,a.createElement(ee,{size:16,type:"activity",color:C})),a.createElement(Jb,{variant:"body2",color:v},s.map(b=>b.replace(/_/g," ")).join(" · "))),h)},Na=E.default(B)`font-weight:400;`,ln=E.default(Na)`${({$clickable:e,$highlightColor:t})=>e&&H.css`
395
+ `,av=({statsCallbacks:e,...t})=>(Qm(e),a.createElement(Ib,{...t})),cv=(e,t,n)=>t&&we.isWelcomeMessage(e,n)&&we.isWelcomeMessage(t,n)?!1:!_c.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),lv=()=>{var ee;const{Template:e}=Ot.useContext(),{Template:t}=Ct.useContext(),{Template:n}=Hn.useContext(),{components:r}=zn.useContext(),{stringSet:s,format:o}=ie(),{announceError:i,announceStatus:c}=lt(),{file:u,messageList:d}=ae().conversation,{config:m,cache:h,agentPreviewConfigs:f,chatSDK:g,handlers:p,state:v}=ue(),{userSession:S,aiAgentInfo:C,connectionError:A}=Oe(),{_statsEnabled:y,conversation:T,channelSource:I,messageSource:N,scrollSource:O,state:{input:k,streamAnimation:R}}=Ae(),{filteredMessages:F,shouldShowOriginalDate:D,renderAgentPreviewWelcomeMessages:Q}=Qb(),re=Jm({enabled:y}),G=Nm(xi(I.channel),Bc(F,S.userId)),[H,q]=l.useState(null),[J,K]=l.useState(null),z=De(I.channel)?void 0:G??R.heldTypingInfo;l.useEffect(()=>{O.actions.onTypingIndicatorUpdate(!!z)},[!!z,O.actions.onTypingIndicatorUpdate]),ev(),Yb({enabled:N.initialized&&N.messages.length>0});const Y=w=>{var _e;return Mc(w,{aiAgentInfo:C,members:(_e=I.channel)==null?void 0:_e.members})},W=w=>{if(w.sendingStatus==="failed"&&!k.disabled)return()=>K(w)},V=({message:w,index:_e})=>{const Re=wc(w),Te=F[_e-1],$=F[_e+1],M=F[F.length-1],x=w===M,L=nt(w,C.userId),P=!(C.isUserFeedbackEnabled&&L&&!we.isWelcomeMessage(w)),X=kc(w,Te,$,P),se=cv(w,Te,C.userId)&&D(_e),Z=Ee=>{q({files:Ee.files.map(Ze=>({...Ze,timestamp:w.createdAt})),index:Ee.index})},be=Ee=>{Z({files:[Ee],index:0})},Xe=se?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:w.createdAt}):null,it={data:w.data,maxBodyWidth:v.expanded?oe.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:w.extendedMessagePayload,createdAt:w.createdAt,groupType:X,onClickMedia:be,onClickMediaFiles:Z,onClickFile:p.onClickLink,onClickCTA:p.onClickLink,onClickCitation:Ee=>p.onClickLink({url:Ee.link}),onClickLink:p.onClickLink},sn=()=>{if(Me.isOutgoing(w,S.userId))return"outgoingmessage";if(Me.isIncoming(w,S.userId))return"incomingmessage"},le=w.createdAt!=null&&w.createdAt!==0?o(w.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,fe=(()=>{var Ze,Ne,Ge,qe,de,$e;const Ee=(Ze=w.message)==null?void 0:Ze.trim();if(w.isFileMessage()){const Pe=((Ne=w.name)==null?void 0:Ne.trim())||"";return sr({markdownText:Ee,comparisonText:Pe,plainText:u.label(Pe,w.type)})}if(w.isMultipleFilesMessage()){const Pe=((de=(qe=(Ge=w.fileInfoList)==null?void 0:Ge[0])==null?void 0:qe.fileName)==null?void 0:de.trim())||"",on=(($e=w.fileInfoList)==null?void 0:$e.length)??0;return sr({markdownText:Ee,comparisonText:Pe,plainText:on>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(on):""})}return Ee?sr({markdownText:Ee}):Di("")})(),ge=(()=>{if(Me.isAdmin(w))return zt({message:fe.text,messageFormat:fe.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Me.isOutgoing(w,S.userId))return zt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:fe.text,messageFormat:"plain",time:le,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Me.isIncoming(w,S.userId))return zt({sender:Y(w).nickname,message:fe.text,messageFormat:fe.format,time:le,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),pe=(()=>{var Ee,Ze;if(Me.isAdmin(w))return Me.isCSAT(w)?T?a.createElement(n,{...it,...T,isResolvedWhenDeterminedByUser:ul(T),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async Ne=>{var Ge;await((Ge=I.channel)==null?void 0:Ge.submitCSAT(Ne))},onScrollToBottom:()=>O.actions.scrollToBottom()}):null:a.createElement(n,{...it,messageType:"admin",message:w.message});if(Me.isSteward(w)){const Ne=re({message:w,isBotMessage:L,aiAgentUserId:C.userId});return a.createElement(av,{steward:w.extendedMessagePayload.steward,statsCallbacks:Ne,onCancelSteward:async()=>{await g.aiAgent.cancelStewardTask({channelUrl:w.channelUrl,messageId:w.messageId})}})}if(Me.isOutgoing(w,S.userId)){const Ne={...it,message:w.message,sender:Y(w),sendingStatus:w.sendingStatus,onClickFailedMessage:W(w)};if(w.isUserMessage())return a.createElement(e,{messageType:"user",...Ne});if(w.isFileMessage()){const[Ge,qe]=((Ee=w.metaArrays.find(de=>de.key===Jo))==null?void 0:Ee.value)??[];return a.createElement(e,{messageType:"file",file:w,metadata:{aspectRatio:Ge&&qe?`${Ge}/${qe}`:"1/1",localFile:(Ze=w.messageParams)==null?void 0:Ze.file},...Ne})}if(w.isMultipleFilesMessage()){const{files:Ge,metadata:qe}=So(w);return a.createElement(e,{messageType:"multipleFiles",files:Ge,metadata:qe,...Ne})}}if(Me.isIncoming(w,S.userId)){const Ne=we.isStreaming(w),Ge=re({message:w,isBotMessage:L,aiAgentUserId:C.userId}),qe={...it,statsCallbacks:Ge,sender:Y(w),message:w.message,suggestedRepliesVisible:x,suggestedRepliesDirection:f==null?void 0:f.suggestedRepliesDirection,isBotMessage:L,isStreaming:Ne,isHandedOff:ct(I.channel),isConversationClosed:De(I.channel),isFeedbackEnabled:C.isUserFeedbackEnabled,isFeedbackCommentEnabled:C.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:m.conversation.list.senderAvatarEnabled,deferredMarkdownElements:m.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:de})=>{N.sendUserMessage({message:de})},onRequestMessageTemplate:async de=>{const{template:$e}=await g.aiAgent.getMessageTemplate(de);return h.template.set(de,$e),$e},onGetCachedMessageTemplate:de=>h.template.get(de),onHandleTemplateInternalAction:de=>{if(de.type==="internal"&&de.internalData){const{method:$e,payload:Pe}=de.internalData;$e==="message.send"&&(Pe!=null&&Pe.message)&&N.sendUserMessage({message:Pe.message})}},onFeedbackUpdate:de=>{const $e={messageId:w.messageId,channelUrl:w.channelUrl};if(!de)return g.aiAgent.deleteMessageFeedback($e);const Pe={...$e,rating:z_(de.rating),comment:de.comment};return we.hasFeedback(w)?g.aiAgent.updateMessageFeedback(Pe):g.aiAgent.createMessageFeedback(Pe)},onSubmitForm:({key:de,data:$e})=>g.aiAgent.submitForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:de,formData:$e}),onCancelForm:({key:de})=>g.aiAgent.cancelForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:de}),onSendChallengeAction:({key:de,requestId:$e,action:Pe,data:on})=>g.aiAgent.sendChallengeAction({channelUrl:w.channelUrl,key:de,requestId:$e,action:Pe,data:on}),onStreamAnimationStart:()=>{R.start(w.messageId)},onStreamAnimationProgress:()=>{O.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{R.stop(w.messageId),O.actions.onStreamingUpdate(!1)},onStreamAnimationHoldChange:de=>{de?R.holdStart(w.messageId,{user:Y(w),isBot:L}):R.holdStop(w.messageId)}};if(w.isUserMessage())return a.createElement(t,{messageType:"user",...qe});if(w.isFileMessage())return a.createElement(t,{messageType:"file",file:w,...qe});if(w.isMultipleFilesMessage()){const{files:de}=So(w);return a.createElement(t,{messageType:"multipleFiles",files:de,...qe})}}})(),Fe=R.isHolding(w.messageId),Ue=d.item({label:ge,holding:Fe});return a.createElement(l.Fragment,{key:Re},Xe,a.createElement("div",{id:`${He}-message-item`,...Ue.props,"data-message-listitem":"","data-layout-id":sn()},pe))};return a.createElement(uv,{id:`${He}-message-list`},a.createElement(_p,{ref:O.ref,onScroll:O.props.onScroll,stackDirection:f==null?void 0:f.messageStackDirection,messages:F,renderMessage:V,onLoadPrev:N.loadPrevious,onLoadNext:N.loadNext,depsForResetScrollPositionToBottom:[N.initialized,N.messages.length!==0],bottomSpacerHeight:O.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!N.initialized||!I.channel,empty:F.length===0&&!z,error:!!(A||I.error),LoadingComponent:a.createElement(Vt,{type:"loading"}),EmptyComponent:(()=>{const w=Q();return w?a.createElement("div",{style:{width:"100%"}},w):a.createElement(Vt,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Vt,{type:"error",label:(A==null?void 0:A.message)??((ee=I.error)==null?void 0:ee.message),action:I.error?{label:s.RETRY,onClick:()=>I.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(tv,{style:{marginTop:16}}),Q()),messageBottomArea:a.createElement(a.Fragment,null,z&&a.createElement("div",{id:`${He}-message-item`,...d.typingItem(z.user.nickname).props,"data-message-listitem":"",style:{marginTop:F.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:z.isBot,sender:z.user,thinkingMessage:z.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:m.conversation.list.senderAvatarEnabled})),m.conversation.list.isTalkToAgentViewEnabled&&a.createElement(sv,null)),overlayArea:a.createElement(a.Fragment,null,m.conversation.list.newMessageIndicatorEnabled&&O.state.isAwayFromBottom&&N.newMessages.length>0&&a.createElement(dv,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(N.newMessages),onClick:()=>O.actions.scrollToBottom()}),O.state.isAwayFromBottom&&N.newMessages.length===0&&!z&&a.createElement(r.ScrollToBottomButton,{onClick:()=>O.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),H&&a.createElement(Ap,{files:H.files,initialIndex:H.index,onClose:()=>q(null),visible:!0}),J&&a.createElement(dt,{visible:!0,onClose:()=>K(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(dt.ActionItem,{onClick:()=>{N.resendMessage(J),K(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(dt.ActionItem,{destructive:!0,onClick:()=>{N.deleteMessage(J),K(null)}},s.FAILED_MESSAGE_REMOVE)))},uv=_.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,dv=_.default(Db)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,mv=()=>a.createElement(lv,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=p=>p.default,style:g={}})=>{const{iconColor:p="#000000",textColor:v="#000000",highlightColor:S=qt.DEFAULT_PRIMARY}=g;return a.createElement(No,null,m,e&&a.createElement(No,null,a.createElement(wn,null,a.createElement(Ft,null,a.createElement(te,{size:16,type:"actionbook",color:p})),a.createElement(gn,{$clickable:!!o,$highlightColor:S,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(C=>a.createElement(Cn,{key:C.key},a.createElement(Ft,null,a.createElement(te,{size:16,type:"function",color:p})),a.createElement(wn,null,a.createElement(gn,{$clickable:!!i,$highlightColor:S,variant:"body2",color:v,onClick:()=>i==null?void 0:i(C),maxTextLines:1},C.name),c&&a.createElement(hv,{role:"button",onClick:()=>c==null?void 0:c(C)},a.createElement(B,{variant:"body2",color:S},"View details"),a.createElement(te,{type:"chevron-right",size:16,color:S}))))),n==null?void 0:n.map(C=>a.createElement(Cn,{key:C.id},a.createElement(Ft,null,f({default:a.createElement(te,{size:16,type:Oo[C.source_type]??Oo.snippet,color:p}),sourceType:C.source_type})),a.createElement(gn,{$clickable:!!u,$highlightColor:S,variant:"body2",color:v,onClick:()=>u==null?void 0:u(C),maxTextLines:1},C.preview_title))),r==null?void 0:r.map(C=>a.createElement(Cn,{key:C.key},a.createElement(Ft,null,a.createElement(te,{size:16,type:"template",color:p})),a.createElement(gn,{$clickable:!!d,$highlightColor:S,variant:"body2",color:v,onClick:()=>d==null?void 0:d(C),maxTextLines:1},C.name))),!!(s!=null&&s.length)&&a.createElement(fv,null,a.createElement(Ft,null,a.createElement(te,{size:16,type:"activity",color:p})),a.createElement(gv,{variant:"body2",color:v},s.map(C=>C.replace(/_/g," ")).join(" · "))),h)},Ha=_.default(B)`font-weight:400;`,gn=_.default(Ha)`${({$clickable:e,$highlightColor:t})=>e&&U.css`
396
396
  cursor: pointer;
397
397
  text-decoration: underline;
398
398
  &:hover {
399
399
  color: ${t};
400
400
  }
401
401
  `}
402
- `,Ot=E.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Tn=E.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Xb=E.default(Tn)`cursor:pointer;gap:4px;`,hn=E.default(Tn)`flex-direction:row;align-items:center;`,Zb=E.default(hn)`align-items:flex-start;max-width:100%;`,Jb=E.default(Na)`min-width:0;`,wo=E.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Da=ve("DashboardTester"),Qb=Da.Provider;function ev({testerType:e,origin:t,children:n}){return a.createElement(Qb,{value:{testerType:e,origin:t}},e&&a.createElement(tv,null),n)}const $a=Da.useContext,tv=()=>a.createElement(a.Fragment,null,a.createElement(pt.MessageLogs,{component:ko}),a.createElement(Rt.MessageLogs,{component:ko})),ko=({extendedMessagePayload:e={}})=>{const{handlers:t}=me(),{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(nv,null,a.createElement(rv,{$width:4}),a.createElement(Oa,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:_.themedColor.textHighEmphasis,textColor:_.themedColor.textHighEmphasis,barColor:_.themedColor.textDisabled},topContent:a.createElement(B,{variant:"caption4",color:_.themedColor.textLowEmphasis},"Only visible in the tester")}))},nv=E.default.div`display:flex;gap:16px;margin:6px ${re.HORIZONTAL_PADDING}px 4px ${re.HORIZONTAL_PADDING+re.AVATAR_SIZE}px;align-self:stretch;`,rv=E.default.div`width:${({$width:e})=>e}px;background-color:${_.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,sv=()=>{var s;const{origin:e}=$a(),{appId:t,aiAgentId:n}=xe(),{channelSource:r}=Te();return(s=r.channel)!=null&&s.conversation?a.createElement(ov,null,a.createElement(vr,{style:{gap:4}},a.createElement(ee,{color:_.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(B,{as:"i",color:_.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(vr,{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:_.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:_.themedColor.primary}},"conversation link")),a.createElement(ee,{color:_.themedColor.primary,size:14,type:"copy"}))):null},vr=E.default.div`display:flex;justify-content:center;align-items:center;`,ov=E.default(vr)`flex-direction:column;padding-block:16px;background-color:${_.themedColor.bg_100_500};gap:8px;`,iv=(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}},Pa=l.createContext(void 0),av=({children:e})=>{var q,K;const{chatSDK:t}=me(),{createAttachmentRules:n}=Ne(),{stringSet:r}=ae(),{channelSource:s,state:o}=Te(),[i,c]=l.useState([]),{announceError:u}=qr(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(q=t.appInfo)==null?void 0:q.uploadSizeLimit}),f=((K=o==null?void 0:o.input)==null?void 0:K.disabled)??!1,g=h.isEnabled(),C=h.maxAttachmentCount,v=()=>m(null),p=L=>m(L),b=()=>{p({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",C.toString())})},y=L=>{p({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",L.toString())}),u({type:"fileSizeExceeded",maxSizeMB:L})},A=L=>{p({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",L.toString())})},T=L=>L.map(V=>({file:V,preview:{url:URL.createObjectURL(V),type:V.type,name:V.name}})),R=L=>{c(V=>[...V,...T(L)])},N=L=>{c(V=>(V.forEach(P=>URL.revokeObjectURL(P.preview.url)),T(L)))},k=L=>{const{passed:V,failedBySize:P,failedByType:Y}=iv(L,h),ge=P.length+Y.length,j=L.length===1?P[0]:void 0;return j?y(h.getUploadSizeLimitInMB(j.type)):ge>0&&A(ge),V},x=L=>{const V=k(L.files);V.length!==0&&(L.type==="append"?R(V):N(V))},D=L=>{if(!g||f||!Du(L))return;const V=Pu({currentFiles:i.map(({file:P})=>P),incomingFiles:L,maxAttachmentCount:C});switch(V.type){case"reject":b();return;case"confirm_replace":p({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}},F=L=>{c(V=>{var Y;const P=(Y=V[L])==null?void 0:Y.preview;return P&&URL.revokeObjectURL(P.url),V.filter((ge,j)=>j!==L)})},U=()=>{c(L=>(L.forEach(V=>URL.revokeObjectURL(V.preview.url)),[]))};return a.createElement(Pa.Provider,{value:{files:i,addFiles:D,removeFile:F,clearFiles:U,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:p}},e,a.createElement(Nn,{visible:!!d,...d??{},onClose:v}))},ns=()=>{const e=l.useContext(Pa);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function cv({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 lv({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 uv=()=>{const{announceError:e}=nt();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},dv=1e3,mv=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=nt(),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]),Cm(t,u,{enabled:o,idleMs:dv})},hv=({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}}},fv=E.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,gv=E.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;}`,pv=E.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;${te.light`
403
- background-color: ${_.color.background50};
402
+ `,Ft=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,wn=_.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,hv=_.default(wn)`cursor:pointer;gap:4px;`,Cn=_.default(wn)`flex-direction:row;align-items:center;`,fv=_.default(Cn)`align-items:flex-start;max-width:100%;`,gv=_.default(Ha)`min-width:0;`,No=_.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ga=ve("DashboardTester"),pv=Ga.Provider;function _v({testerType:e,origin:t,children:n}){return a.createElement(pv,{value:{testerType:e,origin:t}},e&&a.createElement(Ev,null),n)}const za=Ga.useContext,Ev=()=>a.createElement(a.Fragment,null,a.createElement(Ct.MessageLogs,{component:Do}),a.createElement(Ot.MessageLogs,{component:Do})),Do=({extendedMessagePayload:e={}})=>{const{handlers:t}=ue(),{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(Cv,null,a.createElement(bv,{$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")}))},Cv=_.default.div`display:flex;gap:16px;margin:6px ${oe.HORIZONTAL_PADDING}px 4px ${oe.HORIZONTAL_PADDING+oe.AVATAR_SIZE}px;align-self:stretch;`,bv=_.default.div`width:${({$width:e})=>e}px;background-color:${E.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,vv=()=>{var s;const{origin:e}=za(),{appId:t,aiAgentId:n}=ye(),{channelSource:r}=Ae();return(s=r.channel)!=null&&s.conversation?a.createElement(Sv,null,a.createElement(wr,{style:{gap:4}},a.createElement(te,{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(wr,{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(te,{color:E.themedColor.primary,size:14,type:"copy"}))):null},wr=_.default.div`display:flex;justify-content:center;align-items:center;`,Sv=_.default(wr)`flex-direction:column;padding-block:16px;background-color:${E.themedColor.bg_100_500};gap:8px;`,yv=(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),Av=({children:e})=>{var Q,re;const{chatSDK:t}=ue(),{createAttachmentRules:n}=Oe(),{stringSet:r}=ie(),{channelSource:s,state:o}=Ae(),[i,c]=l.useState([]),{announceError:u}=es(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(Q=t.appInfo)==null?void 0:Q.uploadSizeLimit}),f=((re=o==null?void 0:o.input)==null?void 0:re.disabled)??!1,g=h.isEnabled(),p=h.maxAttachmentCount,v=()=>m(null),S=G=>m(G),C=()=>{S({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString())})},A=G=>{S({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",G.toString())}),u({type:"fileSizeExceeded",maxSizeMB:G})},y=G=>{S({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",G.toString())})},T=G=>G.map(H=>({file:H,preview:{url:URL.createObjectURL(H),type:H.type,name:H.name}})),I=G=>{c(H=>[...H,...T(G)])},N=G=>{c(H=>(H.forEach(q=>URL.revokeObjectURL(q.preview.url)),T(G)))},O=G=>{const{passed:H,failedBySize:q,failedByType:J}=yv(G,h),K=q.length+J.length,z=G.length===1?q[0]:void 0;return z?A(h.getUploadSizeLimitInMB(z.type)):K>0&&y(K),H},k=G=>{const H=O(G.files);H.length!==0&&(G.type==="append"?I(H):N(H))},R=G=>{if(!g||f||!ju(G))return;const H=Zu({currentFiles:i.map(({file:q})=>q),incomingFiles:G,maxAttachmentCount:p});switch(H.type){case"reject":C();return;case"confirm_replace":S({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>k(H.action)});return;case"apply":k(H.action);return}},F=G=>{c(H=>{var J;const q=(J=H[G])==null?void 0:J.preview;return q&&URL.revokeObjectURL(q.url),H.filter((K,z)=>z!==G)})},D=()=>{c(G=>(G.forEach(H=>URL.revokeObjectURL(H.preview.url)),[]))};return a.createElement(Va.Provider,{value:{files:i,addFiles:R,removeFile:F,clearFiles:D,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:S}},e,a.createElement(Fn,{visible:!!d,...d??{},onClose:v}))},ds=()=>{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 Iv({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 xv=()=>{const{announceError:e}=lt();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},Rv=1e3,Mv=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=lt(),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]),Dm(t,u,{enabled:o,idleMs:Rv})},wv=({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}}},kv=_.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,Lv=_.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;}`,Ov=_.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;${ne.light`
403
+ background-color: ${E.color.background50};
404
404
  `}
405
- ${te.dark`
406
- background-color: ${_.color.background500};
405
+ ${ne.dark`
406
+ background-color: ${E.color.background500};
407
407
  `}
408
408
  path {
409
- fill: ${_.themedColor.textMidEmphasis};
409
+ fill: ${E.themedColor.textMidEmphasis};
410
410
  }
411
411
 
412
412
  &:hover {
413
413
  path {
414
- fill: ${_.themedColor.textHighEmphasis};
414
+ fill: ${E.themedColor.textHighEmphasis};
415
415
  }
416
416
  }
417
417
 
418
418
  &:focus-visible {
419
419
  opacity: 1;
420
- outline: 2px solid ${_.color.primary.main};
420
+ outline: 2px solid ${E.color.primary.main};
421
421
  outline-offset: 2px;
422
422
  }
423
423
 
424
424
  circle {
425
- stroke: ${_.themedColor.bg_50_600};
425
+ stroke: ${E.themedColor.bg_50_600};
426
426
  }
427
- `,_v=()=>{const e=jt(),{conversation:t}=oe(),{files:n,removeFile:r,isFileUploadEnabled:s}=ns();return s&&n.length>0?a.createElement(fv,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Xr,{name:c,mimeType:i,type:Tr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(gv,{key:u},a.createElement(pv,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(ee,{type:"close-filled",color:_.themedColor.textMidEmphasis})),m)})):null},Ev={textArea:H.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Fa=E.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Re}`,Lo=E.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,Oo=E.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,No=E.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:${Bi}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${na&&Ev.textArea};${({$focusVisible:e})=>e&&H.css`
428
- outline: 2px solid ${_.themedColor.primary};
427
+ `,Nv=()=>{const e=en(),{conversation:t}=ae(),{files:n,removeFile:r,isFileUploadEnabled:s}=ds();return s&&n.length>0?a.createElement(kv,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(os,{name:c,mimeType:i,type:Nr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(Lv,{key:u},a.createElement(Ov,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(te,{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=_.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${xe}`,$o=_.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,Po=_.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Fo=_.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:${Ki}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${ca&&Dv.textArea};${({$focusVisible:e})=>e&&U.css`
428
+ outline: 2px solid ${E.themedColor.primary};
429
429
  outline-offset: 2px;
430
430
  `}
431
431
 
@@ -436,22 +436,22 @@
436
436
  &:disabled {
437
437
  cursor: not-allowed;
438
438
  &::placeholder {
439
- color: ${_.themedColor.textDisabled};
439
+ color: ${E.themedColor.textDisabled};
440
440
  }
441
441
  }
442
442
 
443
- ${({$blocked:e})=>e&&H.css`cursor:not-allowed;&::placeholder{color:${_.themedColor.textDisabled};}`}
444
- `,Cv=E.default.input`display:none;`;E.default.div`display:flex;align-items:center;gap:24px;`;const bv=E.default(Fa)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${_.themedColor.bg_100_500};path{fill:${_.themedColor.textHighEmphasis};}}&:active{background-color:${_.themedColor.bg_200_400};}}`,Do=E.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,$o=e=>e.startsWith("image/"),Po=({disabled:e})=>{const{stringSet:t}=ae(),{conversation:n}=oe(),{config:r}=me(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=ns(),f=m.includes(ir),g=f?["image/*"]:m.filter($o),C=f?[ir]:m.filter(k=>!$o(k)),v=r.conversation.input.gallery.photoEnabled,p=r.conversation.input.fileEnabled,b=()=>f||g.length>0,y=()=>f||C.length>0,A=k=>{const x=k.currentTarget.files;x&&u(Array.from(x)),k.target.value=""},T=()=>{c(!0)},R=l.useMemo(()=>{const k=[];return v&&k.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!b()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=s.current)==null?void 0:x.click()},100)}}),p&&k.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)}}),k},[g,m,t,v,p]);if(!d)return null;const N={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(bv,{...N.attach.props,disabled:e,onClick:T},a.createElement(ee,{type:"add",color:e?_.themedColor.textDisabled:_.color.primary.main,size:20}),N.attach.descriptionNode),R.map(k=>a.createElement(Cv,{key:k.type,type:"file",ref:k.inputRef,multiple:k.type==="image",onChange:A,accept:k.accept})),a.createElement(at,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},R.map(k=>a.createElement(at.ActionItem,{key:k.type,onClick:k.onSelect,icon:k.icon},k.label))))},vv=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=ae(),{conversation:s}=oe(),{rootElement:o}=me(),i=ct(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=hv({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Te(),{files:g,addFiles:C,clearFiles:v}=ns(),p=uv(),{focusPolicy:b,disabled:y,disabledBy:A}=f.input,T=b==="preserve",R=b==="release",N=(()=>{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}})();Cg({onDropFiles:M=>{C(M)}}),lv({blurred:R,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),mv(m.channel,t,!y);const k=t.trim().length>0,x=g.length>0,D=!y&&(k||x),F={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},U=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},q=()=>{var M;d(),(M=e.current)==null||M.focus()},{requestRestore:K,cancelRestore:L}=cv({elementRef:e,ready:T,onRestore:d}),V=M=>{L(),p(M)},P=()=>{L()},Y=async M=>{try{await M(),P()}catch{V(e.current)}},ge=async()=>{if(y)return;const M=t.trim();if(!M&&!g.length)return;const Z=[...g];if(K(),U(),q(),Z.length===0){await Y(()=>h.sendUserMessage({message:M}));return}if(Z.length===1)await Y(()=>h.sendFileMessage({message:M,file:Z[0].file}));else{const ie=Z.map(({file:ye})=>({file:ye}));await Y(()=>h.sendMultipleFilesMessage({message:M,fileInfoList:ie}))}},j=M=>{const Z=Array.from(M.clipboardData.files);Z.length>0&&(M.preventDefault(),C(Z))},W=M=>{M.key!=="Enter"||M.nativeEvent.isComposing||M.shiftKey||(M.preventDefault(),ge())},X=M=>{if(y){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const Z=Math.min(Mh,e.current.scrollHeight);Bi<Z&&(e.current.style.height=`${Z}px`)}n(M.target.value)};return R?a.createElement(Do,null,a.createElement(Po,{disabled:!0}),a.createElement(Lo,null,a.createElement(Oo,null,a.createElement(No,{rows:1,...F.input.props,disabled:!0,placeholder:N,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(Do,{"data-message-composer":""},a.createElement(Po,{disabled:y}),a.createElement(Lo,null,a.createElement(_v,null),a.createElement(Oo,null,a.createElement(No,{ref:e,rows:1,...F.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:N,maxLength:5e3,$blocked:y,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:W,onChange:X,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:j}))),D&&a.createElement(Fa,{...F.send.props,onClick:()=>ge()},a.createElement(ee,{type:"send",color:_.color.primary.main,size:20}),F.send.descriptionNode))},Sv=E.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:${_.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${te.light`
445
- color: ${_.color.information.light};
443
+ ${({$blocked:e})=>e&&U.css`cursor:not-allowed;&::placeholder{color:${E.themedColor.textDisabled};}`}
444
+ `,$v=_.default.input`display:none;`;_.default.div`display:flex;align-items:center;gap:24px;`;const Pv=_.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=_.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}=ie(),{conversation:n}=ae(),{config:r}=ue(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=ds(),f=m.includes(fr),g=f?["image/*"]:m.filter(Bo),p=f?[fr]:m.filter(O=>!Bo(O)),v=r.conversation.input.gallery.photoEnabled,S=r.conversation.input.fileEnabled,C=()=>f||g.length>0,A=()=>f||p.length>0,y=O=>{const k=O.currentTarget.files;k&&u(Array.from(k)),O.target.value=""},T=()=>{c(!0)},I=l.useMemo(()=>{const O=[];return v&&O.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!C()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var k;return(k=s.current)==null?void 0:k.click()},100)}}),S&&O.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!A()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var k;return(k=o.current)==null?void 0:k.click()},100)}}),O},[g,m,t,v,S]);if(!d)return null;const N={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(Pv,{...N.attach.props,disabled:e,onClick:T},a.createElement(te,{type:"add",color:e?E.themedColor.textDisabled:E.color.primary.main,size:20}),N.attach.descriptionNode),I.map(O=>a.createElement($v,{key:O.type,type:"file",ref:O.inputRef,multiple:O.type==="image",onChange:y,accept:O.accept})),a.createElement(dt,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},I.map(O=>a.createElement(dt.ActionItem,{key:O.type,onClick:O.onSelect,icon:O.icon},O.label))))},Fv=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=ie(),{conversation:s}=ae(),{rootElement:o}=ue(),i=mt(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=wv({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Ae(),{files:g,addFiles:p,clearFiles:v}=ds(),S=xv(),{focusPolicy:C,disabled:A,disabledBy:y}=f.input,T=C==="preserve",I=C==="release",N=(()=>{if(!A)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(y){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}})();$g({onDropFiles:V=>{p(V)}}),Iv({blurred:I,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),Mv(m.channel,t,!A);const O=t.trim().length>0,k=g.length>0,R=!A&&(O||k),F={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},D=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},Q=()=>{var V;d(),(V=e.current)==null||V.focus()},{requestRestore:re,cancelRestore:G}=Tv({elementRef:e,ready:T,onRestore:d}),H=V=>{G(),S(V)},q=()=>{G()},J=async V=>{try{await V(),q()}catch{H(e.current)}},K=async()=>{if(A)return;const V=t.trim();if(!V&&!g.length)return;const ee=[...g];if(re(),D(),Q(),ee.length===0){await J(()=>h.sendUserMessage({message:V}));return}if(ee.length===1)await J(()=>h.sendFileMessage({message:V,file:ee[0].file}));else{const w=ee.map(({file:_e})=>({file:_e}));await J(()=>h.sendMultipleFilesMessage({message:V,fileInfoList:w}))}},z=V=>{const ee=Array.from(V.clipboardData.files);ee.length>0&&(V.preventDefault(),p(ee))},Y=V=>{V.key!=="Enter"||V.nativeEvent.isComposing||V.shiftKey||(V.preventDefault(),K())},W=V=>{if(A){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const ee=Math.min(Kh,e.current.scrollHeight);Ki<ee&&(e.current.style.height=`${ee}px`)}n(V.target.value)};return I?a.createElement(Uo,null,a.createElement(Ho,{disabled:!0}),a.createElement($o,null,a.createElement(Po,null,a.createElement(Fo,{rows:1,...F.input.props,disabled:!0,placeholder:N,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(Uo,{"data-message-composer":""},a.createElement(Ho,{disabled:A}),a.createElement($o,null,a.createElement(Nv,null),a.createElement(Po,null,a.createElement(Fo,{ref:e,rows:1,...F.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:N,maxLength:5e3,$blocked:A,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:Y,onChange:W,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:z}))),R&&a.createElement(qa,{...F.send.props,onClick:()=>K()},a.createElement(te,{type:"send",color:E.color.primary.main,size:20}),F.send.descriptionNode))},Uv=_.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;${ne.light`
445
+ color: ${E.color.information.light};
446
446
  `};
447
- ${te.dark`
448
- color: ${_.color.information.main};
447
+ ${ne.dark`
448
+ color: ${E.color.information.main};
449
449
  `};
450
450
  }
451
- `,yv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Av=()=>{const{aiAgentInfo:e,userSession:t}=Ne(),{handlers:n}=me(),{messageSource:r,channelSource:s}=Te(),[o,i]=l.useState(null),c=Ur("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>tt(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(Sv,null,a.createElement(yv,{onClickLink:n.onClickLink},e.specialNotice))},Tv=()=>a.createElement(Iv,null,a.createElement(Av,null),a.createElement(av,null,a.createElement(vv,null))),Iv=E.default.div`z-index:0;border:none;width:100%;`,xv=()=>{var s;const{testerType:e}=$a(),{channelSource:t}=Te(),n=Fe(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(sv,null):a.createElement(Tv,null)},Ua=({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(Rv,{...s},a.createElement(Mv,null,n==="center"&&t&&a.createElement(wv,{$sideWidth:Math.max(c,d)},a.createElement(kv,null,t)),a.createElement(Lv,null,a.createElement(Ov,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Dv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Nv,{ref:i},r))))},Rv=E.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${_.themedColor.textDisabled};`,Mv=E.default.div`position:relative;height:56px;padding:11px 12px;`,wv=E.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;`,kv=E.default.div`max-width:100%;overflow:hidden;`,Lv=E.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Ov=E.default.div`flex-shrink:0;display:flex;align-items:center;`,Nv=E.default.div`flex-shrink:0;display:flex;align-items:center;`,Dv=E.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;`,Mt=(e=16)=>jt()?e*1.5:e,$v=()=>{const{state:e}=me(),{messenger:t}=oe(),n=Mt(),r=()=>{e.setOpened(!1)};return a.createElement(rt,{...t.closeButton().props,type:"close",size:n,onClick:r})},Pv=()=>{const{enableCloseConversationButton:e,dispatcher:t}=me(),{channelSource:n}=Te(),{conversation:r}=oe(),s=n.channel,o=Mt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!xr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(it.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(rt,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},Fv=()=>{const{state:e,enableExpandButton:t}=me(),{messenger:n}=oe(),r=Mt();return t?a.createElement(rt,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Uv=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Sr,null,t,a.createElement(Gv,{$position:n},a.createElement(zv,{variant:"caption1"},e),a.createElement(Bv,{$position:n}))),Bv=({$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:_.themedColor.textHighEmphasis})),Hv={top:H.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:H.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Sr=E.default.div`position:relative;`,Gv=E.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${ft.TOOLTIP};${({$position:e})=>Hv[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Sr}:hover &,${Sr}:focus-within &{opacity:1;}`,zv=E.default(B)`padding:6px 8px;background:${_.themedColor.textHighEmphasis};color:${_.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Vv=2e3,Fo=0,qv=1500,un=Symbol("header-focus-status-pause"),Uo="data-sb-header-focus-protected",Kv="[data-message-composer]",Bo=new WeakMap,sr=e=>{const t=Bo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return Bo.set(e,n),n},or=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},fn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},Yv=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),fn(e)},Wv=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)})},jv=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(Kv),!1),rs=()=>{const{setStatusPauseState:e}=nt(),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()+qv,o();const u=sr(e);or(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(un,!0),fn(u),u.maxPauseTimeout=setTimeout(()=>{Yv(u),e(un,!1)},Vv)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=sr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;or(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,C=g instanceof HTMLElement&&g.hasAttribute(Uo);if(g===d||C||!jv(g))return;const v=Wv(d);d.focus({preventScroll:!0}),v()},Fo)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(fn(m),e(un,!1))},Fo))},[o,e]);return l.useEffect(()=>()=>{const u=sr(e);n.current=!1,o(),or(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(fn(u),e(un,!1))},[o,e]),{[Uo]:"true",onFocus:i,onBlur:c}},Xv=()=>{const{logger:e}=me(),{stringSet:t}=ae(),{channelSource:n}=Te(),{conversation:r}=oe(),s=n.channel,o=Mt(),i=Ur("handoff-button",s),c=!xr(s)||et(s),[u,d]=l.useState(!1),m=rs(),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(Uv,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(rt,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(lt,{portalContainerId:Se.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(es,{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})))},Zv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Jv=()=>{const{logger:e}=me(),{stringSet:t}=ae(),{memoryInfo:n,sdkUser:r}=Ne(),{actions:s}=Te(),{conversation:o}=oe(),i=Mt(20),c=rs(),[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),C=async v=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:v}),d(null)}catch(p){e.error("memoryIndicator.setUserMemoryState: error",p),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(nS,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(ee,{type:"memory",size:i,color:_.themedColor.textHighEmphasis}),a.createElement(rS,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(Qv,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:C}),a.createElement(Nn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},Qv=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=ae(),{colors:s}=H.useTheme(),o=l.useId(),i=l.useId(),c=Nu(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(lt,{visible:!0,portalContainerId:Se.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(es,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(eS,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}}))},eS=({children:e})=>{const{handlers:t}=me();return a.createElement(sS,null,a.createElement(Ht,{fallback:e},a.createElement(Zv,{onClickLink:t.onClickLink},e)))},tS=H.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;`,nS=E.default.button`${tS};cursor:pointer;${Re}`,rS=E.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?_.themedColor.secondary:_.color.background300};box-shadow:0 0 0 2px ${_.color.background50};${te.dark`
452
- box-shadow: 0 0 0 2px ${_.color.background500};
451
+ `,Bv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Hv=()=>{const{aiAgentInfo:e,userSession:t}=Oe(),{handlers:n}=ue(),{messageSource:r,channelSource:s}=Ae(),[o,i]=l.useState(null),c=Wr("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>nt(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(Uv,null,a.createElement(Bv,{onClickLink:n.onClickLink},e.specialNotice))},Gv=()=>a.createElement(zv,null,a.createElement(Hv,null),a.createElement(Av,null,a.createElement(Fv,null))),zv=_.default.div`z-index:0;border:none;width:100%;`,Vv=()=>{var s;const{testerType:e}=za(),{channelSource:t}=Ae(),n=De(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(vv,null):a.createElement(Gv,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(qv,{...s},a.createElement(Kv,null,n==="center"&&t&&a.createElement(Yv,{$sideWidth:Math.max(c,d)},a.createElement(Wv,null,t)),a.createElement(jv,null,a.createElement(Xv,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Jv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Zv,{ref:i},r))))},qv=_.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${E.themedColor.textDisabled};`,Kv=_.default.div`position:relative;height:56px;padding:11px 12px;`,Yv=_.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;`,Wv=_.default.div`max-width:100%;overflow:hidden;`,jv=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Xv=_.default.div`flex-shrink:0;display:flex;align-items:center;`,Zv=_.default.div`flex-shrink:0;display:flex;align-items:center;`,Jv=_.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;`,Nt=(e=16)=>en()?e*1.5:e,Qv=()=>{const{state:e}=ue(),{messenger:t}=ae(),n=Nt(),r=()=>{e.setOpened(!1)};return a.createElement(st,{...t.closeButton().props,type:"close",size:n,onClick:r})},eS=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ue(),{channelSource:n}=Ae(),{conversation:r}=ae(),s=n.channel,o=Nt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!$r(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(at.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(st,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},tS=()=>{const{state:e,enableExpandButton:t}=ue(),{messenger:n}=ae(),r=Nt();return t?a.createElement(st,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},nS=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(kr,null,t,a.createElement(oS,{$position:n},a.createElement(iS,{variant:"caption1"},e),a.createElement(rS,{$position:n}))),rS=({$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})),sS={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%);`},kr=_.default.div`position:relative;`,oS=_.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${_t.TOOLTIP};${({$position:e})=>sS[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${kr}:hover &,${kr}:focus-within &{opacity:1;}`,iS=_.default(B)`padding:6px 8px;background:${E.themedColor.textHighEmphasis};color:${E.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,aS=2e3,Go=0,cS=1500,pn=Symbol("header-focus-status-pause"),zo="data-sb-header-focus-protected",lS="[data-message-composer]",Vo=new WeakMap,mr=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},hr=(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)},uS=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),bn(e)},dS=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)})},mS=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(lS),!1),ms=()=>{const{setStatusPauseState:e}=lt(),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()+cS,o();const u=mr(e);hr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(pn,!0),bn(u),u.maxPauseTimeout=setTimeout(()=>{uS(u),e(pn,!1)},aS)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=mr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;hr(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,p=g instanceof HTMLElement&&g.hasAttribute(zo);if(g===d||p||!mS(g))return;const v=dS(d);d.focus({preventScroll:!0}),v()},Go)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(bn(m),e(pn,!1))},Go))},[o,e]);return l.useEffect(()=>()=>{const u=mr(e);n.current=!1,o(),hr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(bn(u),e(pn,!1))},[o,e]),{[zo]:"true",onFocus:i,onBlur:c}},hS=()=>{const{logger:e}=ue(),{stringSet:t}=ie(),{channelSource:n}=Ae(),{conversation:r}=ae(),s=n.channel,o=Nt(),i=Wr("handoff-button",s),c=!$r(s)||ct(s),[u,d]=l.useState(!1),m=ms(),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(nS,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(st,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(ft,{portalContainerId:Se.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ls,{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})))},fS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),gS=()=>{const{logger:e}=ue(),{stringSet:t}=ie(),{memoryInfo:n,sdkUser:r}=Oe(),{actions:s}=Ae(),{conversation:o}=ae(),i=Nt(20),c=ms(),[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),p=async v=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:v}),d(null)}catch(S){e.error("memoryIndicator.setUserMemoryState: error",S),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(CS,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(te,{type:"memory",size:i,color:E.themedColor.textHighEmphasis}),a.createElement(bS,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(pS,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:p}),a.createElement(Fn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},pS=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=ie(),{colors:s}=U.useTheme(),o=l.useId(),i=l.useId(),c=Wu(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(ft,{visible:!0,portalContainerId:Se.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(ls,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(_S,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}}))},_S=({children:e})=>{const{handlers:t}=ue();return a.createElement(vS,null,a.createElement(Kt,{fallback:e},a.createElement(fS,{onClickLink:t.onClickLink},e)))},ES=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;`,CS=_.default.button`${ES};cursor:pointer;${xe}`,bS=_.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};${ne.dark`
452
+ box-shadow: 0 0 0 2px ${E.color.background500};
453
453
  `}
454
- `,sS=E.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;}`,oS=()=>{const{conversation:e}=oe(),{onNavigateToConversationList:t}=Te();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(rt,{...n.menu.props,...Oi,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Ba=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Ne(),{fallbackIcon:s,url:o}=Br({channel:e,aiAgentInfo:r,userSession:n}),[i,c]=l.useState(),u=H.useTheme();return o&&o!==i?a.createElement(Ca,{src:o,size:t,"aria-hidden":"true",onImageError:c}):a.createElement(iS,{"aria-hidden":"true",$size:t,$bgColor:u.colors.base.primary},a.createElement(ee,{type:s,size:t*.55,color:u.colors.base.primaryContrastContent}))},iS=E.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;`,aS=()=>{const{channelSource:e}=Te(),{aiAgentInfo:t,userSession:n}=Ne(),{conversation:r}=oe(),{config:s}=xe(),{announcementsEnabled:o}=nt(),i=e.channel,c=Br({channel:i,userSession:n,aiAgentInfo:t}),u=s.conversation.header.avatarEnabled,d=rs(),m=la({enabled:o,label:c.title}),h={title:r.header.title(c.title,{active:m.enabled,titleId:m.id,initialFocus:!1})};return a.createElement(cS,null,u&&a.createElement(Ba,{channel:i,size:34}),a.createElement(lS,{...h.title.props,...d},c.title))},cS=E.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,lS=E.default(B).attrs({variant:"h2",color:_.themedColor.textHighEmphasis})`
454
+ `,vS=_.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;}`,SS=()=>{const{conversation:e}=ae(),{onNavigateToConversationList:t}=Ae();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(st,{...n.menu.props,...Ui,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Ya=({channel:e,size:t=40,skeletonColor:n=E.themedColor.bg_100_500})=>{const{userSession:r,aiAgentInfo:s}=Oe(),{fallbackIcon:o,url:i}=jr({channel:e,aiAgentInfo:s,userSession:r}),[c,u]=l.useState();c&&c.url!==i&&u(void 0);const d=U.useTheme(),{primary:m,primaryContrastContent:h}=d.colors.base;if(!o)return a.createElement(qo,{"aria-hidden":"true",$size:t,$bgColor:n});if(i&&(c==null?void 0:c.status)!=="failed"){const f=(c==null?void 0:c.status)==="loaded"?m:n;return a.createElement(Ia,{src:i,size:t,"aria-hidden":"true",onImageError:g=>u({url:g,status:"failed"}),onImageLoad:g=>u({url:g,status:"loaded"}),backgroundColor:f})}return a.createElement(qo,{"aria-hidden":"true",$size:t,$bgColor:m},a.createElement(te,{type:o,size:t*.55,color:h}))},qo=_.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;`,yS=()=>{const{channelSource:e}=Ae(),{aiAgentInfo:t,userSession:n}=Oe(),{conversation:r}=ae(),{config:s}=ye(),{announcementsEnabled:o}=lt(),i=U.useTheme(),c=e.channel,u=jr({channel:c,userSession:n,aiAgentInfo:t}),d=s.conversation.header.avatarEnabled,m=ms(),h=pa({enabled:o,label:u.title}),f={title:r.header.title(u.title,{active:h.enabled,titleId:h.id,initialFocus:!1})};return a.createElement(AS,null,d&&a.createElement(Ya,{channel:c,size:34,skeletonColor:i.colors.conversation.headerProfileSkeleton}),a.createElement(TS,{...f.title.props,...m},u.title))},AS=_.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,TS=_.default(B).attrs({variant:"h2",color:E.themedColor.textHighEmphasis})`
455
455
  margin: 0;
456
456
  flex: 1;
457
457
  min-width: 0;
@@ -463,10 +463,10 @@
463
463
  &:focus {
464
464
  outline: none;
465
465
  }
466
- `,uS=e=>{const{components:t}=_t.useContext();return a.createElement(Ua,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:$i})},dS=()=>{const{components:e}=_t.useContext();return a.createElement(e.MenuButton,null)},mS=()=>{const{components:e}=_t.useContext();return a.createElement(e.Title,null)},hS=()=>{const{components:e}=_t.useContext();return a.createElement(gS,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))},_t=qe({template:uS,components:{StartArea:dS,TitleArea:mS,EndArea:hS,MenuButton:oS,Title:aS,MemoryIndicator:Jv,HandoffButton:Xv,ConversationCloseButton:Pv,ExpandButton:Fv,CloseButton:$v}}),fS=()=>{const{Template:e}=_t.useContext();return a.createElement(e,{titleAlign:"start"})},gS=E.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,ss=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,shouldInitializeConversation:o,announcementsEnabled:i=!0,conversationStatsEnabled:c,initialFocusTarget:u,style:d,closedChannelUrl:m,onClearClosedChannelUrl:h})=>{const{Template:f}=Bn.useContext();return a.createElement(ia,{onNavigateToConversationList:t,channelUrl:n??m,onClearChannelUrl:r??h,conversationStatsEnabled:c,shouldMarkAsRead:s,shouldInitializeConversation:o},a.createElement(pr,null,a.createElement(pr.Consumer,null,g=>a.createElement(yf,{announcementsEnabled:i},a.createElement(pS,null),a.createElement(_S,null),a.createElement(ES,{style:d,dragHandlers:g,initialFocusTarget:u},a.createElement(f,null)),e))))},pS=()=>(yg(),null),_S=()=>(Fg(),Rg(),Dg(),null),ES=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return Sg(s,n),a.createElement(bS,{ref:s,style:e,...t},r)},CS=e=>{const{components:t}=Bn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},Bn=qe({template:CS,components:{Header:fS,Body:jb,Footer:xv}}),bS=E.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Ha=ve("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:he}),vS=Ha.Provider,os=Ha.useContext,SS=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=qr(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(vS,{value:s},e)},{Provider:yS,Context:AS,useContext:Zt}=ve("ConversationList");function Ga({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=he,children:s}){return a.createElement(nm,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(yS,{value:{...o,onOpenConversationView:r}},s))}const TS=e=>{const{announcementsEnabled:t}=os(),{listSource:n}=Zt(),r=qi();ua(e,{enabled:t,ready:n.initialized,suppressed:r})},IS=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=os(),{listSource:n}=Zt(),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])},xS=({channel:e})=>a.createElement(Ba,{channel:e}),yr=99,RS=e=>{var p,b;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=ae(),{userSession:o,aiAgentInfo:i}=Ne(),{conversationList:c}=oe(),u=Br({channel:t,userSession:o,aiAgentInfo:i}),d=Mu(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=ku(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=(p=t.lastMessage)!=null&&p.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=Fe(t)?r.CONVERSATION_LIST__ENDED:"",C=n?()=>n():void 0,v=c.item({agent:f,status:g,lastMessage:d,time:m,unreadCount:h,onActivate:C});return a.createElement(MS,{"data-testid":"sb-conversation-list-item",$clickable:!!C,...v.props},a.createElement(wS,null,a.createElement(xS,{...e})),a.createElement(kS,null,a.createElement(LS,null,(b=t.lastMessage)!=null&&b.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(ga,{variant:"subtitle1",color:_.themedColor.textHighEmphasis},d):a.createElement(B,{variant:"subtitle1",color:_.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(OS,null,Fe(t)&&a.createElement(a.Fragment,null,a.createElement(B,{variant:"caption1",color:_.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(NS,null)),a.createElement(B,{variant:"caption2",color:_.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(DS,{$count:h},a.createElement(B,{variant:"caption3",color:_.themedColor.textHighEmphasisInverse},h<=yr?h:`${yr}+`))),v.descriptionNode)},is=qe({template:RS,components:{}}),MS=E.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"};`,wS=E.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,kS=E.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 ${_.themedColor.textDisabled};`,LS=E.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;`,OS=E.default.div`display:flex;align-items:center;gap:6px;`,NS=E.default.div`width:2px;height:2px;border-radius:1px;background-color:${_.themedColor.textLowEmphasis};`,DS=E.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${_.themedColor.error};${({$count:e})=>e<=yr&&H.css`
466
+ `,IS=e=>{const{components:t}=bt.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:Gi})},xS=()=>{const{components:e}=bt.useContext();return a.createElement(e.MenuButton,null)},RS=()=>{const{components:e}=bt.useContext();return a.createElement(e.Title,null)},MS=()=>{const{components:e}=bt.useContext();return a.createElement(kS,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))},bt=je({template:IS,components:{StartArea:xS,TitleArea:RS,EndArea:MS,MenuButton:SS,Title:yS,MemoryIndicator:gS,HandoffButton:hS,ConversationCloseButton:eS,ExpandButton:tS,CloseButton:Qv}}),wS=()=>{const{Template:e}=bt.useContext();return a.createElement(e,{titleAlign:"start"})},kS=_.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,hs=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,announcementsEnabled:c=!0,conversationStatsEnabled:u,initialFocusTarget:d,style:m,closedChannelUrl:h,onClearClosedChannelUrl:f})=>{const{Template:g}=Vn.useContext();return a.createElement(ha,{onNavigateToConversationList:t,channelUrl:n??h,onClearChannelUrl:r??f,conversationStatsEnabled:u,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i},a.createElement(Tr,null,a.createElement(Tr.Consumer,null,p=>a.createElement(Bf,{announcementsEnabled:c},a.createElement(LS,null),a.createElement(OS,null),a.createElement(NS,{style:m,dragHandlers:p,initialFocusTarget:d},a.createElement(g,null)),e))))},LS=()=>(Bg(),null),OS=()=>(tp(),qg(),Jg(),null),NS=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return Ug(s,n),a.createElement($S,{ref:s,style:e,...t},r)},DS=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:DS,components:{Header:wS,Body:mv,Footer:Vv}}),$S=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Wa=ve("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:me}),PS=Wa.Provider,fs=Wa.useContext,FS=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=es(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(PS,{value:s},e)},{Provider:US,Context:BS,useContext:nn}=ve("ConversationList");function ja({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=me,children:s}){return a.createElement(gm,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(US,{value:{...o,onOpenConversationView:r}},s))}const HS=e=>{const{announcementsEnabled:t}=fs(),{listSource:n}=nn(),r=Zi();_a(e,{enabled:t,ready:n.initialized,suppressed:r})},GS=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=fs(),{listSource:n}=nn(),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])},zS=({channel:e})=>a.createElement(Ya,{channel:e}),Lr=99,VS=e=>{var S,C;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=ie(),{userSession:o,aiAgentInfo:i}=Oe(),{conversationList:c}=ae(),u=jr({channel:t,userSession:o,aiAgentInfo:i}),d=zu(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=qu(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=(S=t.lastMessage)!=null&&S.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=De(t)?r.CONVERSATION_LIST__ENDED:"",p=n?()=>n():void 0,v=c.item({agent:f,status:g,lastMessage:d,time:m,unreadCount:h,onActivate:p});return a.createElement(qS,{"data-testid":"sb-conversation-list-item",$clickable:!!p,...v.props},a.createElement(KS,null,a.createElement(zS,{...e})),a.createElement(YS,null,a.createElement(WS,null,(C=t.lastMessage)!=null&&C.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(jS,null,De(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(ZS,{$count:h},a.createElement(B,{variant:"caption3",color:E.themedColor.textHighEmphasisInverse},h<=Lr?h:`${Lr}+`))),v.descriptionNode)},gs=je({template:VS,components:{}}),qS=_.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"};`,KS=_.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,YS=_.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};`,WS=_.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;`,jS=_.default.div`display:flex;align-items:center;gap:6px;`,XS=_.default.div`width:2px;height:2px;border-radius:1px;background-color:${E.themedColor.textLowEmphasis};`,ZS=_.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<=Lr&&U.css`
467
467
  width: 20px;
468
468
  `}
469
- `,$S=({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(PS,{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(FS,{key:d,role:"listitem"},u)}))},PS=E.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,FS=E.default.div`flex-shrink:0;`,US=()=>{const{stringSet:e}=ae(),{listSource:t,onOpenConversationView:n}=Zt(),{Template:r}=is.useContext();return t.initialized?t.channels.length===0?a.createElement(Ut,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement($S,{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"})},BS=()=>{const{stringSet:e}=ae(),{_aiAgentSDK:t}=xe(),{language:n,countryCode:r,context:s}=me(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Ne(),{onOpenConversationView:u}=Zt(),{conversationList:d}=oe(),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(HS,{...d.footer.button({onActivate:m}).props},a.createElement(GS,{variant:"h1"},e.TALK_TO_AGENT))},HS=E.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,GS=E.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,zS=()=>{const{state:e}=me(),{messenger:t}=oe(),n=Mt(),r=()=>{e.setOpened(!1)};return a.createElement(rt,{...t.closeButton().props,type:"close",size:n,onClick:r})},VS=()=>{const{stringSet:e}=ae(),{announcementsEnabled:t}=os(),{conversationList:n}=oe(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=la({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(qS,{forwardedAs:"h2",variant:"h2",color:_.themedColor.textHighEmphasis,...o.title.props},r)},qS=E.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,KS=e=>{const{components:t}=wt.useContext();return a.createElement(Ua,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:$i})},YS=()=>null,WS=()=>{const{components:e}=wt.useContext();return a.createElement(e.Title,null)},jS=()=>{const{components:e}=wt.useContext();return a.createElement(e.CloseButton,null)},wt=qe({template:KS,components:{StartArea:YS,TitleArea:WS,EndArea:jS,Title:VS,CloseButton:zS}}),XS=()=>{const{Template:e}=wt.useContext();return a.createElement(e,{titleAlign:"start"})},ZS=()=>(IS(),null),as=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=Hn.useContext();return a.createElement(Ga,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(SS,{announcementsEnabled:s},a.createElement(ZS,null),a.createElement(JS,{style:i},a.createElement(c,null)),n))},JS=({style:e,children:t})=>{const n=l.useRef(null);return TS(n),a.createElement(ey,{ref:n,style:e},t)},QS=()=>{const{components:e}=Hn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},Hn=qe({template:QS,components:{Header:XS,Body:US,Footer:BS}}),ey=E.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,ty=H.css`:where(#${Se.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,ny=[ty,jh,Xh],ry=(e,...t)=>H.createGlobalStyle(e,...ny,...t),sy=ry``,oy=Ru(Bn,pt,Rt,Pn,Un,Hn,_t,is,wt,Fn,On),iy=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function za({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){pf(iy?$h:"",t);const[f,g]=l.useState(null),C=l.useCallback(b=>{g(y=>y===b?y:b)},[]),v=m??f,p=a.createElement(H.StyleSheetManager,{target:t},a.createElement(hf,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(Bh,{rootElement:t,boundaryElement:v},a.createElement(im,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(Wh,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(df,{icons:u},a.createElement(oy,null,a.createElement(Fh,{entryElement:v,modalRootElement:h,rootElement:t},i),a.createElement(sy,null))))))));return m?p:a.createElement("div",{ref:C,style:{display:"contents"}},p)}const ay=()=>{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}},cs=l.forwardRef(function({rootElement:t=document.body,logLevel:n=Ce.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var p,b,y;Pt.level!==n&&(Pt.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=ay();gf("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const C=Gi(r),v=zi.has(C)?C:Wt;return a.createElement("div",{ref:f,id:Se.ENTRY,lang:v,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(za,{logger:Pt,rootElement:t,appearance:(p=u.agentPreviewConfigs)==null?void 0:p.appearance,stringSet:u.stringSet,language:v,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(jf,{rootElement:t,language:r,logger:Pt,dispatcher:Va,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(b=u.agentPreviewConfigs)==null?void 0:b.forceCreateChannel,_agentVersion:(y=u.agentPreviewConfigs)==null?void 0:y.agentVersion,...u},a.createElement(rg,{ref:d,userSessionInfo:s},a.createElement(ev,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(vf,null,o))))),a.createElement("div",{ref:g,id:Se.MODAL_ROOT,dir:u.dir}))}),Pt=new ri(Ce.LogLevel.WARN),Va=new ei(Pt),{Provider:cy,useContext:Jt}=ve("PageChildren"),qa=({children:e})=>{const[t,n]=l.useState(()=>ss),[r,s]=l.useState(null),[o,i]=l.useState(()=>as),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(cy,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},ls=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Se.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Ka=({children:e,isOpened:t,zIndex:n=ft.WINDOW})=>a.createElement(jr,null,a.createElement(ly,{isOpened:t,zIndex:n},e)),ly=({children:e,isOpened:t,zIndex:n=ft.WINDOW})=>{const{dir:r,rootElement:s}=me(),o=ct(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Dn();return Ln(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(uy,{ref:i,id:Se.WINDOW,dir:r,...ls(t,c),$visible:t,$zIndex:n},e)},uy=E.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,dy=48,my=2/3,Ho=12;function Ya({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=dy,hasUnread:f=!1}){const g=va(),C=d&&!g,v=dr(m),p=Math.round(h*my);return a.createElement(gy,{dir:u,id:Se.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:C,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(py,{$isOpened:n,$animated:C,$fillColor:v,$iconSize:p,$prefersReducedMotion:g},a.createElement(Go.Open,{url:c,isDefaultIcon:i==="default_icon",size:p})),a.createElement(_y,{$isOpened:n,$animated:C,$fillColor:v,$iconSize:p,$prefersReducedMotion:g},a.createElement(Go.Close,{size:p})),f&&a.createElement(Ey,null),t)}const hy=H.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,fy=H.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%)"};}}`,Wa=H.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>H.css`
469
+ `,JS=({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(QS,{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(ey,{key:d,role:"listitem"},u)}))},QS=_.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,ey=_.default.div`flex-shrink:0;`,ty=()=>{const{stringSet:e}=ie(),{listSource:t,onOpenConversationView:n}=nn(),{Template:r}=gs.useContext();return t.initialized?t.channels.length===0?a.createElement(Vt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(JS,{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,De(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(Vt,{type:"loading"})},ny=()=>{const{stringSet:e}=ie(),{_aiAgentSDK:t}=ye(),{language:n,countryCode:r,context:s}=ue(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Oe(),{onOpenConversationView:u}=nn(),{conversationList:d}=ae(),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(ry,{...d.footer.button({onActivate:m}).props},a.createElement(sy,{variant:"h1"},e.TALK_TO_AGENT))},ry=_.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,sy=_.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,oy=()=>{const{state:e}=ue(),{messenger:t}=ae(),n=Nt(),r=()=>{e.setOpened(!1)};return a.createElement(st,{...t.closeButton().props,type:"close",size:n,onClick:r})},iy=()=>{const{stringSet:e}=ie(),{announcementsEnabled:t}=fs(),{conversationList:n}=ae(),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(ay,{forwardedAs:"h2",variant:"h2",color:E.themedColor.textHighEmphasis,...o.title.props},r)},ay=_.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,cy=e=>{const{components:t}=Dt.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:Gi})},ly=()=>null,uy=()=>{const{components:e}=Dt.useContext();return a.createElement(e.Title,null)},dy=()=>{const{components:e}=Dt.useContext();return a.createElement(e.CloseButton,null)},Dt=je({template:cy,components:{StartArea:ly,TitleArea:uy,EndArea:dy,Title:iy,CloseButton:oy}}),my=()=>{const{Template:e}=Dt.useContext();return a.createElement(e,{titleAlign:"start"})},hy=()=>(GS(),null),ps=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=qn.useContext();return a.createElement(ja,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(FS,{announcementsEnabled:s},a.createElement(hy,null),a.createElement(fy,{style:i},a.createElement(c,null)),n))},fy=({style:e,children:t})=>{const n=l.useRef(null);return HS(n),a.createElement(py,{ref:n,style:e},t)},gy=()=>{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:gy,components:{Header:my,Body:ty,Footer:ny}}),py=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,_y=U.css`:where(#${Se.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,Ey=[_y,hf,ff],Cy=(e,...t)=>U.createGlobalStyle(e,...Ey,...t),by=Cy``,vy=Gu(Vn,Ct,Ot,Hn,zn,qn,bt,gs,Dt,Gn,Pn),Sy=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}){Of(Sy?Qh:"",t);const[f,g]=l.useState(null),p=l.useCallback(C=>{g(A=>A===C?A:C)},[]),v=m??f,S=a.createElement(U.StyleSheetManager,{target:t},a.createElement(wf,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(rf,{rootElement:t,boundaryElement:v},a.createElement(Cm,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(mf,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(Rf,{icons:u},a.createElement(vy,null,a.createElement(tf,{entryElement:v,modalRootElement:h,rootElement:t},i),a.createElement(by,null))))))));return m?S:a.createElement("div",{ref:p,style:{display:"contents"}},S)}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}},_s=l.forwardRef(function({rootElement:t=document.body,logLevel:n=Ce.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var S,C,A;Ht.level!==n&&(Ht.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=yy();Lf("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const p=Wi(r),v=ji.has(p)?p:Qt;return a.createElement("div",{ref:f,id:Se.ENTRY,lang:v,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(Xa,{logger:Ht,rootElement:t,appearance:(S=u.agentPreviewConfigs)==null?void 0:S.appearance,stringSet:u.stringSet,language:v,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(mg,{rootElement:t,language:r,logger:Ht,dispatcher:Za,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(C=u.agentPreviewConfigs)==null?void 0:C.forceCreateChannel,_agentVersion:(A=u.agentPreviewConfigs)==null?void 0:A.agentVersion,...u},a.createElement(bg,{ref:d,userSessionInfo:s},a.createElement(_v,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(Ff,null,o))))),a.createElement("div",{ref:g,id:Se.MODAL_ROOT,dir:u.dir}))}),Ht=new ci(Ce.LogLevel.WARN),Za=new oi(Ht),{Provider:Ay,useContext:rn}=ve("PageChildren"),Ja=({children:e})=>{const[t,n]=l.useState(()=>hs),[r,s]=l.useState(null),[o,i]=l.useState(()=>ps),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(Ay,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},Es=(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=_t.WINDOW})=>a.createElement(ss,null,a.createElement(Ty,{isOpened:t,zIndex:n},e)),Ty=({children:e,isOpened:t,zIndex:n=_t.WINDOW})=>{const{dir:r,rootElement:s}=ue(),o=mt(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(Iy,{ref:i,id:Se.WINDOW,dir:r,...Es(t,c),$visible:t,$zIndex:n},e)},Iy=_.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,xy=48,Ry=2/3,Ko=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=xy,hasUnread:f=!1}){const g=Ra(),p=d&&!g,v=br(m),S=Math.round(h*Ry);return a.createElement(ky,{dir:u,id:Se.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:p,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(Ly,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:S,$prefersReducedMotion:g},a.createElement(Yo.Open,{url:c,isDefaultIcon:i==="default_icon",size:S})),a.createElement(Oy,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:S,$prefersReducedMotion:g},a.createElement(Yo.Close,{size:S})),f&&a.createElement(Ny,null),t)}const My=U.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,wy=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===qt.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`
470
470
  ellipse,
471
471
  path {
472
472
  fill: ${e};
@@ -476,7 +476,7 @@
476
476
  }
477
477
  `}
478
478
  }
479
- `,gy=E.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&&hy}`,ja=E.default.span.attrs({"aria-hidden":"true"})`
479
+ `,ky=_.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:${ua};${({$animated:e})=>e&&My}`,nc=_.default.span.attrs({"aria-hidden":"true"})`
480
480
  position: absolute;
481
481
  width: 100%;
482
482
  height: 100%;
@@ -486,23 +486,23 @@
486
486
  display: flex;
487
487
  justify-content: center;
488
488
  align-items: center;
489
- `,py=E.default(ja)`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)")};${fy}${Wa}`,_y=E.default(ja)`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)")};${Wa}`,Ey=E.default.span.attrs({"aria-hidden":"true"})`
489
+ `,Ly=_.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)")};${wy}${tc}`,Oy=_.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}`,Ny=_.default.span.attrs({"aria-hidden":"true"})`
490
490
  position: absolute;
491
491
  top: 1px;
492
492
  inset-inline-end: 1px;
493
- width: ${Ho}px;
494
- height: ${Ho}px;
493
+ width: ${Ko}px;
494
+ height: ${Ko}px;
495
495
  border-radius: 50%;
496
- background-color: ${_.themedColor.error};
497
- `,Go={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(ee,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(ee,{size:e,type:"chevron-down"})};function Xa({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=H.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=me(),{resolveElement:d}=zr(),{launcher:m}=oe(),{launcherInfo:h}=Ne(),f=i.launcher.unreadBadgeEnabled,g=bi(),C=Um(o,{enabled:f,opened:u.opened,filter:g}),v=(r??n)==="ConversationList",p={launcher:m.button({isOpened:u.opened,opensConversationList:v})};Fm("launcher_toggle"),by();const b=()=>{Ie(()=>{const T=d(Se.WINDOW),R=T?Qi(T):null;R==null||R.focus()})},y=()=>{Ie(()=>{var T;(T=d(Se.LAUNCHER))==null||T.focus()})},A=()=>{const T=!u.opened;u.setOpened(T),T?b():y()};return a.createElement(Ya,{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&&C,...p.launcher.props},p.launcher.descriptionNode)}const Cy=1e3*60;function by(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=me(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===Ce.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")},Cy)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const Za=l.createContext(null);function us(){const e=l.useContext(Za);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Ja({children:e}){const t=us();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}const vy=H.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,Sy=H.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,yy=H.css`animation-name:${vy};animation-duration:0.3s;animation-fill-mode:forwards;`,Ay=H.css``,Ty=H.css`animation-name:${Sy};animation-duration:0.3s;animation-fill-mode:forwards;`,Iy=H.css`visibility:hidden;`,xy=E.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return yy;case"entered":return Ay;case"exiting":return Ty;case"exited":return Iy;default:return""}}}${({$active:e})=>e?H.css`
496
+ background-color: ${E.themedColor.error};
497
+ `,Yo={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(te,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(te,{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}=ue(),{resolveElement:d}=Jr(),{launcher:m}=ae(),{launcherInfo:h}=Oe(),f=i.launcher.unreadBadgeEnabled,g=Ti(),p=nh(o,{enabled:f,opened:u.opened,filter:g}),v=(r??n)==="ConversationList",S={launcher:m.button({isOpened:u.opened,opensConversationList:v})};th("launcher_toggle"),$y();const C=()=>{Ie(()=>{const T=d(Se.WINDOW),I=T?oa(T):null;I==null||I.focus()})},A=()=>{Ie(()=>{var T;(T=d(Se.LAUNCHER))==null||T.focus()})},y=()=>{const T=!u.opened;u.setOpened(T),T?C():A()};return a.createElement(ec,{dir:c,className:e,isOpened:u.opened,onClick:y,type:h.type,imageUrl:h.imageUrl,backgroundColor:s.base.primary,size:t,hasUnread:f&&!u.opened&&p,...S.launcher.props},S.launcher.descriptionNode)}const Dy=1e3*60;function $y(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ue(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===Ce.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")},Dy)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const sc=l.createContext(null);function Kn(){const e=l.useContext(sc);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function oc({children:e}){const t=Kn();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}function ic({children:e}){return a.createElement(a.Fragment,null,e)}const Py=U.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,Fy=U.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,Uy=U.css`animation-name:${Py};animation-duration:0.3s;animation-fill-mode:forwards;`,By=U.css``,Hy=U.css`animation-name:${Fy};animation-duration:0.3s;animation-fill-mode:forwards;`,Gy=U.css`visibility:hidden;`,zy=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return Uy;case"entered":return By;case"exiting":return Hy;case"exited":return Gy;default:return""}}}${({$active:e})=>e?U.css`
498
498
  z-index: 999;
499
- `:H.css`z-index:1;pointer-events:none;`}
500
- `;function gn({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((p,b)=>{r(y=>[...y,p]),h(y=>({...y,[p]:!0})),b!=null&&b.reset&&v(y=>({...y,[p]:(y[p]||0)+1})),g(y=>({...y,[p]:"entering"})),setTimeout(()=>{g(y=>({...y,[p]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(p=>{if(p.length<=1)return p;const b=p[p.length-1];return g(y=>({...y,[b]:"exiting"})),setTimeout(()=>{g(y=>({...y,[b]:"exited"})),r(y=>y.slice(0,-1))},300),p})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(p=>p.type===Ja),[t]),d=l.useMemo(()=>{const p={};return u.forEach(b=>{const{id:y,lazy:A,children:T}=b.props;p[y]={lazy:A,element:typeof T=="function"?T(c):T}}),p},[u,c]),[m,h]=l.useState(()=>{const p={};return Object.entries(d).forEach(([b,{lazy:y}])=>{y===!1&&(p[b]=!0)}),p[e]=!0,p}),[f,g]=l.useState(()=>{const p={};return Object.keys(d).forEach(b=>{b===e?p[b]="entered":p[b]="exited"}),p}),[C,v]=l.useState({});return a.createElement(Za.Provider,{value:c},a.createElement(Ry,null,Object.keys(d).map(p=>{var T;if(!m[p])return null;const b=f[p]||"exited",y=p===s,A=`${p}-${C[p]||0}`;return a.createElement(xy,{key:A,$transitionState:b,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(T=d[p])==null?void 0:T.element)})))}const Ry=E.default.div`position:relative;width:100%;height:100%;`;gn.Screen=Ja;const Ge={conv:"conv",convList:"conv-list"},My=e=>e===Ge.convList?"ConversationList":"Conversation",Qa=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:s})=>{const{conversationComponent:o,conversationChildren:i,conversationListComponent:c,conversationListChildren:u}=Jt(),[d,m]=l.useState(),h=(()=>{switch(t){case"Conversation":return Ge.conv;case"ConversationList":return Ge.convList;default:return Ge.conv}})(),f=a.createElement(a.Fragment,null,a.createElement(wy,{onOpenConversationView:(g,C)=>{r(C),m(void 0),g.navigate(Ge.conv)}}),a.createElement(ky,{onActiveRouteChange:s}));return a.createElement(gn,{initialId:h},a.createElement(gn.Screen,{id:Ge.conv},({navigation:g,activeScreenId:C})=>{const v=C===Ge.conv,p=e&&v;return a.createElement(a.Fragment,null,f,a.createElement(o,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{m(void 0),g.navigate(Ge.convList)},announcementsEnabled:p,conversationStatsEnabled:p,shouldMarkAsRead:p,shouldInitializeConversation:p,initialFocusTarget:d},i))}),a.createElement(gn.Screen,{id:Ge.convList,lazy:!0},({navigation:g,activeScreenId:C})=>{const v=C===Ge.convList,p=e&&v;return a.createElement(a.Fragment,null,f,a.createElement(c,{announcementsEnabled:p,conversationListStatsEnabled:p,onOpenConversationView:(b,y,A)=>{r(b),m(A==null?void 0:A.initialFocusTarget),g.navigate(Ge.conv)}},u))}))},wy=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Ne(),{navigation:n}=us();return t(({channel:r})=>{e(n,r.url)}),null},ky=({onActiveRouteChange:e})=>{const{activeScreenId:t}=us();return l.useEffect(()=>{e==null||e(My(t))},[t,e]),null},Ly=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(jr,null,a.createElement(Oy,{isExpanded:e,isOpened:t,launcher:r},n)),Oy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=me(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Dn();return Ln(t,o,{nameReady:c}),a.createElement(Ny,null,a.createElement(Dy,{ref:o,dir:s,id:Se.WINDOW,...ls(t,i),$isExpanded:e,$isOpened:t},n),r)},Ny=E.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,Dy=E.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&&Py};${({$isExpanded:e})=>e&&$y};`,$y=H.css`width:743px;height:723px;`,Py=H.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;`,Fy=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?Ka:Ly;return a.createElement(cs,{enableExpandButton:!s,ref:r,...n},a.createElement(ta,null,({state:m})=>a.createElement(qa,null,a.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...s&&{zIndex:"auto"},launcher:a.createElement(Xa,{entryPoint:n.entryPoint,activeRoute:c})},a.createElement(Qa,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,onActiveRouteChange:u})),e)))}),{Provider:Uy,useContext:ds}=ve("FixedMessengerStyle");function ec(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: ${Ye(i)}`;break;case"end":d=`inset-inline-end: ${Ye(c)}`;break}switch(t){case"top":u=`top: calc(${Ye(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Ye(o)} + ${r}px)`;break}return H.css`${u};${d};`}function By(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=ds();return a.createElement(Hy,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const Hy=E.default(Xa)`position:fixed;z-index:${ft.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>ec(e,t,n)};`,Gy=({isExpanded:e,isOpened:t,children:n})=>a.createElement(jr,null,a.createElement(zy,{isExpanded:e,isOpened:t},n)),zy=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=me(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=ds(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Dn();return Ln(t,u,{nameReady:m}),a.createElement(Vy,{ref:u,dir:r,id:Se.WINDOW,...ls(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},Vy=E.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})=>ec(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}`};
499
+ `:U.css`z-index:1;pointer-events:none;`}
500
+ `;function xt({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((C,A)=>{r(y=>[...y,C]),f(y=>({...y,[C]:!0})),A!=null&&A.reset&&S(y=>({...y,[C]:(y[C]||0)+1})),p(y=>({...y,[C]:"entering"})),setTimeout(()=>{p(y=>({...y,[C]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(C=>{if(C.length<=1)return C;const A=C[C.length-1];return p(y=>({...y,[A]:"exiting"})),setTimeout(()=>{p(y=>({...y,[A]:"exited"})),r(y=>y.slice(0,-1))},300),C})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(C=>C.type===oc),[t]),d=l.useMemo(()=>l.Children.toArray(t).filter(C=>C.type===ic),[t]),m=l.useMemo(()=>{const C={};return u.forEach(A=>{const{id:y,lazy:T,children:I}=A.props;C[y]={lazy:T,element:typeof I=="function"?I(c):I}}),C},[u,c]),[h,f]=l.useState(()=>{const C={};return Object.entries(m).forEach(([A,{lazy:y}])=>{y===!1&&(C[A]=!0)}),C[e]=!0,C}),[g,p]=l.useState(()=>{const C={};return Object.keys(m).forEach(A=>{A===e?C[A]="entered":C[A]="exited"}),C}),[v,S]=l.useState({});return a.createElement(sc.Provider,{value:c},d,a.createElement(Vy,null,Object.keys(m).map(C=>{var I;if(!h[C])return null;const A=g[C]||"exited",y=C===s,T=`${C}-${v[C]||0}`;return a.createElement(zy,{key:T,$transitionState:A,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(I=m[C])==null?void 0:I.element)})))}const Vy=_.default.div`position:relative;width:100%;height:100%;`;xt.Screen=oc;xt.Effect=ic;const ze={conv:"conv",convList:"conv-list"},qy=e=>e===ze.convList?"ConversationList":"Conversation",ac=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,nudgeConversation:s,onActiveRouteChange:o})=>{const{conversationComponent:i,conversationChildren:c,conversationListComponent:u,conversationListChildren:d}=rn(),[m,h]=l.useState(),f=(()=>{switch(t){case"Conversation":return ze.conv;case"ConversationList":return ze.convList;default:return ze.conv}})(),g=a.createElement(a.Fragment,null,a.createElement(Ky,{onOpenConversationView:(p,v)=>{r(v),h(void 0),p.navigate(ze.conv)}}),a.createElement(Wy,{onActiveRouteChange:o}));return a.createElement(xt,{initialId:f},a.createElement(xt.Effect,null,a.createElement(Yy,{nudgeConversation:s,onNavigate:p=>{h("messageInput"),p.navigate(ze.conv)}})),a.createElement(xt.Screen,{id:ze.conv},({navigation:p,activeScreenId:v})=>{const S=v===ze.conv,C=e&&S;return a.createElement(a.Fragment,null,g,a.createElement(i,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{h(void 0),p.navigate(ze.convList)},announcementsEnabled:C,conversationStatsEnabled:C,shouldMarkAsRead:C,shouldInitializeConversation:C,initialUserMessage:s&&s.channelUrl===n?s.initialUserMessage:void 0,initialFocusTarget:m},c))}),a.createElement(xt.Screen,{id:ze.convList,lazy:!0},({navigation:p,activeScreenId:v})=>{const S=v===ze.convList,C=e&&S;return a.createElement(a.Fragment,null,g,a.createElement(u,{announcementsEnabled:C,conversationListStatsEnabled:C,onOpenConversationView:(A,y,T)=>{r(A),h(T==null?void 0:T.initialFocusTarget),p.navigate(ze.conv)}},d))}))},Ky=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Oe(),{navigation:n}=Kn();return t(({channel:r})=>{e(n,r.url)}),null},Yy=({nudgeConversation:e,onNavigate:t})=>{const{navigation:n}=Kn();return l.useEffect(()=>{e&&t(n)},[e]),null},Wy=({onActiveRouteChange:e})=>{const{activeScreenId:t}=Kn();return l.useEffect(()=>{e==null||e(qy(t))},[t,e]),null},jy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(ss,null,a.createElement(Xy,{isExpanded:e,isOpened:t,launcher:r},n)),Xy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=ue(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Un();return $n(t,o,{nameReady:c}),a.createElement(Zy,null,a.createElement(Jy,{ref:o,dir:s,id:Se.WINDOW,...Es(t,i),$isExpanded:e,$isOpened:t},n),r)},Zy=_.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,Jy=_.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&&eA};${({$isExpanded:e})=>e&&Qy};`,Qy=U.css`width:743px;height:723px;`,eA=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;`,cc=({isMessengerOpened:e,onConversationStarted:t,className:n})=>{const{stringSet:r}=ie(),{dir:s}=ue(),{nudgeMessage:o,nudgeMessageKey:i,dismissNudgeMessage:c,startNudgeConversation:u}=wm({isMessengerOpened:e,onConversationStarted:t});return o?a.createElement(nA,{key:i,className:n,dir:s},a.createElement(rA,{onClick:u},a.createElement(sA,{variant:"body3",color:E.themedColor.textHighEmphasis,maxTextLines:2},o.message)),a.createElement(oA,{type:"close",size:16,"aria-label":r.A11Y_DISMISS_NUDGE_MESSAGE,onClick:c})):null},lc=12,tA=U.keyframes`from{opacity:0;transform:scale(0.8);}`,nA=_.default.div`position:relative;display:flex;align-items:flex-start;gap:8px;padding:16px;min-width:120px;max-width:320px;box-sizing:border-box;border-radius:${lc}px;background-color:${E.themedColor.bg_50_600};box-shadow:${ua};animation-name:${tA};animation-duration:0.3s;animation-timing-function:cubic-bezier(0.31,-0.105,0.43,1.4);@media (prefers-reduced-motion:reduce){animation-name:none;}`,rA=_.default.button`all:unset;flex:1;min-width:0;cursor:pointer;text-align:start;${xe}&::after{content:'';position:absolute;inset:0;border-radius:${lc}px;}`,sA=_.default(B)`line-height:20px;overflow-wrap:anywhere;white-space:pre-line;`,oA=_.default(st)`position:relative;margin:-4px;`,iA=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=en(),[o,i]=l.useState(t),[c,u]=l.useState(),[d,m]=l.useState(n.entryPoint??"Conversation"),h=s?Qa:jy;return a.createElement(_s,{enableExpandButton:!s,ref:r,...n},a.createElement(aa,null,({state:f})=>a.createElement(Ja,null,a.createElement(h,{isExpanded:f.expanded,isOpened:f.opened,...s&&{zIndex:"auto"},launcher:a.createElement(a.Fragment,null,a.createElement(cc,{isMessengerOpened:f.opened,onConversationStarted:g=>{i(g.channelUrl),u(g),f.setOpened(!0)}}),a.createElement(rc,{entryPoint:n.entryPoint,activeRoute:d}))},a.createElement(ac,{isOpened:f.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,nudgeConversation:c,onActiveRouteChange:m})),e)))}),{Provider:aA,useContext:Yn}=ve("FixedMessengerStyle");function uc(e,t,n,r=0){return U.css`&&{position:fixed;z-index:${_t.LAUNCHER};${dc(e,t,n,r)};}`}function dc(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: ${Je(i)}`;break;case"end":d=`inset-inline-end: ${Je(c)}`;break}switch(t){case"top":u=`top: calc(${Je(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Je(o)} + ${r}px)`;break}return U.css`${u};${d};`}function cA(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Yn();return a.createElement(lA,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const lA=_.default(rc)`${({$horizontal:e,$vertical:t,$margin:n})=>uc(e,t,n)};`,uA=({isExpanded:e,isOpened:t,children:n})=>a.createElement(ss,null,a.createElement(dA,{isExpanded:e,isOpened:t},n)),dA=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=ue(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=Yn(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Un();return $n(t,u,{nameReady:m}),a.createElement(mA,{ref:u,dir:r,id:Se.WINDOW,...Es(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},mA=_.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})=>dc(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}`};
501
501
  [dir='rtl'] &:not([dir='ltr']),
502
502
  &[dir='rtl'] {
503
503
  transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
504
504
  }
505
505
 
506
- ${({$isOpened:e})=>e&&Ky};
507
- ${({$isExpanded:e})=>e&&qy};
508
- `,qy=H.css`width:743px;height:723px;`,Ky=H.css`z-index:${ft.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;`,tc={top:24,bottom:24,start:24,end:24},Yy=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(tc),[f,g]=l.useState(48),C=jt(),v=C?Ka:Gy,{horizontal:p,vertical:b}=l.useMemo(()=>{const[y,A]=u.split("-");return{horizontal:y==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[u]);return a.createElement(cs,{enableExpandButton:!C,ref:r,...n},a.createElement(ta,null,({state:y})=>a.createElement(Uy,{value:{horizontal:p,vertical:b,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:g}},a.createElement(qa,null,a.createElement(v,{isExpanded:y.expanded,isOpened:y.opened},a.createElement(Qa,{isOpened:y.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,onActiveRouteChange:c})),a.createElement(By,{entryPoint:n.entryPoint,activeRoute:i}),e))))}),Wy=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=ds();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...tc,...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},jy=({children:e})=>{const{setConversationChildren:t}=Jt();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Xy=({component:e})=>{const{setConversationComponent:t}=Jt();return l.useLayoutEffect(()=>(t(e),()=>t(ss)),[e,t]),null},Zy=({children:e})=>{const{setConversationListChildren:t}=Jt();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Jy=({component:e})=>{const{setConversationListComponent:t}=Jt();return l.useLayoutEffect(()=>(t(e),()=>t(as)),[e,t]),null},Qy=Object.assign(Yy,{Style:Wy,Conversation:Xy,ConversationChildren:jy,ConversationList:Jy,ConversationListChildren:Zy}),eA=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])};di.set(Ce.SendbirdPlatform.JS,{deviceOSPlatform:Rc()?Ce.DeviceOsPlatform.MOBILE_WEB:Ce.DeviceOsPlatform.WEB,messengerVersion:wh,keyValueStorage:Nh(),networkStateAdapter:Oh(),foregroundStateAdapter:Lh});exports.ANCHOR_REL=Gr;exports.AgentProviderContainer=cs;exports.AgentUIProviderContainer=za;exports.AnonymousSessionInfo=ar;exports.CSATType=je;exports.Commands=it;exports.ConnectionDelayLayout=On;exports.Conversation=ss;exports.ConversationContext=pg;exports.ConversationContextProvider=ia;exports.ConversationHeaderLayout=_t;exports.ConversationLayout=Bn;exports.ConversationList=as;exports.ConversationListContext=AS;exports.ConversationListContextProvider=Ga;exports.ConversationListHeaderLayout=wt;exports.ConversationListItemLayout=is;exports.ConversationListLayout=Hn;exports.DefaultMessenger=Fy;exports.DeskTicketPriority=Dr;exports.DeskTicketStatus=Nr;exports.FixedMessenger=Qy;exports.ID_INCOMING=Je;exports.IncomingMessageLayout=pt;exports.LauncherBase=Ya;exports.LogLevel=Mr;exports.ManualSessionInfo=si;exports.MessageListUILayout=Un;exports.MessageLogs=Oa;exports.OutgoingMessageLayout=Rt;exports.PlaceholderLayout=Fn;exports.SystemMessageLayout=Pn;exports.cssVars=_;exports.escapeMarkdownSyntax=Ic;exports.flattenObject=cu;exports.mapCommonStringsToReactFormat=Hi;exports.messengerDispatcher=Va;exports.noop=he;exports.parseToMessageTemplate=li;exports.parseToUITemplate=iu;exports.pickColorByTheme=au;exports.replaceVariablesAsync=uu;exports.replaceVariablesSync=lu;exports.useAIAgentContext=xe;exports.useConversationContext=Te;exports.useConversationListContext=Zt;exports.useLocalizationContext=ae;exports.useMessageTemplateFetchingContext=om;exports.useMessengerContext=me;exports.useMessengerSessionContext=Ne;exports.useMessengerThemeContext=Yi;exports.useRefreshActiveChannel=eA;
506
+ ${({$isOpened:e})=>e&&fA};
507
+ ${({$isExpanded:e})=>e&&hA};
508
+ `,hA=U.css`width:743px;height:723px;`,fA=U.css`z-index:${_t.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;`,gA=8,pA=e=>{const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Yn();return a.createElement(_A,{...e,$horizontal:t,$vertical:n,$margin:r,$launcherSize:s})},_A=_.default(cc)`${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>uc(e,t,n,r+gA)};`,mc={top:24,bottom:24,start:24,end:24},EA=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(),[u,d]=l.useState(n.entryPoint??"Conversation"),[m,h]=l.useState("end-bottom"),[f,g]=l.useState(mc),[p,v]=l.useState(48),S=en(),C=S?Qa:uA,{horizontal:A,vertical:y}=l.useMemo(()=>{const[T,I]=m.split("-");return{horizontal:T==="start"?"start":"end",vertical:I==="top"?"top":"bottom"}},[m]);return a.createElement(_s,{enableExpandButton:!S,ref:r,...n},a.createElement(aa,null,({state:T})=>a.createElement(aA,{value:{horizontal:A,vertical:y,margin:f,launcherSize:p,setPosition:h,setMargin:g,setLauncherSize:v}},a.createElement(Ja,null,a.createElement(C,{isExpanded:T.expanded,isOpened:T.opened},a.createElement(ac,{isOpened:T.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,nudgeConversation:i,onActiveRouteChange:d})),a.createElement(cA,{entryPoint:n.entryPoint,activeRoute:u}),a.createElement(pA,{isMessengerOpened:T.opened,onConversationStarted:I=>{o(I.channelUrl),c(I),T.setOpened(!0)}}),e))))}),CA=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=Yn();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...mc,...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},bA=({children:e})=>{const{setConversationChildren:t}=rn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},vA=({component:e})=>{const{setConversationComponent:t}=rn();return l.useLayoutEffect(()=>(t(e),()=>t(hs)),[e,t]),null},SA=({children:e})=>{const{setConversationListChildren:t}=rn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},yA=({component:e})=>{const{setConversationListComponent:t}=rn();return l.useLayoutEffect(()=>(t(e),()=>t(ps)),[e,t]),null},AA=Object.assign(EA,{Style:CA,Conversation:vA,ConversationChildren:bA,ConversationList:yA,ConversationListChildren:SA}),TA=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(Ce.SendbirdPlatform.JS,{deviceOSPlatform:Hc()?Ce.DeviceOsPlatform.MOBILE_WEB:Ce.DeviceOsPlatform.WEB,messengerVersion:Yh,keyValueStorage:Zh(),networkStateAdapter:Xh(),foregroundStateAdapter:jh});exports.ANCHOR_REL=Zr;exports.AgentProviderContainer=_s;exports.AgentUIProviderContainer=Xa;exports.AnonymousSessionInfo=pr;exports.CSATType=et;exports.Commands=at;exports.ConnectionDelayLayout=Pn;exports.Conversation=hs;exports.ConversationContext=Og;exports.ConversationContextProvider=ha;exports.ConversationHeaderLayout=bt;exports.ConversationLayout=Vn;exports.ConversationList=ps;exports.ConversationListContext=BS;exports.ConversationListContextProvider=ja;exports.ConversationListHeaderLayout=Dt;exports.ConversationListItemLayout=gs;exports.ConversationListLayout=qn;exports.DefaultMessenger=iA;exports.DeskTicketPriority=Vr;exports.DeskTicketStatus=zr;exports.FixedMessenger=AA;exports.ID_INCOMING=ot;exports.IncomingMessageLayout=Ct;exports.LauncherBase=ec;exports.LogLevel=Fr;exports.ManualSessionInfo=li;exports.MessageListUILayout=zn;exports.MessageLogs=Ba;exports.OutgoingMessageLayout=Ot;exports.PlaceholderLayout=Gn;exports.SystemMessageLayout=Hn;exports.cssVars=E;exports.escapeMarkdownSyntax=Fc;exports.flattenObject=Su;exports.mapCommonStringsToReactFormat=Yi;exports.messengerDispatcher=Za;exports.noop=me;exports.parseToMessageTemplate=fi;exports.parseToUITemplate=bu;exports.pickColorByTheme=vu;exports.replaceVariablesAsync=Au;exports.replaceVariablesSync=yu;exports.useAIAgentContext=ye;exports.useConversationContext=Ae;exports.useConversationListContext=nn;exports.useLocalizationContext=ie;exports.useMessageTemplateFetchingContext=Em;exports.useMessengerContext=ue;exports.useMessengerSessionContext=Oe;exports.useMessengerThemeContext=Qi;exports.useRefreshActiveChannel=TA;