@sendbird/ai-agent-messenger-react 1.27.0 → 1.29.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 sa=Object.defineProperty;var oa=(e,t,n)=>t in e?sa(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>oa(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const fe=require("@sendbird/chat"),u=require("react"),D=require("styled-components"),Xe=require("date-fns"),ia=require("date-fns/locale/en-US"),Be=require("@sendbird/chat/message"),aa=require("react-dom"),Ie=require("@sendbird/chat/aiAgent"),ze=require("@sendbird/chat/groupChannel"),la=require("date-fns/isSameDay"),ca=require("dompurify"),er=e=>e&&e.__esModule?e:{default:e};function ua(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 da=er(fe),i=ua(u),p=er(D),so=er(ca),lt="sb-agent",oo="KEY_IMG_ASPECT_RATIO",Pn="*/*",te={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 Xt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Xt||{}),xt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(xt||{});const io=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},ma=e=>e===xt.COMPLETED||e===xt.CANCELED?e:xt.IN_PROGRESS,vn=e=>Qe(e)&&!io(e),Qe=e=>!!e&&"sender"in e,ha=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),fa=(e,t,n,r=!0)=>{if(!r||!vn(e))return"single";const s=()=>{if(!vn(t))return!1;const c=t.sender.userId===e.sender.userId,d=Xe.isSameMinute(t.createdAt,e.createdAt);return c&&d},o=()=>{if(!vn(n))return!1;const c=n.sender.userId===e.sender.userId,d=Xe.isSameMinute(n.createdAt,e.createdAt);return c&&d},a=s(),l=o();return a&&l?"middle":a?"bottom":l?"top":"single"},dt=(e,t)=>(()=>{var r;return Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,xe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>io(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Be.SendingStatus.PENDING)},je=e=>e.startsWith("image/"),tr=e=>e.startsWith("video/"),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"},ao=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},ln=e=>{switch(e){case"top":case"middle":return te.GAP_GROUPED;default:return te.GAP_UNGROUPED}},ga=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...a)=>{const[l,c,d]=a;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.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},pa=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),_a=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Ea=e=>e.replace(/~~/g,"\\~\\~"),ba=e=>{let t=e;return t=pa(t),t=_a(t),t=Ea(t),t},Ca=typeof navigator<"u"&&navigator.product==="ReactNative",Br=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return Ca?e.find(n):e.findLast(n)};function he(){}function va(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function ya(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 Fn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ge={isStreaming(e){const t=Fn(e.data);return typeof t=="object"&&!!t.stream},isWelcomeMessage(e,t){var n;if(((n=e.extendedMessagePayload)==null?void 0:n.bot_message_type)==="welcome")return!0;if(dt(e,t)){const r=Fn(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},yn=`@${lt}`,Sa=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${yn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=ya(`${e}/${t}/${s}`);return`${yn}-udata/${o}`},anonUserSession:()=>`${yn}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const a=JSON.stringify(o);n.set(r.messengerSession(s),a)}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}}}}},lo=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:a=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(o===null||m-o>=t)a?(e(...d),o=m):(s=d,o=m);else if(s=d,l&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&l&&(e(...s),o=Date.now()),r=null,s=null},h)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},c};class co{constructor(t,{filter:n,limit:r=20}){S(this,"filter");S(this,"_sdk");S(this,"_pinnedChannels");S(this,"_channels");S(this,"_isDisposed",!1);S(this,"_handlerId",`handler-id-${Date.now()}`);S(this,"_order",ze.GroupChannelListOrder.LATEST_LAST_MESSAGE);S(this,"_limit");S(this,"_query");S(this,"_token");S(this,"_timestamp");S(this,"_isSyncing");S(this,"_channelHandler");S(this,"_connectionHandler");S(this,"_collectionEventHandler");S(this,"_throttledOnChannelChanged");var s,o,a,l,c,d,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(s=this.filter)==null?void 0:s.aiAgentChannelFilter,aiAgentConversationStatusFilter:(o=this.filter)==null?void 0:o.aiAgentConversationStatusFilter,aiAgentIds:(a=this.filter)==null?void 0:a.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.pinnedChannelUrls,copilotConversationOnly:(d=this.filter)==null?void 0:d.copilotConversationOnly,copilotSupportChannelUrl:(m=this.filter)==null?void 0:m.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=lo(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new ze.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new fe.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var o,a;const n=new Set(((o=this.filter)==null?void 0:o.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let s;r?s=((a=r.lastMessage)==null?void 0:a.createdAt)??r.createdAt:s=this._query.lastResponseAt,this._timestamp>s&&(this._timestamp=s)}async _syncChannelChangelogs(){if(this._isDisposed)return[];if(this._isSyncing)return[];try{this._isSyncing=!0;let t;for(this._token?t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter):t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByTimestamp(this._timestamp,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls);t.hasMore&&t.token;)t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls)}catch{}finally{this._isSyncing=!1}return[]}_upsertPinnedChannelsToArray(t){var l;const n=((l=this.filter)==null?void 0:l.pinnedChannelUrls)??[],r=new Map(n.map((c,d)=>[c,d])),s=[],o=[],a=[];for(const c of t){if(!this._query.belongsTo(c)){a.push(c.url);continue}const d=r.get(c.url);if(d===void 0)continue;const m=Bn(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),o.push(c)):s.push(c);const f=this._pinnedChannels.findIndex(v=>(r.get(v.url)??1/0)>d),E=f===-1?this._pinnedChannels.length:f;this._pinnedChannels.splice(E,0,c)}return{addedChannels:s,updatedChannels:o,unmatchedChannelUrls:a}}_upsertRegularChannelsToArray(t,n=!1){const r=[],s=[],o=[];for(const a of t){if(!this._query.belongsTo(a)){r.push(a.url);continue}const l=Bn(this._channels,a),c=l<0;!c&&this._channels.splice(l,1);const m=Aa(this._channels,a,this._order).place,h=m===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(a),s.push(a)):(this._channels.splice(m,0,a),s.push(a)):(this._channels.splice(m,0,a),o.push(a))}return{addedChannels:s,updatedChannels:o,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var h,f,E,v,y;const r=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),s=[],o=[];for(const C of t)r.has(C.url)?s.push(C):o.push(C);const a=this._upsertPinnedChannelsToArray(s),l=this._upsertRegularChannelsToArray(o,n),c=a.addedChannels.concat(l.addedChannels),d=a.updatedChannels.concat(l.updatedChannels),m=a.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((E=(f=this._collectionEventHandler)==null?void 0:f.onChannelsAdded)==null||E.call(f,{},c)),d.length>0&&((y=(v=this._collectionEventHandler)==null?void 0:v.onChannelsUpdated)==null||y.call(v,{},d)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var s,o,a;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(d=>d.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((a=(o=this._collectionEventHandler)==null?void 0:o.onChannelsDeleted)==null||a.call(o,{},r))}get channels(){return this._isDisposed?[]:[...this._pinnedChannels,...this._channels]}get hasMore(){return this._isDisposed?!1:this._query.hasNext}async loadMore(){if(this._isDisposed)return[];if(this.hasMore){const t=await this._query.next();return this._setDefaultChangelogsSyncTimestamp(t),this._addChannelsToView(t,!0),t}return[]}setConversationListCollectionHandler(t){this._collectionEventHandler=t}dispose(){this._isDisposed||(this._isDisposed=!0,this._throttledOnChannelChanged.cancel(),this._collectionEventHandler=void 0,this._sdk.removeConnectionHandler(this._handlerId),this._sdk.groupChannel.removeGroupChannelHandler(this._handlerId),this._pinnedChannels.length=0,this._channels.length=0)}}const Bn=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Aa=(e,t,n)=>{if(e.length>0){const r=Bn(e,t);let s=0,o=e.length-1,a=Math.floor((s+o)/2);for(;s<o;){const c=Ur(e[a],t,n);if(c>0)o=a,a=Math.floor((s+o)/2);else if(c<0)s=a+1,a=Math.floor((s+o)/2);else return{place:a,oldPosition:r}}return{place:Ur(e[a],t,n)>=0?a:a+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},Ur=(e,t,n)=>{switch(n){case ze.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const r=t.lastMessage.createdAt-e.lastMessage.createdAt;return r===0?t.createdAt-e.createdAt:r}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};class uo{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=xa(),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 xa=()=>{let e=he,t=he;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Fe=(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))(Fe||{});class kt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Ze={CloseConversation:e=>new Ta(e),MessengerSettingsUpdated:e=>new Ia(e),ActiveChannelUpdated:e=>new wa(e),AnonymousSessionTokenExpired:()=>new Ma,AuthTokenRefreshed:()=>new ka};class Ta extends kt{constructor(){super(...arguments);S(this,"type","conv.close")}}class Ia extends kt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class wa extends kt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Ma extends kt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class ka extends kt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}var rr=(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))(rr||{});class mo{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${lt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${lt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${lt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${lt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${lt}/error]`,...t)}}class ho{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 Un{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const Ra=e=>({onSessionTokenRequired:t=>{t(null),e.send(Ze.AnonymousSessionTokenExpired())}}),Oa="ai_agent:stats",La="conversation_initial_render",Na=800220;var be=(e=>(e.AUTH="auth_duration",e.GET_CHANNEL="get_channel_duration",e.GET_MESSAGES="get_messages_duration",e.TOTAL_DURATION="total_duration",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache",e))(be||{});class Da{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"channelUrl",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??Na,this.errorDescription=n,this}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:Date.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:Date.now()}),this)}getDuration(t){const n=this.timers.get(t);return!n||n.startTime===null||n.endTime===null?null:n.endTime-n.startTime}isCommitted(){return this.committed}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(Oa,t)):!1}}class $a extends Da{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return La}buildPayload(){const n=this.getDuration(be.AUTH),r=this.getDuration(be.GET_CHANNEL),s=this.getDuration(be.GET_MESSAGES),o=this.getDuration(be.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(be.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...s!==null&&{get_messages_duration:s},...o!==null&&{total_duration_from_cache:o}},c={key:this.getMetricKey(),value:a!==null?String(a):"0"};return this.conversationId!==null&&(c.conversation_id=this.conversationId),this.errorCode!==null&&(c.error_code=this.errorCode),this.errorDescription!==null&&(c.error_description=this.errorDescription),Object.keys(l).length>0&&(c.extra=l),c}}class Pa{constructor(t){S(this,"commitCallback");S(this,"presentMethod","direct_present");S(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new $a().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(be.TOTAL_DURATION).startTimer(be.TOTAL_DURATION_FROM_CACHE).startTimer(be.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(be.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(be.AUTH).setError(t instanceof fe.SendbirdError?t.code:void 0,t.message).stopTimer(be.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(be.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(be.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(be.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(be.GET_CHANNEL).setError(t instanceof fe.SendbirdError?t.code:void 0,t.message).stopTimer(be.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof fe.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(be.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof fe.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(be.TOTAL_DURATION).stopTimer(be.GET_MESSAGES).commit())}setChannelUrl(t){var n;(n=this.stats)==null||n.setChannelUrl(t)}cleanup(){var t;(t=this.stats)==null||t.commit()}setPresentMethod(t){var n;this.presentMethod=t,(n=this.stats)==null||n.setPresentMethod(t)}clear(){this.stats=null}}function Fa(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,l=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:l},l};return n.isPending=()=>e!==null,n}const fo=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Hr={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},go={conversation:{...Hr,messageAlertSoundEnabled:!1,list:{...Hr,markdownImageRenderMode:"default"},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Gr=e=>e?{conversation:Ba(e.conversation)}:go,Ba=e=>{const t=go.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:a=t.messageAlertSoundEnabled,...l}=e,{camera:c={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h=Et(t.list,l,n);return{...h,messageAlertSoundEnabled:a,list:h,header:Et(t.header,r),input:{camera:Et(t.input.camera,c),gallery:Et(t.input.gallery,d),fileEnabled:m},fileViewer:Et(t.fileViewer,o)}},Et=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,fo(r));return n},Ua=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}),Ha=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Hn=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog}),po=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},ke=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ie.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},sr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ie.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 Ga(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 Va(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function _o(e){return!!e&&e<=Date.now()}function za(e){return!e.title}function Ya(e,t){var n;if(e)return za(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 Wa{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=lo(s=>{var o,a;(a=this._session)==null||a._updateActiveChannel({url:s.url,status:ke(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 ze.GroupChannelHandler({onChannelChanged:s=>{var o,a;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((a=this._handleActiveChannelChangedThrottled)==null||a.call(this,s))}}),r=new fe.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 a=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();a.url===t&&((s=this._session)==null||s._updateActiveChannel({url:a.url,status:ke(a)?"closed":"open",conversationStatus:(r=a.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",a.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});S(this,"_initConversationIfNeeded",async t=>{if(t.isAIAgent&&!t.conversation)try{await t.initConversation({aiAgentId:this.aiAgentId})}catch(n){this._logger.warn("AIAgentEventManager: initConversation failed",n)}});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Fe.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Fe.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Fe.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Fe.AuthTokenRefreshed,t)}))}}class qa{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Ze.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Ze.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 Eo=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)}},bo=e=>JSON.parse(e),Ka=e=>JSON.parse(e);function ja(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Xa(e){const t={};function n(r,s=""){for(const[o,a]of Object.entries(r)){const l=s?`${s}.${o}`:o;a&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t[l]=a}}return n(e),t}function Za({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,a])=>{if(!r&&!["number","boolean","string"].includes(typeof a))throw new Error(`If transformer is not provided, value(${o}:${a}) must be a {string, number, or boolean}`);const l=r?r(a):String(a),c=n(o);return s.replace(c,Eo(l))},e)}async function Ja({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,a])=>{const l=await r(a);return{regex:n(o),transformedValue:l}}))).reduce((o,{regex:a,transformedValue:l})=>o.replace(a,Eo(l)),e)}var Gn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Gn||{});const Co=e=>typeof e=="object"&&e!==null,Vr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Qa=e=>!Co(e)||!Vr(e,"channel_url")||!Vr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},el={1:Qa};function tl(e){if(!Co(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=el[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function nl(e,t,n,r){const s=da.default.init({appId:e,modules:[new ze.GroupChannelModule,new Ie.AIAgentModule],localCacheEnabled:!0,options:new fe.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:fe.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function rl(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 sl=[400300,400301,400302,400310];class or{constructor(t,n,r){S(this,"chatSDK");S(this,"_logger");S(this,"_cache");S(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const o=new fe.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(o),this.chatSDK.aiAgent.addEventHandler(Gn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=tl(a);(l==null?void 0:l.category)===Gn.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(c=n==null?void 0:n.onExternalAuthTokenExpired)==null||c.call(n,l.data))})}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 a=o;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(a))this._logger.warn("ChatClient.connect","offline connect restricted",a.message,a.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(l=>this._logger.warn("ChatClient.connect","clear cached-data failure",l));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",a.message,a.code),a}});S(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.chatSDK.aiAgent.removeAllEventHandlers(),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((a,l)=>t==null?void 0:t(a,l)).then(a=>{a?n==null||n(a):r==null||r(),s(a)}).catch(a=>{r==null||r(),o(a)})}});S(this,"_isCacheRestrictedError",t=>sl.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:a}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of o){const{key:c}=bo(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(a),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(rl(t.chatSDK),n=t.chatSDK):n=nl(t.appId,t.extensions,t.messengerVersion,t.chatParams),new or(n,t.logger,t.cache)}}const $t=new Map,vo={set:(e,t)=>{$t.set(e,t)},get:e=>{if($t.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=$t.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=$t.entries().next().value;return{platform:t[0],...t[1]}}};class zr 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 ir=(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))(ir||{}),ar=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(ar||{}),yo=(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))(yo||{});const ol=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class il{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(!ol(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const a=await this._fetch(n,r);return this._toResult(a)});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 zr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new zr(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}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class Zt{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 Zt({id:t.id,title:t.channelName??null,status:t.status2??ir.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??ar.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 lr{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 Zt._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:fo({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 Zt._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new il(t)}static init(t){return new lr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class cr{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 cr}}function al(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 ll=1440*60*1e3,cl=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function We(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function ul(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class Jt extends Wa{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,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_operationQueue",Fa());S(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.initialRender.clear(),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 a,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(a=s.userSessionCandidate)!=null&&a.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=s.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=o==null?void 0:o.active_channel)==null?void 0:c.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:y,session_token:C,expire_at:_}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:y,authToken:C,expireAt:_}),f={userId:y,authToken:C},this._logger.debug("AIAgent.authenticate: anonymous user created",y)}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(Ze.MessengerSettingsUpdated({settings:h,source:"server"}));const E=(()=>{var y;return s.type==="anonymous"?Ra(this._dispatcher):(y=s.userSessionCandidate)==null?void 0:y.sessionHandler})(),v=await this._chatClient.connect(f,E,y=>{var C;this._logger.debug("AIAgent: session token refreshed"),(C=this._session)==null||C._updateAuthToken(y),this._deskClient.refreshDeskAuthToken(y)},()=>{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:y})=>{var C;if(y===yo.ERR_SESSION_KEY_EXPIRED){await new Promise(b=>setTimeout(b,2e3));const _=(C=this._session)==null?void 0:C.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new qa({sdkUser:v,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.initialRender.onAuthError(h),h}})});S(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var n;this._logger.debug("AIAgent.deauthenticate: start"),await this._chatClient.disconnect(),this._deskClient.deauthenticate(),this._cache.messenger.clear((n=this._session)==null?void 0:n.userSession.userId),this._session=null,this._removeChannelHandler(),this._statsTrackers.initialRender.clear(),this._logger.debug("AIAgent.deauthenticate: end")}));S(this,"createConversation",async n=>{We(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(We(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:Ie.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const a of o)ul(a.context??{},n.context)&&s.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});S(this,"closeConversation",async n=>{var s;We(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===Ie.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Ie.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 co(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{We(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)=>{We(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=>{We(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={})=>{We(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=>{We(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,a=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Hn(a);const l=this._cache.messenger.getSettings(o);if(l){const c={...l,memory:a};this._cache.messenger.setSettings(o,c),this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:c,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",a.enabled),Hn(a)});S(this,"refreshActiveChannel",async n=>{var l,c,d;We(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?(c=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:c.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 a=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:a,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",a),a});S(this,"_getSessionCandidate",n=>n instanceof ho?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Un?{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-ll<=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 Un)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=Gr(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,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={initialRender:new Pa((r,s)=>this._chatClient.chatSDK.aiAgent.appendStat(r,s))}}static init(n){var h;const r=vo.get(n.platform),s=n.logger??new mo(n.logLevel??rr.WARN),o=n.dispatcher??new uo(s),a=n.useMMKVStorage?al(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=Sa({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=or.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:s,cache:c}),m=cl?lr.init({appId:n.appId,logger:s,customApiHost:(h=n.deskParams)==null?void 0:h.customApiHost}):cr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Jt({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:m,cache:c,logger:s,dispatcher:o})}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=Gr(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get statsTrackers(){return this._statsTrackers}}const _e=(e,t)=>{const n=u.createContext(t??null),r=({children:a,value:l})=>i.createElement(n.Provider,{value:l},typeof a=="function"?a(l):a),s=({children:a})=>i.createElement(n.Consumer,null,l=>l?typeof a=="function"?a(l):a:null),o=()=>{const a=u.useContext(n);if(!a)throw new Error(`use${e}Context must be used within a ${e}Provider`);return a};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 Ue(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[a,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:a,updateTemplate:h=>l(()=>h),components:c,updateComponent:(h,f)=>d(E=>({...E,[h]:f}))};return i.createElement(t.Provider,{value:m},o)}function r({template:o,children:a}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{o&&l(o)},[o]),i.createElement(i.Fragment,null,a)}function s({children:o}){return i.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>u.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(o,l)},[l]),null}}),s}function dl(...e){return function({children:n}){return e.reduce((r,s)=>i.createElement(s,null,r),n)}}function ml(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":So(e,t)}function So(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 hl(e,t,n){var a;const r=new Date,s=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),o=Xe.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):Xe.isToday(s)?n.hoursAgo(Xe.differenceInHours(r,s)):t(s,n.dateShortFormat)}const fl=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},Pt=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Yr=(e,t)=>{const n=Pt(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=fl(e);return r?`#${Pt(r[0])}${Pt(r[1])}${Pt(r[2])}${n}`:e},gl=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},pl=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",_l=e=>e.length>0,El=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>je(s.type)),r=e.some(s=>!je(s.type));return n&&r?je(t.type)?e.filter(s=>je(s.type)):[t]:r?[t]:e},Wr=e=>e.length===0?"empty":e.every(t=>je(t.type))?"images":"non_images",bl=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=El(t),s=Wr(e),o=Wr(r),l=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return l.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:l.nextFiles.length}:l.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:l}:{type:"apply",action:l}},ut=3,Ao=6,Cl=e=>e%ut===0?ut:Ao,vl=({index:e,itemCount:t})=>{const n=t%ut,r=n>0,s=r?t-n:t,o=r&&e>=s,a=o?n:ut,l=o?e-s:e%ut,c=!r&&e>=t-ut;return{columnSpan:r?Ao/a:1,rowItemCount:a,isLastInRow:l===a-1,isLastRow:o||c}},xo=_e("AIAgent"),yl=xo.Provider,Oe=xo.useContext;function Sl(e){const t=Al(e);return i.createElement(yl,{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 Al(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=Jt.init(e);else{const s=xl(n.current,e);(s.appId||s.aiAgentId||s.chatSDK)&&(t.current.dispose(),t.current=Jt.init({...e,chatParams:s.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.useEffect(()=>()=>{var s;(s=t.current)==null||s.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}function xl(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}const qr=Symbol("conversationMessageEventBridge"),bt=Symbol("conversationMessageEventPublisher"),Tl=(e,t)=>{const n=e;if(n[bt]=t,n[qr])return e;n[qr]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=o=>{r({...o,onMessagesAdded:(a,l,c)=>{var d,m;(d=o.onMessagesAdded)==null||d.call(o,a,l,c),(m=n[bt])==null||m.call(n,{kind:"messagesAdded",source:a.source,messages:c})},onMessagesUpdated:(a,l,c)=>{var d,m;(d=o.onMessagesUpdated)==null||d.call(o,a,l,c),(m=n[bt])==null||m.call(n,{kind:"messagesUpdated",source:a.source,messages:c})}})};const s=e.initialize.bind(e);return e.initialize=o=>{const a=s(o),l=a.onCacheResult.bind(a),c=a.onApiResult.bind(a);return a.onCacheResult=d=>l((m,h)=>{var f;d(m,h),(f=n[bt])==null||f.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),a.onApiResult=d=>c((m,h)=>{var f;d(m,h),(f=n[bt])==null||f.call(n,{kind:"initialized",source:"api",messages:h??[]})}),a},e},cn=()=>{const[,e]=u.useState(0);return u.useCallback(()=>e(t=>t+1),[])};let Il=0;function wl(){return u.useState(()=>`${Il++}`)[0]}const mt=(e,t,n)=>{const r=u.useRef(t),o=wl();r.current=t,u.useEffect(()=>{var l;const a=c=>{const d=c;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var v;const E=r.current;(v=E[h])==null||v.call(E,...f)}}),d};return(l=e==null?void 0:e.groupChannel)==null||l.addGroupChannelHandler(o,a(new ze.GroupChannelHandler)),()=>{var c;(c=e==null?void 0:e.groupChannel)==null||c.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Ml(e,t){return!e||!t?!0:e.url!==t.url}function De(e){return e!=null&&"sendingStatus"in e}function kl(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return De(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Rl(e,t){return kl(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Kr(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const Qt={collection:{groupChannel:{defaultOrder:ze.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function jr(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Xr(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Ol=({...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=Ll(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const a=De(o)?o.reqId:void 0,l=o.messageId||void 0;[a,l].forEach(c=>{if(!c)return;const d=n[c];Nl(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=>{De(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{De(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=>Rl(s,n));return t.value.clearBeforeAction?e.newMessageMap=Xr(r,Kr):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Xr(r,Kr)}),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&&(De(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(De(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Ll=e=>e.reduce((t,n)=>(De(n)?(t[n.reqId]=n,n.sendingStatus===Be.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Nl=(e,t,n=!1)=>{var r,s;if(!De(e)||!De(t))return!0;if(n&&e&&Jr(e)&&Jr(t)){const o=((r=e.message)==null?void 0:r.length)||0,a=((s=t.message)==null?void 0:s.length)||0;if(o>a)return!1}return e.sendingStatus===Be.SendingStatus.SUCCEEDED?t.sendingStatus===Be.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Dl=(e=$l)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},a]=u.useReducer(Ol,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),l=(C,_,b,A)=>{a({type:"update_messages",value:{messages:C,clearBeforeAction:_,currentUserId:b,strictStreamingOrder:A}})},c=(C,_)=>{a({type:"delete_messages",value:{messageIds:C,reqIds:_}})},d=(C,_,b)=>{a({type:"update_new_messages",value:{messages:C,clearBeforeAction:_,currentUserId:b}})},m=(C,_)=>{a({type:"delete_new_messages",value:{messageIds:C,reqIds:_}})},h=C=>{a({type:"update_initialized",value:{status:C}})},f=C=>{a({type:"update_loading",value:{status:C}})},E=C=>{a({type:"update_refreshing",value:{status:C}})},v=Object.values(o),y=u.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:E,updateMessages:l,deleteMessages:c,initialized:t,loading:n,refreshing:r,messages:y,newMessages:v,updateNewMessages:d,deleteNewMessages:m}},Zr=Math.floor(Number.MAX_SAFE_INTEGER/10);function $l(e,t){let n=0,r=0;return De(e)&&e.sendingStatus!=="succeeded"&&(n=Zr),De(t)&&t.sendingStatus!=="succeeded"&&(r=Zr),e.createdAt+n-(t.createdAt+r)}function Jr(e){try{const t=JSON.parse(e.data||"{}");return typeof t=="object"&&!!t.stream}catch{return!1}}function Ce(e){const t=u.useRef(e);return t.current=e,u.useCallback((...n)=>t.current(...n),[t])}const Pl=(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 ze.MessageFilter(r)})};function Qr(e){return e<Date.now()?Qt.collection.message.searchLimit:Qt.collection.message.defaultLimit}const Fl=(e,t,n={})=>{var Le,Me;const r=u.useRef(n);r.current=n;const s=u.useRef(t);s.current=t;const o=r.current.logger,a=r.current.startingPoint??Number.MAX_SAFE_INTEGER,l=Qr(a),c=r.current.strictStreamingOrder??!1,d=u.useRef({prev:!1,next:!1}),m=cn(),h=u.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:E,refreshing:v,messages:y,newMessages:C,updateMessages:_,updateNewMessages:b,deleteNewMessages:A,deleteMessages:T,updateInitialized:L,updateLoading:k,updateRefreshing:I}=Dl(n==null?void 0:n.sortComparator),w=Ce(x=>{var R,N,j,P;if(!s.current||!s.current.url)return(R=o==null?void 0:o.error)==null?void 0:R.call(o,"[useGroupChannelMessages] channel is required");try{switch(x){case fe.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case fe.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case fe.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(j=(N=r.current).markAsRead)==null||j.call(N,[s.current]);break}}catch(B){(P=o==null?void 0:o.warn)==null||P.call(o,"[useGroupChannelMessages/markAsReadBySource]",B)}}),O=Ce((x,R)=>{var N,j,P,B,F;if(R.length>0)switch(x){case fe.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case fe.CollectionEventSource.SYNC_MESSAGE_FILL:{(j=(N=r.current).shouldCountNewMessages)!=null&&j.call(N)&&b(R,!1,(P=e.currentUser)==null?void 0:P.userId),(F=(B=r.current).onMessagesReceived)==null||F.call(B,R);break}}}),U=Ce(x=>{var R,N;(N=(R=r.current).onCollectionEvent)==null||N.call(R,x)}),Y=Ce(async(x,R,N)=>new Promise((j,P)=>{var $e;h.current.instance&&h.current.instance.dispose(),w(),b([],!0,($e=e.currentUser)==null?void 0:$e.userId);const B=()=>{var ie,ne;const{pendingMessages:ce,failedMessages:re}=h.current.instance??{};jr(ce)&&_(ce,!1,(ie=e.currentUser)==null?void 0:ie.userId),jr(re)&&_(re,!1,(ne=e.currentUser)==null?void 0:ne.userId)},F=Pl(x,N,{...r.current,startingPoint:R});h.current={apiInitialized:!1,initialized:!1,instance:F},F.setMessageCollectionHandler({onMessagesAdded:(ce,re,ie)=>{var ne;w(ce.source),O(ce.source,ie),_(ie,!1,(ne=e.currentUser)==null?void 0:ne.userId,c),U({kind:"messagesAdded",source:ce.source,messages:ie})},onMessagesUpdated:(ce,re,ie)=>{var ne,Z,me;w(ce.source),O(ce.source,ie),_(ie,!1,(ne=e.currentUser)==null?void 0:ne.userId,c),ce.source===fe.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((me=(Z=r.current).onMessagesUpdated)==null||me.call(Z,ie)),U({kind:"messagesUpdated",source:ce.source,messages:ie})},onMessagesDeleted:(ce,re,ie,ne)=>{const Z=ne.map(pe=>pe.messageId),me=ne.filter(De).map(pe=>pe.reqId);T(Z,me),A(Z,me),U({kind:"messagesDeleted",source:ce.source,messages:ne})},onChannelDeleted:(ce,re)=>{var ie,ne;(ne=(ie=r.current).onChannelDeleted)==null||ne.call(ie,re)},onChannelUpdated:(ce,re)=>{var ie,ne;m(),(ne=(ie=r.current).onChannelUpdated)==null||ne.call(ie,re,ce)},onHugeGapDetected:()=>{Y(x,Number.MAX_SAFE_INTEGER,Qt.collection.message.defaultLimit)}});let ue=!1;F.initialize(ze.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ce,re)=>{var ie,ne,Z,me,pe;(ne=(ie=r.current).onCacheResult)==null||ne.call(ie,ce,re??[]),ce?(e.isCacheEnabled&&((Z=o==null?void 0:o.error)==null||Z.call(o,"[useGroupChannelMessages/onCacheResult]",ce)),ue=!0):re&&((me=o==null?void 0:o.debug)==null||me.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",re.length),_(F.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),B(),re.length>0&&(h.current.initialized=!0,j())),U({kind:"initialized",source:"cache",messages:re??[]})}).onApiResult((ce,re)=>{var ie,ne,Z,me,pe,_t,rt;(ne=(ie=r.current).onApiResult)==null||ne.call(ie,ce,re??[]),h.current.initialized=!0,h.current.apiInitialized=!0,ce?((Z=o==null?void 0:o.warn)==null||Z.call(o,"[useGroupChannelMessages/onApiResult]",ce),ue?P(ce):j()):re&&((me=o==null?void 0:o.debug)==null||me.call(o,"[useGroupChannelMessages/onApiResult]","message length:",re.length),_(F.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),r.current.startingPoint||(rt=(_t=r.current).onMessagesReceived)==null||rt.call(_t,re),e.isCacheEnabled&&B(),j()),U({kind:"initialized",source:"api",messages:re??[]})})}));mt(e,{onUserBanned(x,R){var N,j,P;x.isGroupChannel()&&!Ml(x,s.current)&&(R.userId===((N=e.currentUser)==null?void 0:N.userId)?(P=(j=r.current).onCurrentUserBanned)==null||P.call(j):m())}}),u.useLayoutEffect(()=>{const x=setTimeout(async()=>{e.currentUser&&s.current&&(L(!1),k(!0),await Y(s.current,a,l),k(!1),L(!0))});return()=>clearTimeout(x)},[e,(Le=e.currentUser)==null?void 0:Le.userId,(Me=s.current)==null?void 0:Me.url,r.current.replyType]),u.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const V=Ce(async()=>{e.currentUser&&s.current&&(I(!0),await Y(s.current,Number.MAX_SAFE_INTEGER,Qt.collection.message.defaultLimit),I(!1))}),z=Ce(async()=>{var R;const x=h.current.instance;if(x!=null&&x.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const N=await x.loadPrevious();_(N,!1,(R=e.currentUser)==null?void 0:R.userId)}catch{}finally{d.current.prev=!1}}),H=Ce(()=>{const{initialized:x,instance:R}=h.current;return x&&R?R.hasPrevious:!1}),W=Ce(async()=>{var R;const x=h.current.instance;if(x!=null&&x.hasNext&&!d.current.next)try{d.current.next=!0;const N=await x.loadNext();_(N,!1,(R=e.currentUser)==null?void 0:R.userId)}catch{}finally{d.current.next=!1}}),K=Ce(()=>{const{initialized:x,apiInitialized:R,instance:N}=h.current;return R&&x&&N?N.hasNext:!1}),ae=Ce((x,R)=>{var N;if(!s.current||!s.current.url)throw(N=o==null?void 0:o.error)==null||N.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,P)=>{s.current.sendUserMessage(x).onPending(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId),R==null||R(B)}).onSucceeded(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId),j(B)}).onFailed((B,F)=>{var ue;F&&F.channelUrl===s.current.url&&_([F],!1,(ue=e.currentUser)==null?void 0:ue.userId),P(B)})})}),M=Ce((x,R)=>{var N;if(!s.current||!s.current.url)throw(N=o==null?void 0:o.error)==null||N.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,P)=>{s.current.sendFileMessage(x).onPending(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId),R==null||R(B)}).onSucceeded(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId),j(B)}).onFailed((B,F)=>{var ue;F&&F.channelUrl===s.current.url&&_([F],!1,(ue=e.currentUser)==null?void 0:ue.userId),P(B)})})}),ye=Ce(async(x,R)=>{var N;if(!s.current||!s.current.url)throw(N=o==null?void 0:o.error)==null||N.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise(j=>{const P=[];s.current.sendFileMessages(x).onPending(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId),R==null||R(B)}).onSucceeded(B=>{var F;B.isFileMessage()&&B.channelUrl===s.current.url&&(_([B],!1,(F=e.currentUser)==null?void 0:F.userId),P.push(B)),P.length===x.length&&j(P)}).onFailed((B,F)=>{var ue;F&&F.channelUrl===s.current.url?(_([F],!1,(ue=e.currentUser)==null?void 0:ue.userId),P.push(F)):P.push(null),P.length===x.length&&j(P)})})}),X=Ce((x,R)=>{var N;if(!s.current||!s.current.url)throw(N=o==null?void 0:o.error)==null||N.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,P)=>{s.current.sendMultipleFilesMessage(x).onPending(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId),R==null||R(B)}).onFileUploaded(()=>{m()}).onSucceeded(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId),j(B)}).onFailed((B,F)=>{var ue;F&&F.channelUrl===s.current.url&&_([F],!1,(ue=e.currentUser)==null?void 0:ue.userId),P(B)})})}),q=Ce(async(x,R)=>{var j,P;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await s.current.updateUserMessage(x,R);return N.channelUrl===s.current.url&&_([N],!1,(P=e.currentUser)==null?void 0:P.userId),N}),G=Ce(async(x,R)=>{var j,P;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await s.current.updateFileMessage(x,R);return N.channelUrl===s.current.url&&_([N],!1,(P=e.currentUser)==null?void 0:P.userId),N}),ee=Ce(async x=>{var R;if(!s.current||!s.current.url)throw(R=o==null?void 0:o.error)==null||R.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((N,j)=>{let P;x.isUserMessage()&&(P=s.current.resendMessage(x)),x.isFileMessage()&&(P=s.current.resendMessage(x)),x.isMultipleFilesMessage()&&(P=s.current.resendMessage(x)),P&&("onPending"in P&&P.onPending(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId)}),"onFileUploaded"in P&&P.onFileUploaded(()=>{m()}),"onSucceeded"in P&&P.onSucceeded(B=>{var F;B.channelUrl===s.current.url&&_([B],!1,(F=e.currentUser)==null?void 0:F.userId),N(B)}),"onFailed"in P&&P.onFailed((B,F)=>{var ue;F&&F.channelUrl===s.current.url&&_([F],!1,(ue=e.currentUser)==null?void 0:ue.userId),j(B)}))})}),de=Ce(async x=>{var R,N;if(!s.current||!s.current.url)throw(R=o==null?void 0:o.error)==null||R.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(x.sendingStatus==="succeeded")x.isUserMessage()&&await s.current.deleteMessage(x),x.isFileMessage()&&await s.current.deleteMessage(x),x.isMultipleFilesMessage()&&await s.current.deleteMessage(x);else try{await((N=h.current.instance)==null?void 0:N.removeFailedMessage(x.reqId))}finally{T([],[x.reqId])}}),le=Ce(()=>{var x;b([],!0,(x=e.currentUser)==null?void 0:x.userId)}),we=Ce(async x=>{var R;if(e.currentUser&&s.current){const N=Qr(x);k(!0),_([],!0,(R=e.currentUser)==null?void 0:R.userId),await Y(s.current,x,N),k(!1)}});return{initialized:f,loading:E,refreshing:v,messages:y,newMessages:C,resetNewMessages:le,refresh:V,loadPrevious:z,hasPrevious:H,loadNext:W,hasNext:K,sendUserMessage:ae,sendFileMessage:M,sendFileMessages:ye,sendMultipleFilesMessage:X,updateUserMessage:q,updateFileMessage:G,resendMessage:ee,deleteMessage:de,resetWithStartingPoint:we,_dangerous_reducer_updateMessages:_,_dangerous_reducer_deleteMessages:T}},Bl=(e,t,n)=>{const r=u.useRef(0),s=u.useRef(new Set),o=u.useCallback(d=>{const m={id:r.current+=1,...d};s.current.forEach(h=>{h(m)})},[]),a=u.useCallback(d=>{var h;const m=((h=n==null?void 0:n.collectionCreator)==null?void 0:h.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new ze.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return Tl(m,o)},[t,n==null?void 0:n.collectionCreator,o]),l=Fl(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(s.current.add(d),()=>{s.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},It={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function To(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Ul(e){const t=To(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Hl(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Gl(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 a=0,l=0;const c=(r+s)/2;return r!==s&&(l=c>.5?o/(2-r-s):o/(r+s)),r===e?a=(t-n)/o+(t<n?6:0):r===t?a=(n-e)/o+2:r===n&&(a=(e-t)/o+4),a/=6,[a,l,c]}function Vl(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const a=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},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=a(c,l,e+1/3),s=a(c,l,e),o=a(c,l,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function Ft(e,t,n){const[r,s,o]=Ul(e),[a,l,c]=Gl(r,s,o),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,f,E]=Vl(a,m,d);return Hl([Math.round(h),Math.round(f),Math.round(E)])}function zl(e,t="light"){return{extraDark:Ft(e,.6,1.2),dark:Ft(e,.85,1.1),main:e,light:Ft(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Ft(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Vn(e){const t=To(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?It.BLACK:It.WHITE}function Yl(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 Wl=(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"}}),Bt={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)"}},Sn={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 es(e){const t=ql(e),n=Kl(e,t),r=Xl(n,e.colors,e.selectedTheme),s=Jl(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 ql({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Bt.primary.main?Bt.primary:zl(n,e):Bt.primary;return{...Bt,primary:r,...t}}function Kl({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,a=t??Vn(o),l=n??It.DEFAULT_BOT_MSG_BG,c=r??Vn(l);return(e==="light"?Yl:Wl)(s,o,a,l,c)}function jl(e,t,n){return typeof e=="string"?e:e[t]??n}function Xl(e,t,n){var a;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const l of Object.keys(t)){const c=t[l];if(c){s[l]={...s[l]};for(const[d,m]of Object.entries(c))if(m!==void 0){const h=((a=o[l])==null?void 0:a[d])??"";s[l][d]=jl(m,n,h)}}}return r}function Zl(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Jl({typography:e}){if(!e)return Sn;const t={...Sn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Sn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Zl(s,r,o)}}),t}const{Provider:Ql,useContext:ur}=_e("AIAgentTheme");function ec({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const a=u.useRef(null),[l,c]=u.useState(()=>es({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=u.useCallback((m,h)=>{h&&(a.current=h);const f=(s==null?void 0:s.theme)??m,E=a.current?a.current.themes[f]:null,v={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!v.primary&&(E!=null&&E.primary_color)&&(v.primary=E.primary_color,v.primaryContrast=E.primary_contrast_color),!v.botMessageBackground&&(E!=null&&E.bot_message_bg_color)&&(v.botMessageBackground=E.bot_message_bg_color,v.botMessageBackgroundContrast=E.bot_message_bg_contrast_color);const y=es({selectedTheme:f,palette:t,typography:n,colors:r,...v});c(y),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 u.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(l.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),i.createElement(Ql,{value:{theme:l,updateTheme:d}},o)}const An=25*1024*1024,ts=1,ns=new Set(["image/png","image/jpeg","image/jpg"]),rs=new Set(["application/pdf"]),tc={off:"off",always:"always",handed_off_only:"handed_off_only"},nc=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:ts,attachmentMode:"handed_off_only",defaultUploadSizeLimit:An,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:ns,supportedFileMimeTypes:rs})),n=u.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??ts,attachmentMode:tc[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??An,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)??ns),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??rs)})},[]),r=u.useCallback(s=>{const{channel:o,uploadSizeLimit:a=An}=s,l=(d=!0)=>o!=null&&o.isAIAgent?d?et(o):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??a;const m=e.defaultUploadSizeLimit??a,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(l(!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 l()?[Pn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:c,getUploadSizeLimitInMB:d=>c(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},ss=(...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)")},Ct=e=>({...e,context:e.context??{}}),{Provider:rc,useContext:ht}=_e("AIAgentMessengerSession"),sc=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:a}=Oe(),{updateTheme:l}=ur(),[c,d]=u.useState(void 0),[m,h]=u.useState(void 0),[f,E]=u.useState(null),[v,y]=u.useState(null),[C,_]=u.useState(null),[b,A]=u.useState(null),[T,L]=u.useState(null),{updateBaseAttachmentRules:k,createAttachmentRules:I}=nc();u.useEffect(()=>{const Y=r.onMessengerSettingsUpdated(({settings:H})=>{const{appearance:W,bot:K,launcher:ae,memory:M}=H;l(W.selected_theme,W),_(Ua(K)),A(Ha(ae)),L(M?Hn(M):null),k(H)}),V=r.onActiveChannelUpdated(({channelUrl:H,status:W,conversationStatus:K})=>{h({url:H,status:W,conversationStatus:K})}),z=r.onAuthTokenRefreshed(()=>{var W;const H=(W=r.session)==null?void 0:W.userSession.authToken;H&&y(K=>K?{...K,authToken:H}:null)});return()=>{Y(),V(),z()}},[r,l,k]);const w=u.useCallback(async()=>{try{const Y=await r.authenticate(e),V=r.session;return E(V.sdkUser),y(V.userSession),h(V.activeChannel),d(void 0),Y}catch(Y){throw E(null),y(null),h(void 0),d(Y),Y}},[r,e]),O=u.useCallback(async()=>{await r.deauthenticate(),E(null),h(void 0),y(null),_(null),A(null),L(null)},[r]),U=u.useCallback(async()=>{if(!r.session){if(v)return a.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw a.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(v==null?void 0:v.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,a,v]);return u.useImperativeHandle(n,()=>{const Y=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:w,deauthenticate:O,updateContext:async(...V)=>{const z=ss(...V);if(z.type==="active"){const K=await(await Y()).updateContext(o,z.context);return Ct(K)}const H=await s.aiAgent.updateContext(z.aiAgentId,z.channelUrl,z.context);return Ct(H)},patchContext:async(...V)=>{const z=ss(...V);if(z.type==="active"){const K=await(await Y()).patchContext(o,z.context);return Ct(K)}const H=await s.aiAgent.patchContext(z.aiAgentId,z.channelUrl,z.context);return Ct(H)},getContextObject:async()=>{const z=await(await Y()).getContextObject(o);return Ct(z)}}},[w,O,m,s,o,a]),i.createElement(rc,{value:{sdkUser:f,userSessionInfo:e,userSession:v,activeChannel:m,setActiveChannel:h,refreshActiveChannel:U,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:c,aiAgentInfo:C,launcherInfo:b,memoryInfo:T,authenticate:w,deauthenticate:O,createAttachmentRules:I,statsTrackers:r.statsTrackers}},t)}),un=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useLayoutEffect(()=>{const s=new fe.ConnectionHandler({onDisconnected:o=>{var a,l;return(l=(a=r.current).onDisconnected)==null?void 0:l.call(a,o)},onConnected:o=>{var a,l;return(l=(a=r.current).onConnected)==null?void 0:l.call(a,o)},onReconnectStarted:()=>{var o,a;return(a=(o=r.current).onReconnectStarted)==null?void 0:a.call(o)},onReconnectSucceeded:()=>{var o,a;return(a=(o=r.current).onReconnectSucceeded)==null?void 0:a.call(o)},onReconnectFailed:()=>{var o,a;return(a=(o=r.current).onReconnectFailed)==null?void 0:a.call(o)},onConnectionLost:()=>{var o,a;return(a=(o=r.current).onConnectionLost)==null?void 0:a.call(o)},onConnectionDelayed:o=>{var a,l;return(l=(a=r.current).onConnectionDelayed)==null?void 0:l.call(a,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])};function oc(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:s}=Oe(),{sdkUser:o,statsTrackers:a}=ht(),l=cn(),[c,d]=u.useState(void 0),[m,h]=u.useState(void 0),[f,E]=u.useState(!1);function v(C){C.isAIAgent&&!C.conversation&&(E(!0),s.initConversationIfNeeded(C).finally(()=>E(!1)))}async function y(){var C,_,b;if(!o){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),h(void 0),E(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const A=await t.groupChannel.getChannel(e);v(A),d(A),a.initialRender.onGetChannelComplete((C=A.conversation)==null?void 0:C.id),A.url===((_=s.session)==null?void 0:_.activeChannel.url)&&s.session._updateActiveChannel({url:A.url,status:ke(A)?"closed":"open",conversationStatus:(b=A.conversation)==null?void 0:b.status}),n.debug("useChannel.getChannel: fetched channel",A)}catch(A){a.initialRender.onGetChannelError(A),A instanceof fe.SendbirdError&&h(A),n.error("useChannel.getChannel: error",A)}}}return u.useEffect(()=>{y()},[t,o,e,r]),un(t,{async onReconnectSucceeded(){if(!c)return;const C=await c.refresh();v(C),d(C)}}),mt(t,{onChannelChanged:C=>{C.isGroupChannel()&&C.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",C.url),d(C),l())}}),{channel:c,channelFetchError:m,getChannel:y,isInitializingConversation:f}}const ic=new Set(["suggested_replies","steward","system"]),ac=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||!ic.has(r)))return r},lc=e=>{var a;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,s=!!r&&!r.submitted_at&&!r.canceled_at,o=e.isAIAgent&&!!((a=e.conversation)!=null&&a.handedOverAt);return s&&!o},cc=()=>{const{chatSDK:e,networkStateAdapter:t}=Oe(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return un(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),u.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===fe.ConnectionState.OPEN?"connected":o)})},[t,e]),n},uc=3e4,dc=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=u.useState(!1),a=u.useRef(null),l=t&&dt(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),o(!1)},d=f=>{a.current&&clearTimeout(a.current),o(!0),a.current=setTimeout(()=>{o(!1),a.current=null},f)},m=Date.now()-l,h=uc-m;return n||h<=0?c():d(h),()=>{a.current&&clearTimeout(a.current)}},[n,l]),s&&e},Io=e=>{const{chatSDK:t}=Oe(),[n,r]=u.useState([]);return mt(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},mc=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=u.useState(!1),a=Io(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=dt(t,n)&&(Ge.isStreaming(t)||r);o(c||l)},[a,t,n,r]),s},hc=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ht(),a=cc(),l=mc({channel:e,lastMessage:Br(t,[Be.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),c=dc({shouldApply:!!(e!=null&&e.isAIAgent)&&!et(e),isBlockedWhileAIResponding:l,lastMessage:Br(t,[Be.SendingStatus.PENDING,Be.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||a==="disconnected")return d("unavailable");if(a==="reconnecting")return d("reconnecting");if(ke(e))return d("conversation_closed");if(Ga(e))return d("handoff_pending");if(lc(e))return d("form_active");const m=ac(e);return d(m||(l||c||r?"ai_responding":""))},fc=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(s=>{t(o=>{if(o.has(s))return o;const a=new Set(o);return a.add(s),a})},[]),r=u.useCallback(s=>{t(o=>{if(!o.has(s))return o;const a=new Set(o);return a.delete(s),a})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:gc}=_e("AIAgentConversation");function pc({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:o,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=he,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var Y;const f=()=>d&&(_==null?void 0:_.markAsRead()),{_aiAgentSDK:E,chatSDK:v,logger:y,dispatcher:C}=Oe(),{channel:_,channelFetchError:b,getChannel:A,isInitializingConversation:T}=oc(t),{statsTrackers:L}=ht();u.useEffect(()=>{if(t)return L.initialRender.setChannelUrl(t),()=>{L.initialRender.cleanup()}},[t,L]);const k=Bl(v,_,{replyType:Be.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:V=>r==null?void 0:r(V),onMessagesUpdated:V=>s==null?void 0:s(V),onCacheResult:V=>L.initialRender.onCacheResult(V),onApiResult:V=>L.initialRender.onApiResult(V),logger:y,markAsRead:f,sortComparator:h}),I=fc(),w=hc({channel:_,messages:k.messages,isStreamAnimating:I.isAnimating,isInitializingConversation:T});u.useEffect(()=>{f()},[d,_]);const O=ke(_);u.useEffect(()=>{o==null||o(O)},[O,o]),u.useEffect(()=>{const V=async z=>{const H=typeof(z==null?void 0:z.channelUrl)=="string";_&&H&&z.channelUrl!==_.url||(y.debug("conversation.dispatcher: try to close conversation",_),_!=null&&_.conversation&&_.conversation.status===Ie.ConversationStatus.OPEN&&(await _.closeConversation(),a==null||a()))};return C.subscribe(Fe.ConversationClose,V),()=>{C.unsubscribe(Fe.ConversationClose,V)}},[C,_,y,(Y=_==null?void 0:_.conversation)==null?void 0:Y.status,a]);const U={conversation:(_==null?void 0:_.conversation)??void 0,actions:{setUserMemoryState:E.setUserMemoryState},channelSource:{channel:_,error:b,refetch:()=>A(),closeConversation:async()=>{ke(_)||await(_==null?void 0:_.closeConversation())}},messageSource:{messages:k.messages,newMessages:k.newMessages,initialized:k.initialized,subscribeMessageEvents:k.subscribeMessageEvents,loadPrevious:()=>k.loadPrevious(),loadNext:()=>k.loadNext(),deleteMessage:V=>k.deleteMessage(V),resendMessage:V=>k.resendMessage(V),resetNewMessages:()=>k.resetNewMessages(),sendUserMessage:async V=>{var H;if(((H=_==null?void 0:_.conversation)==null?void 0:H.status)===Ie.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(V=await l(V));const z=await k.sendUserMessage(V,c);return c==null||c(z),z},sendFileMessage:async V=>{var H;if(((H=_==null?void 0:_.conversation)==null?void 0:H.status)===Ie.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(V=await l(V));const z=await k.sendFileMessage(V,c);return c==null||c(z),z},sendMultipleFilesMessage:async V=>{var H;if(((H=_==null?void 0:_.conversation)==null?void 0:H.status)===Ie.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(V=await l(V));const z=await k.sendMultipleFilesMessage(V,c);return c==null||c(z),z}},state:{streamAnimation:I,input:w}};return i.createElement(gc,{value:U},e)}function _c(e,t){var E,v,y,C,_,b,A,T,L,k;const[n,r]=u.useState(!1),[s,o]=u.useState(null),[a,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),h=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),o(null),l([]);try{c==null||c.dispose();const I=new co(e,t);I.setConversationListCollectionHandler({onChannelsAdded:()=>{l(I.channels)},onChannelsUpdated:()=>{l(I.channels)},onChannelsDeleted:()=>{l(I.channels)}}),await I.loadMore(),d(I),o(null)}catch(I){d(null),o(I)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(E=t.filter)==null?void 0:E.aiAgentChannelFilter,(y=(v=t.filter)==null?void 0:v.aiAgentConversationStatusFilter)==null?void 0:y.join(),(_=(C=t.filter)==null?void 0:C.aiAgentIds)==null?void 0:_.join(),(b=t.filter)==null?void 0:b.deskChannelFilter,(T=(A=t.filter)==null?void 0:A.pinnedChannelUrls)==null?void 0:T.join(),(L=t.filter)==null?void 0:L.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),f=u.useCallback(async()=>{if(c)try{await c.loadMore()}catch(I){o(I)}},[c]);return un(e,{onConnected:()=>h()}),u.useEffect(()=>{h()},[h]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:s,channels:a,loadMore:f}}const{Provider:Ec}=_e("AIAgentConversationList");function bc({conversationListLimit:e,conversationListFilter:t,children:n}){var h,f;const{chatSDK:r,aiAgentId:s,queryParams:o}=Oe(),a={aiAgentIds:[s],aiAgentConversationStatusFilter:[Ie.ConversationStatus.CLOSED,Ie.ConversationStatus.OPEN]},l=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c={...a,...(f=o==null?void 0:o.conversationListParams)==null?void 0:f.filter,...t},d=_c(r,{limit:l,filter:c}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return i.createElement(Ec,{value:m},n)}function Cc(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:vc,useContext:yc}=_e("MessageTemplateFetching");function Sc({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[s,o]=u.useState({}),a=u.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const E=m(h);if(E)return E;const v=r.current[h];if(v)return v;f||a(h,{fetching:!0});const y=d(h).catch(C=>{throw f||a(h,{error:!0}),C}).finally(()=>{f||a(h,{fetching:!1}),delete r.current[h]});return r.current[h]=y,y},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Cc(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 i.createElement(vc,{value:c},e)}const Ac="remove_powered_by",dr=(e,t)=>{var s,o;const{chatSDK:n}=Oe(),{aiAgentInfo:r}=ht();if(e==="handoff-button"){const a=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&a&&sr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const a=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return u.useMemo(()=>!(Array.isArray(a)&&a.includes(Ac)),[a])}throw new Error("Unsupported feature")},xc={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"},Tc={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}}},Ic={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}}},wc={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}}},Mc={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(a=>!e.options.includes(a)).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}}},kc={text:Tc,number:Ic,"single-select":wc,"multi-select":Mc},Rc={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function wo(e){return kc[e.type]||Rc}function os(e){return wo(e).getValueOrDefault(e)}function Oc(e,t,n={}){const r={...xc,...n};return wo(e).validate(e,t,r)}const Lc=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,a]=u.useState({}),[l,c]=u.useState(()=>{const y={};return e.fields.forEach(C=>{y[C.key]=os(C)}),y}),d=u.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);u.useEffect(()=>{if(d==="submitted"||d==="canceled"){const y={};let C=!1;e.fields.forEach(_=>{const b=os(_);JSON.stringify(l[_.key])!==JSON.stringify(b)&&(C=!0),y[_.key]=b}),C&&c(y)}},[d]);const m=(y,C)=>{c(_=>({..._,[y]:C})),a(_=>({..._,[y]:void 0}))},h=e.fields.map(y=>{var b,A,T;const C=l[y.key]??null,_={key:y.key,label:y.label,error:o[y.key],required:y.required};return y.type==="text"?{..._,type:"text",layout:y.layout,value:C,...y.placeholder&&{placeholder:y.placeholder},...((b=y.rules)==null?void 0:b.max_length)&&{maxLength:y.rules.max_length}}:y.type==="number"?{..._,type:"number",layout:y.layout,value:C,...y.placeholder&&{placeholder:y.placeholder},...((A=y.rules)==null?void 0:A.max)&&{max:y.rules.max}}:y.type==="single-select"?{..._,type:"single-select",layout:y.layout,value:C,options:y.options}:y.type==="multi-select"?{..._,type:"multi-select",layout:y.layout,value:C,options:y.options,...((T=y.rules)==null?void 0:T.max_select)&&{maxSelect:y.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:y=>h.find(C=>C.key===y),updateFieldValue:m,submit:async()=>{const y={};let C=!1;for(const _ of e.fields){const b=l[_.key]??null,A=Oc(_,b,n);A.isValid||(y[_.key]=A.error,C=!0)}if(a(y),!C&&r){const _={};e.fields.forEach(b=>{_[b.key]=l[b.key]??null}),await r(_)}},cancel:async()=>{await(s==null?void 0:s())}}},Nc=e=>{const{chatSDK:t,handlers:n,logger:r}=Oe(),{aiAgentInfo:s}=ht(),o=u.useRef(new Set),a=u.useRef(new Set),l=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!dt(m,s.userId))return;const f=m.messageId;if(Ge.isStreaming(m)){a.current.add(f);return}h==="updated"&&!a.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),a.current.delete(f))},c=u.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=Fn(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&&(l(h,f),c(h))};return mt(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:c}},Dc=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},Mo=e=>{const{aiAgentInfo:t}=ht(),n=Io(e);if(ke(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Dc(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},$c=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=u.useRef(null),o=u.useRef(t),a=u.useRef(t),l=u.useRef(!1);o.current=t,u.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(l.current?a.current:o.current)(!1),l.current=!1,a.current=o.current;return}l.current=!0,a.current=o.current,a.current(!0),s.current=setTimeout(()=>{s.current=null,a.current(!1),l.current=!1,a.current=o.current},r)},[n,r,e]),u.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(l.current?a.current:o.current)(!1),l.current=!1,a.current=o.current},[])},Pc=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:l=>{const c=Date.now(),d=t.get(l);return d!==void 0&&c-d<n?!1:(t.set(l,c),!0)},setInterval:l=>{n=l},reset:()=>{t.clear()}}},Fc=(e,t,n=1e4,r=!0)=>{const s=u.useRef(null),o=u.useRef(null),a=u.useRef(!1);s.current||(s.current=Pc(n));const l=(e==null?void 0:e.nickname.trim())||null,c=(e==null?void 0:e.userId)??l;u.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),u.useEffect(()=>{var h;if(!r){a.current=!1,o.current=c;return}if(!c||!l){a.current=!1,o.current=null;return}const d=!a.current,m=o.current!==c;a.current=!0,o.current=c,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(c)&&t(l)},[c,l,r,t])};var Ve=(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))(Ve||{});const Bc=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r})=>{const s=!!n&&n.visibility&&!!Ve[n.type],o=!r&&typeof e!="number"&&_o(t),a=cn();return u.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const l=t-Date.now();if(l<=0&&r)return;const c=setTimeout(a,Math.max(0,l));return()=>clearTimeout(c)},[a,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},Uc=({csat:e,csatExpireAt:t,csatPayload:n,announceStatus:r,onSubmittedAnnounced:s,isSubmitInFlight:o=!1})=>{const{isRenderableCSAT:a,isExpiredNow:l}=Bc({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:o}),c=(n==null?void 0:n.csat_submitted_label)??"",d=u.useRef(a&&typeof e=="number"),m=u.useRef(a&&l);return u.useEffect(()=>{a&&c&&(typeof e!="number"||d.current||(d.current=!0,r({event:"csatSubmitted",submittedLabel:c}),s==null||s()))},[r,e,a,s,c]),u.useEffect(()=>{a&&l&&(m.current||(m.current=!0,r({event:"csatExpired"})))},[r,l,a]),{isExpiredNow:l,isRenderableCSAT:a}},mr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=po(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")},is=e=>u.useReducer((t,n)=>({...t,...n}),e),Hc=new Set(["free_text","single_choice"]),Gc=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,a]=is({csatType:t,csat:n,csatReason:r,isResolved:s}),[l,c]=is({followUpItem:!1}),d=u.useMemo(()=>{var C;const E=o.csat,v=typeof E=="number",y=(C=e.follow_up)==null?void 0:C.find(_=>v?_.scores.includes(E):_.always_visible??!1);if(Hc.has(y==null?void 0:y.response_type))return y},[o.csat,e.follow_up]),m=(()=>{var E;if(typeof n=="number")return"submitted";if((t===Ve.AI_AGENT_CSAT_5||t===Ve.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Ve.AI_AGENT_CSAT_5_WITH_CRE){const v=typeof o.csat=="number",y=!((E=e.cre)!=null&&E.required)||typeof o.isResolved=="boolean";if(v&&y)return"submittable"}return"unsubmittable"})(),h=u.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(c({followUpItem:!0}),!1):!0,[o,d,c]);return u.useEffect(()=>{r||(a({csatReason:""}),c({followUpItem:!1}))},[r,d,a,c]),{params:o,setParams:a,error:l,setError:c,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},xn=5,Vc=250,zc=50,as=e=>Math.max(0,e-zc),Yc=e=>e<1e3?{speed:xn*.5,chunkSize:2}:e<2e3?{speed:xn*.8,chunkSize:2}:{speed:xn*.6,chunkSize:3},Ut=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Wc=(e,t)=>{if(!t)return e;let n="",r=0,s=0;for(;r<e.length;){if(e[r]==="`"&&!Ut(e,r)){let c=1;for(;e[r+c]==="`";)c++;s===0?s=c:c===s&&(s=0),n+=e.slice(r,r+c),r+=c;continue}if(s>0||e[r]!=="!"||e[r+1]!=="["||Ut(e,r)){n+=e[r],r++;continue}const o=r;r+=2;let a=1;for(;r<e.length&&a>0;){if(Ut(e,r)){r++;continue}e[r]==="["?a++:e[r]==="]"&&a--,r++}if(a>0||r>=e.length)return n;if(e[r]!=="("){n+=e.slice(o,r);continue}r++;let l=1;for(;r<e.length&&l>0;){if(Ut(e,r)){r++;continue}e[r]==="("?l++:e[r]===")"&&l--,r++}if(l>0)return n;n+=e.slice(o,r)}return n},qc=e=>{const{text:t,enabled:n=!1,markdownImageRenderMode:r="default",onAnimationStart:s,onAnimationProgress:o,onAnimationComplete:a}=e,[l,c]=u.useState(()=>as(t.length)),d=u.useRef(null),m=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,h=u.useRef({onStart:s,onProgress:o,onComplete:a}).current,f=u.useRef({startCalled:!1,completeCalled:!1}).current,E=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,v=n,y=l<t.length,C=E.initialEnabled&&(v||y);return u.useLayoutEffect(()=>{h.onStart=s,h.onProgress=o,h.onComplete=a,E.textLength=t.length,E.enabled=n}),u.useLayoutEffect(()=>{var b;E.initialEnabled&&(f.startCalled||(f.startCalled=!0,(b=h.onStart)==null||b.call(h)),c(A=>t.length<A?t.length:A))},[t]),u.useEffect(()=>{if(!E.initialEnabled)return;let b=as(t.length);m.lastUpdate=0,m.startTime=0,m.lastProgressCall=0;const A=T=>{var V;m.lastUpdate===0&&(m.lastUpdate=T,m.startTime=T,m.lastProgressCall=T);const L=E.textLength,k=T-m.lastUpdate,I=T-m.startTime,{speed:w,chunkSize:O}=Yc(I),U=w*O;k>=U&&b<L&&(b=Math.min(b+O,L),c(b),m.lastUpdate=T),T-m.lastProgressCall>=Vc&&(m.lastProgressCall=T,(V=h.onProgress)==null||V.call(h)),(b<L||E.enabled)&&(d.current=requestAnimationFrame(A))};return d.current=requestAnimationFrame(A),()=>{var T;d.current&&cancelAnimationFrame(d.current),f.startCalled&&!f.completeCalled&&(f.completeCalled=!0,(T=h.onComplete)==null||T.call(h))}},[]),u.useEffect(()=>{var L;const b=E.initialEnabled&&f.startCalled,A=!n,T=l>=t.length&&t.length>0;b&&A&&T&&!f.completeCalled&&(f.completeCalled=!0,(L=h.onComplete)==null||L.call(h))},[n,l,t.length]),{streamText:u.useMemo(()=>{const b=E.initialEnabled?t.slice(0,l):t;return r!=="complete-only"?b:Wc(b,C)},[t,l,r,C]),isAnimating:C}},ls={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Kc=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),jc=(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}},Xc=()=>{const{chatSDK:e}=Oe(),[t,n]=u.useState(ls),r=()=>n(ls);return un(e,{onConnectionDelayed:s=>{s>0?n(Kc(s)):r()},onReconnectSucceeded:r,onConnected:r}),u.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>jc(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},Zc=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Jc=(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)}},hr=e=>e.replace(/\s+/g," ").trim(),Qc="Code block",ko=e=>`A11Y_INLINE_CODE_${e}`,Ro=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}},Oo=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}},eu=e=>{const{blockquotePrefix:t,content:n}=Ro(e),{content:r}=Oo(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],a=s[2],l=o[0];if(!(l!=="`"&&l!=="~"||!o.split("").every(c=>c===l))&&!(l==="`"&&a.includes("`")))return{char:l,blockquotePrefix:t,length:o.length}},tu=(e,t)=>{const{blockquotePrefix:n,content:r}=Ro(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=Oo(r);if(o)return!1;const a=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!a)return!1;const l=a[1];return l[0]===t.char&&l.length>=t.length&&l.split("").every(c=>c===t.char)},nu=(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},ru=(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},su=(e,t)=>{let n=t,r=1,s,o=!1,a=!1;for(;n<e.length&&r>0;){const l=e[n];if(l==="\\"&&n+1<e.length){n+=2;continue}if(s){l===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(l)){a=!0,n+=1;continue}if(r===1&&a&&(l==='"'||l==="'")){s=l,n+=1;continue}if(l==="("){r+=1,o=!0,n+=1;continue}if(l===")"){r-=1,n+=1;continue}/\s/.test(l)||(o=!0),n+=1}return r===0?n:-1},ou=e=>{let t=0,n="";for(;t<e.length;){const r=nu(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=ru(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&en(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]==="!"&&!en(e,r-1)?r-1:r;n+=e.slice(t,o);const a=e.slice(r+1,s),l=su(e,s+2);if(l===-1){n+=e.slice(o);break}n+=a,t=l}return n},Lo=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},iu=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const a=o[s+t.length]??"";return Lo(n,r,a)?t:`${n}${r}`}),au=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),lu=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),cu=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,a)=>{const l=a[o+n.length]??"";return Lo(r,s,l)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},uu=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),du=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},cs=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))},us=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 a=n.trim();a&&t.push(a),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},mu=e=>{const t=e.split(`
2
- `),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],a=us(s);if(a.length>0&&o&&cs(o)){for(n.push(a.join(" ")),r+=2;r<t.length;){const l=t[r],c=us(l);if(c.length===0||cs(l))break;n.push(c.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
3
- `)},hu=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),fu=(e,t)=>{const n=e.split(`
4
- `),r=[];let s=0;for(;s<n.length;){const o=n[s],a=eu(o);if(!a){r.push(o),s+=1;continue}let l=-1;for(let c=s+1;c<n.length;c++)if(tu(n[c],a)){l=c;break}if(l===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=l+1}return r.join(`
5
- `)},en=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},gu=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||en(e,n)){r+=s,n+=1;continue}let o=n;for(;o<e.length&&e[o]==="`";)o+=1;const a=e.slice(n,o);let l=o,c=!1;for(;l<e.length&&e[l]!==`
6
- `;){if(e[l]==="`"&&!en(e,l)&&e.startsWith(a,l)){const d=e.slice(o,l),m=t.push(d)-1;r+=ko(m),n=l+a.length,c=!0;break}l+=1}c||(r+=a,n=o)}return{text:r,inlineCodes:t}},No=(e,{codeBlockPlaceholder:t=Qc}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
7
- `);if(!n)return;const r=[];let s=n;s=fu(s,t),s=du(s);const o=gu(s);s=o.text,r.push(...o.inlineCodes),s=ou(s),s=iu(s),s=au(s),s=lu(s),s=cu(s),s=mu(s),s=hu(s),s=uu(s);for(let l=0;l<r.length;l++)s=s.replaceAll(ko(l),r[l]);return hr(s)||void 0},pu=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return je(r)?t.image:tr(r)?t.video:r==="application/pdf"||/\.pdf$/i.test(n)?t.pdf(n):t.document(n)},tn=e=>(e==null?void 0:e.trim())||"",_u=e=>(e?hr(e):void 0)||void 0,Do=e=>({text:tn(e),format:"plain"}),Eu=e=>({text:tn(e),format:"markdown"}),Tn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=tn(e);return r&&r!==tn(n)?Eu(r):Do(t)},yt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],a=n==="markdown"?No(t,{codeBlockPlaceholder:s}):_u(t);if(r&&o.push(r),e&&o.push(e),a&&o.push(a),o.length!==0)return o.join(", ")},$o=(e,t)=>No(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),bu=(...e)=>hr(e.filter(Boolean).join(", "))||void 0,ds=(e,t,n,r)=>{if(!t||t===n)return e;const s=$o(t,r);return s?bu(e,s):e},Cu=(e,t)=>{var r,s,o,a;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const l=((s=e.name)==null?void 0:s.trim())||"",c=pu({name:l,mimeType:e.type},t);return ds(c,n,l,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const l=e.fileInfoList??[],c=l.length;if(c===0)return;const d=((a=(o=l[0])==null?void 0:o.fileName)==null?void 0:a.trim())||"",h=l.every(f=>{var E;return(E=f.mimeType)==null?void 0:E.startsWith("image")})?t.receivedFilesImageCount(c):t.multipleFilesCount(c);return ds(h,n,d,t.codeBlockPlaceholder)}return $o(n,t.codeBlockPlaceholder)},vu=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let a=null;const l=[];let c=null,d=null,m=null,h=!1,f=0;const E=(w,O,U)=>({text:w,ignoreSuppression:O,queueOrder:f++,dedupeKey:U}),v=()=>{const w=l[0]??null,O=a;return w&&O?O.queueOrder<w.queueOrder?(a=null,O):l.shift()??null:w?l.shift()??null:O!==null?(a=null,O):null},y=()=>{for(;;){const w=v();if(!w)return null;if(!(!w.ignoreSuppression&&(r!=null&&r())))return w}},C=w=>{c=w.text,d=w.dedupeKey??null,h=!0,e(w.text),m=setTimeout(()=>{m=null,h=!1;const O=y();O&&C(O)},n)},_=w=>{c=w.text,d=w.dedupeKey??null,e(w.text)},b=(w,O,U,Y)=>O!=null&&Y!=null?O===Y:O==null&&Y==null?w!=null&&w===U:!1,A=(w,O,U)=>{if(!w||!O&&(r!=null&&r()))return;const Y=U==null?void 0:U.dedupeKey;if(!(h&&b(w,Y,c,d)))if(h){if(((U==null?void 0:U.mode)??"latestOnly")==="ordered"){const z=l[l.length-1];if(z&&b(w,Y,z.text,z.dedupeKey))return;l.push(E(w,O,Y)),l.length>o&&l.shift();return}a=E(w,O,Y)}else a=null,C(E(w,O,Y))};return{announce:(w,O)=>{A(w,!1,O)},announceIgnoringSuppression:(w,O)=>{A(w,!0,O)},flush:()=>{const w=[];let O=v();for(;O!==null;)w.push(O),O=v();if(m!==null&&(clearTimeout(m),m=null),h=!1,w.length!==0)for(const U of w)_(U)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),a=null,l.length=0,c=null,d=null,h=!1}}},yu=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Su=(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(". "),Au=(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}},xu=(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}},Tu=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Iu=(e,t)=>xe.isAdmin(e)?xe.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,wu=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Mu=e=>e===fe.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===fe.CollectionEventSource.EVENT_MESSAGE_UPDATED,ku=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Ru=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Ou=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Lu=({intent:e,strings:t})=>({label:Ru(e,t),hint:Ou(e,t)}),Nu="1.27.0",Ne="sb-agent",Ee={ENTRY:`${Ne}-entry`,MODAL_ROOT:`${Ne}-modal-root`,WINDOW:`${Ne}-window`,LAUNCHER:`${Ne}-launcher`,WINDOW_TITLE:`${Ne}-window-title`},Po="data-sb-initial-focus",Fo="true",Du=`[${Po}="${Fo}"]`,Bo={[Po]:Fo},fr="data-sb-focus-trap-sentinel",$u="true",Uo="data-sb-initial-focus-header",Ho="true",Pu=`[${Uo}="${Ho}"]`,Go={[Uo]:Ho},Ht=2147483647,ot={MODAL:Ht-1,TOOLTIP:Ht-2,WINDOW:Ht-3,LAUNCHER:Ht-4},Vo=36,Fu=100,Bu=Nu,gr="noopener noreferrer nofollow";function Uu(){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 Gt={};function Hu(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Gt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Gt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Gt[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(Gt).filter(t=>t.startsWith(e))}}}}const Gu={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_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:"User 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}`}},zn={language:"en",strings:Gu,dateLocale:ia.enUS},zo=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_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}),Yo=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Rt},Rt="en",Wo=new Set([Rt,"ko","es","pt","fr","hi","it","de","tr","ja"]),Vu='@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:zu,useContext:pr}=_e("AgentUIElementResolver"),Yu=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=u.useMemo(()=>{const o=n??document.body,a=e??o,l=t??o,c=d=>d===Ee.MODAL_ROOT?l:a.querySelector(`#${d}`);return{resolveElement:c,resolvePortalContainer:d=>c(d)??l}},[e,t,n]);return i.createElement(zu,{value:s},r)};function st(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const ms=()=>{const e=[];let t=0;return{register:n=>{const r=++t;return e.push({id:r,handler:n}),()=>{const s=e.findIndex(o=>o.id===r);s>=0&&e.splice(s,1)}},dismissTopmost:()=>{const n=e[e.length-1];return n?(n.handler(),!0):!1}}},{Provider:Wu,useContext:qo}=_e("EscapeDismissStack"),hs=e=>{e.stopPropagation(),e.stopImmediatePropagation()},qu=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=u.useRef(null),s=u.useRef(null);r.current||(r.current=ms()),s.current||(s.current=ms());const o=r.current,a=s.current;u.useLayoutEffect(()=>{const c=t??st(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){hs(m);return}a.dismissTopmost()&&hs(m)}};return c.addEventListener("keydown",d),()=>c.removeEventListener("keydown",d)},[t,e,a,o]);const l=u.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:a.register}),[a,o]);return i.createElement(Wu,{value:l},n)},Ko=(e,t,n)=>{const r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t},[t]),u.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Ku=(e,t)=>{const{register:n}=qo();Ko(e,t,n)},ju=(e,t)=>{const{registerShellDismissHandler:n}=qo();Ko(e,t,n)},Xu=(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.":""))))})},fs=zo(zn.strings),Zu={...fs,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:fs.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"},nn={language:zn.language,dateLocale:zn.dateLocale,stringSet:Zu},Ju=Object.freeze(Object.defineProperty({__proto__:null,default:nn},Symbol.toStringTag,{value:"Module"})),Yn=new Map([[Rt,nn]]);async function Qu(e){const t=Yn.get(e);if(t)return t;try{if(Wo.has(e)){const{default:n}=await Xu(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/CCEnmnDV.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Ju),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/0hIk0F0O.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/CSiVLAQX.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BA3mgvxo.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/aLvBaYD0.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/CybHF_pZ.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/DVsz-h87.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/D57XEzyM.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/CUwm0Oc7.cjs"))}),`./languages/${e}.ts`,3);return Yn.set(e,n),n}return nn}catch{return nn}}const{Provider:ed,useContext:oe}=_e("Localization"),td=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,a]=u.useState(Yn.get(Rt));return u.useEffect(()=>{const l=t??Yo(e);o.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:l}),Qu(l).then(a))},[e,t,n]),i.createElement(ed,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(l,c,d)=>Xe.format(l,c,{locale:o.dateLocale,...d})}},s)},rn="data-sb-agent-theme",gs=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${rn}='${e}'] & { ${r} }`},J={light:gs("light"),dark:gs("dark")},nd=D.css(({theme:e})=>{const{palette:t}=e;return`
1
+ "use strict";var ia=Object.defineProperty;var aa=(e,t,n)=>t in e?ia(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>aa(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ge=require("@sendbird/chat"),u=require("react"),D=require("styled-components"),Xe=require("date-fns"),la=require("date-fns/locale/en-US"),Be=require("@sendbird/chat/message"),ca=require("react-dom"),be=require("@sendbird/chat/aiAgent"),ze=require("@sendbird/chat/groupChannel"),ua=require("date-fns/isSameDay"),da=require("dompurify"),er=e=>e&&e.__esModule?e:{default:e};function ma(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 fa=er(ge),i=ma(u),p=er(D),is=er(da),ct="sb-agent",as="KEY_IMG_ASPECT_RATIO",Fn="*/*",ne={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 Zt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Zt||{}),xt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(xt||{});const ls=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},ha=e=>e===xt.COMPLETED||e===xt.CANCELED?e:xt.IN_PROGRESS,yn=e=>Qe(e)&&!ls(e),Qe=e=>!!e&&"sender"in e,ga=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),pa=(e,t,n,r=!0)=>{if(!r||!yn(e))return"single";const o=()=>{if(!yn(t))return!1;const c=t.sender.userId===e.sender.userId,d=Xe.isSameMinute(t.createdAt,e.createdAt);return c&&d},s=()=>{if(!yn(n))return!1;const c=n.sender.userId===e.sender.userId,d=Xe.isSameMinute(n.createdAt,e.createdAt);return c&&d},a=o(),l=s();return a&&l?"middle":a?"bottom":l?"top":"single"},ft=(e,t)=>(()=>{var r;return Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Ie={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>ls(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Be.SendingStatus.PENDING)},He=e=>e.startsWith("image/"),cn=e=>e.startsWith("video/"),cs=({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"},us=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},un=e=>{switch(e){case"top":case"middle":return ne.GAP_GROUPED;default:return ne.GAP_UNGROUPED}},_a=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(s,...a)=>{const[l,c,d]=a;return o<d&&r.push({type:"text",value:e.slice(o,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),o=d+s.length,s}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),t?r.map(s=>s.type!=="text"?s:{...s,value:t(s.value)}):r},Ea=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),ba=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Ca=e=>e.replace(/~~/g,"\\~\\~"),va=e=>{let t=e;return t=Ea(t),t=ba(t),t=Ca(t),t},ya=typeof navigator<"u"&&navigator.product==="ReactNative",Br=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return ya?e.find(n):e.findLast(n)};function he(){}function Sa(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Aa(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 Bn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ve={isStreaming(e){const t=Bn(e.data);return typeof t=="object"&&!!t.stream},isWelcomeMessage(e,t){var n;if(((n=e.extendedMessagePayload)==null?void 0:n.bot_message_type)==="welcome")return!0;if(ft(e,t)){const r=Bn(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},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)}},Sn=`@${ct}`,xa=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Sn}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const s=Aa(`${e}/${t}/${o}`);return`${Sn}-udata/${s}`},anonUserSession:()=>`${Sn}-session/${e}/${t}`};return{template:{set:(o,s)=>n.set(r.template(o),s),get:o=>n.get(r.template(o)),setCachedToken:o=>n.set(r.templateToken(),o),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:o=>{try{const s=n.get(r.messengerSession(o));return s?JSON.parse(s):null}catch{return null}},setSettings:(o,s)=>{try{delete s.auto_created_user;const a=JSON.stringify(s);n.set(r.messengerSession(o),a)}catch{return}},getAnonUser:()=>{try{const o=n.get(r.anonUserSession());return o?JSON.parse(o):null}catch{return null}},setAnonUser:o=>{try{const s=JSON.stringify(o);n.set(r.anonUserSession(),s)}catch{return}},clear:o=>{try{o&&n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}},ds=(e,t,n={})=>{let r=null,o=null,s=null;const{leading:a=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(s===null||m-s>=t)a?(e(...d),s=m):(o=d,s=m);else if(o=d,l&&!r){const f=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},f)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},c},Ta=()=>{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 Ia{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??be.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[be.ConversationStatus.OPEN,be.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??be.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:o,aiAgentConversationStatusFilter:s,aiAgentIds:a,deskChannelFilter:l}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||o===be.AIAgentChannelFilter.EXCLUDE||a&&a.length>0&&!a.includes(t.conversation.aiAgentId)||s&&s.length>0&&!s.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?l!==be.DeskChannelFilter.EXCLUDE:!1}}class ms extends ze.BaseChannelCollection{constructor(n,r){const o=new Ia(r.filter),s=n,a=s.aiAgent._manager,l=r.limit??20,c=ze.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,f,h,_)=>a.getMyGroupChannels(m,f.params,_),changeLogSync:m=>{const{aiAgentChannelFilter:f,aiAgentIds:h,deskChannelFilter:_,pinnedChannelUrls:y,copilotConversationOnly:C,copilotSupportChannelUrl:v}=o.params,b={aiAgentChannelFilter:f,aiAgentIds:h,deskChannelFilter:_,pinnedChannelUrls:y,copilotConversationOnly:C,copilotSupportChannelUrl:v};return a.getMyGroupChannelChangeLogs(m,b,ze.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(s.aiAgent._iid,{filter:o,order:c,limit:l,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-${Ta()}`,this._throttledOnChannelChanged=ds(()=>{var _;const m=[...this._pendingChannels];this._pendingChannels=[];const f=new Map;for(const{channel:y,context:C}of m)f.delete(y.url),f.set(y.url,{channel:y,context:C});const h=new Map;for(const{channel:y,context:C}of f.values())h.has(C)||h.set(C,new Map),h.get(C).set(y.url,y);for(const[y,C]of h){const v=Array.from(C.values()),b=(_=this._sdk.currentUser)==null?void 0:_.userId,E=v.filter(x=>this.filter.match(x,b)),A=v.filter(x=>!this.filter.match(x,b)).map(x=>x.url);E.length>0&&this._base._addChannelsToView(E,y,!1),A.length>0&&this._removeChannels(A,y)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,f)=>{for(const h of m)this._pendingChannels.push({channel:h,context:f});this._throttledOnChannelChanged()},onRemove:(m,f)=>{this._removeChannels(m,f)}})}get _base(){return this}_removeChannels(n,r){const o=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:s})=>!o.has(s.url)),this._base._removeChannelsFromView(n,r)}get channels(){var l;const n=((l=this._params.filter)==null?void 0:l.pinnedChannelUrls)??[],r=[],o=new Map(super.channels.map(c=>[c.url,c])),s=new Set;for(const c of n){const d=o.get(c);d&&!s.has(c)&&(r.push(d),s.add(c))}const a=super.channels.filter(c=>!s.has(c.url));return[...r,...a]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class fs{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=wa(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(s=>s(t.payload));await Promise.all(o).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}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(o=>o!==n))}}const wa=()=>{let e=he,t=he;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var Fe=(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))(Fe||{});class kt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Ze={CloseConversation:e=>new Ma(e),MessengerSettingsUpdated:e=>new ka(e),ActiveChannelUpdated:e=>new Ra(e),AnonymousSessionTokenExpired:()=>new La,AuthTokenRefreshed:()=>new Oa};class Ma extends kt{constructor(){super(...arguments);S(this,"type","conv.close")}}class ka extends kt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class Ra extends kt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class La extends kt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Oa extends kt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}var nr=(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))(nr||{});class hs{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 gs{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 Un{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const Na=e=>({onSessionTokenRequired:t=>{t(null),e.send(Ze.AnonymousSessionTokenExpired())}}),Da="ai_agent:stats",$a="conversation_initial_render",Pa=800220;var ve=(e=>(e.AUTH="auth_duration",e.GET_CHANNEL="get_channel_duration",e.GET_MESSAGES="get_messages_duration",e.TOTAL_DURATION="total_duration",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache",e))(ve||{});class Fa{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"channelUrl",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??Pa,this.errorDescription=n,this}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:Date.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:Date.now()}),this)}getDuration(t){const n=this.timers.get(t);return!n||n.startTime===null||n.endTime===null?null:n.endTime-n.startTime}isCommitted(){return this.committed}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(Da,t)):!1}}class Ba extends Fa{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return $a}buildPayload(){const n=this.getDuration(ve.AUTH),r=this.getDuration(ve.GET_CHANNEL),o=this.getDuration(ve.GET_MESSAGES),s=this.getDuration(ve.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(ve.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...o!==null&&{get_messages_duration:o},...s!==null&&{total_duration_from_cache:s}},c={key:this.getMetricKey(),value:a!==null?String(a):"0"};return this.conversationId!==null&&(c.conversation_id=this.conversationId),this.errorCode!==null&&(c.error_code=this.errorCode),this.errorDescription!==null&&(c.error_description=this.errorDescription),Object.keys(l).length>0&&(c.extra=l),c}}class Ua{constructor(t){S(this,"commitCallback");S(this,"presentMethod","direct_present");S(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Ba().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(ve.TOTAL_DURATION).startTimer(ve.TOTAL_DURATION_FROM_CACHE).startTimer(ve.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(ve.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ve.AUTH).setError(t instanceof ge.SendbirdError?t.code:void 0,t.message).stopTimer(ve.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(ve.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(ve.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(ve.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ve.GET_CHANNEL).setError(t instanceof ge.SendbirdError?t.code:void 0,t.message).stopTimer(ve.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ge.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ve.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ge.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ve.TOTAL_DURATION).stopTimer(ve.GET_MESSAGES).commit())}setChannelUrl(t){var n;(n=this.stats)==null||n.setChannelUrl(t)}cleanup(){var t;(t=this.stats)==null||t.commit()}setPresentMethod(t){var n;this.presentMethod=t,(n=this.stats)==null||n.setPresentMethod(t)}clear(){this.stats=null}}function Ha(){let e=null,t=0;const n=(r,o)=>{if((e==null?void 0:e.key)===r)return e.promise;const s=++t,l=(e?e.promise.catch(()=>{}).then(()=>o()):o()).finally(()=>{(e==null?void 0:e.id)===s&&(e=null)});return e={key:r,id:s,promise:l},l};return n.isPending=()=>e!==null,n}const ps=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Ur={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},rr={conversation:{...Ur,messageAlertSoundEnabled:!1,list:{...Ur,markdownImageRenderMode:"default"},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Hr=e=>e?{conversation:za(e.conversation),launcher:Ga(e.launcher)}:rr,Ga=e=>ut(rr.launcher,e),za=e=>{const t=rr.conversation;if(!e)return t;const{list:n={},header:r={},input:o,fileViewer:s={},messageAlertSoundEnabled:a=t.messageAlertSoundEnabled,...l}=e,{camera:c={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=o??{},f=ut(t.list,l,n);return{...f,messageAlertSoundEnabled:a,list:f,header:ut(t.header,r),input:{camera:ut(t.input.camera,c),gallery:ut(t.input.gallery,d),fileEnabled:m},fileViewer:ut(t.fileViewer,s)}},ut=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,ps(r));return n},Va=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}),Ya=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Hn=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog}),_s=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Re=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===be.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},or=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===be.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,o;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((o=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:o.timestamp))=="number"}function Wa(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 qa(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Es(e){return!!e&&e<=Date.now()}function Ka(e){return!e.title}function ja(e,t){var n;if(e)return Ka(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 Xa{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ds(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:Re(o)?"closed":"open",conversationStatus:(s=o.conversation)==null?void 0:s.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",o.url)},250,{leading:!0,trailing:!1});const n=new ze.GroupChannelHandler({onChannelChanged:o=>{var s,a;o.isGroupChannel()&&o.url===((s=this._session)==null?void 0:s.activeChannel.url)&&((a=this._handleActiveChannelChangedThrottled)==null||a.call(this,o))}}),r=new ge.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,o;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const a=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();a.url===t&&((o=this._session)==null||o._updateActiveChannel({url:a.url,status:Re(a)?"closed":"open",conversationStatus:(r=a.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",a.url))}catch(s){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",s)}});S(this,"_initConversationIfNeeded",async t=>{if(t.isAIAgent&&!t.conversation)try{await t.initConversation({aiAgentId:this.aiAgentId})}catch(n){this._logger.warn("AIAgentEventManager: initConversation failed",n)}});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Fe.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Fe.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Fe.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Fe.AuthTokenRefreshed,t)}))}}class Za{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Ze.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Ze.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 bs=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)}},Cs=e=>JSON.parse(e),Ja=e=>JSON.parse(e);function Qa(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function el(e){const t={};function n(r,o=""){for(const[s,a]of Object.entries(r)){const l=o?`${o}.${s}`:s;a&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t[l]=a}}return n(e),t}function tl({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((o,[s,a])=>{if(!r&&!["number","boolean","string"].includes(typeof a))throw new Error(`If transformer is not provided, value(${s}:${a}) must be a {string, number, or boolean}`);const l=r?r(a):String(a),c=n(s);return o.replace(c,bs(l))},e)}async function nl({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([s,a])=>{const l=await r(a);return{regex:n(s),transformedValue:l}}))).reduce((s,{regex:a,transformedValue:l})=>s.replace(a,bs(l)),e)}var Gn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Gn||{});const vs=e=>typeof e=="object"&&e!==null,Gr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",rl=e=>!vs(e)||!Gr(e,"channel_url")||!Gr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},ol={1:rl};function sl(e){if(!vs(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=ol[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function il(e,t,n,r){const o=fa.default.init({appId:e,modules:[new ze.GroupChannelModule,new be.AIAgentModule],localCacheEnabled:!0,options:new ge.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:ge.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function al(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 ll=[400300,400301,400302,400310];class sr{constructor(t,n,r){S(this,"chatSDK");S(this,"_logger");S(this,"_cache");S(this,"connect",async(t,n,r,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const s=new ge.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(s),this.chatSDK.aiAgent.addEventHandler(Gn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=sl(a);(l==null?void 0:l.category)===Gn.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(c=n==null?void 0:n.onExternalAuthTokenExpired)==null||c.call(n,l.data))})}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(s){const a=s;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(a))this._logger.warn("ChatClient.connect","offline connect restricted",a.message,a.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(l=>this._logger.warn("ChatClient.connect","clear cached-data failure",l));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",a.message,a.code),a}});S(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.chatSDK.aiAgent.removeAllEventHandlers(),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 o;if(t.userId===""){const s=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",s),s}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",(o=r.active_channel)==null?void 0:o.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(o,s)=>{new Promise((a,l)=>t==null?void 0:t(a,l)).then(a=>{a?n==null||n(a):r==null||r(),o(a)}).catch(a=>{r==null||r(),s(a)})}});S(this,"_isCacheRestrictedError",t=>ll.some(n=>t.code===n));S(this,"_syncTemplatesIfNeeded",async()=>{var r,o;const t=(o=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:o.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:s,token:a}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=Cs(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(a),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(s){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",s)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(al(t.chatSDK),n=t.chatSDK):n=il(t.appId,t.extensions,t.messengerVersion,t.chatParams),new sr(n,t.logger,t.cache)}}const Pt=new Map,ys={set:(e,t)=>{Pt.set(e,t)},get:e=>{if(Pt.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=Pt.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Pt.entries().next().value;return{platform:t[0],...t[1]}}};class zr extends Error{constructor(n,r){const o=(r==null?void 0:r.detail)??"";super(o||`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=o}}var ir=(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))(ir||{}),ar=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(ar||{}),Ss=(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))(Ss||{});const cl=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class ul{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,o=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const s=await this._fetch(o,n);return r&&s.status===401?this._handleUnauthorized(s,o,n):this._toResult(s)});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 o=await this._parseErrorCode(t);if(!cl(o))return this._toResult(t);if(!await this._refresh(o)||this._credential===null)return this._toResult(t);const a=await this._fetch(n,r);return this._toResult(a)});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 zr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new zr(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}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class Jt{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 Jt({id:t.id,title:t.channelName??null,status:t.status2??ir.INITIALIZED,agent:(()=>{var s;const o=(s=t.recentAssignment)==null?void 0:s.agent;return o?{userId:o.sendbirdId??"",name:o.displayName??"",profileUrl:o.photoThumbnailUrl??""}:null})(),priority:t.priority??ar.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(o=>[o.key,o.value]))??[])},n)}}class lr{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 Jt._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:ps({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 Jt._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new ul(t)}static init(t){return new lr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class cr{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 cr}}function dl(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 ml=1440*60*1e3,fl=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function qe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function hl(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class Qt extends Xa{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,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_operationQueue",Ha());S(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.initialRender.clear(),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 a,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const o=this._getSessionCandidate(n),s=(a=o.userSessionCandidate)!=null&&a.userId?this._cache.messenger.getSettings(o.userSessionCandidate.userId):null;s!=null&&s.bot&&this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:s,source:"cache"}));try{const f=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=o.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=s==null?void 0:s.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let h;if(f.auto_created_user)if(o.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),h={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:C,session_token:v,expire_at:b}=f.auto_created_user;this._cache.messenger.setAnonUser({userId:C,authToken:v,expireAt:b}),h={userId:C,authToken:v},this._logger.debug("AIAgent.authenticate: anonymous user created",C)}else h={userId:((d=o.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=o.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(h.userId,f),this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:f,source:"server"}));const _=(()=>{var C;return o.type==="anonymous"?Na(this._dispatcher):(C=o.userSessionCandidate)==null?void 0:C.sessionHandler})(),y=await this._chatClient.connect(h,_,C=>{var v;this._logger.debug("AIAgent: session token refreshed"),(v=this._session)==null||v._updateAuthToken(C),this._deskClient.refreshDeskAuthToken(C)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:h.userId,accessToken:h.authToken,onDeskTokenRefreshRequired:async({reason:C})=>{var v;if(C===Ss.ERR_SESSION_KEY_EXPIRED){await new Promise(E=>setTimeout(E,2e3));const b=(v=this._session)==null?void 0:v.userSession.authToken;return b?await this._deskClient.refreshDeskAuthToken(b):!1}return!1}}),(s==null?void 0:s.language)!==f.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Za({sdkUser:y,userSession:h,activeChannel:{url:f.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:h.userId}),f}catch(f){throw this._statsTrackers.initialRender.onAuthError(f),f}})});S(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var n;this._logger.debug("AIAgent.deauthenticate: start"),await this._chatClient.disconnect(),this._deskClient.deauthenticate(),this._cache.messenger.clear((n=this._session)==null?void 0:n.userSession.userId),this._session=null,this._removeChannelHandler(),this._statsTrackers.initialRender.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}),o=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",o),o});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:be.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const s=await r.next();for(const a of s)hl(a.context??{},n.context)&&o.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:o.length}),o});S(this,"closeConversation",async n=>{var o;qe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===be.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:be.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 ms(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{qe(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const o=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",o),{...o,context:o.context??{}}});S(this,"updateContext",async(n,r)=>{qe(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const o=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",o),{...o,context:o.context??{}}});S(this,"getContextObject",async n=>{qe(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const o=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",o),{...o,context:o.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 o={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},s=r.userSession.userId,a=await this._chatClient.setUserMemoryState(o);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Hn(a);const l=this._cache.messenger.getSettings(s);if(l){const c={...l,memory:a};this._cache.messenger.setSettings(s,c),this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:c,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",a.enabled),Hn(a)});S(this,"refreshActiveChannel",async n=>{var l,c,d;qe(this._session);const r=this._session,o=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:o});const s=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:o?(c=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:c.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)??s.active_channel.channel_url;const a=s.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,s),this._session._updateActiveChannel({url:a,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",a),a});S(this,"_getSessionCandidate",n=>n instanceof gs?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Un?{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-ml<=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 Un)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(o=>!(o 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=Hr(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,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={initialRender:new Ua((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var f;const r=ys.get(n.platform),o=n.logger??new hs(n.logLevel??nr.WARN),s=n.dispatcher??new fs(o),a=n.useMMKVStorage?dl(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=xa({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=sr.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:o,cache:c}),m=fl?lr.init({appId:n.appId,logger:o,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):cr.init();return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Qt({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:m,cache:c,logger:o,dispatcher:s})}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=Hr(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get statsTrackers(){return this._statsTrackers}}const Ee=(e,t)=>{const n=u.createContext(t??null),r=({children:a,value:l})=>i.createElement(n.Provider,{value:l},typeof a=="function"?a(l):a),o=({children:a})=>i.createElement(n.Consumer,null,l=>l?typeof a=="function"?a(l):a:null),s=()=>{const a=u.useContext(n);if(!a)throw new Error(`use${e}Context must be used within a ${e}Provider`);return a};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,o.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:s}};function Ue(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){const[a,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:a,updateTemplate:f=>l(()=>f),components:c,updateComponent:(f,h)=>d(_=>({..._,[f]:h}))};return i.createElement(t.Provider,{value:m},s)}function r({template:s,children:a}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{s&&l(s)},[s]),i.createElement(i.Fragment,null,a)}function o({children:s}){return i.createElement(n,null,s)}return o.defaults=e,o.useContext=()=>u.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(s=>{o[s]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),o}function gl(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function pl(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":As(e,t)}function As(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 o=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,o))??`${o} photos`}return e.name}function _l(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=Xe.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Xe.isToday(o)?n.hoursAgo(Xe.differenceInHours(r,o)):t(o,n.dateShortFormat)}const El=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},Ft=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Vr=(e,t)=>{const n=Ft(Math.round(t*255));if(e.startsWith("#")){const o=e.slice(1);return o.length===3||o.length===4?`#${o[0]}${o[0]}${o[1]}${o[1]}${o[2]}${o[2]}${n}`:`#${o.slice(0,6)}${n}`}const r=El(e);return r?`#${Ft(r[0])}${Ft(r[1])}${Ft(r[2])}${n}`:e},bl=(e,t)=>{if(!t)return e;const n={...e};for(const[r,o]of Object.entries(t))o&&(n[r]=o);return n},Cl=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",vl=e=>e.length>0,yl=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>He(o.type)),r=e.some(o=>!He(o.type));return n&&r?He(t.type)?e.filter(o=>He(o.type)):[t]:r?[t]:e},Yr=e=>e.length===0?"empty":e.every(t=>He(t.type))?"images":"non_images",Sl=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=yl(t),o=Yr(e),s=Yr(r),l=o==="images"&&s==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return l.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:l.nextFiles.length}:l.type==="replace"&&o!=="empty"&&o!==s?{type:"confirm_replace",action:l}:{type:"apply",action:l}},mt=3,xs=6,Al=e=>e%mt===0?mt:xs,xl=({index:e,itemCount:t})=>{const n=t%mt,r=n>0,o=r?t-n:t,s=r&&e>=o,a=s?n:mt,l=s?e-o:e%mt,c=!r&&e>=t-mt;return{columnSpan:r?xs/a:1,rowItemCount:a,isLastInRow:l===a-1,isLastRow:s||c}},Ts=Ee("AIAgent"),Tl=Ts.Provider,Me=Ts.useContext;function Il(e){const t=wl(e);return i.createElement(Tl,{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 wl(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=Qt.init(e);else{const o=Ml(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=Qt.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.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}function Ml(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}const Wr=Symbol("conversationMessageEventBridge"),bt=Symbol("conversationMessageEventPublisher"),kl=(e,t)=>{const n=e;if(n[bt]=t,n[Wr])return e;n[Wr]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=s=>{r({...s,onMessagesAdded:(a,l,c)=>{var d,m;(d=s.onMessagesAdded)==null||d.call(s,a,l,c),(m=n[bt])==null||m.call(n,{kind:"messagesAdded",source:a.source,messages:c})},onMessagesUpdated:(a,l,c)=>{var d,m;(d=s.onMessagesUpdated)==null||d.call(s,a,l,c),(m=n[bt])==null||m.call(n,{kind:"messagesUpdated",source:a.source,messages:c})}})};const o=e.initialize.bind(e);return e.initialize=s=>{const a=o(s),l=a.onCacheResult.bind(a),c=a.onApiResult.bind(a);return a.onCacheResult=d=>l((m,f)=>{var h;d(m,f),(h=n[bt])==null||h.call(n,{kind:"initialized",source:"cache",messages:f??[]})}),a.onApiResult=d=>c((m,f)=>{var h;d(m,f),(h=n[bt])==null||h.call(n,{kind:"initialized",source:"api",messages:f??[]})}),a},e},dn=()=>{const[,e]=u.useState(0);return u.useCallback(()=>e(t=>t+1),[])};let Rl=0;function Ll(){return u.useState(()=>`${Rl++}`)[0]}const ht=(e,t,n)=>{const r=u.useRef(t),s=Ll();r.current=t,u.useEffect(()=>{var l;const a=c=>{const d=c;return Object.keys(d).forEach(f=>{d[f]=(...h)=>{var y;const _=r.current;(y=_[f])==null||y.call(_,...h)}}),d};return(l=e==null?void 0:e.groupChannel)==null||l.addGroupChannelHandler(s,a(new ze.GroupChannelHandler)),()=>{var c;(c=e==null?void 0:e.groupChannel)==null||c.removeGroupChannelHandler(s)}},[e==null?void 0:e.groupChannel,s])};function Ol(e,t){return!e||!t?!0:e.url!==t.url}function De(e){return e!=null&&"sendingStatus"in e}function Nl(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return De(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Dl(e,t){return Nl(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function qr(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const en={collection:{groupChannel:{defaultOrder:ze.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Kr(e){return!e||!Array.isArray(e)?!1:e.length!==0}function jr(e,t){return e.reduce((n,r)=>{const o=t(r);return n[o]=r,n},{})}const $l=({...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=Pl(t.value.messages);else{const n={...e.messageMap},r=[],o=[];t.value.messages.forEach(s=>{const a=De(s)?s.reqId:void 0,l=s.messageId||void 0;[a,l].forEach(c=>{if(!c)return;const d=n[c];Fl(d,s,t.value.strictStreamingOrder)&&(d&&r.push(d),s.parentMessageId>0&&(d!=null&&d.parentMessage)&&s.applyParentMessage(d.parentMessage),o.push(s))})}),r.forEach(s=>{De(s)&&delete n[s.reqId],delete n[s.messageId]}),o.forEach(s=>{De(s)&&(n[s.reqId]=s),s.messageId!==0&&(n[s.messageId]=s)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(o=>Dl(o,n));return t.value.clearBeforeAction?e.newMessageMap=jr(r,qr):(r.map(s=>s.messageId).forEach(s=>delete e.newMessageMap[s]),e.newMessageMap={...e.newMessageMap,...jr(r,qr)}),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 o=e[n][r];o&&(De(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),t.value.reqIds.forEach(r=>{const o=e[n][r];o&&(De(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),e}}},Pl=e=>e.reduce((t,n)=>(De(n)?(t[n.reqId]=n,n.sendingStatus===Be.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Fl=(e,t,n=!1)=>{var r,o;if(!De(e)||!De(t))return!0;if(n&&e&&Zr(e)&&Zr(t)){const s=((r=e.message)==null?void 0:r.length)||0,a=((o=t.message)==null?void 0:o.length)||0;if(s>a)return!1}return e.sendingStatus===Be.SendingStatus.SUCCEEDED?t.sendingStatus===Be.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Bl=(e=Ul)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:o,newMessageMap:s},a]=u.useReducer($l,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),l=(v,b,E,A)=>{a({type:"update_messages",value:{messages:v,clearBeforeAction:b,currentUserId:E,strictStreamingOrder:A}})},c=(v,b)=>{a({type:"delete_messages",value:{messageIds:v,reqIds:b}})},d=(v,b,E)=>{a({type:"update_new_messages",value:{messages:v,clearBeforeAction:b,currentUserId:E}})},m=(v,b)=>{a({type:"delete_new_messages",value:{messageIds:v,reqIds:b}})},f=v=>{a({type:"update_initialized",value:{status:v}})},h=v=>{a({type:"update_loading",value:{status:v}})},_=v=>{a({type:"update_refreshing",value:{status:v}})},y=Object.values(s),C=u.useMemo(()=>Array.from(new Set(Object.values(o))).sort(e),[o]);return{updateInitialized:f,updateLoading:h,updateRefreshing:_,updateMessages:l,deleteMessages:c,initialized:t,loading:n,refreshing:r,messages:C,newMessages:y,updateNewMessages:d,deleteNewMessages:m}},Xr=Math.floor(Number.MAX_SAFE_INTEGER/10);function Ul(e,t){let n=0,r=0;return De(e)&&e.sendingStatus!=="succeeded"&&(n=Xr),De(t)&&t.sendingStatus!=="succeeded"&&(r=Xr),e.createdAt+n-(t.createdAt+r)}function Zr(e){try{const t=JSON.parse(e.data||"{}");return typeof t=="object"&&!!t.stream}catch{return!1}}function ye(e){const t=u.useRef(e);return t.current=e,u.useCallback((...n)=>t.current(...n),[t])}const Hl=(e,t,n)=>{var s;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},o=(s=n==null?void 0:n.collectionCreator)==null?void 0:s.call(n,r);return o||e.createMessageCollection({...r,filter:new ze.MessageFilter(r)})};function Jr(e){return e<Date.now()?en.collection.message.searchLimit:en.collection.message.defaultLimit}const Gl=(e,t,n={})=>{var Oe,ke;const r=u.useRef(n);r.current=n;const o=u.useRef(t);o.current=t;const s=r.current.logger,a=r.current.startingPoint??Number.MAX_SAFE_INTEGER,l=Jr(a),c=r.current.strictStreamingOrder??!1,d=u.useRef({prev:!1,next:!1}),m=dn(),f=u.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:h,loading:_,refreshing:y,messages:C,newMessages:v,updateMessages:b,updateNewMessages:E,deleteNewMessages:A,deleteMessages:x,updateInitialized:k,updateLoading:R,updateRefreshing:I}=Bl(n==null?void 0:n.sortComparator),w=ye(T=>{var M,N,j,B;if(!o.current||!o.current.url)return(M=s==null?void 0:s.error)==null?void 0:M.call(s,"[useGroupChannelMessages] channel is required");try{switch(T){case ge.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ge.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case ge.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(j=(N=r.current).markAsRead)==null||j.call(N,[o.current]);break}}catch(z){(B=s==null?void 0:s.warn)==null||B.call(s,"[useGroupChannelMessages/markAsReadBySource]",z)}}),O=ye((T,M)=>{var N,j,B,z,U;if(M.length>0)switch(T){case ge.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ge.CollectionEventSource.SYNC_MESSAGE_FILL:{(j=(N=r.current).shouldCountNewMessages)!=null&&j.call(N)&&E(M,!1,(B=e.currentUser)==null?void 0:B.userId),(U=(z=r.current).onMessagesReceived)==null||U.call(z,M);break}}}),$=ye(T=>{var M,N;(N=(M=r.current).onCollectionEvent)==null||N.call(M,T)}),V=ye(async(T,M,N)=>new Promise((j,B)=>{var $e;f.current.instance&&f.current.instance.dispose(),w(),E([],!0,($e=e.currentUser)==null?void 0:$e.userId);const z=()=>{var ie,re;const{pendingMessages:ae,failedMessages:te}=f.current.instance??{};Kr(ae)&&b(ae,!1,(ie=e.currentUser)==null?void 0:ie.userId),Kr(te)&&b(te,!1,(re=e.currentUser)==null?void 0:re.userId)},U=Hl(T,N,{...r.current,startingPoint:M});f.current={apiInitialized:!1,initialized:!1,instance:U},U.setMessageCollectionHandler({onMessagesAdded:(ae,te,ie)=>{var re;w(ae.source),O(ae.source,ie),b(ie,!1,(re=e.currentUser)==null?void 0:re.userId,c),$({kind:"messagesAdded",source:ae.source,messages:ie})},onMessagesUpdated:(ae,te,ie)=>{var re,Z,le;w(ae.source),O(ae.source,ie),b(ie,!1,(re=e.currentUser)==null?void 0:re.userId,c),ae.source===ge.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((le=(Z=r.current).onMessagesUpdated)==null||le.call(Z,ie)),$({kind:"messagesUpdated",source:ae.source,messages:ie})},onMessagesDeleted:(ae,te,ie,re)=>{const Z=re.map(pe=>pe.messageId),le=re.filter(De).map(pe=>pe.reqId);x(Z,le),A(Z,le),$({kind:"messagesDeleted",source:ae.source,messages:re})},onChannelDeleted:(ae,te)=>{var ie,re;(re=(ie=r.current).onChannelDeleted)==null||re.call(ie,te)},onChannelUpdated:(ae,te)=>{var ie,re;m(),(re=(ie=r.current).onChannelUpdated)==null||re.call(ie,te,ae)},onHugeGapDetected:()=>{V(T,Number.MAX_SAFE_INTEGER,en.collection.message.defaultLimit)}});let ue=!1;U.initialize(ze.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ae,te)=>{var ie,re,Z,le,pe;(re=(ie=r.current).onCacheResult)==null||re.call(ie,ae,te??[]),ae?(e.isCacheEnabled&&((Z=s==null?void 0:s.error)==null||Z.call(s,"[useGroupChannelMessages/onCacheResult]",ae)),ue=!0):te&&((le=s==null?void 0:s.debug)==null||le.call(s,"[useGroupChannelMessages/onCacheResult]","message length:",te.length),b(U.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),z(),te.length>0&&(f.current.initialized=!0,j())),$({kind:"initialized",source:"cache",messages:te??[]})}).onApiResult((ae,te)=>{var ie,re,Z,le,pe,rt,ot;(re=(ie=r.current).onApiResult)==null||re.call(ie,ae,te??[]),f.current.initialized=!0,f.current.apiInitialized=!0,ae?((Z=s==null?void 0:s.warn)==null||Z.call(s,"[useGroupChannelMessages/onApiResult]",ae),ue?B(ae):j()):te&&((le=s==null?void 0:s.debug)==null||le.call(s,"[useGroupChannelMessages/onApiResult]","message length:",te.length),b(U.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),r.current.startingPoint||(ot=(rt=r.current).onMessagesReceived)==null||ot.call(rt,te),e.isCacheEnabled&&z(),j()),$({kind:"initialized",source:"api",messages:te??[]})})}));ht(e,{onUserBanned(T,M){var N,j,B;T.isGroupChannel()&&!Ol(T,o.current)&&(M.userId===((N=e.currentUser)==null?void 0:N.userId)?(B=(j=r.current).onCurrentUserBanned)==null||B.call(j):m())}}),u.useLayoutEffect(()=>{const T=setTimeout(async()=>{e.currentUser&&o.current&&(k(!1),R(!0),await V(o.current,a,l),R(!1),k(!0))});return()=>clearTimeout(T)},[e,(Oe=e.currentUser)==null?void 0:Oe.userId,(ke=o.current)==null?void 0:ke.url,r.current.replyType]),u.useEffect(()=>()=>{f.current.instance&&f.current.instance.dispose()},[]);const H=ye(async()=>{e.currentUser&&o.current&&(I(!0),await V(o.current,Number.MAX_SAFE_INTEGER,en.collection.message.defaultLimit),I(!1))}),Y=ye(async()=>{var M;const T=f.current.instance;if(T!=null&&T.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const N=await T.loadPrevious();b(N,!1,(M=e.currentUser)==null?void 0:M.userId)}catch{}finally{d.current.prev=!1}}),G=ye(()=>{const{initialized:T,instance:M}=f.current;return T&&M?M.hasPrevious:!1}),W=ye(async()=>{var M;const T=f.current.instance;if(T!=null&&T.hasNext&&!d.current.next)try{d.current.next=!0;const N=await T.loadNext();b(N,!1,(M=e.currentUser)==null?void 0:M.userId)}catch{}finally{d.current.next=!1}}),q=ye(()=>{const{initialized:T,apiInitialized:M,instance:N}=f.current;return M&&T&&N?N.hasNext:!1}),ce=ye((T,M)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,B)=>{o.current.sendUserMessage(T).onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),M==null||M(z)}).onSucceeded(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),j(z)}).onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url&&b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),B(z)})})}),_e=ye((T,M)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,B)=>{o.current.sendFileMessage(T).onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),M==null||M(z)}).onSucceeded(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),j(z)}).onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url&&b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),B(z)})})}),L=ye(async(T,M)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise(j=>{const B=[];o.current.sendFileMessages(T).onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),M==null||M(z)}).onSucceeded(z=>{var U;z.isFileMessage()&&z.channelUrl===o.current.url&&(b([z],!1,(U=e.currentUser)==null?void 0:U.userId),B.push(z)),B.length===T.length&&j(B)}).onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url?(b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),B.push(U)):B.push(null),B.length===T.length&&j(B)})})}),X=ye((T,M)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,B)=>{o.current.sendMultipleFilesMessage(T).onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),M==null||M(z)}).onFileUploaded(()=>{m()}).onSucceeded(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),j(z)}).onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url&&b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),B(z)})})}),K=ye(async(T,M)=>{var j,B;if(!o.current||!o.current.url)throw(j=s==null?void 0:s.error)==null||j.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateUserMessage(T,M);return N.channelUrl===o.current.url&&b([N],!1,(B=e.currentUser)==null?void 0:B.userId),N}),F=ye(async(T,M)=>{var j,B;if(!o.current||!o.current.url)throw(j=s==null?void 0:s.error)==null||j.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateFileMessage(T,M);return N.channelUrl===o.current.url&&b([N],!1,(B=e.currentUser)==null?void 0:B.userId),N}),ee=ye(async T=>{var M;if(!o.current||!o.current.url)throw(M=s==null?void 0:s.error)==null||M.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((N,j)=>{let B;T.isUserMessage()&&(B=o.current.resendMessage(T)),T.isFileMessage()&&(B=o.current.resendMessage(T)),T.isMultipleFilesMessage()&&(B=o.current.resendMessage(T)),B&&("onPending"in B&&B.onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId)}),"onFileUploaded"in B&&B.onFileUploaded(()=>{m()}),"onSucceeded"in B&&B.onSucceeded(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),N(z)}),"onFailed"in B&&B.onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url&&b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),j(z)}))})}),de=ye(async T=>{var M,N;if(!o.current||!o.current.url)throw(M=s==null?void 0:s.error)==null||M.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(T.sendingStatus==="succeeded")T.isUserMessage()&&await o.current.deleteMessage(T),T.isFileMessage()&&await o.current.deleteMessage(T),T.isMultipleFilesMessage()&&await o.current.deleteMessage(T);else try{await((N=f.current.instance)==null?void 0:N.removeFailedMessage(T.reqId))}finally{x([],[T.reqId])}}),fe=ye(()=>{var T;E([],!0,(T=e.currentUser)==null?void 0:T.userId)}),xe=ye(async T=>{var M;if(e.currentUser&&o.current){const N=Jr(T);R(!0),b([],!0,(M=e.currentUser)==null?void 0:M.userId),await V(o.current,T,N),R(!1)}});return{initialized:h,loading:_,refreshing:y,messages:C,newMessages:v,resetNewMessages:fe,refresh:H,loadPrevious:Y,hasPrevious:G,loadNext:W,hasNext:q,sendUserMessage:ce,sendFileMessage:_e,sendFileMessages:L,sendMultipleFilesMessage:X,updateUserMessage:K,updateFileMessage:F,resendMessage:ee,deleteMessage:de,resetWithStartingPoint:xe,_dangerous_reducer_updateMessages:b,_dangerous_reducer_deleteMessages:x}},zl=(e,t,n)=>{const r=u.useRef(0),o=u.useRef(new Set),s=u.useCallback(d=>{const m={id:r.current+=1,...d};o.current.forEach(f=>{f(m)})},[]),a=u.useCallback(d=>{var f;const m=((f=n==null?void 0:n.collectionCreator)==null?void 0:f.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new ze.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return kl(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=Gl(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},It={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Is(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Vl(e){const t=Is(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Yl(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Wl(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),s=r-o;let a=0,l=0;const c=(r+o)/2;return r!==o&&(l=c>.5?s/(2-r-o):s/(r+o)),r===e?a=(t-n)/s+(t<n?6:0):r===t?a=(n-e)/s+2:r===n&&(a=(e-t)/s+4),a/=6,[a,l,c]}function ql(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const a=function(m,f,h){return h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?m+(f-m)*6*h:h<.5?f:h<.6666666666666666?m+(f-m)*(.6666666666666666-h)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=a(c,l,e+1/3),o=a(c,l,e),s=a(c,l,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(s*255)]}function Bt(e,t,n){const[r,o,s]=Vl(e),[a,l,c]=Wl(r,o,s),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[f,h,_]=ql(a,m,d);return Yl([Math.round(f),Math.round(h),Math.round(_)])}function Kl(e,t="light"){return{extraDark:Bt(e,.6,1.2),dark:Bt(e,.85,1.1),main:e,light:Bt(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Bt(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function zn(e){const t=Is(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+s*.114>n?It.BLACK:It.WHITE}function jl(e,t,n,r,o){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:o,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 Xl=(e,t,n,r,o)=>({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:o,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"}}),Ut={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)"}},An={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 Qr(e){const t=Zl(e),n=Jl(e,t),r=ec(n,e.colors,e.selectedTheme),o=nc(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:o}}function Zl({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ut.primary.main?Ut.primary:Kl(n,e):Ut.primary;return{...Ut,primary:r,...t}}function Jl({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??zn(s),l=n??It.DEFAULT_BOT_MSG_BG,c=r??zn(l);return(e==="light"?jl:Xl)(o,s,a,l,c)}function Ql(e,t,n){return typeof e=="string"?e:e[t]??n}function ec(e,t,n){var a;if(!t||Object.keys(t).length===0)return e;const r={...e},o=r,s=e;for(const l of Object.keys(t)){const c=t[l];if(c){o[l]={...o[l]};for(const[d,m]of Object.entries(c))if(m!==void 0){const f=((a=s[l])==null?void 0:a[d])??"";o[l][d]=Ql(m,n,f)}}}return r}function tc(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function nc({typography:e}){if(!e)return An;const t={...An};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=An[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=tc(o,r,s)}}),t}const{Provider:rc,useContext:ur}=Ee("AIAgentTheme");function oc({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=u.useRef(null),[l,c]=u.useState(()=>Qr({selectedTheme:(o==null?void 0:o.theme)??"light",palette:t,typography:n,colors:r,primary:o==null?void 0:o.primaryColor,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor})),d=u.useCallback((m,f)=>{f&&(a.current=f);const h=(o==null?void 0:o.theme)??m,_=a.current?a.current.themes[h]:null,y={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!y.primary&&(_!=null&&_.primary_color)&&(y.primary=_.primary_color,y.primaryContrast=_.primary_contrast_color),!y.botMessageBackground&&(_!=null&&_.bot_message_bg_color)&&(y.botMessageBackground=_.bot_message_bg_color,y.botMessageBackgroundContrast=_.bot_message_bg_contrast_color);const C=Qr({selectedTheme:h,palette:t,typography:n,colors:r,...y});c(C),e==null||e.info("theme.update:",h)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor,t,n,r,e]);return u.useEffect(()=>{(o!=null&&o.theme||o!=null&&o.primaryColor||o!=null&&o.botMessageBackgroundColor)&&d(l.selectedTheme)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor]),i.createElement(rc,{value:{theme:l,updateTheme:d}},s)}const xn=25*1024*1024,eo=1,to=new Set(["image/png","image/jpeg","image/jpg"]),no=new Set(["application/pdf"]),sc={off:"off",always:"always",handed_off_only:"handed_off_only"},ic=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:eo,attachmentMode:"handed_off_only",defaultUploadSizeLimit:xn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:to,supportedFileMimeTypes:no})),n=u.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??eo,attachmentMode:sc[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??xn,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??to),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??no)})},[]),r=u.useCallback(o=>{const{channel:s,uploadSizeLimit:a=xn}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?et(s):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??a;const m=e.defaultUploadSizeLimit??a,f=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,f)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(l(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return et(s);default:return!0}},get supportedMimeTypes(){return l()?[Fn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:c,getUploadSizeLimitInMB:d=>c(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},ro=(...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)")},Ct=e=>({...e,context:e.context??{}}),{Provider:ac,useContext:gt}=Ee("AIAgentMessengerSession"),lc=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=Me(),{updateTheme:l}=ur(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[h,_]=u.useState(null),[y,C]=u.useState(null),[v,b]=u.useState(null),[E,A]=u.useState(null),[x,k]=u.useState(null),{updateBaseAttachmentRules:R,createAttachmentRules:I}=ic();u.useEffect(()=>{const V=r.onMessengerSettingsUpdated(({settings:G})=>{const{appearance:W,bot:q,launcher:ce,memory:_e}=G;l(W.selected_theme,W),b(Va(q)),A(Ya(ce)),k(_e?Hn(_e):null),R(G)}),H=r.onActiveChannelUpdated(({channelUrl:G,status:W,conversationStatus:q})=>{f({url:G,status:W,conversationStatus:q})}),Y=r.onAuthTokenRefreshed(()=>{var W;const G=(W=r.session)==null?void 0:W.userSession.authToken;G&&C(q=>q?{...q,authToken:G}:null)});return()=>{V(),H(),Y()}},[r,l,R]);const w=u.useCallback(async()=>{try{const V=await r.authenticate(e),H=r.session;return _(H.sdkUser),C(H.userSession),f(H.activeChannel),d(void 0),V}catch(V){throw _(null),C(null),f(void 0),d(V),V}},[r,e]),O=u.useCallback(async()=>{await r.deauthenticate(),_(null),f(void 0),C(null),b(null),A(null),k(null)},[r]),$=u.useCallback(async()=>{if(!r.session){if(y)return a.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw a.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(y==null?void 0:y.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(f(void 0),await r.refreshActiveChannel())},[r,a,y]);return u.useImperativeHandle(n,()=>{const V=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await o.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:o,authenticate:w,deauthenticate:O,updateContext:async(...H)=>{const Y=ro(...H);if(Y.type==="active"){const q=await(await V()).updateContext(s,Y.context);return Ct(q)}const G=await o.aiAgent.updateContext(Y.aiAgentId,Y.channelUrl,Y.context);return Ct(G)},patchContext:async(...H)=>{const Y=ro(...H);if(Y.type==="active"){const q=await(await V()).patchContext(s,Y.context);return Ct(q)}const G=await o.aiAgent.patchContext(Y.aiAgentId,Y.channelUrl,Y.context);return Ct(G)},getContextObject:async()=>{const Y=await(await V()).getContextObject(s);return Ct(Y)}}},[w,O,m,o,s,a]),i.createElement(ac,{value:{sdkUser:h,userSessionInfo:e,userSession:y,activeChannel:m,setActiveChannel:f,refreshActiveChannel:$,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:c,aiAgentInfo:v,launcherInfo:E,memoryInfo:x,authenticate:w,deauthenticate:O,createAttachmentRules:I,statsTrackers:r.statsTrackers}},t)}),Rt=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useLayoutEffect(()=>{const o=new ge.ConnectionHandler({onDisconnected:s=>{var a,l;return(l=(a=r.current).onDisconnected)==null?void 0:l.call(a,s)},onConnected:s=>{var a,l;return(l=(a=r.current).onConnected)==null?void 0:l.call(a,s)},onReconnectStarted:()=>{var s,a;return(a=(s=r.current).onReconnectStarted)==null?void 0:a.call(s)},onReconnectSucceeded:()=>{var s,a;return(a=(s=r.current).onReconnectSucceeded)==null?void 0:a.call(s)},onReconnectFailed:()=>{var s,a;return(a=(s=r.current).onReconnectFailed)==null?void 0:a.call(s)},onConnectionLost:()=>{var s,a;return(a=(s=r.current).onConnectionLost)==null?void 0:a.call(s)},onConnectionDelayed:s=>{var a,l;return(l=(a=r.current).onConnectionDelayed)==null?void 0:l.call(a,s)}});return e.addConnectionHandler(n,o),()=>{e.removeConnectionHandler(n)}},[e,n])};function cc(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=Me(),{sdkUser:s,statsTrackers:a}=gt(),l=dn(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[h,_]=u.useState(!1);function y(v){v.isAIAgent&&!v.conversation&&(_(!0),o.initConversationIfNeeded(v).finally(()=>_(!1)))}async function C(){var v,b,E;if(!s){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),f(void 0),_(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const A=await t.groupChannel.getChannel(e);y(A),d(A),a.initialRender.onGetChannelComplete((v=A.conversation)==null?void 0:v.id),A.url===((b=o.session)==null?void 0:b.activeChannel.url)&&o.session._updateActiveChannel({url:A.url,status:Re(A)?"closed":"open",conversationStatus:(E=A.conversation)==null?void 0:E.status}),n.debug("useChannel.getChannel: fetched channel",A)}catch(A){a.initialRender.onGetChannelError(A),A instanceof ge.SendbirdError&&f(A),n.error("useChannel.getChannel: error",A)}}}return u.useEffect(()=>{C()},[t,s,e,r]),Rt(t,{async onReconnectSucceeded(){if(!c)return;const v=await c.refresh();y(v),d(v)}}),ht(t,{onChannelChanged:v=>{v.isGroupChannel()&&v.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",v.url),d(v),l())}}),{channel:c,channelFetchError:m,getChannel:C,isInitializingConversation:h}}const uc=new Set(["suggested_replies","steward","system"]),dc=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||!uc.has(r)))return r},mc=e=>{var a;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,o=!!r&&!r.submitted_at&&!r.canceled_at,s=e.isAIAgent&&!!((a=e.conversation)!=null&&a.handedOverAt);return o&&!s},fc=()=>{const{chatSDK:e,networkStateAdapter:t}=Me(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Rt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),u.useEffect(()=>{if(t)return t.subscribe(o=>{if(!o){r("reconnecting");return}r(s=>s==="reconnecting"&&e.connectionState===ge.ConnectionState.OPEN?"connected":s)})},[t,e]),n},hc=3e4,gc=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,s]=u.useState(!1),a=u.useRef(null),l=t&&ft(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),s(!1)},d=h=>{a.current&&clearTimeout(a.current),s(!0),a.current=setTimeout(()=>{s(!1),a.current=null},h)},m=Date.now()-l,f=hc-m;return n||f<=0?c():d(f),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},ws=e=>{const{chatSDK:t}=Me(),[n,r]=u.useState([]);return ht(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},pc=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=u.useState(!1),a=ws(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=ft(t,n)&&(Ve.isStreaming(t)||r);s(c||l)},[a,t,n,r]),o},_c=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=gt(),a=fc(),l=pc({channel:e,lastMessage:Br(t,[Be.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=gc({shouldApply:!!(e!=null&&e.isAIAgent)&&!et(e),isBlockedWhileAIResponding:l,lastMessage:Br(t,[Be.SendingStatus.PENDING,Be.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""}),d=f=>f===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:f==="ai_responding"?{disabled:!0,disabledBy:f,focusPolicy:"preserve"}:{disabled:!0,disabledBy:f,focusPolicy:"release"};if(!e||a==="disconnected")return d("unavailable");if(a==="reconnecting")return d("reconnecting");if(Re(e))return d("conversation_closed");if(Wa(e))return d("handoff_pending");if(mc(e))return d("form_active");const m=dc(e);return d(m||(l||c||r?"ai_responding":""))},Ec=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(o=>{t(s=>{if(s.has(o))return s;const a=new Set(s);return a.add(o),a})},[]),r=u.useCallback(o=>{t(s=>{if(!s.has(o))return s;const a=new Set(s);return a.delete(o),a})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:bc}=Ee("AIAgentConversation");function Cc({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=he,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:f}){var V;const h=()=>d&&(b==null?void 0:b.markAsRead()),{_aiAgentSDK:_,chatSDK:y,logger:C,dispatcher:v}=Me(),{channel:b,channelFetchError:E,getChannel:A,isInitializingConversation:x}=cc(t),{statsTrackers:k}=gt();u.useEffect(()=>{if(t)return k.initialRender.setChannelUrl(t),()=>{k.initialRender.cleanup()}},[t,k]);const R=zl(y,b,{replyType:Be.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:H=>r==null?void 0:r(H),onMessagesUpdated:H=>o==null?void 0:o(H),onCacheResult:H=>k.initialRender.onCacheResult(H),onApiResult:H=>k.initialRender.onApiResult(H),logger:C,markAsRead:h,sortComparator:f}),I=Ec(),w=_c({channel:b,messages:R.messages,isStreamAnimating:I.isAnimating,isInitializingConversation:x});u.useEffect(()=>{h()},[d,b]);const O=Re(b);u.useEffect(()=>{s==null||s(O)},[O,s]),u.useEffect(()=>{const H=async Y=>{const G=typeof(Y==null?void 0:Y.channelUrl)=="string";b&&G&&Y.channelUrl!==b.url||(C.debug("conversation.dispatcher: try to close conversation",b),b!=null&&b.conversation&&b.conversation.status===be.ConversationStatus.OPEN&&(await b.closeConversation(),a==null||a()))};return v.subscribe(Fe.ConversationClose,H),()=>{v.unsubscribe(Fe.ConversationClose,H)}},[v,b,C,(V=b==null?void 0:b.conversation)==null?void 0:V.status,a]);const $={conversation:(b==null?void 0:b.conversation)??void 0,actions:{setUserMemoryState:_.setUserMemoryState},channelSource:{channel:b,error:E,refetch:()=>A(),closeConversation:async()=>{Re(b)||await(b==null?void 0:b.closeConversation())}},messageSource:{messages:R.messages,newMessages:R.newMessages,initialized:R.initialized,subscribeMessageEvents:R.subscribeMessageEvents,loadPrevious:()=>R.loadPrevious(),loadNext:()=>R.loadNext(),deleteMessage:H=>R.deleteMessage(H),resendMessage:H=>R.resendMessage(H),resetNewMessages:()=>R.resetNewMessages(),sendUserMessage:async H=>{var G;if(((G=b==null?void 0:b.conversation)==null?void 0:G.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(H=await l(H));const Y=await R.sendUserMessage(H,c);return c==null||c(Y),Y},sendFileMessage:async H=>{var G;if(((G=b==null?void 0:b.conversation)==null?void 0:G.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(H=await l(H));const Y=await R.sendFileMessage(H,c);return c==null||c(Y),Y},sendMultipleFilesMessage:async H=>{var G;if(((G=b==null?void 0:b.conversation)==null?void 0:G.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(H=await l(H));const Y=await R.sendMultipleFilesMessage(H,c);return c==null||c(Y),Y}},state:{streamAnimation:I,input:w}};return i.createElement(bc,{value:$},e)}function vc(e,t){var _,y,C,v,b,E,A,x,k,R;const[n,r]=u.useState(!1),[o,s]=u.useState(null),[a,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),f=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),s(null),l([]);try{c==null||c.dispose();const I=new ms(e,t);I.setConversationListCollectionHandler({onChannelsAdded:()=>{l(I.channels)},onChannelsUpdated:()=>{l(I.channels)},onChannelsDeleted:()=>{l(I.channels)}}),await I.loadMore(),l(I.channels),d(I),s(null)}catch(I){d(null),s(I)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(C=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:C.join(),(b=(v=t.filter)==null?void 0:v.aiAgentIds)==null?void 0:b.join(),(E=t.filter)==null?void 0:E.deskChannelFilter,(x=(A=t.filter)==null?void 0:A.pinnedChannelUrls)==null?void 0:x.join(),(k=t.filter)==null?void 0:k.copilotConversationOnly,(R=t.filter)==null?void 0:R.copilotSupportChannelUrl,t.limit]),h=u.useCallback(async()=>{if(c)try{await c.loadMore(),l(c.channels)}catch(I){s(I)}},[c]);return Rt(e,{onConnected:()=>f()}),u.useEffect(()=>{f()},[f]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:o,channels:a,loadMore:h}}const Ms=e=>{var o;const{aiAgentId:t,queryParams:n}=Me(),r=(o=n==null?void 0:n.conversationListParams)==null?void 0:o.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[be.ConversationStatus.CLOSED,be.ConversationStatus.OPEN],...r,...e}},{Provider:yc}=Ee("AIAgentConversationList");function Sc({conversationListLimit:e,conversationListFilter:t,children:n}){var d;const{chatSDK:r,queryParams:o}=Me(),s=e??((d=o==null?void 0:o.conversationListParams)==null?void 0:d.limit),a=Ms(t),l=vc(r,{limit:s,filter:a}),c={listSource:{initialized:l.initialized,error:l.error??void 0,channels:l.channels,loadMore:()=>l.loadMore()}};return i.createElement(yc,{value:c},n)}function Ac(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:xc,useContext:Tc}=Ee("MessageTemplateFetching");function Ic({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[o,s]=u.useState({}),a=u.useCallback((d,m)=>{s(f=>({...f,[d]:{fetching:!1,error:!1,...f[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:f,suspense:h=!1})=>{const _=m(f);if(_)return _;const y=r.current[f];if(y)return y;h||a(f,{fetching:!0});const C=d(f).catch(v=>{throw h||a(f,{error:!0}),v}).finally(()=>{h||a(f,{fetching:!1}),delete r.current[f]});return r.current[f]=C,C},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const f=Ac(m());return n.current[d]=f,f},getIsFetching:d=>{var m;return((m=o[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=o[d])==null?void 0:m.error)??!1}};return i.createElement(xc,{value:c},e)}const wc="remove_powered_by",dr=(e,t)=>{var o,s;const{chatSDK:n}=Me(),{aiAgentInfo:r}=gt();if(e==="handoff-button"){const a=!!((o=t==null?void 0:t.conversation)!=null&&o.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&a&&or(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const a=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return u.useMemo(()=>!(Array.isArray(a)&&a.includes(wc)),[a])}throw new Error("Unsupported feature")},Mc={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"},kc={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:o}=e;if(o){if(o.min_length!==void 0&&r.length<o.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(o.min_length):n.minLength};if(o.max_length!==void 0&&r.length>o.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(o.max_length):n.maxLength};if(o.regex&&!new RegExp(o.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Rc={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:o}=e;if(o){if(o.min!==void 0&&r<o.min)return{isValid:!1,error:typeof n.min=="function"?n.min(o.min):n.min};if(o.max!==void 0&&r>o.max)return{isValid:!1,error:typeof n.max=="function"?n.max(o.max):n.max}}return{isValid:!0}}},Lc={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}}},Oc={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(a=>!e.options.includes(a)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:s}=e;if(s){if(s.min_select!==void 0&&r.length<s.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(s.min_select):n.minSelect};if(s.max_select!==void 0&&r.length>s.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(s.max_select):n.maxSelect}}return{isValid:!0}}},Nc={text:kc,number:Rc,"single-select":Lc,"multi-select":Oc},Dc={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function ks(e){return Nc[e.type]||Dc}function oo(e){return ks(e).getValueOrDefault(e)}function $c(e,t,n={}){const r={...Mc,...n};return ks(e).validate(e,t,r)}const Pc=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=u.useState({}),[l,c]=u.useState(()=>{const C={};return e.fields.forEach(v=>{C[v.key]=oo(v)}),C}),d=u.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);u.useEffect(()=>{if(d==="submitted"||d==="canceled"){const C={};let v=!1;e.fields.forEach(b=>{const E=oo(b);JSON.stringify(l[b.key])!==JSON.stringify(E)&&(v=!0),C[b.key]=E}),v&&c(C)}},[d]);const m=(C,v)=>{c(b=>({...b,[C]:v})),a(b=>({...b,[C]:void 0}))},f=e.fields.map(C=>{var E,A,x;const v=l[C.key]??null,b={key:C.key,label:C.label,error:s[C.key],required:C.required};return C.type==="text"?{...b,type:"text",layout:C.layout,value:v,...C.placeholder&&{placeholder:C.placeholder},...((E=C.rules)==null?void 0:E.max_length)&&{maxLength:C.rules.max_length}}:C.type==="number"?{...b,type:"number",layout:C.layout,value:v,...C.placeholder&&{placeholder:C.placeholder},...((A=C.rules)==null?void 0:A.max)&&{max:C.rules.max}}:C.type==="single-select"?{...b,type:"single-select",layout:C.layout,value:v,options:C.options}:C.type==="multi-select"?{...b,type:"multi-select",layout:C.layout,value:v,options:C.options,...((x=C.rules)==null?void 0:x.max_select)&&{maxSelect:C.rules.max_select}}:{...b,type:"unknown",layout:"default",value:null}});return{state:d,fields:f,getField:C=>f.find(v=>v.key===C),updateFieldValue:m,submit:async()=>{const C={};let v=!1;for(const b of e.fields){const E=l[b.key]??null,A=$c(b,E,n);A.isValid||(C[b.key]=A.error,v=!0)}if(a(C),!v&&r){const b={};e.fields.forEach(E=>{b[E.key]=l[E.key]??null}),await r(b)}},cancel:async()=>{await(o==null?void 0:o())}}},Fc=e=>{const{chatSDK:t,handlers:n,logger:r}=Me(),{aiAgentInfo:o}=gt(),s=u.useRef(new Set),a=u.useRef(new Set),l=(m,f)=>{if(!(n!=null&&n.onCustomEvent)||!(o!=null&&o.userId)||!ft(m,o.userId))return;const h=m.messageId;if(Ve.isStreaming(m)){a.current.add(h);return}f==="updated"&&!a.current.has(h)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),a.current.delete(h))},c=u.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!s.current.has(m.messageId)){const f=Bn(m.data);Array.isArray(f.history)&&f.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",f),n.onCustomEvent({type:"user-action-requested",data:f}),s.current.add(m.messageId))}},[n,r]),d=(m,f,h)=>{m.url===e&&(l(f,h),c(f))};return ht(t,{onMessageReceived:(m,f)=>d(m,f,"received"),onMessageUpdated:(m,f)=>d(m,f,"updated")}),{checkForUserActionRequired:c}},Bc=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},Rs=e=>{const{aiAgentInfo:t}=gt(),n=ws(e);if(Re(e))return null;const r=n[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?Bc(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},Uc=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const o=u.useRef(null),s=u.useRef(t),a=u.useRef(t),l=u.useRef(!1);s.current=t,u.useEffect(()=>{if(o.current&&(clearTimeout(o.current),o.current=null),!n||!e){(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current;return}l.current=!0,a.current=s.current,a.current(!0),o.current=setTimeout(()=>{o.current=null,a.current(!1),l.current=!1,a.current=s.current},r)},[n,r,e]),u.useEffect(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null),(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current},[])},Hc=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:l=>{const c=Date.now(),d=t.get(l);return d!==void 0&&c-d<n?!1:(t.set(l,c),!0)},setInterval:l=>{n=l},reset:()=>{t.clear()}}},Gc=(e,t,n=1e4,r=!0)=>{const o=u.useRef(null),s=u.useRef(null),a=u.useRef(!1);o.current||(o.current=Hc(n));const l=(e==null?void 0:e.nickname.trim())||null,c=(e==null?void 0:e.userId)??l;u.useEffect(()=>{var d;(d=o.current)==null||d.setInterval(n)},[n]),u.useEffect(()=>{var f;if(!r){a.current=!1,s.current=c;return}if(!c||!l){a.current=!1,s.current=null;return}const d=!a.current,m=s.current!==c;a.current=!0,s.current=c,!(!d&&!m)&&(f=o.current)!=null&&f.shouldAnnounce(c)&&t(l)},[c,l,r,t])};var Ye=(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))(Ye||{});const zc=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r})=>{const o=!!n&&n.visibility&&!!Ye[n.type],s=!r&&typeof e!="number"&&Es(t),a=dn();return u.useEffect(()=>{if(!o||typeof e=="number"||t==null||s)return;const l=t-Date.now();if(l<=0&&r)return;const c=setTimeout(a,Math.max(0,l));return()=>clearTimeout(c)},[a,e,t,s,o,r]),{isRenderableCSAT:o,isExpiredNow:s}},Vc=({csat:e,csatExpireAt:t,csatPayload:n,announceStatus:r,onSubmittedAnnounced:o,isSubmitInFlight:s=!1})=>{const{isRenderableCSAT:a,isExpiredNow:l}=zc({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:s}),c=(n==null?void 0:n.csat_submitted_label)??"",d=u.useRef(a&&typeof e=="number"),m=u.useRef(a&&l);return u.useEffect(()=>{a&&c&&(typeof e!="number"||d.current||(d.current=!0,r({event:"csatSubmitted",submittedLabel:c}),o==null||o()))},[r,e,a,o,c]),u.useEffect(()=>{a&&l&&(m.current||(m.current=!0,r({event:"csatExpired"})))},[r,l,a]),{isExpiredNow:l,isRenderableCSAT:a}},mr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=_s(e,t.userId),o={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?et(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},so=e=>u.useReducer((t,n)=>({...t,...n}),e),Yc=new Set(["free_text","single_choice"]),Wc=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=so({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=so({followUpItem:!1}),d=u.useMemo(()=>{var v;const _=s.csat,y=typeof _=="number",C=(v=e.follow_up)==null?void 0:v.find(b=>y?b.scores.includes(_):b.always_visible??!1);if(Yc.has(C==null?void 0:C.response_type))return C},[s.csat,e.follow_up]),m=(()=>{var _;if(typeof n=="number")return"submitted";if((t===Ye.AI_AGENT_CSAT_5||t===Ye.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===Ye.AI_AGENT_CSAT_5_WITH_CRE){const y=typeof s.csat=="number",C=!((_=e.cre)!=null&&_.required)||typeof s.isResolved=="boolean";if(y&&C)return"submittable"}return"unsubmittable"})(),f=u.useCallback(()=>typeof s.csat>"u"?!1:d!=null&&d.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,d,c]);return u.useEffect(()=>{r||(a({csatReason:""}),c({followUpItem:!1}))},[r,d,a,c]),{params:s,setParams:a,error:l,setError:c,followUpItem:d,state:m,validateParams:f,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Tn=5,qc=250,Kc=50,io=e=>Math.max(0,e-Kc),jc=e=>e<1e3?{speed:Tn*.5,chunkSize:2}:e<2e3?{speed:Tn*.8,chunkSize:2}:{speed:Tn*.6,chunkSize:3},Ht=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Xc=(e,t)=>{if(!t)return e;let n="",r=0,o=0;for(;r<e.length;){if(e[r]==="`"&&!Ht(e,r)){let c=1;for(;e[r+c]==="`";)c++;o===0?o=c:c===o&&(o=0),n+=e.slice(r,r+c),r+=c;continue}if(o>0||e[r]!=="!"||e[r+1]!=="["||Ht(e,r)){n+=e[r],r++;continue}const s=r;r+=2;let a=1;for(;r<e.length&&a>0;){if(Ht(e,r)){r++;continue}e[r]==="["?a++:e[r]==="]"&&a--,r++}if(a>0||r>=e.length)return n;if(e[r]!=="("){n+=e.slice(s,r);continue}r++;let l=1;for(;r<e.length&&l>0;){if(Ht(e,r)){r++;continue}e[r]==="("?l++:e[r]===")"&&l--,r++}if(l>0)return n;n+=e.slice(s,r)}return n},Zc=e=>{const{text:t,enabled:n=!1,markdownImageRenderMode:r="default",onAnimationStart:o,onAnimationProgress:s,onAnimationComplete:a}=e,[l,c]=u.useState(()=>io(t.length)),d=u.useRef(null),m=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,f=u.useRef({onStart:o,onProgress:s,onComplete:a}).current,h=u.useRef({startCalled:!1,completeCalled:!1}).current,_=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,y=n,C=l<t.length,v=_.initialEnabled&&(y||C);return u.useLayoutEffect(()=>{f.onStart=o,f.onProgress=s,f.onComplete=a,_.textLength=t.length,_.enabled=n}),u.useLayoutEffect(()=>{var E;_.initialEnabled&&(h.startCalled||(h.startCalled=!0,(E=f.onStart)==null||E.call(f)),c(A=>t.length<A?t.length:A))},[t]),u.useEffect(()=>{if(!_.initialEnabled)return;let E=io(t.length);m.lastUpdate=0,m.startTime=0,m.lastProgressCall=0;const A=x=>{var H;m.lastUpdate===0&&(m.lastUpdate=x,m.startTime=x,m.lastProgressCall=x);const k=_.textLength,R=x-m.lastUpdate,I=x-m.startTime,{speed:w,chunkSize:O}=jc(I),$=w*O;R>=$&&E<k&&(E=Math.min(E+O,k),c(E),m.lastUpdate=x),x-m.lastProgressCall>=qc&&(m.lastProgressCall=x,(H=f.onProgress)==null||H.call(f)),(E<k||_.enabled)&&(d.current=requestAnimationFrame(A))};return d.current=requestAnimationFrame(A),()=>{var x;d.current&&cancelAnimationFrame(d.current),h.startCalled&&!h.completeCalled&&(h.completeCalled=!0,(x=f.onComplete)==null||x.call(f))}},[]),u.useEffect(()=>{var k;const E=_.initialEnabled&&h.startCalled,A=!n,x=l>=t.length&&t.length>0;E&&A&&x&&!h.completeCalled&&(h.completeCalled=!0,(k=f.onComplete)==null||k.call(f))},[n,l,t.length]),{streamText:u.useMemo(()=>{const E=_.initialEnabled?t.slice(0,l):t;return r!=="complete-only"?E:Xc(E,v)},[t,l,r,v]),isAnimating:v}},ao={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Jc=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Qc=(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}},eu=()=>{const{chatSDK:e}=Me(),[t,n]=u.useState(ao),r=()=>n(ao);return Rt(e,{onConnectionDelayed:o=>{o>0?n(Jc(o)):r()},onReconnectSucceeded:r,onConnected:r}),u.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const o=setTimeout(()=>{n(s=>Qc(s))},1e3);return()=>clearTimeout(o)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},tu=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},nu=(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)}},ru=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var c,d,m;const[o,s]=u.useState(!1),a=u.useRef(0),l=()=>{if(!t)return;const f=++a.current;e.aiAgent.getUnreadMessageCount(r).then(h=>{f===a.current&&s(h.total>0)}).catch(()=>{})};return u.useEffect(()=>{if(!t){s(!1),a.current++;return}e.connectionState===ge.ConnectionState.OPEN&&l()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(c=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:c.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]),u.useEffect(()=>{n&&(s(!1),a.current++)},[n]),Rt(e,{onConnected:l,onReconnectSucceeded:l}),o},fr=e=>e.replace(/\s+/g," ").trim(),ou="Code block",Ls=e=>`A11Y_INLINE_CODE_${e}`,Os=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}},Ns=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}},su=e=>{const{blockquotePrefix:t,content:n}=Os(e),{content:r}=Ns(n),o=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!o)return;const s=o[1],a=o[2],l=s[0];if(!(l!=="`"&&l!=="~"||!s.split("").every(c=>c===l))&&!(l==="`"&&a.includes("`")))return{char:l,blockquotePrefix:t,length:s.length}},iu=(e,t)=>{const{blockquotePrefix:n,content:r}=Os(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=Ns(r);if(s)return!1;const a=o.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!a)return!1;const l=a[1];return l[0]===t.char&&l.length>=t.length&&l.split("").every(c=>c===t.char)},au=(e,t,n)=>{let r=n;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o===t)return r;r+=1}return-1},lu=(e,t)=>{let n=1,r=t;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o==="["){n+=1,r+=1;continue}if(o==="]"&&(n-=1,n===0))return r;r+=1}return-1},cu=(e,t)=>{let n=t,r=1,o,s=!1,a=!1;for(;n<e.length&&r>0;){const l=e[n];if(l==="\\"&&n+1<e.length){n+=2;continue}if(o){l===o&&(o=void 0),n+=1;continue}if(r===1&&s&&/\s/.test(l)){a=!0,n+=1;continue}if(r===1&&a&&(l==='"'||l==="'")){o=l,n+=1;continue}if(l==="("){r+=1,s=!0,n+=1;continue}if(l===")"){r-=1,n+=1;continue}/\s/.test(l)||(s=!0),n+=1}return r===0?n:-1},uu=e=>{let t=0,n="";for(;t<e.length;){const r=au(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=lu(e,r+1);if(o===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&tn(e,r-1)){n+=e.slice(t,o+1),t=o+1;continue}if(e[o+1]!=="("){n+=e.slice(t,o+1),t=o+1;continue}const s=r>0&&e[r-1]==="!"&&!tn(e,r-1)?r-1:r;n+=e.slice(t,s);const a=e.slice(r+1,o),l=cu(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},Ds=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},du=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return Ds(n,r,a)?t:`${n}${r}`}),mu=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),fu=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),hu=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,o,s,a)=>{const l=a[s+n.length]??"";return Ds(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},gu=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),pu=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},lo=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))},co=e=>{const t=[];let n="",r=!1;for(const s of e.trim()){if(r){n+=s==="|"?"|":`\\${s}`,r=!1;continue}if(s==="\\"){r=!0;continue}if(s==="|"){const a=n.trim();a&&t.push(a),n="";continue}n+=s}r&&(n+="\\");const o=n.trim();return o&&t.push(o),t},_u=e=>{const t=e.split(`
2
+ `),n=[];let r=0;for(;r<t.length;){const o=t[r],s=t[r+1],a=co(o);if(a.length>0&&s&&lo(s)){for(n.push(a.join(" ")),r+=2;r<t.length;){const l=t[r],c=co(l);if(c.length===0||lo(l))break;n.push(c.join(" ")),r+=1}continue}n.push(o),r+=1}return n.join(`
3
+ `)},Eu=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),bu=(e,t)=>{const n=e.split(`
4
+ `),r=[];let o=0;for(;o<n.length;){const s=n[o],a=su(s);if(!a){r.push(s),o+=1;continue}let l=-1;for(let c=o+1;c<n.length;c++)if(iu(n[c],a)){l=c;break}if(l===-1){r.push(s),o+=1;continue}r.push(` ${t} `),o=l+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},Cu=e=>{const t=[];let n=0,r="";for(;n<e.length;){const o=e[n];if(o!=="`"||tn(e,n)){r+=o,n+=1;continue}let s=n;for(;s<e.length&&e[s]==="`";)s+=1;const a=e.slice(n,s);let l=s,c=!1;for(;l<e.length&&e[l]!==`
6
+ `;){if(e[l]==="`"&&!tn(e,l)&&e.startsWith(a,l)){const d=e.slice(s,l),m=t.push(d)-1;r+=Ls(m),n=l+a.length,c=!0;break}l+=1}c||(r+=a,n=s)}return{text:r,inlineCodes:t}},$s=(e,{codeBlockPlaceholder:t=ou}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
7
+ `);if(!n)return;const r=[];let o=n;o=bu(o,t),o=pu(o);const s=Cu(o);o=s.text,r.push(...s.inlineCodes),o=uu(o),o=du(o),o=mu(o),o=fu(o),o=hu(o),o=_u(o),o=Eu(o),o=gu(o);for(let l=0;l<r.length;l++)o=o.replaceAll(Ls(l),r[l]);return fr(o)||void 0},vu=(e,t)=>{var o;const n=((o=e.name)==null?void 0:o.trim())||"",r=e.mimeType??"";return He(r)?t.image:cn(r)?t.video:cs({name:n,mimeType:r})?t.pdf(n):t.document(n)},nn=e=>(e==null?void 0:e.trim())||"",yu=e=>(e?fr(e):void 0)||void 0,Ps=e=>({text:nn(e),format:"plain"}),Su=e=>({text:nn(e),format:"markdown"}),In=({markdownText:e,plainText:t,comparisonText:n})=>{const r=nn(e);return r&&r!==nn(n)?Su(r):Ps(t)},yt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?$s(t,{codeBlockPlaceholder:o}):yu(t);if(r&&s.push(r),e&&s.push(e),a&&s.push(a),s.length!==0)return s.join(", ")},Fs=(e,t)=>$s(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Au=(...e)=>fr(e.filter(Boolean).join(", "))||void 0,uo=(e,t,n,r)=>{if(!t||t===n)return e;const o=Fs(t,r);return o?Au(e,o):e},xu=(e,t)=>{var r,o,s,a;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const l=((o=e.name)==null?void 0:o.trim())||"",c=vu({name:l,mimeType:e.type},t);return uo(c,n,l,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const l=e.fileInfoList??[],c=l.length;if(c===0)return;const d=((a=(s=l[0])==null?void 0:s.fileName)==null?void 0:a.trim())||"",f=l.every(h=>{var _;return(_=h.mimeType)==null?void 0:_.startsWith("image")})?t.receivedFilesImageCount(c):t.multipleFilesCount(c);return uo(f,n,d,t.codeBlockPlaceholder)}return Fs(n,t.codeBlockPlaceholder)},Tu=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:o=10}=t,s=Math.max(1,o);let a=null;const l=[];let c=null,d=null,m=null,f=!1,h=0;const _=(w,O,$)=>({text:w,ignoreSuppression:O,queueOrder:h++,dedupeKey:$}),y=()=>{const w=l[0]??null,O=a;return w&&O?O.queueOrder<w.queueOrder?(a=null,O):l.shift()??null:w?l.shift()??null:O!==null?(a=null,O):null},C=()=>{for(;;){const w=y();if(!w)return null;if(!(!w.ignoreSuppression&&(r!=null&&r())))return w}},v=w=>{c=w.text,d=w.dedupeKey??null,f=!0,e(w.text),m=setTimeout(()=>{m=null,f=!1;const O=C();O&&v(O)},n)},b=w=>{c=w.text,d=w.dedupeKey??null,e(w.text)},E=(w,O,$,V)=>O!=null&&V!=null?O===V:O==null&&V==null?w!=null&&w===$:!1,A=(w,O,$)=>{if(!w||!O&&(r!=null&&r()))return;const V=$==null?void 0:$.dedupeKey;if(!(f&&E(w,V,c,d)))if(f){if((($==null?void 0:$.mode)??"latestOnly")==="ordered"){const Y=l[l.length-1];if(Y&&E(w,V,Y.text,Y.dedupeKey))return;l.push(_(w,O,V)),l.length>s&&l.shift();return}a=_(w,O,V)}else a=null,v(_(w,O,V))};return{announce:(w,O)=>{A(w,!1,O)},announceIgnoringSuppression:(w,O)=>{A(w,!0,O)},flush:()=>{const w=[];let O=y();for(;O!==null;)w.push(O),O=y();if(m!==null&&(clearTimeout(m),m=null),f=!1,w.length!==0)for(const $ of w)b($)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),a=null,l.length=0,c=null,d=null,f=!1}}},Iu=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},wu=(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(". "),Mu=(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}},ku=(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}},Ru=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Lu=(e,t)=>Ie.isAdmin(e)?Ie.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Ou=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Nu=e=>e===ge.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===ge.CollectionEventSource.EVENT_MESSAGE_UPDATED,Du=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",$u=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Pu=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Fu=({intent:e,strings:t})=>({label:$u(e,t),hint:Pu(e,t)}),Bu="1.29.0",Ne="sb-agent",Ce={ENTRY:`${Ne}-entry`,MODAL_ROOT:`${Ne}-modal-root`,WINDOW:`${Ne}-window`,LAUNCHER:`${Ne}-launcher`,WINDOW_TITLE:`${Ne}-window-title`},Bs="data-sb-initial-focus",Us="true",Uu=`[${Bs}="${Us}"]`,Hs={[Bs]:Us},hr="data-sb-focus-trap-sentinel",Hu="true",Gs="data-sb-initial-focus-header",zs="true",Gu=`[${Gs}="${zs}"]`,Vs={[Gs]:zs},Gt=2147483647,it={MODAL:Gt-1,TOOLTIP:Gt-2,WINDOW:Gt-3,LAUNCHER:Gt-4},Ys=36,zu=100,Vu=Bu,gr="noopener noreferrer nofollow";function Yu(){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 zt={};function Wu(){return{get:e=>{try{return localStorage.getItem(e)}catch{return zt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{zt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete zt[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(zt).filter(t=>t.startsWith(e))}}}}const qu={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:"User 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}`}},Vn={language:"en",strings:qu,dateLocale:la.enUS},Ws=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}),qs=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Lt},Lt="en",Ks=new Set([Lt,"ko","es","pt","fr","hi","it","de","tr","ja"]),Ku='@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:ju,useContext:pr}=Ee("AgentUIElementResolver"),Xu=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const o=u.useMemo(()=>{const s=n??document.body,a=e??s,l=t??s,c=d=>d===Ce.MODAL_ROOT?l:a.querySelector(`#${d}`);return{resolveElement:c,resolvePortalContainer:d=>c(d)??l}},[e,t,n]);return i.createElement(ju,{value:o},r)};function st(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const mo=()=>{const e=[];let t=0;return{register:n=>{const r=++t;return e.push({id:r,handler:n}),()=>{const o=e.findIndex(s=>s.id===r);o>=0&&e.splice(o,1)}},dismissTopmost:()=>{const n=e[e.length-1];return n?(n.handler(),!0):!1}}},{Provider:Zu,useContext:js}=Ee("EscapeDismissStack"),fo=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Ju=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=u.useRef(null),o=u.useRef(null);r.current||(r.current=mo()),o.current||(o.current=mo());const s=r.current,a=o.current;u.useLayoutEffect(()=>{const c=t??st(e),d=m=>{if(m.key==="Escape"){if(s.dismissTopmost()){fo(m);return}a.dismissTopmost()&&fo(m)}};return c.addEventListener("keydown",d),()=>c.removeEventListener("keydown",d)},[t,e,a,s]);const l=u.useMemo(()=>({register:s.register,dismissTopmost:s.dismissTopmost,registerShellDismissHandler:a.register}),[a,s]);return i.createElement(Zu,{value:l},n)},Xs=(e,t,n)=>{const r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t},[t]),u.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Qu=(e,t)=>{const{register:n}=js();Xs(e,t,n)},ed=(e,t)=>{const{registerShellDismissHandler:n}=js();Xs(e,t,n)},td=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((o,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},ho=Ws(Vn.strings),nd={...ho,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:ho.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"},rn={language:Vn.language,dateLocale:Vn.dateLocale,stringSet:nd},rd=Object.freeze(Object.defineProperty({__proto__:null,default:rn},Symbol.toStringTag,{value:"Module"})),Yn=new Map([[Lt,rn]]);async function od(e){const t=Yn.get(e);if(t)return t;try{if(Ks.has(e)){const{default:n}=await td(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/BrQW3MrE.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>rd),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/ByN4PZlT.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/B7ulsf2M.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BVmiN3Wy.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/BeAZATeH.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/Dl7xer_X.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/h1huMI7F.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/BSS6fNF-.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/CjZUGQLK.cjs"))}),`./languages/${e}.ts`,3);return Yn.set(e,n),n}return rn}catch{return rn}}const{Provider:sd,useContext:se}=Ee("Localization"),id=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=u.useState(Yn.get(Lt));return u.useEffect(()=>{const l=t??qs(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),od(l).then(a))},[e,t,n]),i.createElement(sd,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,c,d)=>Xe.format(l,c,{locale:s.dateLocale,...d})}},o)},on="data-sb-agent-theme",go=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${on}='${e}'] & { ${r} }`},J={light:go("light"),dark:go("dark")},ad=D.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
- `}),rd=D.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);}`,g={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 wt extends u.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:s}=this.props;return this.state.hasError?n:i.createElement(u.Suspense,{fallback:r},s)}}const He=e=>{const t=e;return typeof t=="number"?`${t}px`:t},sd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.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"})),od=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},i.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"})),id=e=>i.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},i.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"})),ad=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},i.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"})),ld=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.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"})),cd=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),ud={close:sd,send:ld,menu:ad,expand:id,collapse:od,spinner:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs")))},dd=e=>({size:t=24,color:n=g.color.primary.main,flipInRtl:r=!1})=>i.createElement(hd,{$size:t,$color:n,$rtlFlip:r},i.createElement(wt,{errorFallback:i.createElement(fd,null)},i.createElement(e,null))),jo=Object.fromEntries(Object.entries(ud).map(([e,t])=>[e,dd(t)])),md=D.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,hd=p.default.span.attrs({"aria-hidden":"true"})`
57
- width: ${({$size:e})=>He(e)};
58
- height: ${({$size:e})=>He(e)};
56
+ `}),ld=D.css`[${on}='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);}[${on}='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);}`,g={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 wt extends u.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:o}=this.props;return this.state.hasError?n:i.createElement(u.Suspense,{fallback:r},o)}}const Ge=e=>{const t=e;return typeof t=="number"?`${t}px`:t},cd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.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"})),ud=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},i.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"})),dd=e=>i.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},i.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"})),md=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},i.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"})),fd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.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"})),hd=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),gd={close:cd,send:fd,menu:md,expand:dd,collapse:ud,spinner:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs")))},pd=e=>({size:t=24,color:n=g.color.primary.main,flipInRtl:r=!1})=>i.createElement(Ed,{$size:t,$color:n,$rtlFlip:r},i.createElement(wt,{errorFallback:i.createElement(bd,null)},i.createElement(e,null))),Zs=Object.fromEntries(Object.entries(gd).map(([e,t])=>[e,pd(t)])),_d=D.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Ed=p.default.span.attrs({"aria-hidden":"true"})`
57
+ width: ${({$size:e})=>Ge(e)};
58
+ height: ${({$size:e})=>Ge(e)};
59
59
  display: inline-block;
60
60
 
61
61
  svg {
@@ -74,21 +74,21 @@
74
74
  stroke-linejoin: round;
75
75
  }
76
76
 
77
- ${({$rtlFlip:e})=>e&&md};
78
- `,fd=()=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},i.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),i.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),i.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:gd,useContext:pd}=_e("MessengerIcon",{icons:jo}),_d=({icons:e,children:t})=>{const n=u.useMemo(()=>({icons:gl(jo,e)}),[e]);return i.createElement(gd,{value:n},t)},{Provider:Ed,useContext:Xo}=_e("MessengerTheme");function bd(e){const{theme:t,appearance:n,logger:r}=e;return i.createElement(ec,{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},i.createElement(Cd,{...e}))}function Cd({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=ur();return u.useLayoutEffect(()=>{e.setAttribute(rn,n.selectedTheme)},[e,n.selectedTheme]),i.createElement(D.ThemeProvider,{theme:n},i.createElement(Ed,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const vd=(e,t)=>{u.useEffect(()=>{const n=st(t)instanceof ShadowRoot,r=st(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])},yd=(e,t=document.body)=>{u.useEffect(()=>{if(!e)return;const n=st(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let a=s.querySelector(`style#${o}`);a?a.textContent!==e&&(a.textContent=e):(a=s.ownerDocument.createElement("style"),a.id=o,a.textContent=e,s.appendChild(a))},[e,t])},Sd=80,Ad=()=>{const{stringSet:e}=oe(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=u.useRef(t);return n.current=t,n},Zo=_e("AriaLiveRegion",{announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,flush:he,setSuppressionState:he}),xd=Zo.Provider,_r=Zo.useContext,Td={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Id=({children:e})=>{const t=u.useRef(null),n=u.useRef(new Set),r=u.useRef(he),s=Ad(),[o]=u.useState(()=>vu(E=>{r.current(E)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=E=>{const v=t.current;v&&(v.textContent="",requestAnimationFrame(()=>{v.textContent=E}))},u.useEffect(()=>()=>{o.destroy()},[o]);const a=o.announce,l=o.flush,c=u.useCallback(E=>{const v=Su(E,s.current);a(v)},[a]),d=u.useCallback((E,v)=>{const y=Au(E,s.current),C=(v==null?void 0:v.mode)??yu(E.event);a(y,{mode:C,dedupeKey:v==null?void 0:v.dedupeKey})},[a]),m=u.useCallback((E,v)=>{const y=xu(E,s.current);o.announceIgnoringSuppression(y),v&&setTimeout(()=>{v.focus()},Sd)},[o]),h=u.useCallback((E,v)=>{if(v){n.current.add(E);return}n.current.delete(E)},[]),f=u.useMemo(()=>({announce:a,announceScreenEntry:c,announceStatus:d,announceError:m,flush:l,setSuppressionState:h}),[a,m,c,d,l,h]);return i.createElement(xd,{value:f},e,i.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:Td}))},Jo=_e("ConversationAnnouncements",{announcementsEnabled:!0,announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,setIsSuppressed:he,setStatusPauseState:he,flush:he}),wd=Jo.Provider,qe=Jo.useContext,Md=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:a,setSuppressionState:l}=_r(),c=u.useRef([]),d=u.useRef(new Set),m=u.useRef(Symbol("conversation-announcements")),h=u.useCallback(T=>{if(!t||!T){l(m.current,!1);return}l(m.current,!0)},[t,l]),f=u.useCallback(()=>{c.current=[]},[]),E=u.useCallback(()=>{if(c.current.length===0)return;if(!t){f();return}const T=[...c.current];f(),T.forEach(L=>{a(),s(L.params,L.options)})},[s,t,f,a]),v=u.useCallback((T,L)=>{if(L){d.current.add(T);return}d.current.delete(T),d.current.size===0&&E()},[E]),y=u.useCallback(T=>{t&&n(T)},[n,t]),C=u.useCallback(T=>{t&&r(T)},[r,t]),_=u.useCallback((T,L)=>{if(t){if(d.current.size>0){c.current.push({params:T,options:L});return}s(T,L)}},[s,t]),b=u.useCallback((T,L)=>{t&&o(T,L)},[o,t]);u.useLayoutEffect(()=>(t||(f(),l(m.current,!1)),()=>{f(),l(m.current,!1)}),[t,f,l]);const A=u.useMemo(()=>({announcementsEnabled:t,announce:y,announceScreenEntry:C,announceStatus:_,announceError:b,setIsSuppressed:h,setStatusPauseState:v,flush:a}),[t,a,y,b,C,_,h,v]);return i.createElement(wd,{value:A},e)},$=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>i.createElement(Od,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),ps=new WeakMap,kd=(e,t)=>{let n=ps.get(t);n||(n=new Map,ps.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=D.css`font-size:${He(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
79
- ${s.lineHeight?`line-height: ${s.lineHeight};`:"line-height: 100%;"}
80
- `;return n.set(e,o),o},Rd=e=>e?D.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Od=p.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>kd(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Rd(e)}`,dn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),Qo=`${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};async function Er(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Re(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const sn=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(fr)&&Mt(n))return n;return null},ei=e=>{let t=null,n=null;for(const r of e.querySelectorAll(dn))r.hasAttribute(fr)||Mt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},br=e=>sn(e,Du),ti=e=>br(e)??sn(e,dn),Ld=e=>{const t=br(e);if(t)return t;const n=e.querySelector(Pu);return(n?sn(n,Qo):null)??sn(e,dn)},Wn='[role="dialog"][aria-modal="true"]',Nd=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Wn)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(Wn);return r&&r!==e&&n.add(r),n},Dd=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Wn)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Mt(n)),$d=e=>{const t=ti(e)??e;t===e&&ni(e),t.focus()},ni=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Pd=(e,t)=>{const n=ei(e);if(!n){ni(e),e.focus();return}n[t].focus()},_s=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(fr,$u),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Pd(e,t)),n},Fd=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ei(t)||(e.preventDefault(),t.focus())))},Bd=(e,t)=>t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,mn=(e,t)=>{const n=u.useRef(0);u.useEffect(()=>{if(!e||!t.current)return;n.current+=1;const r=n.current,s=t.current,o=s.getRootNode(),a=o.activeElement instanceof HTMLElement?o.activeElement:null,l=Nd(s,a);let c=!1;return Re(()=>{c||!s.isConnected||$d(s)}),()=>{c=!0,a&&Re(()=>{if(n.current!==r)return;const d=o.activeElement;s.isConnected&&d instanceof HTMLElement&&d!==s&&!s.contains(d)&&!Bd(o,d)&&d.matches(Qo)&&Mt(d)||Dd(s,l)||!a.isConnected||!Mt(a)||a.focus()})}},[e,t]),u.useEffect(()=>{if(!e||!t.current)return;const r=t.current,s=_s(r,"last"),o=_s(r,"first"),a=l=>Fd(l,r);return r.insertBefore(s,r.firstChild),r.appendChild(o),r.addEventListener("keydown",a),()=>{r.removeEventListener("keydown",a),s.remove(),o.remove()}},[e,t])},nt=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":a,"aria-labelledby":l,"aria-describedby":c})=>{const d=u.useRef(null),{resolvePortalContainer:m}=pr();return mn(n,d),Ku(n,o?r:he),n?aa.createPortal(i.createElement(Ud,{onClick:o?r:void 0,style:e},i.createElement(Hd,{ref:d,role:"dialog","aria-modal":"true","aria-label":a,"aria-labelledby":l,"aria-describedby":c,onClick:h=>h.stopPropagation()},s)),m(t)):null},Ud=p.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${g.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${ot.MODAL};`,Hd=p.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:${ot.MODAL};`,Gd=({id:e,children:t})=>i.createElement(Vd,{id:e},t),Vd=p.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;`,Es=(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,...Bo}:n},zd=()=>{const e=`${u.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=u.createElement(Gd,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},bs=({name:e,mimeType:t,selected:n},r)=>{var o;let s=r.A11Y_FILE_DOCUMENT(e);return t!=null&&t.startsWith("image")&&(s=r.A11Y_FILE_IMAGE(e)),t!=null&&t.startsWith("video")&&(s=r.A11Y_FILE_VIDEO(e)),n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},Yd=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},St=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Yd(e)}),Wd=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var c;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 a=s.currentTarget.parentElement,l=a==null?void 0:a.querySelectorAll('[role="radio"]');(c=l==null?void 0:l[o])==null||c.focus()},Cs=(e,t,n,r,s,o)=>{let a=-1;return(e||!s&&n===0)&&(a=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:Wd({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:a}},se=()=>{const{stringSet:e}=oe(),t=zd(),n=(a,l)=>{let c=e.A11Y_HINT_OPEN_FILE,d="of";a!=null&&a.startsWith("image")&&(c=e.A11Y_HINT_OPEN_IMAGE,d="oi"),l!==void 0&&(d+=l);const m=t(c,d);return{props:m.props,descriptionNode:m.node}},r=a=>({"aria-label":bs(a,e)});return{launcher:{button:({isOpened:a,opensConversationList:l})=>{const c=Lu({intent:ku({isOpened:a,opensConversationList:l}),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";c.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),c.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(c.hint,d);return{props:{"aria-label":c.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:a=>{let l=e.A11Y_EXPAND_MESSENGER;return a&&(l=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":l},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const a=e.A11Y_HINT_OPEN_MENU,l=t(a,"mb");return{props:{"aria-label":e.A11Y_MENU,...l.props},descriptionNode:l.node}},closeConversationButton:()=>{const a=e.A11Y_HINT_CLOSE_CONVERSATION,l=t(a,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...l.props},descriptionNode:l.node}},handoffButton:()=>{const a=e.A11Y_HINT_CONNECT_TO_AGENT,l=t(a,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...l.props},descriptionNode:l.node}},title:(a,l)=>({props:Es(a,l),descriptionNode:null}),memoryIndicator:a=>{let l=e.A11Y_MEMORY_INDICATOR_OFF,c="mof";a&&(l=e.A11Y_MEMORY_INDICATOR_ON,c="mon");const d=t(l,c);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const a=e.A11Y_HINT_ATTACH_FILE,l=t(a,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...l.props},descriptionNode:l.node}},sendButton:()=>{const a=e.A11Y_HINT_SEND_MESSAGE,l=t(a,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...l.props},descriptionNode:l.node}},textInput:a=>({props:{role:"textbox","aria-label":a},descriptionNode:null})},suggestedReplies:{item:(a,l)=>{const c=e.A11Y_HINT_SEND_REPLY,d=t(c,`sr${l}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${a}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const a=e.A11Y_HINT_SELECT_RATING,l=t(a,"fb");return{props:l.props,descriptionNode:l.node}},button:(a,l)=>{const c=e.A11Y_HINT_SELECT_RATING,d=t(c,`f${a}`);let m=e.FEEDBACK_BAD;return a==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":l},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...l.props},descriptionNode:l.node}},scrollToBottomButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...l.props},descriptionNode:l.node}},startNewConversationButton:({onActivate:a})=>({props:{...St({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(a=e.RETRY)=>({props:{"aria-label":a},descriptionNode:null}),file:{label:(a,l,c)=>a?bs({name:a,mimeType:l,selected:c},e):"",preview:a=>({props:r(a),descriptionNode:null}),buttonLikePreview:({onActivate:a,...l},c)=>{const d=n(l.mimeType,c);return{props:{...St({onActivate:a}),...r(l),...d.props},descriptionNode:d.descriptionNode}},removeButton:a=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(a)},descriptionNode:null})},csat:{scoresContainer:a=>{const l=e.A11Y_HINT_SELECT_RATING,c=t(l,"cs");return{props:{role:"radiogroup","aria-label":a,...c.props},descriptionNode:c.node}},scoreItem:({score:a,label:l,selected:c,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:E})=>{var _;const v=l.trim()||l,y=e.A11Y_HINT_SELECT_RATING,C=t(y,`cs${a}`);return{props:{disabled:d,onClick:()=>E(a),...Cs(c,d,m,h,f,b=>E(b+1)),...C.props,"aria-label":((_=e.A11Y_CSAT_RATING_LABEL)==null?void 0:_.call(e,a,v))??`${a} / ${h} — ${v}`},descriptionNode:C.node}},submitButton:a=>({props:{"aria-label":a},descriptionNode:null})},form:{button:a=>({props:{"aria-label":a},descriptionNode:null}),textInput:(a,l,c)=>({props:{"aria-label":a,"aria-required":l,"aria-disabled":c},descriptionNode:null}),numberInput:(a,l,c)=>({props:{"aria-label":a,"aria-required":l,"aria-disabled":c},descriptionNode:null}),singleSelectGroup:a=>{const l={role:"radiogroup"};return a&&(l["aria-label"]=a),{props:l,descriptionNode:null}},singleSelectOption:(a,l,c,d,m,h,f)=>({props:{...Cs(l,c,d,m,h,f),"aria-label":a},descriptionNode:null}),multiSelectOption:(a,l,c)=>({props:{"aria-label":a,"aria-pressed":l,"aria-disabled":c},descriptionNode:null})}},conversationList:{headerTitle:(a,l)=>({props:Es(a,l),descriptionNode:null}),footer:{button:({onActivate:a})=>({props:{...St({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:a,status:l,time:c,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:null};const h=e.A11Y_HINT_OPEN_CONVERSATION,f=t(h,"cli");return{props:{...St({onActivate:m}),...f.props,"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:f.node}}}}},qd=({title:e,description:t,highlightedText:n})=>{const r=Jc(t,n);return i.createElement(jd,null,i.createElement(Xd,null,i.createElement($,{as:"div",variant:"h1",color:g.themedColor.textHighEmphasis},e),t&&i.createElement(Zd,null,i.createElement($,{as:"div",variant:"body3",color:g.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?i.createElement(Jd,null,r.highlightedText):null,r.afterText))))},Kd=()=>{const{components:e}=hn.useContext(),{stringSet:t}=oe(),{messenger:n}=se(),r=Xc(),s=r.showDescription?Zc(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return i.createElement(nt,{portalContainerId:Ee.WINDOW,visible:r.visible,onClose:he,...n.connectionDelayDialog().props},i.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},hn=Ue({template:Kd,components:{Dialog:qd}}),jd=p.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Xd=p.default.div`display:flex;flex-direction:column;`,Zd=p.default.div`margin-top:16px;`,Jd=p.default.strong`font-weight:700;`,{Provider:Qd,Consumer:ri,useContext:ge}=_e("Messenger");function em({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[a,l]=u.useState(!1),[c,d]=u.useState(!1),m={opened:(t==null?void 0:t.opened)??a,setOpened:(t==null?void 0:t.setOpened)??l,expanded:(t==null?void 0:t.expanded)??c,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=pr(),f=u.useCallback(()=>{var v;m.setOpened(!1),(v=h(Ee.LAUNCHER))==null||v.focus()},[m.setOpened,h]);ju(m.opened,f);const{Template:E}=hn.useContext();return i.createElement(Sl,{...o},v=>i.createElement(Qd,{value:{...o,...v,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s}},i.createElement(E,null),e))}const si=/iPad|iPhone|iPod/.test(navigator.userAgent),tm=/Android/.test(navigator.userAgent),Ot=e=>si||tm;let vt=null,In=null;const nm=(e,t=5e3)=>{vt&&(clearInterval(vt),clearTimeout(In));const n=document.title;vt=setInterval(()=>{document.title=document.title===e?n:e},750),In=setTimeout(()=>{clearInterval(vt),vt=null,In=null,document.title=n},t)},oi=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Se=D.css`&:focus-visible{outline:2px solid ${g.themedColor.primary};outline-offset:2px;}`,vs=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:a,onClose:l,"aria-label":c})=>{const d=u.useId(),m=u.useId(),h=c??vs(t)??vs(n),f=c?void 0:t?d:n?m:void 0,E=t&&n?m:void 0,v=()=>{l(),Re(()=>o==null?void 0:o())},y=()=>{l(),Re(()=>a==null?void 0:a())};return i.createElement(nt,{portalContainerId:Ee.WINDOW,visible:e,onClose:l,"aria-label":h,"aria-labelledby":f,"aria-describedby":E},i.createElement(rm,null,i.createElement(sm,null,t&&i.createElement("div",{id:d},i.createElement($,{variant:"h1",color:g.themedColor.textHighEmphasis},t)),n&&i.createElement(om,{id:m},i.createElement($,{variant:"body3",color:g.themedColor.textMidEmphasis},n))),i.createElement(im,null,s&&i.createElement(ys,{onClick:y},i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasis},s)),i.createElement(ys,{onClick:v},i.createElement($,{variant:"button",color:g.themedColor.primary},r)))))},rm=p.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};`,sm=p.default.div`margin-bottom:16px;`,om=p.default.div`margin-top:16px;`,im=p.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ys=p.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Se}`,{Provider:am,useContext:Te}=_e("MessengerSession"),lm=u.forwardRef(function({children:e,...t},n){return i.createElement(sc,{ref:n,...t},r=>i.createElement(cm,{...r},e))}),cm=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=ge(),{userSessionInfo:h,authenticate:f,userSession:E,aiAgentInfo:v,launcherInfo:y}=t,[C,_]=u.useState(!1),b=u.useRef(null);mt(n,{async onUserJoined(T,L){var I,w,O,U;T.conversation&&T.conversation.type===Ie.ConversationType.PROACTIVE&&L.userId===((I=n.currentUser)==null?void 0:I.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(O=m.session)==null||O._updateActiveChannel({url:T.url,status:"open",conversationStatus:(w=T.conversation)==null?void 0:w.status}),l.setOpened(!0),um({sound:document.hidden||!l.opened}),(U=b.current)==null||U.call(b,{channel:T}))}}),u.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!Ot()&&setTimeout(()=>l.setOpened(!0),500)}).catch(T=>{var L;r.error("messengerSession: failed to initialize",T),(L=c==null?void 0:c.onInitializeFailed)==null||L.call(c,T)})},[n,s,o,h==null?void 0:h.userId]),u.useEffect(()=>{const T=()=>_(!0);return d.subscribe(Fe.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Fe.AnonymousSessionTokenExpired,T)},[d]);const A=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!E||!v||!y?null:i.createElement(am,{value:{...t,userSession:E,aiAgentInfo:{...v,...a==null?void 0:a.bot},launcherInfo:{...y,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:T=>b.current=T}},e,i.createElement(fn,{visible:C,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:he}))};function um({sound:e}){nm("🔔You have received a new message"),e&&oi()}const on=`@${Ne}-focused-channel`,ii=`${Date.now()}-${Math.random().toString(36).slice(2)}`,dm=()=>{try{const e=localStorage.getItem(on);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},Ss=e=>{try{localStorage.setItem(on,JSON.stringify({channelUrl:e,tabId:ii}))}catch{}},As=()=>{try{const e=localStorage.getItem(on);if(!e)return;JSON.parse(e).tabId===ii&&localStorage.removeItem(on)}catch{}},mm=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>Ss(e),r=()=>As();return document.hasFocus()&&Ss(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),As()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||dm()===e}),hm=e=>{const{config:t,chatSDK:n}=ge(),{sdkUser:r}=Te(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=mm(e,s);mt(n,{onMessageReceived(a,l){if(!s||a.url!==e||o())return;(Qe(l)&&l.sender.userId!==(r==null?void 0:r.userId)||l.isAdminMessage()&&!l.silent)&&oi()}})};function fm(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 gm(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await fm(e.file);return new Be.MessageMetaArray({key:oo,value:[t,n]})}}const pm=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ge(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await gm(s),a={...s,metaArrays:o?[o]:void 0},l=_m(r.current);return l?{...a,data:JSON.stringify(l)}:a},onAfterSendMessage:s=>{var o,a,l;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===Be.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Be.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:s}}))}}},_m=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},ct=50,wn=ct-40,{Provider:Em,useContext:ai}=_e("ConversationScroll"),xs={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Mn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function bm({scrollMode:e,messageStackDirection:t,children:n}){const r=u.useRef(null),s=u.useRef(null),o=u.useRef(0),a=u.useRef(0),l=u.useRef(!1),c=u.useRef(!1),d=u.useRef(null),m=u.useRef(xs),h=u.useRef(!1),f=u.useRef(null),[E,v]=u.useState(0),[y,C]=u.useState(0),[_,b]=u.useState(!1),[A,T]=u.useState(!1),[L,k]=u.useState(!0),I=x=>{const R=Mn(x);return o.current=R,C(R),R},w=()=>{d.current&&(clearTimeout(d.current),d.current=null)},O=u.useMemo(()=>_||t==="bottom"?"auto":e,[_,t,e]),U=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},Y=()=>{const x=r.current;!x||!m.current.shouldUpdate||v(R=>{m.current.shouldUpdate=!1;const{contentHeight:N,contentSnapshotHeight:j,shouldRecalc:P}=m.current,B=x.clientHeight;if(j>N)return R;const F=V(x,{messageType:"outgoing"});let ue=0;if(F){const $e=F.message.offsetTop-wn+B;ue=Math.max(0,$e-N)}else{const $e=N-j,ce=B-wn;ue=Math.max(0,$e-ce)}return R===0||ue!==R||P?(m.current.shouldRecalc=!1,ue):R})},V=u.useCallback((x,R)=>{const{messageType:N="all"}=R??{},j=Array.from(x.querySelectorAll(`#${Ne}-message-item`));let P=j;N==="outgoing"&&(P=j.filter(re=>re.getAttribute("data-layout-id")==="outgoingmessage"));const B=P[P.length-1];if(!B)return null;const F=x.getBoundingClientRect(),ue=B.getBoundingClientRect(),$e=x.scrollTop+(ue.top-F.top),ce=$e+B.offsetHeight;return{message:B,scrollTop:$e,lastMessageBottom:ce}},[]),z=u.useCallback(()=>{const x=r.current;if(!x||O!=="fixed")return;const R=V(x);m.current.contentHeight=(R==null?void 0:R.lastMessageBottom)??x.scrollHeight,!h.current&&m.current.contentSnapshotHeight>0&&U(),c.current?o.current=Mn(x):I(x),Y()},[O,V]),H=u.useCallback(()=>{s.current&&(s.current.disconnect(),s.current=null),w(),m.current=xs,v(0),C(0),k(!0),o.current=0,l.current=!1,a.current=0,c.current=!1},[]),W=u.useCallback((x=!0)=>{const R=o.current>ct;if(l.current=!1,C(0),!R){Re(()=>{const N=r.current;N&&!l.current&&N.scrollTo({top:N.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,k(!1),w()),Re(()=>{const N=r.current;if(!N){c.current=!1,k(!0);return}if(l.current){c.current=!1,I(N),k(!0);return}const j=()=>{if(r.current!==N){c.current=!1,r.current&&I(r.current),k(!0);return}c.current=!1,I(N),k(!0)};if(x&&!d.current){const P=setTimeout(j,500);d.current=P,N.addEventListener("scrollend",()=>{clearTimeout(P),d.current=null,j()},{once:!0})}N.scrollTo({top:N.scrollHeight,behavior:x?"smooth":"auto"}),x||j()})},[]),K=u.useCallback(x=>{x&&(r.current=x,O==="fixed"&&(H(),m.current.viewport=x.clientHeight,s.current=new MutationObserver(()=>{z()}),s.current.observe(x,{childList:!0,subtree:!0})))},[O,z,H]),ae=u.useCallback(()=>{const x=r.current;if(!x)return;const R=V(x,{messageType:"outgoing"});R&&(x.scrollTo({top:R.message.offsetTop-wn,behavior:"smooth"}),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{T(!1)},500))},[V]),M=(x,R,N)=>{const j=Mn(x);if(N&&j>ct){c.current=!1,l.current=!0,w(),I(x),k(!0),a.current=R;return}o.current=j},ye=(x,R,N)=>{const P=I(x)<=ct;R&&!P&&(l.current=!0,w()),N&&P&&(l.current=!1)},X=x=>{const{scrollTop:R}=x.currentTarget,N=a.current;c.current?M(x.currentTarget,R,R<N):ye(x.currentTarget,R<N,R>N),a.current=R},q=u.useCallback(()=>{O==="fixed"&&(T(!0),U())},[O]),G=u.useCallback(()=>{O==="fixed"?setTimeout(()=>ae(),300):W()},[O,ae]),ee=u.useCallback(x=>{h.current=x,O==="fixed"?U():l.current||W()},[O,W]),de=u.useCallback(x=>{b(x),x&&(v(0),s.current&&(s.current.disconnect(),s.current=null))},[]),le=u.useCallback(x=>{O==="auto"&&x&&!l.current&&W()},[O,W]),Le=!(y<=ct)&&!A,Me=u.useCallback(()=>o.current>ct,[]);return i.createElement(Em,{value:{ref:K,state:{bottomSpace:E,isAwayFromBottom:Le,isScrollPositionReconciled:L,shouldCountNewMessages:Me},props:{onScroll:X},actions:{scrollToBottom:W,onBeforeMessageSend:q,onAfterMessageSend:G,onStreamingUpdate:ee,onConversationClosed:de,onTypingIndicatorUpdate:le}}},n)}const{Provider:Cm,Context:vm,useContext:ve}=_e("Conversation"),ym=({children:e})=>{var s;const{channelSource:t}=ve(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=Nc(n);return u.useEffect(()=>{var a;const o=(a=t.channel)==null?void 0:a.lastMessage;o&&r(o)},[t.channel,r]),i.createElement(i.Fragment,null,e)},Sm=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:s})=>{const{activeChannel:o,refreshActiveChannel:a}=Te(),l=ai(),c=e||(o==null?void 0:o.url);hm(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=pm({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),h=u.useCallback(v=>(l.actions.onBeforeMessageSend(),d(v)),[l.actions,d]),f=u.useCallback(v=>{const y=v.some(C=>Ge.isStreaming(C));l.actions.onStreamingUpdate(y)},[l.actions.onStreamingUpdate]),E=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(pc,{key:c,channelUrl:c,onBeforeSendMessage:h,onAfterSendMessage:m,onMessagesUpdated:f,onMessagesReceived:f,onChannelDeleted:E,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},v=>i.createElement(Cm,{value:{...v,scrollSource:l,goToActiveConversation:E,onNavigateToConversationList:n}},i.createElement(ym,null,s)))},li=({children:e,...t})=>{const{config:n}=Oe(),{agentPreviewConfigs:r}=ge(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return i.createElement(bm,{scrollMode:s,messageStackDirection:o},i.createElement(Sm,{...t},e))},Cr=u.createContext({onDrop:he,subscribe:()=>he}),qn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(Cr.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)},Am=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(Cr);u.useEffect(()=>t(e),[e])};qn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(Cr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const xm=e=>{const t=Ld(e)??e;t===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),t.focus()},ci=(e,{enabled:t,ready:n})=>{const r=u.useRef(!1);u.useEffect(()=>{if(!t){r.current=!1;return}if(r.current||!e.current||!(br(e.current)!=null)&&!n)return;let o=!1;return Re(()=>{o||r.current||!e.current||(r.current=!0,xm(e.current))}),()=>{o=!0}},[t,n,e])},Tm=e=>{const{announcementsEnabled:t}=qe(),{channelSource:n}=ve(),r=n.channel!=null||n.error!=null;ci(e,{enabled:t,ready:r})},Im=e=>je(e)||tr(e);function wm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function Mm(e,t){return e.filter(n=>Ge.isWelcomeMessage(n,t))}const ui=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>wm(r)?!1:t.length>0?!Ge.isWelcomeMessage(r,n):!0),km=[],di=()=>{var v,y,C,_,b,A;const{agentPreviewConfigs:e={},aiAgentId:t}=ge(),{aiAgentInfo:n,userSession:r}=Te(),{channelSource:s,messageSource:o,state:{input:a,streamAnimation:l}}=ve(),c=e.welcomeMessages??km,d=u.useMemo(()=>ui(o.messages,{previewWelcomeMessages:c,aiAgentUserId:t}),[t,o.messages,c]),m=et(s.channel),h=(y=(v=po(s.channel,r.userId))==null?void 0:v.nickname)==null?void 0:y.trim(),f=m?(_=(C=s.channel)==null?void 0:C.name)==null?void 0:_.trim():(b=n==null?void 0:n.nickname)==null?void 0:b.trim(),E=h||f||void 0;return{initialized:o.initialized,channelUrl:(A=s.channel)==null?void 0:A.url,agentName:E,isClosed:ke(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:c.length>0,inputDisabled:a.disabled,inputDisabledBy:a.disabledBy,isStreamAnimating:l.isAnimating,subscribeMessageEvents:o.subscribeMessageEvents,currentUserId:r.userId}},Rm=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=qe(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:a=!1,messages:l=[],hasWelcomeMessages:c=!1}=e,d=u.useRef(null),m=u.useMemo(()=>l.some(f=>xe.isAdmin(f)&&xe.isCSAT(f)),[l]),h=l.length===0&&!c;u.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:a,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,a,h])},Om=()=>{const e=di();Rm(e)},Lm=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}),Ts=(e,t,n=Xe.format)=>{const r=Cu(e,Lm(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}},Nm={senderName:!0,body:!0,time:!0},Dm=Object.keys(Nm),$m=(e,t)=>Dm.every(n=>e[n]===t[n]),Is=2e3,ws=400,Kn=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]},mi=e=>{if(!xe.isAdmin(e)||!xe.isCSAT(e))return null;const t=wu(e);return t?`csat:${t}`:null},Pm=e=>{const t=new Set;for(const n of e){const r=mi(n);r&&t.add(r)}return t},Fm=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Kn(r).some(s=>t.includes(s)))return r}},kn=(e,t)=>e.some(n=>t.includes(n)),Ms=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,Rn=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Bm=()=>{const{announceStatus:e,announcementsEnabled:t}=qe(),{stringSet:n,format:r}=oe(),{channelUrl:s,messages:o,isClosed:a,isHandedOff:l,agentName:c,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,subscribeMessageEvents:E,currentUserId:v}=di(),{outgoingMessageStates:y,outgoingMessageStatusSignature:C}=u.useMemo(()=>{if(!v)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const X=o.flatMap(q=>{const G=Tu(q,v);return!G||!("sendingStatus"in q)?[]:[{key:G,sendingStatus:q.sendingStatus}]});return{outgoingMessageStates:X,outgoingMessageStatusSignature:X.map(({key:q,sendingStatus:G})=>`${q}:${G}`).join(",")}},[v,o]),_=u.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:Rn(y)}),b=u.useRef({messages:o,currentUserId:v,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=u.useRef([]),T=u.useRef(null),L=u.useRef([]),k=u.useRef(new Set),I=u.useRef(new Set),w=u.useRef(!1),O=u.useRef(s);b.current={messages:o,currentUserId:v,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const U=()=>b.current.isStreamAnimating||b.current.inputDisabledBy==="ai_responding",Y=()=>{T.current!=null&&(clearTimeout(T.current),T.current=null)},V=(X,q,G)=>{const ee=G==null?void 0:G.replaceableForMs;if(X.length===0||!ee)return;const de=Date.now();L.current=[...L.current.filter(({replaceableUntil:le})=>le>de),{eventKeys:X,parts:q,replaceableUntil:de+ee}]},z=()=>A.current.length>0,H=()=>{A.current=[]},W=()=>{const[X,...q]=A.current;if(!X)return!1;A.current=q;const{eventKeys:G,parts:ee,dedupeKey:de}=X,le=Me=>{V(G,Me,{replaceableForMs:G.length>0?Is:void 0}),e({event:"newMessage",...Me},de?{dedupeKey:de}:void 0)};if(G.length===0)return le(ee),!0;const we=b.current,Le=Fm(we.messages,G);if(Le){const Me=Ts(Le,we.stringSet,we.format);return le(Me),!0}return le(ee),!0},K=()=>{for(Y();W(););},ae=(X=Is)=>{Y(),T.current=setTimeout(()=>{if(T.current=null,U())return;const q=Ms(),[G]=A.current;if(!G)return;if(G.focusTarget!==q){A.current=[{...G,focusTarget:q},...A.current.slice(1)],ae(ws);return}W()&&z()&&ae(ws)},X)},M=(X,q,G)=>{const ee={eventKeys:q,parts:X,focusTarget:Ms(),dedupeKey:G?G.dedupeKey??void 0:q[0]},de=q.length===0?-1:A.current.findIndex(({eventKeys:le})=>kn(le,q));de>=0?A.current=A.current.map((le,we)=>we===de?{...ee,dedupeKey:G?ee.dedupeKey:le.dedupeKey}:le):A.current=[...A.current,ee],ae()},ye=(X,q,G)=>{if(X!=="messagesUpdated"||q.length===0)return!1;const ee=Date.now(),de=L.current.find(le=>le.replaceableUntil>ee&&kn(le.eventKeys,q));return de?!$m(G,de.parts):!1};u.useEffect(()=>{const X=O.current!==s;(!t||!d||X)&&(w.current=!1,I.current.clear(),H(),L.current=[],k.current.clear(),Y(),X&&(O.current=s),!t||!d)||w.current||(w.current=!0,O.current=s,_.current={isClosed:a,isHandedOff:l,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:Rn(y)},k.current=new Set(o.flatMap(q=>{if(!Ge.isStreaming(q))return[];const G="sender"in q?q.sender:void 0;return(G==null?void 0:G.userId)===b.current.currentUserId?[]:Kn(q)})),I.current=Pm(o))},[e,t,s,d,m,a,l,C]),u.useEffect(()=>{const X=(q,G)=>{const ee=b.current,de=Kn(q),le=mi(q);if(le!=null){if(I.current.has(le))return;I.current.add(le),e({event:"csatDisplayed"});return}if(Ge.isStreaming(q)){de.forEach(P=>{k.current.add(P)});return}const we=de.filter(P=>k.current.has(P)),Le=G==="messagesUpdated"&&we.length>0;Le&&we.forEach(P=>{k.current.delete(P)});const Me=G==="messagesUpdated"&&A.current.some(({eventKeys:P})=>kn(P,de)),x=Ts(q,ee.stringSet,ee.format),R=ye(G,de,x);if(!Le&&G!=="messagesAdded"&&!Me&&!R)return;const N=R?{dedupeKey:null}:void 0;if(Le||U()||Me){M(x,[...new Set([...we,...de])],N);return}if(R){M(x,de,N);return}z()&&K();const j=de[0];e({event:"newMessage",...x},j?{dedupeKey:j}:void 0)};return E(q=>{if(!w.current||q.kind==="initialized"||!Mu(q.source))return;const G=b.current.currentUserId;for(const ee of q.messages)ee&&Iu(ee,G)&&X(ee,q.kind)})},[e,E]),u.useEffect(()=>{w.current&&(U()||z()&&ae())},[h,f]),u.useEffect(()=>()=>{Y()},[]),u.useEffect(()=>{if(!w.current)return;const X=_.current,q=X.outgoingMessageStatuses;X.outgoingMessageStatuses=Rn(y),y.some(({key:ee,sendingStatus:de})=>{const le=q.get(ee);return le!==void 0&&le!=="failed"&&de==="failed"})&&e({event:"sendFailed"})},[e,C]),u.useEffect(()=>{if(!w.current)return;const X=_.current;a&&!X.isClosed&&e({event:"conversationClosed"}),X.isClosed=a},[e,a]),u.useEffect(()=>{if(!w.current)return;const X=_.current;l&&!X.isHandedOff&&e({event:"agentConnected",agentName:c}),X.isHandedOff=l},[c,e,l]),u.useEffect(()=>{if(!w.current)return;const X=_.current;m&&h!=="ai_responding"&&(!X.inputDisabled||X.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),X.inputDisabled=m,X.inputDisabledBy=h},[e,m,h])},Um=()=>{const{channelSource:e}=ve(),t=Mo(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Hm=e=>{const{announceStatus:t,announcementsEnabled:n}=qe();Fc(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Gm=()=>{const e=Um();Hm(e)},Q=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=pd(),o=s[e];return i.createElement(Vm,{className:n},i.createElement(o,{size:t,color:r??g.color.primary.main,flipInRtl:cd.has(e)}))},Vm=p.default.span.attrs({"aria-hidden":"true"})`
77
+ ${({$rtlFlip:e})=>e&&_d};
78
+ `,bd=()=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},i.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),i.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),i.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Cd,useContext:vd}=Ee("MessengerIcon",{icons:Zs}),yd=({icons:e,children:t})=>{const n=u.useMemo(()=>({icons:bl(Zs,e)}),[e]);return i.createElement(Cd,{value:n},t)},{Provider:Sd,useContext:Js}=Ee("MessengerTheme");function Ad(e){const{theme:t,appearance:n,logger:r}=e;return i.createElement(oc,{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},i.createElement(xd,{...e}))}function xd({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=ur();return u.useLayoutEffect(()=>{e.setAttribute(on,n.selectedTheme)},[e,n.selectedTheme]),i.createElement(D.ThemeProvider,{theme:n},i.createElement(Sd,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Td=(e,t)=>{u.useEffect(()=>{const n=st(t)instanceof ShadowRoot,r=st(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const s=r.createElement("link");s.rel="stylesheet",s.href=e,(n?t:r.head).appendChild(s)}},[e,t])},Id=(e,t=document.body)=>{u.useEffect(()=>{if(!e)return;const n=st(t),o=n instanceof ShadowRoot?t:n.head;if(!o)return;const s=`sba-${btoa(e).slice(0,10)}`;let a=o.querySelector(`style#${s}`);a?a.textContent!==e&&(a.textContent=e):(a=o.ownerDocument.createElement("style"),a.id=s,a.textContent=e,o.appendChild(a))},[e,t])},wd=80,Md=()=>{const{stringSet:e}=se(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=u.useRef(t);return n.current=t,n},Qs=Ee("AriaLiveRegion",{announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,flush:he,setSuppressionState:he}),kd=Qs.Provider,_r=Qs.useContext,Rd={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Ld=({children:e})=>{const t=u.useRef(null),n=u.useRef(new Set),r=u.useRef(he),o=Md(),[s]=u.useState(()=>Tu(_=>{r.current(_)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=_=>{const y=t.current;y&&(y.textContent="",requestAnimationFrame(()=>{y.textContent=_}))},u.useEffect(()=>()=>{s.destroy()},[s]);const a=s.announce,l=s.flush,c=u.useCallback(_=>{const y=wu(_,o.current);a(y)},[a]),d=u.useCallback((_,y)=>{const C=Mu(_,o.current),v=(y==null?void 0:y.mode)??Iu(_.event);a(C,{mode:v,dedupeKey:y==null?void 0:y.dedupeKey})},[a]),m=u.useCallback((_,y)=>{const C=ku(_,o.current);s.announceIgnoringSuppression(C),y&&setTimeout(()=>{y.focus()},wd)},[s]),f=u.useCallback((_,y)=>{if(y){n.current.add(_);return}n.current.delete(_)},[]),h=u.useMemo(()=>({announce:a,announceScreenEntry:c,announceStatus:d,announceError:m,flush:l,setSuppressionState:f}),[a,m,c,d,l,f]);return i.createElement(kd,{value:h},e,i.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:Rd}))},ei=Ee("ConversationAnnouncements",{announcementsEnabled:!0,announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,setIsSuppressed:he,setStatusPauseState:he,flush:he}),Od=ei.Provider,Ke=ei.useContext,Nd=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:o,announceError:s,flush:a,setSuppressionState:l}=_r(),c=u.useRef([]),d=u.useRef(new Set),m=u.useRef(Symbol("conversation-announcements")),f=u.useCallback(x=>{if(!t||!x){l(m.current,!1);return}l(m.current,!0)},[t,l]),h=u.useCallback(()=>{c.current=[]},[]),_=u.useCallback(()=>{if(c.current.length===0)return;if(!t){h();return}const x=[...c.current];h(),x.forEach(k=>{a(),o(k.params,k.options)})},[o,t,h,a]),y=u.useCallback((x,k)=>{if(k){d.current.add(x);return}d.current.delete(x),d.current.size===0&&_()},[_]),C=u.useCallback(x=>{t&&n(x)},[n,t]),v=u.useCallback(x=>{t&&r(x)},[r,t]),b=u.useCallback((x,k)=>{if(t){if(d.current.size>0){c.current.push({params:x,options:k});return}o(x,k)}},[o,t]),E=u.useCallback((x,k)=>{t&&s(x,k)},[s,t]);u.useLayoutEffect(()=>(t||(h(),l(m.current,!1)),()=>{h(),l(m.current,!1)}),[t,h,l]);const A=u.useMemo(()=>({announcementsEnabled:t,announce:C,announceScreenEntry:v,announceStatus:b,announceError:E,setIsSuppressed:f,setStatusPauseState:y,flush:a}),[t,a,C,E,v,b,f,y]);return i.createElement(Od,{value:A},e)},P=({as:e,variant:t="body1",color:n,maxTextLines:r,className:o,...s})=>i.createElement(Pd,{as:e,$variant:t,className:o,$color:n,$maxTextLines:r,...s}),po=new WeakMap,Dd=(e,t)=>{let n=po.get(t);n||(n=new Map,po.set(t,n));const r=n.get(e);if(r)return r;const o=t[e]??t.body1,s=D.css`font-size:${Ge(o.fontSize)};font-weight:${o.fontWeight};${o.fontFamily?`font-family: ${o.fontFamily};`:""}
79
+ ${o.lineHeight?`line-height: ${o.lineHeight};`:"line-height: 100%;"}
80
+ `;return n.set(e,s),s},$d=e=>e?D.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Pd=p.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Dd(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>$d(e)}`,mn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ti=`${mn}, [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};async function Er(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Le(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const sn=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(hr)&&Mt(n))return n;return null},ni=e=>{let t=null,n=null;for(const r of e.querySelectorAll(mn))r.hasAttribute(hr)||Mt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},br=e=>sn(e,Uu),ri=e=>br(e)??sn(e,mn),Fd=e=>{const t=br(e);if(t)return t;const n=e.querySelector(Gu);return(n?sn(n,ti):null)??sn(e,mn)},Wn='[role="dialog"][aria-modal="true"]',Bd=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Wn)).filter(o=>o!==e&&(o.contains(e)||e.contains(o)))),r=t==null?void 0:t.closest(Wn);return r&&r!==e&&n.add(r),n},Ud=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Wn)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Mt(n)),Hd=e=>{const t=ri(e)??e;t===e&&oi(e),t.focus()},oi=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Gd=(e,t)=>{const n=ni(e);if(!n){oi(e),e.focus();return}n[t].focus()},_o=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(hr,Hu),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Gd(e,t)),n},zd=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ni(t)||(e.preventDefault(),t.focus())))},Vd=(e,t)=>t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,fn=(e,t)=>{const n=u.useRef(0);u.useEffect(()=>{if(!e||!t.current)return;n.current+=1;const r=n.current,o=t.current,s=o.getRootNode(),a=s.activeElement instanceof HTMLElement?s.activeElement:null,l=Bd(o,a);let c=!1;return Le(()=>{c||!o.isConnected||Hd(o)}),()=>{c=!0,a&&Le(()=>{if(n.current!==r)return;const d=s.activeElement;o.isConnected&&d instanceof HTMLElement&&d!==o&&!o.contains(d)&&!Vd(s,d)&&d.matches(ti)&&Mt(d)||Ud(o,l)||!a.isConnected||!Mt(a)||a.focus()})}},[e,t]),u.useEffect(()=>{if(!e||!t.current)return;const r=t.current,o=_o(r,"last"),s=_o(r,"first"),a=l=>zd(l,r);return r.insertBefore(o,r.firstChild),r.appendChild(s),r.addEventListener("keydown",a),()=>{r.removeEventListener("keydown",a),o.remove(),s.remove()}},[e,t])},nt=({style:e,portalContainerId:t,visible:n,onClose:r,children:o,cancelable:s=!0,"aria-label":a,"aria-labelledby":l,"aria-describedby":c})=>{const d=u.useRef(null),{resolvePortalContainer:m}=pr();return fn(n,d),Qu(n,s?r:he),n?ca.createPortal(i.createElement(Yd,{onClick:s?r:void 0,style:e},i.createElement(Wd,{ref:d,role:"dialog","aria-modal":"true","aria-label":a,"aria-labelledby":l,"aria-describedby":c,onClick:f=>f.stopPropagation()},o)),m(t)):null},Yd=p.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${g.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${it.MODAL};`,Wd=p.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:${it.MODAL};`,qd=({id:e,children:t})=>i.createElement(Kd,{id:e},t),Kd=p.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;`,Eo=(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,...Hs}:n},jd=()=>{const e=`${u.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,o=u.createElement(qd,{id:r,children:t});return{props:{"aria-describedby":r},node:o}}},bo=({name:e,mimeType:t,selected:n},r)=>{var s;const o=He(t??"")?r.A11Y_FILE_IMAGE(e):cn(t??"")?r.A11Y_FILE_VIDEO(e):cs({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((s=r.A11Y_FILE_SELECTED)==null?void 0:s.call(r,o))??`${o}, selected`:o},Xd=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},St=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Xd(e)}),Zd=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>o=>{var c;if(e||n<=0)return;let s=null;switch(o.key){case"ArrowRight":case"ArrowDown":s=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":s=(t-1+n)%n;break;default:return}o.preventDefault(),r(s);const a=o.currentTarget.parentElement,l=a==null?void 0:a.querySelectorAll('[role="radio"]');(c=l==null?void 0:l[s])==null||c.focus()},Co=(e,t,n,r,o,s)=>{let a=-1;return(e||!o&&n===0)&&(a=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:Zd({disabled:t,currentIndex:n,totalCount:r,onNavigate:s}),tabIndex:a}},oe=()=>{const{stringSet:e}=se(),t=jd(),n=(a,l)=>{let c=e.A11Y_HINT_OPEN_FILE,d="of";He(a??"")&&(c=e.A11Y_HINT_OPEN_IMAGE,d="oi"),l!==void 0&&(d+=l);const m=t(c,d);return{props:m.props,descriptionNode:m.node}},r=a=>({"aria-label":bo(a,e)});return{launcher:{button:({isOpened:a,opensConversationList:l})=>{const c=Fu({intent:Du({isOpened:a,opensConversationList:l}),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";c.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),c.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(c.hint,d);return{props:{"aria-label":c.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:a=>{let l=e.A11Y_EXPAND_MESSENGER;return a&&(l=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":l},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const a=e.A11Y_HINT_OPEN_MENU,l=t(a,"mb");return{props:{"aria-label":e.A11Y_MENU,...l.props},descriptionNode:l.node}},closeConversationButton:()=>{const a=e.A11Y_HINT_CLOSE_CONVERSATION,l=t(a,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...l.props},descriptionNode:l.node}},handoffButton:()=>{const a=e.A11Y_HINT_CONNECT_TO_AGENT,l=t(a,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...l.props},descriptionNode:l.node}},title:(a,l)=>({props:Eo(a,l),descriptionNode:null}),memoryIndicator:a=>{let l=e.A11Y_MEMORY_INDICATOR_OFF,c="mof";a&&(l=e.A11Y_MEMORY_INDICATOR_ON,c="mon");const d=t(l,c);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const a=e.A11Y_HINT_ATTACH_FILE,l=t(a,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...l.props},descriptionNode:l.node}},sendButton:()=>{const a=e.A11Y_HINT_SEND_MESSAGE,l=t(a,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...l.props},descriptionNode:l.node}},textInput:a=>({props:{role:"textbox","aria-label":a},descriptionNode:null})},suggestedReplies:{item:(a,l)=>{const c=e.A11Y_HINT_SEND_REPLY,d=t(c,`sr${l}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${a}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const a=e.A11Y_HINT_SELECT_RATING,l=t(a,"fb");return{props:l.props,descriptionNode:l.node}},button:(a,l)=>{const c=e.A11Y_HINT_SELECT_RATING,d=t(c,`f${a}`);let m=e.FEEDBACK_BAD;return a==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":l},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...l.props},descriptionNode:l.node}},scrollToBottomButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...l.props},descriptionNode:l.node}},startNewConversationButton:({onActivate:a})=>({props:{...St({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(a=e.RETRY)=>({props:{"aria-label":a},descriptionNode:null}),file:{label:(a,l,c)=>a?bo({name:a,mimeType:l,selected:c},e):"",preview:a=>({props:r(a),descriptionNode:null}),buttonLikePreview:({onActivate:a,...l},c)=>{const d=n(l.mimeType,c);return{props:{...St({onActivate:a}),...r(l),...d.props},descriptionNode:d.descriptionNode}},removeButton:a=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(a)},descriptionNode:null})},csat:{scoresContainer:a=>{const l=e.A11Y_HINT_SELECT_RATING,c=t(l,"cs");return{props:{role:"radiogroup","aria-label":a,...c.props},descriptionNode:c.node}},scoreItem:({score:a,label:l,selected:c,disabled:d,currentIndex:m,totalCount:f,hasSelection:h,onChange:_})=>{var b;const y=l.trim()||l,C=e.A11Y_HINT_SELECT_RATING,v=t(C,`cs${a}`);return{props:{disabled:d,onClick:()=>_(a),...Co(c,d,m,f,h,E=>_(E+1)),...v.props,"aria-label":((b=e.A11Y_CSAT_RATING_LABEL)==null?void 0:b.call(e,a,y))??`${a} / ${f} — ${y}`},descriptionNode:v.node}},submitButton:a=>({props:{"aria-label":a},descriptionNode:null})},form:{button:a=>({props:{"aria-label":a},descriptionNode:null}),textInput:(a,l,c)=>({props:{"aria-label":a,"aria-required":l,"aria-disabled":c},descriptionNode:null}),numberInput:(a,l,c)=>({props:{"aria-label":a,"aria-required":l,"aria-disabled":c},descriptionNode:null}),singleSelectGroup:a=>{const l={role:"radiogroup"};return a&&(l["aria-label"]=a),{props:l,descriptionNode:null}},singleSelectOption:(a,l,c,d,m,f,h)=>({props:{...Co(l,c,d,m,f,h),"aria-label":a},descriptionNode:null}),multiSelectOption:(a,l,c)=>({props:{"aria-label":a,"aria-pressed":l,"aria-disabled":c},descriptionNode:null})}},conversationList:{headerTitle:(a,l)=>({props:Eo(a,l),descriptionNode:null}),footer:{button:({onActivate:a})=>({props:{...St({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:a,status:l,time:c,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:null};const f=e.A11Y_HINT_OPEN_CONVERSATION,h=t(f,"cli");return{props:{...St({onActivate:m}),...h.props,"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:h.node}}}}},Jd=({title:e,description:t,highlightedText:n})=>{const r=nu(t,n);return i.createElement(em,null,i.createElement(tm,null,i.createElement(P,{as:"div",variant:"h1",color:g.themedColor.textHighEmphasis},e),t&&i.createElement(nm,null,i.createElement(P,{as:"div",variant:"body3",color:g.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?i.createElement(rm,null,r.highlightedText):null,r.afterText))))},Qd=()=>{const{components:e}=hn.useContext(),{stringSet:t}=se(),{messenger:n}=oe(),r=eu(),o=r.showDescription?tu(r.remainingTime):"",s=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(o):"";return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:r.visible,onClose:he,...n.connectionDelayDialog().props},i.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:s,highlightedText:o||void 0}))},hn=Ue({template:Qd,components:{Dialog:Jd}}),em=p.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,tm=p.default.div`display:flex;flex-direction:column;`,nm=p.default.div`margin-top:16px;`,rm=p.default.strong`font-weight:700;`,om=({url:e})=>Er(e),{Provider:sm,Consumer:si,useContext:me}=Ee("Messenger");function im({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:o=!0,...s}){const[a,l]=u.useState(!1),[c,d]=u.useState(!1),m={opened:(t==null?void 0:t.opened)??a,setOpened:(t==null?void 0:t.setOpened)??l,expanded:(t==null?void 0:t.expanded)??c,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:f}=pr(),h=u.useCallback(()=>{var C;m.setOpened(!1),(C=f(Ce.LAUNCHER))==null||C.focus()},[m.setOpened,f]);ed(m.opened,h);const{Template:_}=hn.useContext(),y=u.useMemo(()=>{var C;return{...s.handlers,onClickLink:((C=s.handlers)==null?void 0:C.onClickLink)??om}},[s.handlers]);return i.createElement(Il,{...s},C=>i.createElement(sm,{value:{...s,...C,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o,handlers:y}},i.createElement(_,null),e))}const ii=/iPad|iPhone|iPod/.test(navigator.userAgent),am=/Android/.test(navigator.userAgent),Ot=e=>ii||am;let vt=null,wn=null;const lm=(e,t=5e3)=>{vt&&(clearInterval(vt),clearTimeout(wn));const n=document.title;vt=setInterval(()=>{document.title=document.title===e?n:e},750),wn=setTimeout(()=>{clearInterval(vt),vt=null,wn=null,document.title=n},t)},ai=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Ae=D.css`&:focus-visible{outline:2px solid ${g.themedColor.primary};outline-offset:2px;}`,vo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},gn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:o,onConfirm:s,onCancel:a,onClose:l,"aria-label":c})=>{const d=u.useId(),m=u.useId(),f=c??vo(t)??vo(n),h=c?void 0:t?d:n?m:void 0,_=t&&n?m:void 0,y=()=>{l(),Le(()=>s==null?void 0:s())},C=()=>{l(),Le(()=>a==null?void 0:a())};return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:e,onClose:l,"aria-label":f,"aria-labelledby":h,"aria-describedby":_},i.createElement(cm,null,i.createElement(um,null,t&&i.createElement("div",{id:d},i.createElement(P,{variant:"h1",color:g.themedColor.textHighEmphasis},t)),n&&i.createElement(dm,{id:m},i.createElement(P,{variant:"body3",color:g.themedColor.textMidEmphasis},n))),i.createElement(mm,null,o&&i.createElement(yo,{onClick:C},i.createElement(P,{variant:"button",color:g.themedColor.textHighEmphasis},o)),i.createElement(yo,{onClick:y},i.createElement(P,{variant:"button",color:g.themedColor.primary},r)))))},cm=p.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};`,um=p.default.div`margin-bottom:16px;`,dm=p.default.div`margin-top:16px;`,mm=p.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,yo=p.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Ae}`,{Provider:fm,useContext:we}=Ee("MessengerSession"),hm=u.forwardRef(function({children:e,...t},n){return i.createElement(lc,{ref:n,...t},r=>i.createElement(gm,{...r},e))}),gm=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=me(),{userSessionInfo:f,authenticate:h,userSession:_,aiAgentInfo:y,launcherInfo:C}=t,[v,b]=u.useState(!1),E=u.useRef(null);ht(n,{async onUserJoined(x,k){var I,w,O,$;x.conversation&&x.conversation.type===be.ConversationType.PROACTIVE&&k.userId===((I=n.currentUser)==null?void 0:I.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",x.url),(O=m.session)==null||O._updateActiveChannel({url:x.url,status:"open",conversationStatus:(w=x.conversation)==null?void 0:w.status}),l.setOpened(!0),pm({sound:document.hidden||!l.opened}),($=E.current)==null||$.call(E,{channel:x}))}}),u.useEffect(()=>{h().then(({launcher:x})=>{x.auto_open&&!Ot()&&setTimeout(()=>l.setOpened(!0),500)}).catch(x=>{var k;r.error("messengerSession: failed to initialize",x),(k=c==null?void 0:c.onInitializeFailed)==null||k.call(c,x)})},[n,o,s,f==null?void 0:f.userId]),u.useEffect(()=>{const x=()=>b(!0);return d.subscribe(Fe.AnonymousSessionTokenExpired,x),()=>d.unsubscribe(Fe.AnonymousSessionTokenExpired,x)},[d]);const A=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!_||!y||!C?null:i.createElement(fm,{value:{...t,userSession:_,aiAgentInfo:{...y,...a==null?void 0:a.bot},launcherInfo:{...C,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:x=>E.current=x}},e,i.createElement(gn,{visible:v,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:he}))};function pm({sound:e}){lm("🔔You have received a new message"),e&&ai()}const an=`@${Ne}-focused-channel`,li=`${Date.now()}-${Math.random().toString(36).slice(2)}`,_m=()=>{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:li}))}catch{}},Ao=()=>{try{const e=localStorage.getItem(an);if(!e)return;JSON.parse(e).tabId===li&&localStorage.removeItem(an)}catch{}},Em=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>So(e),r=()=>Ao();return document.hasFocus()&&So(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),Ao()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||_m()===e}),bm=e=>{const{config:t,chatSDK:n}=me(),{sdkUser:r}=we(),o=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:s}=Em(e,o);ht(n,{onMessageReceived(a,l){if(!o||a.url!==e||s())return;(Qe(l)&&l.sender.userId!==(r==null?void 0:r.userId)||l.isAdminMessage()&&!l.silent)&&ai()}})};function Cm(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),o=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:o})},n.src=URL.createObjectURL(e)})}async function vm(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Cm(e.file);return new Be.MessageMetaArray({key:as,value:[t,n]})}}const ym=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=me(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await vm(o),a={...o,metaArrays:s?[s]:void 0},l=Sm(r.current);return l?{...a,data:JSON.stringify(l)}:a},onAfterSendMessage:o=>{var s,a,l;e(),(s=n==null?void 0:n.onMessageSend)==null||s.call(n,o.message),o.sendingStatus===Be.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===Be.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},Sm=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},dt=50,Mn=dt-40,{Provider:Am,useContext:ci}=Ee("ConversationScroll"),xo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},kn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function xm({scrollMode:e,messageStackDirection:t,children:n}){const r=u.useRef(null),o=u.useRef(null),s=u.useRef(0),a=u.useRef(0),l=u.useRef(!1),c=u.useRef(!1),d=u.useRef(null),m=u.useRef(xo),f=u.useRef(!1),h=u.useRef(null),[_,y]=u.useState(0),[C,v]=u.useState(0),[b,E]=u.useState(!1),[A,x]=u.useState(!1),[k,R]=u.useState(!0),I=T=>{const M=kn(T);return s.current=M,v(M),M},w=()=>{d.current&&(clearTimeout(d.current),d.current=null)},O=u.useMemo(()=>b||t==="bottom"?"auto":e,[b,t,e]),$=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},V=()=>{const T=r.current;!T||!m.current.shouldUpdate||y(M=>{m.current.shouldUpdate=!1;const{contentHeight:N,contentSnapshotHeight:j,shouldRecalc:B}=m.current,z=T.clientHeight;if(j>N)return M;const U=H(T,{messageType:"outgoing"});let ue=0;if(U){const $e=U.message.offsetTop-Mn+z;ue=Math.max(0,$e-N)}else{const $e=N-j,ae=z-Mn;ue=Math.max(0,$e-ae)}return M===0||ue!==M||B?(m.current.shouldRecalc=!1,ue):M})},H=u.useCallback((T,M)=>{const{messageType:N="all"}=M??{},j=Array.from(T.querySelectorAll(`#${Ne}-message-item`));let B=j;N==="outgoing"&&(B=j.filter(te=>te.getAttribute("data-layout-id")==="outgoingmessage"));const z=B[B.length-1];if(!z)return null;const U=T.getBoundingClientRect(),ue=z.getBoundingClientRect(),$e=T.scrollTop+(ue.top-U.top),ae=$e+z.offsetHeight;return{message:z,scrollTop:$e,lastMessageBottom:ae}},[]),Y=u.useCallback(()=>{const T=r.current;if(!T||O!=="fixed")return;const M=H(T);m.current.contentHeight=(M==null?void 0:M.lastMessageBottom)??T.scrollHeight,!f.current&&m.current.contentSnapshotHeight>0&&$(),c.current?s.current=kn(T):I(T),V()},[O,H]),G=u.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),w(),m.current=xo,y(0),v(0),R(!0),s.current=0,l.current=!1,a.current=0,c.current=!1},[]),W=u.useCallback((T=!0)=>{const M=s.current>dt;if(l.current=!1,v(0),!M){Le(()=>{const N=r.current;N&&!l.current&&N.scrollTo({top:N.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,R(!1),w()),Le(()=>{const N=r.current;if(!N){c.current=!1,R(!0);return}if(l.current){c.current=!1,I(N),R(!0);return}const j=()=>{if(r.current!==N){c.current=!1,r.current&&I(r.current),R(!0);return}c.current=!1,I(N),R(!0)};if(T&&!d.current){const B=setTimeout(j,500);d.current=B,N.addEventListener("scrollend",()=>{clearTimeout(B),d.current=null,j()},{once:!0})}N.scrollTo({top:N.scrollHeight,behavior:T?"smooth":"auto"}),T||j()})},[]),q=u.useCallback(T=>{T&&(r.current=T,O==="fixed"&&(G(),m.current.viewport=T.clientHeight,o.current=new MutationObserver(()=>{Y()}),o.current.observe(T,{childList:!0,subtree:!0})))},[O,Y,G]),ce=u.useCallback(()=>{const T=r.current;if(!T)return;const M=H(T,{messageType:"outgoing"});M&&(T.scrollTo({top:M.message.offsetTop-Mn,behavior:"smooth"}),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{x(!1)},500))},[H]),_e=(T,M,N)=>{const j=kn(T);if(N&&j>dt){c.current=!1,l.current=!0,w(),I(T),R(!0),a.current=M;return}s.current=j},L=(T,M,N)=>{const B=I(T)<=dt;M&&!B&&(l.current=!0,w()),N&&B&&(l.current=!1)},X=T=>{const{scrollTop:M}=T.currentTarget,N=a.current;c.current?_e(T.currentTarget,M,M<N):L(T.currentTarget,M<N,M>N),a.current=M},K=u.useCallback(()=>{O==="fixed"&&(x(!0),$())},[O]),F=u.useCallback(()=>{O==="fixed"?setTimeout(()=>ce(),300):W()},[O,ce]),ee=u.useCallback(T=>{f.current=T,O==="fixed"?$():l.current||W()},[O,W]),de=u.useCallback(T=>{E(T),T&&(y(0),o.current&&(o.current.disconnect(),o.current=null))},[]),fe=u.useCallback(T=>{O==="auto"&&T&&!l.current&&W()},[O,W]),Oe=!(C<=dt)&&!A,ke=u.useCallback(()=>s.current>dt,[]);return i.createElement(Am,{value:{ref:q,state:{bottomSpace:_,isAwayFromBottom:Oe,isScrollPositionReconciled:k,shouldCountNewMessages:ke},props:{onScroll:X},actions:{scrollToBottom:W,onBeforeMessageSend:K,onAfterMessageSend:F,onStreamingUpdate:ee,onConversationClosed:de,onTypingIndicatorUpdate:fe}}},n)}const{Provider:Tm,Context:Im,useContext:Se}=Ee("Conversation"),wm=({children:e})=>{var o;const{channelSource:t}=Se(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=Fc(n);return u.useEffect(()=>{var a;const s=(a=t.channel)==null?void 0:a.lastMessage;s&&r(s)},[t.channel,r]),i.createElement(i.Fragment,null,e)},Mm=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=we(),l=ci(),c=e||(s==null?void 0:s.url);bm(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=ym({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),f=u.useCallback(y=>(l.actions.onBeforeMessageSend(),d(y)),[l.actions,d]),h=u.useCallback(y=>{const C=y.some(v=>Ve.isStreaming(v));l.actions.onStreamingUpdate(C)},[l.actions.onStreamingUpdate]),_=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(Cc,{key:c,channelUrl:c,onBeforeSendMessage:f,onAfterSendMessage:m,onMessagesUpdated:h,onMessagesReceived:h,onChannelDeleted:_,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},y=>i.createElement(Tm,{value:{...y,scrollSource:l,goToActiveConversation:_,onNavigateToConversationList:n}},i.createElement(wm,null,o)))},ui=({children:e,...t})=>{const{config:n}=Me(),{agentPreviewConfigs:r}=me(),o=n.conversation.list.scrollMode,s=r==null?void 0:r.messageStackDirection;return i.createElement(xm,{scrollMode:o,messageStackDirection:s},i.createElement(Mm,{...t},e))},Cr=u.createContext({onDrop:he,subscribe:()=>he}),qn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(Cr.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const o=Array.from(n.dataTransfer.files);o.length>0&&t.current.forEach(s=>s(o))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},km=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(Cr);u.useEffect(()=>t(e),[e])};qn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(Cr);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const Rm=e=>{const t=Fd(e)??e;t===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),t.focus()},di=(e,{enabled:t,ready:n})=>{const r=u.useRef(!1);u.useEffect(()=>{if(!t){r.current=!1;return}if(r.current||!e.current||!(br(e.current)!=null)&&!n)return;let s=!1;return Le(()=>{s||r.current||!e.current||(r.current=!0,Rm(e.current))}),()=>{s=!0}},[t,n,e])},Lm=e=>{const{announcementsEnabled:t}=Ke(),{channelSource:n}=Se(),r=n.channel!=null||n.error!=null;di(e,{enabled:t,ready:r})},Om=e=>He(e)||cn(e);function Nm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function Dm(e,t){return e.filter(n=>Ve.isWelcomeMessage(n,t))}const mi=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>Nm(r)?!1:t.length>0?!Ve.isWelcomeMessage(r,n):!0),$m=[],fi=()=>{var y,C,v,b,E,A;const{agentPreviewConfigs:e={},aiAgentId:t}=me(),{aiAgentInfo:n,userSession:r}=we(),{channelSource:o,messageSource:s,state:{input:a,streamAnimation:l}}=Se(),c=e.welcomeMessages??$m,d=u.useMemo(()=>mi(s.messages,{previewWelcomeMessages:c,aiAgentUserId:t}),[t,s.messages,c]),m=et(o.channel),f=(C=(y=_s(o.channel,r.userId))==null?void 0:y.nickname)==null?void 0:C.trim(),h=m?(b=(v=o.channel)==null?void 0:v.name)==null?void 0:b.trim():(E=n==null?void 0:n.nickname)==null?void 0:E.trim(),_=f||h||void 0;return{initialized:s.initialized,channelUrl:(A=o.channel)==null?void 0:A.url,agentName:_,isClosed:Re(o.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:c.length>0,inputDisabled:a.disabled,inputDisabledBy:a.disabledBy,isStreamAnimating:l.isAnimating,subscribeMessageEvents:s.subscribeMessageEvents,currentUserId:r.userId}},Pm=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=Ke(),{initialized:r=!1,channelUrl:o,agentName:s,isClosed:a=!1,messages:l=[],hasWelcomeMessages:c=!1}=e,d=u.useRef(null),m=u.useMemo(()=>l.some(h=>Ie.isAdmin(h)&&Ie.isCSAT(h)),[l]),f=l.length===0&&!c;u.useEffect(()=>{if(!n){d.current=null;return}!r||!o||d.current!==o&&(t({screen:"conversation",agentName:s,isClosed:a,hasCSAT:m,...f?{isEmpty:!0}:{}}),d.current=o)},[s,t,n,o,m,r,a,f])},Fm=()=>{const e=fi();Pm(e)},Bm=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}),To=(e,t,n=Xe.format)=>{const r=xu(e,Bm(t)),o="sender"in e?e.sender:void 0,s=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(o==null?void 0:o.nickname)=="string"&&o.nickname.trim()||void 0,body:r||void 0,time:s}},Um={senderName:!0,body:!0,time:!0},Hm=Object.keys(Um),Gm=(e,t)=>Hm.every(n=>e[n]===t[n]),Io=2e3,wo=400,Kn=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]},hi=e=>{if(!Ie.isAdmin(e)||!Ie.isCSAT(e))return null;const t=Ou(e);return t?`csat:${t}`:null},zm=e=>{const t=new Set;for(const n of e){const r=hi(n);r&&t.add(r)}return t},Vm=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Kn(r).some(o=>t.includes(o)))return r}},Rn=(e,t)=>e.some(n=>t.includes(n)),Mo=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,Ln=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Ym=()=>{const{announceStatus:e,announcementsEnabled:t}=Ke(),{stringSet:n,format:r}=se(),{channelUrl:o,messages:s,isClosed:a,isHandedOff:l,agentName:c,initialized:d,inputDisabled:m,inputDisabledBy:f,isStreamAnimating:h,subscribeMessageEvents:_,currentUserId:y}=fi(),{outgoingMessageStates:C,outgoingMessageStatusSignature:v}=u.useMemo(()=>{if(!y)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const X=s.flatMap(K=>{const F=Ru(K,y);return!F||!("sendingStatus"in K)?[]:[{key:F,sendingStatus:K.sendingStatus}]});return{outgoingMessageStates:X,outgoingMessageStatusSignature:X.map(({key:K,sendingStatus:F})=>`${K}:${F}`).join(",")}},[y,s]),b=u.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:Ln(C)}),E=u.useRef({messages:s,currentUserId:y,inputDisabledBy:f,isStreamAnimating:h,stringSet:n,format:r}),A=u.useRef([]),x=u.useRef(null),k=u.useRef([]),R=u.useRef(new Set),I=u.useRef(new Set),w=u.useRef(!1),O=u.useRef(o);E.current={messages:s,currentUserId:y,inputDisabledBy:f,isStreamAnimating:h,stringSet:n,format:r};const $=()=>E.current.isStreamAnimating||E.current.inputDisabledBy==="ai_responding",V=()=>{x.current!=null&&(clearTimeout(x.current),x.current=null)},H=(X,K,F)=>{const ee=F==null?void 0:F.replaceableForMs;if(X.length===0||!ee)return;const de=Date.now();k.current=[...k.current.filter(({replaceableUntil:fe})=>fe>de),{eventKeys:X,parts:K,replaceableUntil:de+ee}]},Y=()=>A.current.length>0,G=()=>{A.current=[]},W=()=>{const[X,...K]=A.current;if(!X)return!1;A.current=K;const{eventKeys:F,parts:ee,dedupeKey:de}=X,fe=ke=>{H(F,ke,{replaceableForMs:F.length>0?Io:void 0}),e({event:"newMessage",...ke},de?{dedupeKey:de}:void 0)};if(F.length===0)return fe(ee),!0;const xe=E.current,Oe=Vm(xe.messages,F);if(Oe){const ke=To(Oe,xe.stringSet,xe.format);return fe(ke),!0}return fe(ee),!0},q=()=>{for(V();W(););},ce=(X=Io)=>{V(),x.current=setTimeout(()=>{if(x.current=null,$())return;const K=Mo(),[F]=A.current;if(!F)return;if(F.focusTarget!==K){A.current=[{...F,focusTarget:K},...A.current.slice(1)],ce(wo);return}W()&&Y()&&ce(wo)},X)},_e=(X,K,F)=>{const ee={eventKeys:K,parts:X,focusTarget:Mo(),dedupeKey:F?F.dedupeKey??void 0:K[0]},de=K.length===0?-1:A.current.findIndex(({eventKeys:fe})=>Rn(fe,K));de>=0?A.current=A.current.map((fe,xe)=>xe===de?{...ee,dedupeKey:F?ee.dedupeKey:fe.dedupeKey}:fe):A.current=[...A.current,ee],ce()},L=(X,K,F)=>{if(X!=="messagesUpdated"||K.length===0)return!1;const ee=Date.now(),de=k.current.find(fe=>fe.replaceableUntil>ee&&Rn(fe.eventKeys,K));return de?!Gm(F,de.parts):!1};u.useEffect(()=>{const X=O.current!==o;(!t||!d||X)&&(w.current=!1,I.current.clear(),G(),k.current=[],R.current.clear(),V(),X&&(O.current=o),!t||!d)||w.current||(w.current=!0,O.current=o,b.current={isClosed:a,isHandedOff:l,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:Ln(C)},R.current=new Set(s.flatMap(K=>{if(!Ve.isStreaming(K))return[];const F="sender"in K?K.sender:void 0;return(F==null?void 0:F.userId)===E.current.currentUserId?[]:Kn(K)})),I.current=zm(s))},[e,t,o,d,m,a,l,v]),u.useEffect(()=>{const X=(K,F)=>{const ee=E.current,de=Kn(K),fe=hi(K);if(fe!=null){if(I.current.has(fe))return;I.current.add(fe),e({event:"csatDisplayed"});return}if(Ve.isStreaming(K)){de.forEach(B=>{R.current.add(B)});return}const xe=de.filter(B=>R.current.has(B)),Oe=F==="messagesUpdated"&&xe.length>0;Oe&&xe.forEach(B=>{R.current.delete(B)});const ke=F==="messagesUpdated"&&A.current.some(({eventKeys:B})=>Rn(B,de)),T=To(K,ee.stringSet,ee.format),M=L(F,de,T);if(!Oe&&F!=="messagesAdded"&&!ke&&!M)return;const N=M?{dedupeKey:null}:void 0;if(Oe||$()||ke){_e(T,[...new Set([...xe,...de])],N);return}if(M){_e(T,de,N);return}Y()&&q();const j=de[0];e({event:"newMessage",...T},j?{dedupeKey:j}:void 0)};return _(K=>{if(!w.current||K.kind==="initialized"||!Nu(K.source))return;const F=E.current.currentUserId;for(const ee of K.messages)ee&&Lu(ee,F)&&X(ee,K.kind)})},[e,_]),u.useEffect(()=>{w.current&&($()||Y()&&ce())},[f,h]),u.useEffect(()=>()=>{V()},[]),u.useEffect(()=>{if(!w.current)return;const X=b.current,K=X.outgoingMessageStatuses;X.outgoingMessageStatuses=Ln(C),C.some(({key:ee,sendingStatus:de})=>{const fe=K.get(ee);return fe!==void 0&&fe!=="failed"&&de==="failed"})&&e({event:"sendFailed"})},[e,v]),u.useEffect(()=>{if(!w.current)return;const X=b.current;a&&!X.isClosed&&e({event:"conversationClosed"}),X.isClosed=a},[e,a]),u.useEffect(()=>{if(!w.current)return;const X=b.current;l&&!X.isHandedOff&&e({event:"agentConnected",agentName:c}),X.isHandedOff=l},[c,e,l]),u.useEffect(()=>{if(!w.current)return;const X=b.current;m&&f!=="ai_responding"&&(!X.inputDisabled||X.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),X.inputDisabled=m,X.inputDisabledBy=f},[e,m,f])},Wm=()=>{const{channelSource:e}=Se(),t=Rs(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},qm=e=>{const{announceStatus:t,announcementsEnabled:n}=Ke();Gc(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Km=()=>{const e=Wm();qm(e)},Q=({type:e,size:t=24,className:n,color:r})=>{const{icons:o}=vd(),s=o[e];return i.createElement(jm,{className:n},i.createElement(s,{size:t,color:r??g.color.primary.main,flipInRtl:hd.has(e)}))},jm=p.default.span.attrs({"aria-hidden":"true"})`
81
81
  display: inline-flex;
82
82
  &:focus {
83
83
  outline: none;
84
84
  }
85
- `,zm=.75,hi=6,Ym=hi*2;let jn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(jn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Wm=e=>jn?Array.from(jn.segment(e),t=>t.segment):[...e],qm=e=>{const t=Math.floor(e.length*zm),n=Math.max(0,e.length-hi);return Math.max(t,n)},ks=(e,t="")=>{if(e.length<Ym)return{start:e+t,end:""};const n=Wm(e),r=qm(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Km=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return ks(t);const s=t.slice(0,n),o=t.slice(n);return ks(s,o)},fi=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>Km(e),[e]);return r?i.createElement(jm,null,i.createElement(Xm,{...t},n),i.createElement(Zm,{...t},r)):i.createElement($,{...t},n)},jm=p.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,Xm=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,Zm=p.default($)`flex-shrink:0;white-space:nowrap;`,vr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:a})=>{const{colors:l}=D.useTheme(),{conversation:c}=se(),d=o?c.file.buttonLikePreview({name:e,mimeType:t,selected:a,onActivate:o}):c.file.preview({name:e,mimeType:t,selected:a});return i.createElement(Jm,{...d.props,$clickable:!!o},i.createElement(eh,{$bgColor:s??l.base.primary},i.createElement(Q,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(th,null,i.createElement(fi,{variant:"button",color:g.themedColor.textHighEmphasis},e),i.createElement($,{color:g.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},Jm=p.default.div`border:none;border-radius:12px;gap:8px;width:${te.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${g.themedColor.textDisabled};background-color:${g.themedColor.bg_50_600};${({$clickable:e})=>e&&Qm}`,Qm=D.css`cursor:pointer;${Se}&:hover{background-color:${g.themedColor.bg_100_500};}`,eh=p.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,th=p.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function nh({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(rh,null,i.createElement(vr,{name:e.name,mimeType:e.type,type:nr(e.name,e.type),onClick:r}),t)}const rh=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,Ye=`${Ne}-incoming-msg`,sh=`${Ne}-marked-text`;function oh({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=se(),o=e.type.startsWith("image"),a=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),l=a?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:a}):s.file.preview({name:e.name,mimeType:e.type}),c=()=>o?i.createElement(lh,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(ch,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(c){const d={id:`${Ye}-media-body`,...l.props};return i.createElement(ih,null,i.createElement(ah,{...d},c(),l.descriptionNode),r)}return null}const ih=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,ah=p.default.div`width:${te.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${J.light`
85
+ `,Xm=.75,gi=6,Zm=gi*2;let jn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(jn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Jm=e=>jn?Array.from(jn.segment(e),t=>t.segment):[...e],Qm=e=>{const t=Math.floor(e.length*Xm),n=Math.max(0,e.length-gi);return Math.max(t,n)},ko=(e,t="")=>{if(e.length<Zm)return{start:e+t,end:""};const n=Jm(e),r=Qm(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},ef=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return ko(t);const o=t.slice(0,n),s=t.slice(n);return ko(o,s)},pi=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>ef(e),[e]);return r?i.createElement(tf,null,i.createElement(nf,{...t},n),i.createElement(rf,{...t},r)):i.createElement(P,{...t},n)},tf=p.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,nf=p.default(P)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,rf=p.default(P)`flex-shrink:0;white-space:nowrap;`,vr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:o,onClick:s,selected:a})=>{const{colors:l}=D.useTheme(),{conversation:c}=oe(),d=s?c.file.buttonLikePreview({name:e,mimeType:t,selected:a,onActivate:s}):c.file.preview({name:e,mimeType:t,selected:a});return i.createElement(of,{...d.props,$clickable:!!s},i.createElement(af,{$bgColor:o??l.base.primary},i.createElement(Q,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(lf,null,i.createElement(pi,{variant:"button",color:g.themedColor.textHighEmphasis},e),i.createElement(P,{color:g.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},of=p.default.div`border:none;border-radius:12px;gap:8px;width:${ne.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${g.themedColor.textDisabled};background-color:${g.themedColor.bg_50_600};${({$clickable:e})=>e&&sf}`,sf=D.css`cursor:pointer;${Ae}&:hover{background-color:${g.themedColor.bg_100_500};}`,af=p.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,lf=p.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function cf({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(uf,null,i.createElement(vr,{name:e.name,mimeType:e.type,type:tr(e.name,e.type),onClick:r}),t)}const uf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ne.GAP_GROUPED}px;`,We=`${Ne}-incoming-msg`,df=`${Ne}-marked-text`;function mf({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:o}=oe(),s=e.type.startsWith("image"),a=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),l=a?o.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:a}):o.file.preview({name:e.name,mimeType:e.type}),c=()=>s?i.createElement(gf,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(pf,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(c){const d={id:`${We}-media-body`,...l.props};return i.createElement(ff,null,i.createElement(hf,{...d},c(),l.descriptionNode),r)}return null}const ff=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ne.GAP_GROUPED}px;`,hf=p.default.div`width:${ne.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${J.light`
86
86
  background-color: ${g.color.background100};
87
87
  `}
88
88
  ${J.dark`
89
89
  background-color: ${g.color.background400};
90
90
  `}
91
- `,lh=p.default.img`width:100%;height:100%;object-fit:cover;`,ch=p.default.video`width:100%;height:100%;object-fit:cover;`,it=({className:e,children:t,size:n=26})=>i.createElement(uh,{className:e,$size:n},t??i.createElement(Q,{type:"spinner",size:n})),uh=p.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>He(e)};height:${({$size:e})=>He(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,gi=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=se(),s=e.length;if(s===0)return null;const o=Cl(s),a=!!n&&!t;return i.createElement(mh,{$width:te.BODY_MAX_WIDTH,$columns:o},e.map((l,c)=>{const{columnSpan:d}=vl({index:c,itemCount:s}),m=l.name||"",h=()=>{t||n==null||n(c)},f=l.type??"image/*",E=a?r.file.buttonLikePreview({name:m,mimeType:f,onActivate:h},c):r.file.preview({name:m,mimeType:f});return i.createElement(hh,{key:l.url,$clickable:a,$itemSpan:d,$isPending:t,...E.props},i.createElement(dh,{src:l.url,alt:l.name||""}),t&&i.createElement(fh,null),E.descriptionNode)}))},dh=({src:e,alt:t})=>{const[n,r]=u.useState(!1),[s,o]=u.useState(!1);return i.createElement(i.Fragment,null,!n&&!s&&i.createElement(gh,null,i.createElement(it,{size:20},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&i.createElement(ph,null,i.createElement(Q,{type:"photo",color:"textLowEmphasis",size:24})),!s&&i.createElement(_h,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},mh=p.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,hh=p.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${J.light`
91
+ `,gf=p.default.img`width:100%;height:100%;object-fit:cover;`,pf=p.default.video`width:100%;height:100%;object-fit:cover;`,at=({className:e,children:t,size:n=26})=>i.createElement(_f,{className:e,$size:n},t??i.createElement(Q,{type:"spinner",size:n})),_f=p.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ge(e)};height:${({$size:e})=>Ge(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,_i=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=oe(),o=e.length;if(o===0)return null;const s=Al(o),a=!!n&&!t;return i.createElement(bf,{$width:ne.BODY_MAX_WIDTH,$columns:s},e.map((l,c)=>{const{columnSpan:d}=xl({index:c,itemCount:o}),m=l.name||"",f=()=>{t||n==null||n(c)},h=l.type??"image/*",_=a?r.file.buttonLikePreview({name:m,mimeType:h,onActivate:f},c):r.file.preview({name:m,mimeType:h});return i.createElement(Cf,{key:l.url,$clickable:a,$itemSpan:d,$isPending:t,..._.props},i.createElement(Ef,{src:l.url,alt:l.name||""}),t&&i.createElement(vf,null),_.descriptionNode)}))},Ef=({src:e,alt:t})=>{const[n,r]=u.useState(!1),[o,s]=u.useState(!1);return i.createElement(i.Fragment,null,!n&&!o&&i.createElement(yf,null,i.createElement(at,{size:20},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:20}))),o&&i.createElement(Sf,null,i.createElement(Q,{type:"photo",color:"textLowEmphasis",size:24})),!o&&i.createElement(Af,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>s(!0)}))},bf=p.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Cf=p.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${J.light`
92
92
  background-color: ${g.color.background100};
93
93
  `}
94
94
  ${J.dark`
@@ -111,19 +111,19 @@
111
111
  }
112
112
  `}
113
113
  }
114
- `,fh=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${g.color.overlay.dark};pointer-events:none;`,pi=p.default.div`display:flex;align-items:center;justify-content:center;`,gh=p.default(pi)`position:absolute;inset:0;`,ph=p.default(pi)`position:absolute;inset:0;${J.light`
114
+ `,vf=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${g.color.overlay.dark};pointer-events:none;`,Ei=p.default.div`display:flex;align-items:center;justify-content:center;`,yf=p.default(Ei)`position:absolute;inset:0;`,Sf=p.default(Ei)`position:absolute;inset:0;${J.light`
115
115
  background-color: ${g.color.background200};
116
116
  `}
117
117
  ${J.dark`
118
118
  background-color: ${g.color.background500};
119
119
  `}
120
- `,_h=p.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Eh=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=o=>{const a=e[o];a&&(r?r({files:e,index:o}):n&&n({url:a.url,type:a.type||"image/*"}))};return i.createElement(bh,null,i.createElement(gi,{images:e,onClickImage:s}),t)},bh=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,Ch="✱",_i=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Ch}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${sh} aria-label="masked-text">${o}</span>`:n)},vh=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),Rs=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)}}},yh=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs"))).MarkdownText})),Os=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function Sh(e){var s,o;const t=e.maxBodyWidth??te.BODY_MAX_WIDTH,n=u.useMemo(()=>ga(e.message,_i),[e.message]),r={id:`${Ye}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor,$surface:e.surface??"bubble"};return n.length===0?e.children?i.createElement(Ls,{...r},e.children):null:i.createElement(Ls,{...r},n.map((a,l)=>a.type==="text"?i.createElement(Ns,{key:l,variant:"body3"},i.createElement(wt,{fallback:a.value},i.createElement(yh,{onClickImage:c=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:c,type:"image/*"})}},a.value))):a.type==="code"?Os?i.createElement(wt,{key:l,fallback:i.createElement(Ns,{variant:"body3"},a.value)},i.createElement(Os,{code:a.value,language:a.language})):i.createElement(Ah,{key:l},i.createElement("code",null,a.value)):null),e.children)}const Ls=p.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);${({theme:e,$color:t,$bgColor:n,$surface:r})=>D.css`
120
+ `,Af=p.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,xf=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const o=s=>{const a=e[s];a&&(r?r({files:e,index:s}):n&&n({url:a.url,type:a.type||"image/*"}))};return i.createElement(Tf,null,i.createElement(_i,{images:e,onClickImage:o}),t)},Tf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ne.GAP_GROUPED}px;`,If="✱",bi=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${If}+)`,"g");return e.replace(t,(n,r,o,s)=>r?n:s?`<span id=${df} aria-label="masked-text">${s}</span>`:n)},wf=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),Ro=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)}}},Mf=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),Lo=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function kf(e){var o,s;const t=e.maxBodyWidth??ne.BODY_MAX_WIDTH,n=u.useMemo(()=>_a(e.message,bi),[e.message]),r={id:`${We}-text-body`,$maxWidth:t,$color:(o=e.customStyle)==null?void 0:o.bubbleContentColor,$bgColor:(s=e.customStyle)==null?void 0:s.bubbleBackgroundColor,$surface:e.surface??"bubble"};return n.length===0?e.children?i.createElement(Oo,{...r},e.children):null:i.createElement(Oo,{...r},n.map((a,l)=>a.type==="text"?i.createElement(No,{key:l,variant:"body3"},i.createElement(wt,{fallback:a.value},i.createElement(Mf,{onClickImage:c=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:c,type:"image/*"})},onClickLink:e.onClickLink},a.value))):a.type==="code"?Lo?i.createElement(wt,{key:l,fallback:i.createElement(No,{variant:"body3"},a.value)},i.createElement(Lo,{code:a.value,language:a.language})):i.createElement(Rf,{key:l},i.createElement("code",null,a.value)):null),e.children)}const Oo=p.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);${({theme:e,$color:t,$bgColor:n,$surface:r})=>D.css`
121
121
  color: ${t||e.colors.messageIncoming.text};
122
122
  ${r==="bubble"?D.css`background-color:${n||e.colors.messageIncoming.background};border-radius:12px;overflow:hidden;padding:12px 0;`:D.css`background-color:transparent;border-radius:0;overflow:visible;padding:0;`}
123
123
  `}
124
124
  transition: max-width 0.3s;
125
125
  overflow-wrap: break-word;
126
- `,Ns=p.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Ah=p.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 Ei({id:e,src:t,size:n=56,onClick:r,style:s,...o}){return i.createElement(xh,{id:e,tabIndex:r?0:void 0,onClick:r,$size:He(n),style:s,...o},t?i.createElement(Th,{src:t,alt:""}):i.createElement(Q,{type:"user",size:n}))}const xh=p.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:${g.themedColor.bg_100_500};&:focus{outline:none;}${Se}`,Th=p.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,Ih=({sender:e,isBotMessage:t})=>{const n=`${Ye}-sender-avatar`;return t&&!e.profileUrl?i.createElement(wh,{id:n},i.createElement(Q,{type:"delight",size:"100%"})):i.createElement(Ei,{id:n,size:te.AVATAR_SIZE,src:e.profileUrl})},wh=p.default.div`flex-shrink:0;width:${te.AVATAR_SIZE}px;height:${te.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;}}`,Mh=({sender:e})=>i.createElement(kh,{id:`${Ye}-sender-name`,variant:"caption1",color:g.themedColor.textMidEmphasis},e.nickname),kh=p.default($)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Rh=({createdAt:e})=>{const{stringSet:t,format:n}=oe();return e?i.createElement($,{id:`${Ye}-sent-time`,variant:"caption4",color:g.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},bi="(prefers-reduced-motion: reduce)",Oh=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(bi).matches,Ci=()=>{const[e,t]=u.useState(Oh);return u.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(bi);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},Lh=({thinkingMessage:e,customStyle:t})=>{const n=Ci();return e?i.createElement($h,{$prefersReducedMotion:n},i.createElement(Ph,null,e),!n&&i.createElement(Fh,null)):i.createElement(Nh,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>i.createElement(Dh,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},Nh=p.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};`,Dh=p.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;}`,$h=p.default.div.attrs({id:`${Ye}-typing-indicator`})`
126
+ `,No=p.default(P)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Rf=p.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 Ci({id:e,src:t,size:n=56,onClick:r,style:o,...s}){return i.createElement(Lf,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ge(n),style:o,...s},t?i.createElement(Of,{src:t,alt:""}):i.createElement(Q,{type:"user",size:n}))}const Lf=p.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:${g.themedColor.bg_100_500};&:focus{outline:none;}${Ae}`,Of=p.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,Nf=({sender:e,isBotMessage:t})=>{const n=`${We}-sender-avatar`;return t&&!e.profileUrl?i.createElement(Df,{id:n},i.createElement(Q,{type:"delight",size:"100%"})):i.createElement(Ci,{id:n,size:ne.AVATAR_SIZE,src:e.profileUrl})},Df=p.default.div`flex-shrink:0;width:${ne.AVATAR_SIZE}px;height:${ne.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;}}`,$f=({sender:e})=>i.createElement(Pf,{id:`${We}-sender-name`,variant:"caption1",color:g.themedColor.textMidEmphasis},e.nickname),Pf=p.default(P)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Ff=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?i.createElement(P,{id:`${We}-sent-time`,variant:"caption4",color:g.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},vi="(prefers-reduced-motion: reduce)",Bf=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(vi).matches,yi=()=>{const[e,t]=u.useState(Bf);return u.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(vi);t(n.matches);const r=o=>{t(o.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},Uf=({thinkingMessage:e,customStyle:t})=>{const n=yi();return e?i.createElement(zf,{$prefersReducedMotion:n},i.createElement(Vf,null,e),!n&&i.createElement(Yf,null)):i.createElement(Hf,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>i.createElement(Gf,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},Hf=p.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};`,Gf=p.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;}`,zf=p.default.div.attrs({id:`${We}-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
- `,Ph=p.default($).attrs({variant:"body3"})`
138
+ `,Vf=p.default(P).attrs({variant:"body3"})`
139
139
  white-space: pre-wrap;
140
140
  word-break: break-word;
141
141
  color: ${g.themedColor.textHighEmphasis};
142
- `,Fh=p.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=Yr(e.colors.base.background,.5),n=Yr(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
143
- `,Bh=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Er(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return i.createElement(Uh,{id:`${Ye}-ext-cta-button`,onClick:r},i.createElement(Hh,{variant:"button"},n.label))},Uh=p.default.button.attrs({type:"button"})`
142
+ `,Yf=p.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=Vr(e.colors.base.background,.5),n=Vr(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
143
+ `,Wf=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Er(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return i.createElement(qf,{id:`${We}-ext-cta-button`,onClick:r},i.createElement(Kf,{variant:"button"},n.label))},qf=p.default.button.attrs({type:"button"})`
144
144
  all: unset;
145
145
  display: flex;
146
146
  width: 100%;
@@ -156,8 +156,8 @@
156
156
  background-color: ${g.color.ondark.textDisabled};
157
157
  `}
158
158
 
159
- ${Se}
160
- `,Hh=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Gh=({extendedMessagePayload:e,onClickCitation:t=n=>Er(n.link)})=>{const{stringSet:n}=oe(),{theme:r}=ur(),s=e==null?void 0:e.citations;return!s||s.length===0?null:i.createElement(Vh,{id:`${Ye}-ext-citation`},i.createElement(zh,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),i.createElement(Yh,null,s.map((o,a)=>i.createElement(qh,{key:`${o.embedding_id}-${a}`,onClick:()=>t(o)},i.createElement(Q,{type:"source",size:16,color:r.colors.messageIncoming.text}),i.createElement(Wh,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},Vh=p.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,zh=p.default($)`opacity:0.5;`,Yh=p.default.div`display:flex;flex-direction:column;gap:8px;`,Wh=p.default($)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,qh=p.default.button.attrs({type:"button"})`
159
+ ${Ae}
160
+ `,Kf=p.default(P)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,jf=e=>i.createElement(i.Fragment,null),Xf=({extendedMessagePayload:e,onClickCitation:t=n=>Er(n.link)})=>{const{stringSet:n}=se(),{theme:r}=ur(),o=e==null?void 0:e.citations;return!o||o.length===0?null:i.createElement(Zf,{id:`${We}-ext-citation`},i.createElement(Jf,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),i.createElement(Qf,null,o.map((s,a)=>i.createElement(th,{key:`${s.embedding_id}-${a}`,onClick:()=>t(s)},i.createElement(Q,{type:"source",size:16,color:r.colors.messageIncoming.text}),i.createElement(eh,{variant:"body3",color:r.colors.messageIncoming.text},s.title)))))},Zf=p.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,Jf=p.default(P)`opacity:0.5;`,Qf=p.default.div`display:flex;flex-direction:column;gap:8px;`,eh=p.default(P)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,th=p.default.button.attrs({type:"button"})`
161
161
  background: none;
162
162
  border: none;
163
163
  padding: 0;
@@ -172,25 +172,25 @@
172
172
  &:hover {
173
173
  opacity: 0.5;
174
174
  }
175
- `,Kh=e=>i.createElement(i.Fragment,null),jh=({visible:e,onClose:t,children:n,"aria-label":r})=>i.createElement(nt,{portalContainerId:Ee.WINDOW,visible:e,onClose:t,"aria-label":r},i.createElement(Qh,null,n)),Xh=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>i.createElement(Zh,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&i.createElement(Jh,null,i.createElement(Q,{type:n,size:24,color:g.themedColor.primary})),s),Je=Object.assign(jh,{ActionItem:Xh}),Zh=p.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?g.themedColor.error:g.themedColor.textHighEmphasis};${Se}`,Jh=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Qh=p.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};`,Xn=e=>`${e}-filled`,ef=e=>e==="good"?Ie.AIAgentMessageFeedbackRating.GOOD:Ie.AIAgentMessageFeedbackRating.BAD,yr=D.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,Vt={good:{onlight:g.color.secondary.dark,ondark:g.color.secondary.light},bad:{onlight:g.color.error.dark,ondark:g.color.error.light}},tf={good:g.themedColor.secondary,bad:g.themedColor.error},vi=e=>D.css`color:${Vt[e].onlight};border-color:${Vt[e].onlight};${J.dark`
175
+ `,nh=e=>i.createElement(i.Fragment,null),rh=({visible:e,onClose:t,children:n,"aria-label":r})=>i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:e,onClose:t,"aria-label":r},i.createElement(ah,null,n)),oh=({onClick:e,destructive:t,icon:n,initialFocus:r,children:o})=>i.createElement(sh,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&i.createElement(ih,null,i.createElement(Q,{type:n,size:24,color:g.themedColor.primary})),o),Je=Object.assign(rh,{ActionItem:oh}),sh=p.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?g.themedColor.error:g.themedColor.textHighEmphasis};${Ae}`,ih=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,ah=p.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};`,Xn=e=>`${e}-filled`,lh=e=>e==="good"?be.AIAgentMessageFeedbackRating.GOOD:be.AIAgentMessageFeedbackRating.BAD,yr=D.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,Vt={good:{onlight:g.color.secondary.dark,ondark:g.color.secondary.light},bad:{onlight:g.color.error.dark,ondark:g.color.error.light}},ch={good:g.themedColor.secondary,bad:g.themedColor.error},Si=e=>D.css`color:${Vt[e].onlight};border-color:${Vt[e].onlight};${J.dark`
176
176
  color: ${Vt[e].ondark};
177
177
  border-color: ${Vt[e].ondark};
178
178
  `}
179
- `,nf=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:a=!1})=>{const{stringSet:l}=oe(),{conversation:c}=se(),{rootElement:d}=Xo(),m=st(d),[h,f]=u.useState(r),[E,v]=u.useState(s),[y,C]=u.useState(!1),_=u.useRef(!1),b=h??r??"good",A=c.feedback;u.useLayoutEffect(()=>{e?(f(r),v(s)):(f(void 0),v(""))},[e,r,s]),u.useEffect(()=>{if(!e)return;const I=O=>{const U=O;U.metaKey||U.altKey||U.ctrlKey||(_.current=!0)},w=()=>{_.current=!1,C(!1)};return m.addEventListener("keydown",I),m.addEventListener("pointerdown",w),()=>{m.removeEventListener("keydown",I),m.removeEventListener("pointerdown",w)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:E.trim()||void 0}),t())},L=()=>{t()};if(!e)return null;const k={feedback:A.container()};return i.createElement(nt,{portalContainerId:Ee.WINDOW,visible:e,onClose:L,"aria-label":l.FEEDBACK_TITLE},i.createElement(rf,null,i.createElement(sf,null,i.createElement($,{variant:"h2",color:g.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),i.createElement(of,null,i.createElement(af,{...k.feedback.props},["good","bad"].map(I=>{const w=h===I,O=I==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD,U=A.button(I,w);return i.createElement(u.Fragment,{key:I},i.createElement(lf,{type:"button",$selected:w,$rating:I,...U.props,onClick:()=>f(I),"data-sb-initial-focus":I===b?"true":void 0},i.createElement(Q,{type:w?Xn(I):I,size:24,color:"currentColor"}),i.createElement($,{variant:"caption1",color:"currentColor"},O)),U.descriptionNode)}),k.feedback.descriptionNode),a&&i.createElement(cf,null,i.createElement($,{variant:"caption3",color:g.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),i.createElement(uf,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:E,onChange:I=>v(I.target.value),onFocus:()=>C(_.current),onBlur:()=>C(!1),maxLength:100,$focusVisible:y,"data-focus-visible":y?"true":"false"}))),i.createElement(df,null,i.createElement(mf,{onClick:L},i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),i.createElement(hf,{onClick:T,disabled:!h},i.createElement($,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT)))))},rf=p.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,sf=p.default.div`padding:24px;`,of=p.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,af=p.default.div`display:flex;gap:4px;`,lf=p.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${g.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:${g.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&vi(t)}${yr}`,cf=p.default.div`display:flex;flex-direction:column;gap:6px;`,uf=p.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${g.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${g.themedColor.textHighEmphasis};background-color:${g.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${g.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&D.css`
179
+ `,uh=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:o="",onSubmit:s,isCommentEnabled:a=!1})=>{const{stringSet:l}=se(),{conversation:c}=oe(),{rootElement:d}=Js(),m=st(d),[f,h]=u.useState(r),[_,y]=u.useState(o),[C,v]=u.useState(!1),b=u.useRef(!1),E=f??r??"good",A=c.feedback;u.useLayoutEffect(()=>{e?(h(r),y(o)):(h(void 0),y(""))},[e,r,o]),u.useEffect(()=>{if(!e)return;const I=O=>{const $=O;$.metaKey||$.altKey||$.ctrlKey||(b.current=!0)},w=()=>{b.current=!1,v(!1)};return m.addEventListener("keydown",I),m.addEventListener("pointerdown",w),()=>{m.removeEventListener("keydown",I),m.removeEventListener("pointerdown",w)}},[m,e]);const x=()=>{f&&(s({rating:f,comment:_.trim()||void 0}),t())},k=()=>{t()};if(!e)return null;const R={feedback:A.container()};return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:e,onClose:k,"aria-label":l.FEEDBACK_TITLE},i.createElement(dh,null,i.createElement(mh,null,i.createElement(P,{variant:"h2",color:g.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),i.createElement(fh,null,i.createElement(hh,{...R.feedback.props},["good","bad"].map(I=>{const w=f===I,O=I==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD,$=A.button(I,w);return i.createElement(u.Fragment,{key:I},i.createElement(gh,{type:"button",$selected:w,$rating:I,...$.props,onClick:()=>h(I),"data-sb-initial-focus":I===E?"true":void 0},i.createElement(Q,{type:w?Xn(I):I,size:24,color:"currentColor"}),i.createElement(P,{variant:"caption1",color:"currentColor"},O)),$.descriptionNode)}),R.feedback.descriptionNode),a&&i.createElement(ph,null,i.createElement(P,{variant:"caption3",color:g.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),i.createElement(_h,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:_,onChange:I=>y(I.target.value),onFocus:()=>v(b.current),onBlur:()=>v(!1),maxLength:100,$focusVisible:C,"data-focus-visible":C?"true":"false"}))),i.createElement(Eh,null,i.createElement(bh,{onClick:k},i.createElement(P,{variant:"button",color:g.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),i.createElement(Ch,{onClick:x,disabled:!f},i.createElement(P,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT)))))},dh=p.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,mh=p.default.div`padding:24px;`,fh=p.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,hh=p.default.div`display:flex;gap:4px;`,gh=p.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${g.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:${g.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Si(t)}${yr}`,ph=p.default.div`display:flex;flex-direction:column;gap:6px;`,_h=p.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${g.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${g.themedColor.textHighEmphasis};background-color:${g.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${g.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&D.css`
180
180
  outline: 2px solid ${g.themedColor.primary};
181
181
  outline-offset: 2px;
182
182
  `}
183
- `,df=p.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,yi=p.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;`,mf=p.default(yi)`background-color:transparent;${yr}`,hf=p.default(yi)`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};}`,ff=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:a})=>{const{stringSet:l}=oe(),{conversation:c}=se(),[d,m]=u.useState(!1),[h,f]=u.useState(!1),[E,v]=u.useState(void 0),[y,C]=u.useState(""),_=u.useRef(null),b=u.useRef(null),A=u.useRef(null),T=u.useRef(!1),L=c.feedback,k=o==null?void 0:o.feedback,I=(k==null?void 0:k.rating)??"none";if(I!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const O=K=>{K&&Re(()=>{const ae=K==="good"?_.current:b.current;ae==null||ae.focus()})},U=({restoreTrigger:K=!0}={})=>{f(!1),K&&O(A.current)},Y=K=>{I==="none"?(v(K),C(""),m(!0)):(A.current=K,f(!0))},V=()=>{a==null||a(null),U()},z=()=>{T.current=!0,U({restoreTrigger:!1}),v(k==null?void 0:k.rating),C((k==null?void 0:k.comment)??""),m(!0)},H=K=>{T.current=!1,a==null||a(K),m(!1),O(A.current)},W=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&I!=="none"?i.createElement(Ds,{role:"presentation",$horizontal:!0},i.createElement(gf,null,i.createElement(Q,{type:Xn(I),size:12,color:tf[I]})),(k==null?void 0:k.comment)&&i.createElement($s,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):i.createElement(i.Fragment,null,i.createElement(Ds,{role:"presentation"},i.createElement(pf,{role:"presentation"},["good","bad"].map(K=>{const ae=I===K,M=L.button(K,ae);return i.createElement(u.Fragment,{key:K},i.createElement(_f,{$selected:ae,$rating:K,ref:K==="good"?_:b,...M.props,onClick:()=>Y(K)},i.createElement(Q,{type:ae?Xn(K):K,size:14,color:"currentColor"})),M.descriptionNode)})),I!=="none"&&(k==null?void 0:k.comment)&&i.createElement($s,{variant:"caption2"},k.comment)),i.createElement(Je,{visible:h,onClose:U,...L.optionsBottomSheet().props},i.createElement(Je.ActionItem,{onClick:z,initialFocus:!0},l.FEEDBACK_EDIT),i.createElement(Je.ActionItem,{onClick:V,destructive:!0},l.FEEDBACK_REMOVE)),i.createElement(nf,{visible:d,onClose:W,isEdit:I!=="none",initialRating:E,initialComment:y,onSubmit:H,isCommentEnabled:s}))},Ds=p.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:${te.BODY_MAX_WIDTH}px;`,gf=p.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,pf=p.default.div`display:flex;gap:2px;`,_f=p.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:${g.themedColor.textMidEmphasis};border:1px solid ${g.color.background200};background-color:transparent;${J.dark`
183
+ `,Eh=p.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Ai=p.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;`,bh=p.default(Ai)`background-color:transparent;${yr}`,Ch=p.default(Ai)`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};}`,vh=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:o,extendedMessagePayload:s,onFeedbackUpdate:a})=>{const{stringSet:l}=se(),{conversation:c}=oe(),[d,m]=u.useState(!1),[f,h]=u.useState(!1),[_,y]=u.useState(void 0),[C,v]=u.useState(""),b=u.useRef(null),E=u.useRef(null),A=u.useRef(null),x=u.useRef(!1),k=c.feedback,R=s==null?void 0:s.feedback,I=(R==null?void 0:R.rating)??"none";if(I!=="none"?!1:!!(n||!e||!r||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const O=q=>{q&&Le(()=>{const ce=q==="good"?b.current:E.current;ce==null||ce.focus()})},$=({restoreTrigger:q=!0}={})=>{h(!1),q&&O(A.current)},V=q=>{I==="none"?(y(q),v(""),m(!0)):(A.current=q,h(!0))},H=()=>{a==null||a(null),$()},Y=()=>{x.current=!0,$({restoreTrigger:!1}),y(R==null?void 0:R.rating),v((R==null?void 0:R.comment)??""),m(!0)},G=q=>{x.current=!1,a==null||a(q),m(!1),O(A.current)},W=()=>{m(!1),x.current&&(x.current=!1,h(!0))};return t&&I!=="none"?i.createElement(Do,{role:"presentation",$horizontal:!0},i.createElement(yh,null,i.createElement(Q,{type:Xn(I),size:12,color:ch[I]})),(R==null?void 0:R.comment)&&i.createElement($o,{variant:"caption2",style:{lineHeight:"16px"}},R.comment)):i.createElement(i.Fragment,null,i.createElement(Do,{role:"presentation"},i.createElement(Sh,{role:"presentation"},["good","bad"].map(q=>{const ce=I===q,_e=k.button(q,ce);return i.createElement(u.Fragment,{key:q},i.createElement(Ah,{$selected:ce,$rating:q,ref:q==="good"?b:E,..._e.props,onClick:()=>V(q)},i.createElement(Q,{type:ce?Xn(q):q,size:14,color:"currentColor"})),_e.descriptionNode)})),I!=="none"&&(R==null?void 0:R.comment)&&i.createElement($o,{variant:"caption2"},R.comment)),i.createElement(Je,{visible:f,onClose:$,...k.optionsBottomSheet().props},i.createElement(Je.ActionItem,{onClick:Y,initialFocus:!0},l.FEEDBACK_EDIT),i.createElement(Je.ActionItem,{onClick:H,destructive:!0},l.FEEDBACK_REMOVE)),i.createElement(uh,{visible:d,onClose:W,isEdit:I!=="none",initialRating:_,initialComment:C,onSubmit:G,isCommentEnabled:o}))},Do=p.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:${ne.BODY_MAX_WIDTH}px;`,yh=p.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,Sh=p.default.div`display:flex;gap:2px;`,Ah=p.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:${g.themedColor.textMidEmphasis};border:1px solid ${g.color.background200};background-color:transparent;${J.dark`
184
184
  border: 1px solid ${g.color.background400};
185
185
  `}
186
186
 
187
- ${({$selected:e,$rating:t})=>e&&vi(t)}
187
+ ${({$selected:e,$rating:t})=>e&&Si(t)}
188
188
 
189
189
  ${yr}
190
- `,$s=p.default($)`color:${g.themedColor.textMidEmphasis};${J.dark`
190
+ `,$o=p.default(P)`color:${g.themedColor.textMidEmphasis};${J.dark`
191
191
  color: ${g.themedColor.textHighEmphasis};
192
192
  `}
193
- `,Sr=D.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;${Se}&:disabled{cursor:not-allowed;}`,Ps=p.default.button`${Sr};background-color:${g.themedColor.primary};color:${g.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,Ef=p.default.button`${Sr};color:${g.themedColor.primary};${J.light`
193
+ `,Sr=D.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;${Ae}&:disabled{cursor:not-allowed;}`,Po=p.default.button`${Sr};background-color:${g.themedColor.primary};color:${g.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,xh=p.default.button`${Sr};color:${g.themedColor.primary};${J.light`
194
194
  background-color: ${g.color.background50};
195
195
  `};
196
196
  ${J.dark`
@@ -200,7 +200,7 @@
200
200
  &:hover:not(:disabled) {
201
201
  opacity: 0.9;
202
202
  }
203
- `,bf=p.default.button`${Sr};background-color:transparent;color:${g.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,Cf=e=>{switch(e){case"primary":return Ps;case"secondary":return Ef;case"clear":return bf;default:return Ps}},vf=p.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);}}`,yf=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...a})=>{const l=()=>{switch(n){case"primary":return g.themedColor.textHighEmphasisInverse;case"secondary":return g.themedColor.primary;case"clear":return g.themedColor.textHighEmphasis;default:return g.themedColor.textHighEmphasisInverse}},c=Cf(n);return i.createElement(c,{onClick:t,disabled:r||s,className:o,...a},s?i.createElement(vf,null,i.createElement(Q,{type:"spinner",size:22,color:l()})):i.createElement($,{variant:"button",color:l()},e))},Sf=({children:e,className:t,style:n,id:r,role:s})=>i.createElement($,{variant:"caption4",color:g.themedColor.error,className:t,style:n,id:r,role:s},e),Af=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:a}=oe();return i.createElement($,{id:e,variant:"caption3",color:g.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&i.createElement("span",{style:{color:g.themedColor.textLowEmphasis}},` (${a.OPTIONAL})`))},xf=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:a=!1,max:l,...c})=>{const d=h=>{const E=h.target.value.replace(/[^0-9.-]/g,""),v=E.split("."),C=v.length>1?v[0]+"."+v.slice(1).join("").replace(/\./g,""):E;if(h.target.value=C,C===""||C==="-")t==null||t(null);else{const _=Number(C);if(!isNaN(_)){if(l!==void 0&&_>l)return;t==null||t(_)}}},m=e==null?"":String(e);return i.createElement(kf,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:a||s,inputMode:"decimal",$error:r,$submitted:s,...c})},Tf=D.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;${Se}&::placeholder{color:${g.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,If=D.css`color:${g.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${J.light`
203
+ `,Th=p.default.button`${Sr};background-color:transparent;color:${g.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,Ih=e=>{switch(e){case"primary":return Po;case"secondary":return xh;case"clear":return Th;default:return Po}},wh=p.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);}}`,Mh=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:o=!1,className:s,...a})=>{const l=()=>{switch(n){case"primary":return g.themedColor.textHighEmphasisInverse;case"secondary":return g.themedColor.primary;case"clear":return g.themedColor.textHighEmphasis;default:return g.themedColor.textHighEmphasisInverse}},c=Ih(n);return i.createElement(c,{onClick:t,disabled:r||o,className:s,...a},o?i.createElement(wh,null,i.createElement(Q,{type:"spinner",size:22,color:l()})):i.createElement(P,{variant:"button",color:l()},e))},kh=({children:e,className:t,style:n,id:r,role:o})=>i.createElement(P,{variant:"caption4",color:g.themedColor.error,className:t,style:n,id:r,role:o},e),Rh=({id:e,children:t,className:n,style:r,required:o,"aria-hidden":s})=>{const{stringSet:a}=se();return i.createElement(P,{id:e,variant:"caption3",color:g.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":s},t,!o&&i.createElement("span",{style:{color:g.themedColor.textLowEmphasis}},` (${a.OPTIONAL})`))},Lh=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:o=!1,className:s,disabled:a=!1,max:l,...c})=>{const d=f=>{const _=f.target.value.replace(/[^0-9.-]/g,""),y=_.split("."),v=y.length>1?y[0]+"."+y.slice(1).join("").replace(/\./g,""):_;if(f.target.value=v,v===""||v==="-")t==null||t(null);else{const b=Number(v);if(!isNaN(b)){if(l!==void 0&&b>l)return;t==null||t(b)}}},m=e==null?"":String(e);return i.createElement(Ph,{type:"text",value:m,onChange:d,placeholder:n,className:s,disabled:a||o,inputMode:"decimal",$error:r,$submitted:o,...c})},Oh=D.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;${Ae}&::placeholder{color:${g.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,Nh=D.css`color:${g.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${J.light`
204
204
  background-color: ${g.color.ondark.textMidEmphasis};
205
205
  `}
206
206
  ${J.dark`
@@ -210,13 +210,13 @@
210
210
  &::placeholder {
211
211
  color: ${g.themedColor.textLowEmphasis};
212
212
  }
213
- `,wf=D.css`border:1px solid ${g.themedColor.error};color:${g.themedColor.textHighEmphasis};${J.light`
213
+ `,Dh=D.css`border:1px solid ${g.themedColor.error};color:${g.themedColor.textHighEmphasis};${J.light`
214
214
  background-color: ${g.color.background50};
215
215
  `}
216
216
  ${J.dark`
217
217
  background-color: ${g.color.onlight.textLowEmphasis};
218
218
  `}
219
- `,Mf=D.css`border:1px solid ${g.themedColor.textDisabled};color:${g.themedColor.textHighEmphasis};${J.light`
219
+ `,$h=D.css`border:1px solid ${g.themedColor.textDisabled};color:${g.themedColor.textHighEmphasis};${J.light`
220
220
  background-color: ${g.color.background50};
221
221
  `}
222
222
  ${J.dark`
@@ -226,12 +226,12 @@
226
226
  &:focus {
227
227
  border-color: ${g.themedColor.primary};
228
228
  }
229
- `,kf=p.default.input`${Tf}${({$error:e,$submitted:t})=>t?If:e?wf:Mf}`,Rf=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:a=>{if(s)return;if(t.includes(a)){const c=t.filter(d=>d!==a);n==null||n(c)}else{if(r&&t.length>=r)return;const c=[...t,a];n==null||n(c)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},Si=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:a}=se(),l=e.multiple===!0,{selectedValues:c,handleOptionClick:d}=Rf(e),m=t.some(h=>c.includes(h.value));return i.createElement(Lf,{className:s,...l?void 0:a.form.singleSelectGroup(o).props},t.map((h,f)=>{const E=c.includes(h.value),v=o?`${o}, ${h.label}`:h.label;return i.createElement(Uf,{key:h.value,type:"button",$active:E,$submitted:n,$error:r,...(l?a.form.multiSelectOption(v,E,n):a.form.singleSelectOption(v,E,n,f,t.length,m,y=>{const C=t[y];C&&d(C.value)})).props,disabled:n,onClick:()=>d(h.value)},i.createElement($,{variant:"caption1",color:Of(E,n)},h.label))}))},Of=(e,t)=>t?e?g.themedColor.textHighEmphasis:g.themedColor.textDisabled:e?g.themedColor.primary:g.themedColor.textMidEmphasis,Lf=p.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,Nf=D.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,Df=D.css`cursor:default;background-color:${g.color.ondark.textMidEmphasis};color:${g.themedColor.textHighEmphasis};${J.dark`
229
+ `,Ph=p.default.input`${Oh}${({$error:e,$submitted:t})=>t?Nh:e?Dh:$h}`,Fh=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:o=!1}=e;return{selectedValues:t,handleOptionClick:a=>{if(o)return;if(t.includes(a)){const c=t.filter(d=>d!==a);n==null||n(c)}else{if(r&&t.length>=r)return;const c=[...t,a];n==null||n(c)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:s=>{r||t!==s&&(n==null||n(s))}}}},xi=e=>{const{options:t,submitted:n=!1,error:r=!1,className:o,groupLabel:s}=e,{conversation:a}=oe(),l=e.multiple===!0,{selectedValues:c,handleOptionClick:d}=Fh(e),m=t.some(f=>c.includes(f.value));return i.createElement(Uh,{className:o,...l?void 0:a.form.singleSelectGroup(s).props},t.map((f,h)=>{const _=c.includes(f.value),y=s?`${s}, ${f.label}`:f.label;return i.createElement(qh,{key:f.value,type:"button",$active:_,$submitted:n,$error:r,...(l?a.form.multiSelectOption(y,_,n):a.form.singleSelectOption(y,_,n,h,t.length,m,C=>{const v=t[C];v&&d(v.value)})).props,disabled:n,onClick:()=>d(f.value)},i.createElement(P,{variant:"caption1",color:Bh(_,n)},f.label))}))},Bh=(e,t)=>t?e?g.themedColor.textHighEmphasis:g.themedColor.textDisabled:e?g.themedColor.primary:g.themedColor.textMidEmphasis,Uh=p.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,Hh=D.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,Gh=D.css`cursor:default;background-color:${g.color.ondark.textMidEmphasis};color:${g.themedColor.textHighEmphasis};${J.dark`
230
230
  background-color: transparent;
231
231
  border: 1px solid white;
232
232
  color: white;
233
233
  `}
234
- `,$f=D.css`cursor:default;${J.light`
234
+ `,zh=D.css`cursor:default;${J.light`
235
235
  background-color: ${g.color.ondark.textMidEmphasis};
236
236
  color: ${g.themedColor.textDisabled};
237
237
  `}
@@ -240,7 +240,7 @@
240
240
  border: 1px solid ${g.color.onlight.textLowEmphasis};
241
241
  color: ${g.themedColor.textDisabled};
242
242
  `}
243
- `,Pf=D.css`cursor:pointer;border:1px solid ${g.themedColor.primary};${J.light`
243
+ `,Vh=D.css`cursor:pointer;border:1px solid ${g.themedColor.primary};${J.light`
244
244
  background-color: ${g.color.background50};
245
245
  color: ${g.themedColor.primary};
246
246
  `}
@@ -248,7 +248,7 @@
248
248
  background-color: ${g.color.onlight.textLowEmphasis};
249
249
  color: ${g.themedColor.primary};
250
250
  `}
251
- `,Ff=D.css`cursor:pointer;border:1px solid ${g.themedColor.textDisabled};${J.light`
251
+ `,Yh=D.css`cursor:pointer;border:1px solid ${g.themedColor.textDisabled};${J.light`
252
252
  background-color: ${g.color.background50};
253
253
  color: ${g.themedColor.textMidEmphasis};
254
254
  `}
@@ -256,10 +256,10 @@
256
256
  background-color: ${g.color.onlight.textLowEmphasis};
257
257
  color: ${g.themedColor.textMidEmphasis};
258
258
  `}
259
- `,Bf=D.css`border-color:${g.themedColor.error}!important;`,Uf=p.default.button`${Nf}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?Df:$f;const r=e?Pf:Ff;return n?D.css`
260
- ${r} ${Bf}
259
+ `,Wh=D.css`border-color:${g.themedColor.error}!important;`,qh=p.default.button`${Hh}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?Gh:zh;const r=e?Vh:Yh;return n?D.css`
260
+ ${r} ${Wh}
261
261
  `:r}}
262
- `,Hf=e=>i.createElement(Si,{...e,multiple:!1}),Gf=e=>i.createElement(Si,{...e,multiple:!0}),Vf=p.default.div`width:100%;height:1px;background-color:${g.themedColor.textDisabled};`,zf=({className:e})=>i.createElement(Vf,{className:e}),Yf=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:a=!1,className:l,disabled:c=!1,maxLength:d,...m})=>{const f={id:e,value:t,onChange:E=>{const v=E.target.value;d&&v.length>d||n==null||n(v)},placeholder:r,className:l,disabled:c||a,maxLength:d,$error:o,$submitted:a,...m};return s==="multi-line"?i.createElement(qf,{...f}):i.createElement(Wf,{...f})},Ai=D.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;${Se}&::placeholder{color:${g.themedColor.textLowEmphasis};}`,xi=D.css`color:${g.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${J.light`
262
+ `,Kh=e=>i.createElement(xi,{...e,multiple:!1}),jh=e=>i.createElement(xi,{...e,multiple:!0}),Xh=p.default.div`width:100%;height:1px;background-color:${g.themedColor.textDisabled};`,Zh=({className:e})=>i.createElement(Xh,{className:e}),Jh=({id:e,value:t="",onChange:n,placeholder:r,variant:o="single-line",error:s=!1,submitted:a=!1,className:l,disabled:c=!1,maxLength:d,...m})=>{const h={id:e,value:t,onChange:_=>{const y=_.target.value;d&&y.length>d||n==null||n(y)},placeholder:r,className:l,disabled:c||a,maxLength:d,$error:s,$submitted:a,...m};return o==="multi-line"?i.createElement(eg,{...h}):i.createElement(Qh,{...h})},Ti=D.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;${Ae}&::placeholder{color:${g.themedColor.textLowEmphasis};}`,Ii=D.css`color:${g.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${J.light`
263
263
  background-color: ${g.color.ondark.textMidEmphasis};
264
264
  `}
265
265
  ${J.dark`
@@ -269,13 +269,13 @@
269
269
  &::placeholder {
270
270
  color: ${g.themedColor.textLowEmphasis};
271
271
  }
272
- `,Ti=D.css`border:1px solid ${g.themedColor.error};color:${g.themedColor.textHighEmphasis};${J.light`
272
+ `,wi=D.css`border:1px solid ${g.themedColor.error};color:${g.themedColor.textHighEmphasis};${J.light`
273
273
  background-color: ${g.color.background50};
274
274
  `}
275
275
  ${J.dark`
276
276
  background-color: ${g.color.onlight.textLowEmphasis};
277
277
  `}
278
- `,Ii=D.css`border:1px solid ${g.themedColor.textDisabled};color:${g.themedColor.textHighEmphasis};${J.light`
278
+ `,Mi=D.css`border:1px solid ${g.themedColor.textDisabled};color:${g.themedColor.textHighEmphasis};${J.light`
279
279
  background-color: ${g.color.background50};
280
280
  `}
281
281
  ${J.dark`
@@ -285,14 +285,14 @@
285
285
  &:focus {
286
286
  border-color: ${g.themedColor.primary};
287
287
  }
288
- `,Wf=p.default.input`${Ai};height:36px;${({$error:e,$submitted:t})=>t?xi:e?Ti:Ii}`,qf=p.default.textarea`${Ai};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?xi:e?Ti:Ii}`,Kf=({children:e,className:t,style:n})=>i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasis,className:t,style:n},e),Ae={Title:Kf,Label:Af,ErrorLabel:Sf,Separator:zf,Button:yf,TextInput:Yf,NumberInput:xf,SingleSelect:Hf,MultiSelect:Gf},jf=1,Xf=new Set(["text","number","single-select","multi-select"]),Zf=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,Jf=e=>{var _;if(!Zf)return null;const t=(_=e.extendedMessagePayload)==null?void 0:_.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=oe(),{conversation:r}=se(),[s,o]=u.useState({submitting:!1,canceling:!1}),[a,l]=u.useState({visible:!1}),{state:c,fields:d,submit:m,cancel:h,updateFieldValue:f}=Lc(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:b=>{var A;return(A=e.onSubmitForm)==null?void 0:A.call(e,{key:t.key,data:b})},onCancel:()=>{var b;return(b=e.onCancelForm)==null?void 0:b.call(e,{key:t.key})}}),E=c==="submitted",v=async()=>{o(b=>({...b,submitting:!0}));try{await m()}catch(b){l({visible:!0,description:b instanceof Error?b.message:n.TRY_AGAIN})}finally{o(b=>({...b,submitting:!1}))}},y=async()=>{o(b=>({...b,canceling:!0}));try{await h()}catch(b){l({visible:!0,description:b instanceof Error?b.message:n.TRY_AGAIN})}finally{o(b=>({...b,canceling:!1}))}},C=u.useMemo(()=>{const b=()=>t.version>jf,A=()=>t.fields.some(T=>!Xf.has(T.type));return b()||A()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:c==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,c,e.isHandedOff,e.isConversationClosed]);return c==="canceled"?null:C.visible?i.createElement(u.Fragment,null,i.createElement(Fs,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH},i.createElement(Ae.Title,null,t.title),i.createElement(Qf,null,d.map(b=>i.createElement(eg,{key:b.key},i.createElement(Ae.Label,{style:{marginBottom:"6px"},required:b.required},b.label),b.type==="text"&&i.createElement(Ae.TextInput,{value:b.value||"",placeholder:b.placeholder,onChange:A=>f(b.key,A),disabled:E,error:!!b.error,submitted:E,variant:b.layout==="multiline"?"multi-line":"single-line",maxLength:b.maxLength,...r.form.textInput(b.label,b.required??!1,E).props}),b.type==="number"&&i.createElement(Ae.NumberInput,{value:b.value||null,placeholder:b.placeholder,onChange:A=>f(b.key,A),disabled:E,error:!!b.error,submitted:E,max:b.max,...r.form.numberInput(b.label,b.required??!1,E).props}),b.type==="single-select"&&i.createElement(Ae.SingleSelect,{options:b.options.map(A=>({label:A,value:A})),value:b.value||"",onChange:A=>f(b.key,A),submitted:E,groupLabel:b.label}),b.type==="multi-select"&&i.createElement(Ae.MultiSelect,{options:b.options.map(A=>({label:A,value:A})),value:b.value||[],onChange:A=>f(b.key,A),submitted:E,maxSelect:b.maxSelect,groupLabel:b.label}),b.error&&i.createElement(Ae.ErrorLabel,{style:{marginTop:"4px"}},b.error)))),i.createElement(Ae.Separator,null),i.createElement(tg,null,i.createElement(Ae.Button,{variant:E?"clear":"primary",...r.form.button(E?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:v,disabled:E||s.canceling,loading:s.submitting},E?n.SUBMITTED:n.BUTTON__SUBMIT),c!=="submitted"&&i.createElement(Ae.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:y,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),i.createElement(fn,{...a,onClose:()=>l({visible:!1,title:""})})):i.createElement(Fs,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH},i.createElement($,{variant:"body3"},C.reason),C.cancelable&&i.createElement(Ae.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:y,loading:s.canceling},n.BUTTON__CANCEL))},Fs=p.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>D.css`
288
+ `,Qh=p.default.input`${Ti};height:36px;${({$error:e,$submitted:t})=>t?Ii:e?wi:Mi}`,eg=p.default.textarea`${Ti};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Ii:e?wi:Mi}`,tg=({children:e,className:t,style:n})=>i.createElement(P,{variant:"button",color:g.themedColor.textHighEmphasis,className:t,style:n},e),Te={Title:tg,Label:Rh,ErrorLabel:kh,Separator:Zh,Button:Mh,TextInput:Jh,NumberInput:Lh,SingleSelect:Kh,MultiSelect:jh},ng=1,rg=new Set(["text","number","single-select","multi-select"]),og=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,sg=e=>{var b;if(!og)return null;const t=(b=e.extendedMessagePayload)==null?void 0:b.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=se(),{conversation:r}=oe(),[o,s]=u.useState({submitting:!1,canceling:!1}),[a,l]=u.useState({visible:!1}),{state:c,fields:d,submit:m,cancel:f,updateFieldValue:h}=Pc(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:E=>{var A;return(A=e.onSubmitForm)==null?void 0:A.call(e,{key:t.key,data:E})},onCancel:()=>{var E;return(E=e.onCancelForm)==null?void 0:E.call(e,{key:t.key})}}),_=c==="submitted",y=async()=>{s(E=>({...E,submitting:!0}));try{await m()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{s(E=>({...E,submitting:!1}))}},C=async()=>{s(E=>({...E,canceling:!0}));try{await f()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{s(E=>({...E,canceling:!1}))}},v=u.useMemo(()=>{const E=()=>t.version>ng,A=()=>t.fields.some(x=>!rg.has(x.type));return E()||A()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:c==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,c,e.isHandedOff,e.isConversationClosed]);return c==="canceled"?null:v.visible?i.createElement(u.Fragment,null,i.createElement(Fo,{$maxWidth:e.maxBodyWidth??ne.BODY_MAX_WIDTH},i.createElement(Te.Title,null,t.title),i.createElement(ig,null,d.map(E=>i.createElement(ag,{key:E.key},i.createElement(Te.Label,{style:{marginBottom:"6px"},required:E.required},E.label),E.type==="text"&&i.createElement(Te.TextInput,{value:E.value||"",placeholder:E.placeholder,onChange:A=>h(E.key,A),disabled:_,error:!!E.error,submitted:_,variant:E.layout==="multiline"?"multi-line":"single-line",maxLength:E.maxLength,...r.form.textInput(E.label,E.required??!1,_).props}),E.type==="number"&&i.createElement(Te.NumberInput,{value:E.value||null,placeholder:E.placeholder,onChange:A=>h(E.key,A),disabled:_,error:!!E.error,submitted:_,max:E.max,...r.form.numberInput(E.label,E.required??!1,_).props}),E.type==="single-select"&&i.createElement(Te.SingleSelect,{options:E.options.map(A=>({label:A,value:A})),value:E.value||"",onChange:A=>h(E.key,A),submitted:_,groupLabel:E.label}),E.type==="multi-select"&&i.createElement(Te.MultiSelect,{options:E.options.map(A=>({label:A,value:A})),value:E.value||[],onChange:A=>h(E.key,A),submitted:_,maxSelect:E.maxSelect,groupLabel:E.label}),E.error&&i.createElement(Te.ErrorLabel,{style:{marginTop:"4px"}},E.error)))),i.createElement(Te.Separator,null),i.createElement(lg,null,i.createElement(Te.Button,{variant:_?"clear":"primary",...r.form.button(_?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:y,disabled:_||o.canceling,loading:o.submitting},_?n.SUBMITTED:n.BUTTON__SUBMIT),c!=="submitted"&&i.createElement(Te.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:C,disabled:o.submitting,loading:o.canceling},n.BUTTON__CANCEL))),i.createElement(gn,{...a,onClose:()=>l({visible:!1,title:""})})):i.createElement(Fo,{$maxWidth:e.maxBodyWidth??ne.BODY_MAX_WIDTH},i.createElement(P,{variant:"body3"},v.reason),v.cancelable&&i.createElement(Te.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:C,loading:o.canceling},n.BUTTON__CANCEL))},Fo=p.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>D.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
- `,Qf=p.default.div`display:flex;flex-direction:column;gap:12px;`,eg=p.default.div`display:flex;flex-direction:column;`,tg=p.default.div`display:flex;flex-direction:column;gap:8px;`,ng=e=>i.createElement(i.Fragment,null),Bs=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BjKg30ip.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,rg=e=>Bs?i.createElement(wt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},i.createElement(Bs,{...e})):null,sg=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=se(),[s,o]=u.useState(!1),{suggestedReplies:a}=r,l=(e==null?void 0:e.suggested_replies)??[];if(l.length===0||s)return null;const c=d=>{t&&(t({reply:d}),o(!0))};return i.createElement(og,{id:`${Ye}-ext-suggested-replies`,role:"presentation",$type:n},l.map((d,m)=>{const h=a.item(d,m);return i.createElement(u.Fragment,{key:m},i.createElement(ig,{$type:n,...h.props,onClick:()=>c(d)},i.createElement(ag,{variant:"body3"},d)),h.descriptionNode)}))},og=p.default.div`margin:16px 0;padding:0 ${te.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?lg:cg};`,ig=p.default.button.attrs({type:"button"})`
295
+ `,ig=p.default.div`display:flex;flex-direction:column;gap:12px;`,ag=p.default.div`display:flex;flex-direction:column;`,lg=p.default.div`display:flex;flex-direction:column;gap:8px;`,cg=e=>i.createElement(i.Fragment,null),Bo=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BjKg30ip.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,ug=e=>Bo?i.createElement(wt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},i.createElement(Bo,{...e})):null,dg=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=oe(),[o,s]=u.useState(!1),{suggestedReplies:a}=r,l=(e==null?void 0:e.suggested_replies)??[];if(l.length===0||o)return null;const c=d=>{t&&(t({reply:d}),s(!0))};return i.createElement(mg,{id:`${We}-ext-suggested-replies`,role:"presentation",$type:n},l.map((d,m)=>{const f=a.item(d,m);return i.createElement(u.Fragment,{key:m},i.createElement(fg,{$type:n,...f.props,onClick:()=>c(d)},i.createElement(hg,{variant:"body3"},d)),f.descriptionNode)}))},mg=p.default.div`margin:16px 0;padding:0 ${ne.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?gg:pg};`,fg=p.default.button.attrs({type:"button"})`
296
296
  all: unset;
297
297
  box-sizing: border-box;
298
298
  padding: 8px 12px;
@@ -310,22 +310,22 @@
310
310
  background-color: ${g.themedColor.bg_100_500};
311
311
  }
312
312
 
313
- ${Se}
313
+ ${Ae}
314
314
 
315
- ${({$type:e,theme:t})=>D.css`${e==="vertical"?ug:dg};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
316
- `,ag=p.default($)`color:inherit;`,lg=D.css`flex-direction:column;align-items:flex-end;`,cg=D.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,ug=D.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,dg=D.css`white-space:nowrap;`,mg=e=>{const{components:t}=tt.useContext(),{stringSet:n}=oe(),r=ao(e)?i.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")?i.createElement(t.MediaMessageBody,{...e},r):i.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},r):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},hg=e=>i.createElement(wi,{...e,testerMode:!1}),tt=Ue({template:hg,components:{SenderName:Mh,SenderAvatar:Ih,SentTime:Rh,MessageBody:mg,TextMessageBody:Sh,MediaMessageBody:oh,FileMessageBody:nh,MultipleFilesMessageBody:Eh,TypingIndicator:Lh,SuggestedReplies:sg,MessageTemplate:rg,CustomMessageTemplate:Kh,CTAButton:Bh,Citation:Gh,Form:Jf,Feedback:ff,MessageLogs:ng}}),fg=/(?:!\[[^\]]*]\([^)]+\)|\[[^\]]+]\([^)]+\)|https?:\/\/\S+|www\.\S+)/i,gg=e=>e?fg.test(e):!1,wi=e=>{var A,T,L,k,I,w,O;const{components:t}=tt.useContext(),{streamText:n,isAnimating:r}=qc({text:e.message,enabled:e.isStreaming,markdownImageRenderMode:e.markdownImageRenderMode,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),s={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},o=!!s.isTyping,a=s.testerMode,l=!!s.isSenderAvatarVisible,c=!!((A=s.extendedMessagePayload)!=null&&A.form)&&!((T=s.extendedMessagePayload)!=null&&T.form.canceled_at),d=!!((L=s.extendedMessagePayload)!=null&&L.message_template),m=!!((k=s.extendedMessagePayload)!=null&&k.cta_button),h=!!((I=s.extendedMessagePayload)!=null&&I.citations)&&s.extendedMessagePayload.citations.length>0,f=!!s.createdAt,E=m||h,v=s.messageType==="user"&&!gg(s.message),y=s.groupType==="top"||s.groupType==="single",C=s.groupType==="bottom"||s.groupType==="single",_=a||!l?0:te.AVATAR_SIZE,b=U=>v?i.createElement(Cg,null,U):U;return i.createElement(pg,{$marginBottom:o?0:ln(s.groupType)},y&&i.createElement(bg,{"aria-hidden":"true"},!a&&l&&i.createElement(t.SenderAvatar,{...s}),i.createElement(t.SenderName,{...s})),i.createElement(yg,null,i.createElement(On,{$extraStartPadding:_},o?i.createElement(t.TypingIndicator,{...s}):E?i.createElement(_g,{$maxWidth:s.maxBodyWidth??te.BODY_MAX_WIDTH},b(i.createElement(t.MessageBody,{...s,surface:"plain"})),m&&i.createElement(Eg,{$marginTop:12,$paddingInline:12},i.createElement(t.CTAButton,{...s})),h&&i.createElement(t.Citation,{...s})):b(i.createElement(t.MessageBody,{...s}))),d&&i.createElement(Us,{$startPadding:0,$endPadding:0},i.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??i.createElement(On,{$extraStartPadding:_},i.createElement(t.MessageBody,{...s,messageType:"user",message:((O=(w=s.extendedMessagePayload)==null?void 0:w.message_template)==null?void 0:O.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??i.createElement(On,{$extraStartPadding:_},i.createElement(t.TypingIndicator,{...s}))})),i.createElement(t.CustomMessageTemplate,{...s}),c&&i.createElement(Us,{$extraStartPadding:_},i.createElement(t.Form,{...s}))),C&&f&&i.createElement(vg,{$extraStartPadding:_+8,"aria-hidden":"true"},i.createElement(t.SentTime,{...s})),i.createElement(u.Fragment,null,!o&&i.createElement(Lt,{$extraStartPadding:_+8},i.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&i.createElement(t.SuggestedReplies,{...s}),i.createElement(t.MessageLogs,{...s})))},pg=p.default.div.attrs({role:"presentation"})`
315
+ ${({$type:e,theme:t})=>D.css`${e==="vertical"?_g:Eg};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
316
+ `,hg=p.default(P)`color:inherit;`,gg=D.css`flex-direction:column;align-items:flex-end;`,pg=D.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,_g=D.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,Eg=D.css`white-space:nowrap;`,bg=e=>{const{components:t}=tt.useContext(),{stringSet:n}=se(),r=us(e)?i.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const o=e.file;return o.type.startsWith("image")||o.type.startsWith("video")?i.createElement(t.MediaMessageBody,{...e},r):i.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},r):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},Cg=e=>i.createElement(ki,{...e,testerMode:!1}),tt=Ue({template:Cg,components:{SenderName:$f,SenderAvatar:Nf,SentTime:Ff,MessageBody:bg,TextMessageBody:kf,MediaMessageBody:mf,FileMessageBody:cf,MultipleFilesMessageBody:xf,TypingIndicator:Uf,SuggestedReplies:dg,MessageTemplate:ug,CustomMessageTemplate:nh,Challenge:jf,CTAButton:Wf,Citation:Xf,Form:sg,Feedback:vh,MessageLogs:cg}}),vg=/(?:!\[[^\]]*]\([^)]+\)|\[[^\]]+]\([^)]+\)|https?:\/\/\S+|www\.\S+)/i,yg=e=>e?vg.test(e):!1,ki=e=>{var x,k,R,I,w,O,$,V;const{components:t}=tt.useContext(),{streamText:n,isAnimating:r}=Zc({text:e.message,enabled:e.isStreaming,markdownImageRenderMode:e.markdownImageRenderMode,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},s=!!o.isTyping,a=o.testerMode,l=!!o.isSenderAvatarVisible,c=!!((x=o.extendedMessagePayload)!=null&&x.form)&&!((k=o.extendedMessagePayload)!=null&&k.form.canceled_at),d=!!((R=o.extendedMessagePayload)!=null&&R.message_template),m=!!((I=o.extendedMessagePayload)!=null&&I.challenge),f=!!((w=o.extendedMessagePayload)!=null&&w.cta_button),h=!!((O=o.extendedMessagePayload)!=null&&O.citations)&&o.extendedMessagePayload.citations.length>0,_=!!o.createdAt,y=f||h,C=o.messageType==="user"&&!yg(o.message),v=o.groupType==="top"||o.groupType==="single",b=o.groupType==="bottom"||o.groupType==="single",E=a||!l?0:ne.AVATAR_SIZE,A=H=>C?i.createElement(Ig,null,H):H;return i.createElement(Sg,{$marginBottom:s?0:un(o.groupType)},v&&i.createElement(Tg,{"aria-hidden":"true"},!a&&l&&i.createElement(t.SenderAvatar,{...o}),i.createElement(t.SenderName,{...o})),i.createElement(Mg,null,i.createElement(On,{$extraStartPadding:E},s?i.createElement(t.TypingIndicator,{...o}):y?i.createElement(Ag,{$maxWidth:o.maxBodyWidth??ne.BODY_MAX_WIDTH},A(i.createElement(t.MessageBody,{...o,surface:"plain"})),f&&i.createElement(xg,{$marginTop:12,$paddingInline:12},i.createElement(t.CTAButton,{...o})),h&&i.createElement(t.Citation,{...o})):A(i.createElement(t.MessageBody,{...o}))),d&&i.createElement(Uo,{$startPadding:0,$endPadding:0},i.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??i.createElement(On,{$extraStartPadding:E},i.createElement(t.MessageBody,{...o,messageType:"user",message:((V=($=o.extendedMessagePayload)==null?void 0:$.message_template)==null?void 0:V.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??i.createElement(On,{$extraStartPadding:E},i.createElement(t.TypingIndicator,{...o}))})),i.createElement(t.CustomMessageTemplate,{...o}),m&&i.createElement(t.Challenge,{...o}),c&&i.createElement(Uo,{$extraStartPadding:E},i.createElement(t.Form,{...o}))),b&&_&&i.createElement(wg,{$extraStartPadding:E+8,"aria-hidden":"true"},i.createElement(t.SentTime,{...o})),i.createElement(u.Fragment,null,!s&&i.createElement(Nt,{$extraStartPadding:E+8},i.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&i.createElement(t.SuggestedReplies,{...o}),i.createElement(t.MessageLogs,{...o})))},Sg=p.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
- `,Lt=p.default.div.attrs({role:"presentation"})`
321
+ `,Nt=p.default.div.attrs({role:"presentation"})`
322
322
  display: flex;
323
323
  align-self: stretch;
324
324
  justify-content: flex-start;
325
- ${({$startPadding:e=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
325
+ ${({$startPadding:e=ne.HORIZONTAL_PADDING,$endPadding:t=ne.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
326
326
  padding-inline: ${e+n}px ${t}px;
327
327
  `}
328
- `,_g=p.default.div.attrs({role:"presentation"})`
328
+ `,Ag=p.default.div.attrs({role:"presentation"})`
329
329
  display: flex;
330
330
  flex-direction: column;
331
331
  min-width: 0;
@@ -334,53 +334,53 @@
334
334
  overflow: hidden;
335
335
  padding: 12px 0;
336
336
  ${({theme:e})=>D.css`color:${e.colors.messageIncoming.text};background-color:${e.colors.messageIncoming.background};`}
337
- `,Eg=p.default.div.attrs({role:"presentation"})`
337
+ `,xg=p.default.div.attrs({role:"presentation"})`
338
338
  display: flex;
339
339
  flex-direction: column;
340
340
  min-width: 0;
341
341
  ${({$marginTop:e=0,$paddingInline:t=0})=>D.css`margin-top:${e}px;padding-inline:${t}px;`}
342
- `,bg=p.default(Lt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,On=p.default(Lt)`display:flex;`,Cg=p.default.div.attrs({"aria-hidden":"true",role:"presentation"})``,vg=p.default(Lt)`margin-top:${te.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Us=p.default(Lt).attrs({role:"presentation"})`
342
+ `,Tg=p.default(Nt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,On=p.default(Nt)`display:flex;`,Ig=p.default.div.attrs({"aria-hidden":"true",role:"presentation"})``,wg=p.default(Nt)`margin-top:${ne.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Uo=p.default(Nt).attrs({role:"presentation"})`
343
343
  display: flex;
344
- ${({$startPadding:e=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
344
+ ${({$startPadding:e=ne.HORIZONTAL_PADDING,$endPadding:t=ne.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
345
345
  padding-inline: ${e+n}px ${t}px;
346
346
  `}
347
- `,yg=p.default.div.attrs({role:"presentation"})`
347
+ `,Mg=p.default.div.attrs({role:"presentation"})`
348
348
  display: flex;
349
349
  flex-direction: column;
350
350
  min-width: 0;
351
351
  max-width: 100%;
352
- gap: ${te.GAP_GROUPED}px;
353
- `;function Sg({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return i.createElement(Ag,null,i.createElement(vr,{name:e.name,mimeType:e.type,type:nr(e.name,e.type),onClick:s}),t)}const Ag=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`;function xg({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:a}=se(),{aspectRatio:l,localFile:c}=n,[d]=u.useState(()=>c instanceof Blob?URL.createObjectURL(c):t.url),[m,h]=u.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})}})(),E=f?a.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:f}):a.file.preview({name:t.name,mimeType:t.type}),v={...E.props,$ratio:l,$clickable:!!f};return i.createElement(Tg,null,i.createElement(Ig,{...v},!m&&i.createElement(it,{size:26},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:26})),i.createElement(wg,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),E.descriptionNode),o)}const Tg=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`,Ig=p.default.div`width:${te.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;${J.light`
352
+ gap: ${ne.GAP_GROUPED}px;
353
+ `;function kg({file:e,children:t,onClickFile:n,sendingStatus:r}){const o=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return i.createElement(Rg,null,i.createElement(vr,{name:e.name,mimeType:e.type,type:tr(e.name,e.type),onClick:o}),t)}const Rg=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ne.GAP_GROUPED}px;`;function Lg({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s}){const{conversation:a}=oe(),{aspectRatio:l,localFile:c}=n,[d]=u.useState(()=>c instanceof Blob?URL.createObjectURL(c):t.url),[m,f]=u.useState(!1),h=(()=>{if(e!=="failed"){if(o)return()=>o({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),_=h?a.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:h}):a.file.preview({name:t.name,mimeType:t.type}),y={..._.props,$ratio:l,$clickable:!!h};return i.createElement(Og,null,i.createElement(Ng,{...y},!m&&i.createElement(at,{size:26},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:26})),i.createElement(Dg,{$loaded:m,src:d,alt:"image-message",onLoad:()=>f(!0)}),_.descriptionNode),s)}const Og=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ne.GAP_GROUPED}px;`,Ng=p.default.div`width:${ne.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;${J.light`
354
354
  background-color: ${g.color.background100};
355
355
  `}
356
356
  ${J.dark`
357
357
  background-color: ${g.color.background400};
358
358
  `}
359
- `,wg=p.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;`,Mg=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[a]=u.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),l=e==="pending",c=e==="failed",d=m=>{if(c||l)return;const h=a[m];h&&(s?s({files:a,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return i.createElement(kg,null,i.createElement(gi,{images:a,isPending:l,onClickImage:d}),o)},kg=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`;function Rg(e){var n,r;const t=u.useMemo(()=>{const s=vh(_i(e.message));return so.default.sanitize(s)},[e.message]);return i.createElement(Og,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},i.createElement(Lg,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const Og=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>D.css`
359
+ `,Dg=p.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;`,$g=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s})=>{const[a]=u.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),l=e==="pending",c=e==="failed",d=m=>{if(c||l)return;const f=a[m];f&&(o?o({files:a,index:m}):r&&r({url:f.url,type:f.type||"image/*"}))};return i.createElement(Pg,null,i.createElement(_i,{images:a,isPending:l,onClickImage:d}),s)},Pg=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ne.GAP_GROUPED}px;`;function Fg(e){var n,r;const t=u.useMemo(()=>{const o=wf(bi(e.message));return is.default.sanitize(o)},[e.message]);return i.createElement(Bg,{$maxWidth:e.maxBodyWidth??ne.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},i.createElement(Ug,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const Bg=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>D.css`
360
360
  color: ${t||e.colors.messageOutgoing.text};
361
361
  background-color: ${n||e.colors.messageOutgoing.background};
362
362
  `}
363
363
  padding: 12px 0;
364
364
  transition: max-width 0.3s;
365
365
  overflow-wrap: break-word;
366
- `,Lg=p.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Ng=({sendingStatus:e})=>{const t=D.useTheme();switch(e){case"pending":return i.createElement(Dg,{size:16},i.createElement(Q,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return i.createElement("div",{style:{marginBottom:2}},i.createElement(Q,{type:"error",color:g.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return i.createElement("div",{style:{marginBottom:2}},i.createElement(Q,{type:"done",color:g.themedColor.secondary,size:16}))}},Dg=p.default(it)`margin-bottom:2px;width:16px;height:16px;`,$g=({createdAt:e})=>{const{stringSet:t,format:n}=oe();return e?i.createElement($,{variant:"caption4",color:g.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Pg=e=>{const{components:t}=Nt.useContext(),{stringSet:n}=oe(),r=()=>{const a=ao(e)?i.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?a:e.messageType==="file"?e.file.type.startsWith("image")?i.createElement(t.MediaMessageBody,{...e},a):i.createElement(t.FileMessageBody,{...e},a):e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},a):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,o=s?St({onActivate:()=>{var a;return(a=e.onClickFailedMessage)==null?void 0:a.call(e)}}):{};return i.createElement("div",{...o,style:{display:"contents",cursor:s?"pointer":"default"}},r())},Fg=e=>{const{components:t}=Nt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single",s=e.messageType==="user"&&e.sendingStatus!=="failed";return i.createElement(Bg,{$marginBottom:ln(e.groupType)},i.createElement(Ug,{"aria-hidden":s?"true":void 0},i.createElement(t.MessageBody,{...e})),r&&i.createElement(Hg,{$extraEndPadding:8,"aria-hidden":n?"true":void 0},n?i.createElement(t.SentTime,{...e}):i.createElement(t.SendingStatus,{...e})))},Nt=Ue({template:Fg,components:{SendingStatus:Ng,SentTime:$g,MessageBody:Pg,TextMessageBody:Rg,MediaMessageBody:xg,FileMessageBody:Sg,MultipleFilesMessageBody:Mg}}),Bg=p.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
367
- `,Mi=p.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
368
- `,Ug=p.default(Mi)``,Hg=p.default(Mi)`margin-top:${te.BODY_TIME_GAP}px;`,Gg=e=>e.messageType!=="admin"?null:i.createElement(Vg,null,i.createElement($,{variant:"caption2",color:g.themedColor.textMidEmphasis},zg(so.default.sanitize(e.message)))),Vg=p.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${te.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,zg=e=>{try{const t=[];let n=e,r=0;for(;n;){const s=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),o=n.match(/\*\*([^*]+)\*\*/),a=[s&&{match:s,type:"link"},o&&{match:o,type:"bold"}].filter(h=>!!h);if(!a.length){t.push(n);break}const l=a.reduce((h,f)=>f.match.index<h.match.index?f:h),{match:c,type:d}=l,m=c.index;m>0&&t.push(n.slice(0,m)),d==="link"?t.push(i.createElement("a",{key:r++,href:c[2],target:"_blank",rel:gr},c[1])):d==="bold"&&t.push(i.createElement("strong",{key:r++},c[1])),n=n.slice(m+c[0].length)}return t.filter(s=>s!=="")}catch{return[e]}},Yg=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,ki=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const a=u.useRef([]),l=e.findIndex(h=>h.value===t),c=l>=0?l:0,d=h=>{requestAnimationFrame(()=>{var f;(f=a.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=>{a.current[h]=f},tabIndex:n?-1:h===c?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(Yg({direction:f,currentIndex:h,totalCount:e.length}))}})}},Wg=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},qg=({event:e,onClick:t,onArrowNavigate:n})=>{if(Kg(e))return;const r=Wg(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},Kg=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Ar=u.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:a,onArrowNavigate:l},c)=>{const d=t?g.themedColor.primary:r?g.themedColor.textDisabled:g.themedColor.textLowEmphasis,m=t?g.themedColor.textHighEmphasis:r?g.themedColor.textLowEmphasis:g.themedColor.textHighEmphasis;return i.createElement(Zg,{ref:c,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":a,onClick:r?void 0:e,onKeyDown:h=>qg({event:h,onClick:e,onArrowNavigate:l})},i.createElement(jg,{"aria-hidden":"true"},i.createElement(Q,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(Xg,{"aria-hidden":"true",variant:o,color:m},n))});Ar.displayName="Radio";const jg=p.default.div`width:20px;height:20px;`,Xg=p.default($)`line-height:20px;word-break:break-word;`,Zg=p.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Se}&[aria-disabled='false']{cursor:pointer;}`,Jg=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var c,d;const o=[{label:((c=e.cre)==null?void 0:c.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],a=ki({options:o,value:r,disabled:t,onChange:s});if(u.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const l=e.cre;return i.createElement(Qg,null,i.createElement(Ae.Label,{required:l.required,"aria-hidden":!0},l.question),i.createElement(ep,{...a.radioGroupProps(l.question)},o.map((m,h)=>i.createElement(Ar,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},Qg=p.default.div`display:flex;flex-direction:column;gap:8px;`,ep=p.default.div`display:flex;flex-direction:column;gap:8px;`,tp=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=oe(),{conversation:a}=se(),l=u.useId(),c=e.response_type!=="free_text",d=e.response_type==="single_choice"?e.options.map(h=>({label:h,value:h})):[],m=ki({options:d,value:n,disabled:t,hasError:s,errorId:l,onChange:r});return i.createElement(np,null,i.createElement(Ae.Label,{required:e.required,"aria-hidden":c},e.question),e.response_type==="free_text"&&i.createElement(Ae.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:h=>r(h),error:s,...a.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t).props,"aria-invalid":s,"aria-errormessage":s?l:void 0}),e.response_type==="single_choice"&&i.createElement(rp,{...m.radioGroupProps(e.question)},d.map((h,f)=>i.createElement(Ar,{key:h.value,checked:n===h.value,label:h.label,disabled:t,...m.getRadioProps(f),onClick:()=>r==null?void 0:r(h.value),labelVariant:"body3"}))),s&&i.createElement(sp,{role:"alert",id:l},o.FORM_VALIDATION_REQUIRED))},np=p.default.div`display:flex;flex-direction:column;gap:8px;`,rp=p.default.div`display:flex;flex-direction:column;gap:8px;`,sp=p.default(Ae.ErrorLabel)``,op=({value:e,selected:t})=>i.createElement(ip,{$selected:t,"aria-hidden":"true"},ap[e-1]),ip=p.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,ap=[i.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},i.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)"}),i.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"}),i.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"}),i.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"}),i.createElement("defs",null,i.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},i.createElement("stop",{stopColor:"#FF2D1D"}),i.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.createElement("g",{clipPath:"url(#clip0_159_173224)"},i.createElement("g",{clipPath:"url(#clip1_159_173224)"},i.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"})),i.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},i.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"})),i.createElement("g",{mask:"url(#mask0_159_173224)"},i.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"}))),i.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"}),i.createElement("defs",null,i.createElement("clipPath",{id:"clip0_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),i.createElement("clipPath",{id:"clip1_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],lp=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=se(),a=o.csat.scoresContainer(e.csat_question);return i.createElement(up,null,i.createElement($,{variant:"caption3",color:g.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(dp,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:c},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,E=o.csat.scoreItem({score:m,label:l,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return i.createElement(mp,{key:d,type:"button",...E.props},i.createElement(cp,{value:m,selected:s||h,src:c}),!!l&&i.createElement($,{"aria-hidden":"true",color:h?g.themedColor.textHighEmphasis:g.themedColor.textLowEmphasis,variant:"caption3"},l),E.descriptionNode)})))},cp=({value:e,src:t,selected:n})=>{const[r,s]=u.useState(!1),o=r?i.createElement(op,{value:e,selected:n}):i.createElement(fp,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return i.createElement(hp,null,o)},up=p.default.div`display:flex;flex-direction:column;gap:8px;`,dp=p.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,mp=p.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;${Se}&:not(:disabled):hover span{color:${g.themedColor.textHighEmphasis};}`,hp=p.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${g.color.background200};${J.dark`
366
+ `,Ug=p.default(P)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Hg=({sendingStatus:e})=>{const t=D.useTheme();switch(e){case"pending":return i.createElement(Gg,{size:16},i.createElement(Q,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return i.createElement("div",{style:{marginBottom:2}},i.createElement(Q,{type:"error",color:g.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return i.createElement("div",{style:{marginBottom:2}},i.createElement(Q,{type:"done",color:g.themedColor.secondary,size:16}))}},Gg=p.default(at)`margin-bottom:2px;width:16px;height:16px;`,zg=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?i.createElement(P,{variant:"caption4",color:g.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Vg=e=>{const{components:t}=Dt.useContext(),{stringSet:n}=se(),r=()=>{const a=us(e)?i.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?a:e.messageType==="file"?e.file.type.startsWith("image")?i.createElement(t.MediaMessageBody,{...e},a):i.createElement(t.FileMessageBody,{...e},a):e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},a):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},o=e.sendingStatus==="failed"&&e.onClickFailedMessage,s=o?St({onActivate:()=>{var a;return(a=e.onClickFailedMessage)==null?void 0:a.call(e)}}):{};return i.createElement("div",{...s,style:{display:"contents",cursor:o?"pointer":"default"}},r())},Yg=e=>{const{components:t}=Dt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single",o=e.messageType==="user"&&e.sendingStatus!=="failed";return i.createElement(Wg,{$marginBottom:un(e.groupType)},i.createElement(qg,{"aria-hidden":o?"true":void 0},i.createElement(t.MessageBody,{...e})),r&&i.createElement(Kg,{$extraEndPadding:8,"aria-hidden":n?"true":void 0},n?i.createElement(t.SentTime,{...e}):i.createElement(t.SendingStatus,{...e})))},Dt=Ue({template:Yg,components:{SendingStatus:Hg,SentTime:zg,MessageBody:Vg,TextMessageBody:Fg,MediaMessageBody:Lg,FileMessageBody:kg,MultipleFilesMessageBody:$g}}),Wg=p.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
367
+ `,Ri=p.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=ne.HORIZONTAL_PADDING,$endPadding:t=ne.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
368
+ `,qg=p.default(Ri)``,Kg=p.default(Ri)`margin-top:${ne.BODY_TIME_GAP}px;`,jg=e=>e.messageType!=="admin"?null:i.createElement(Xg,null,i.createElement(P,{variant:"caption2",color:g.themedColor.textMidEmphasis},Zg(is.default.sanitize(e.message),e.onClickLink))),Xg=p.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ne.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,Zg=(e,t)=>{try{const n=[];let r=e,o=0;for(;r;){const s=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=r.match(/\*\*([^*]+)\*\*/),l=[s&&{match:s,type:"link"},a&&{match:a,type:"bold"}].filter(h=>!!h);if(!l.length){n.push(r);break}const c=l.reduce((h,_)=>_.match.index<h.match.index?_:h),{match:d,type:m}=c,f=d.index;f>0&&n.push(r.slice(0,f)),m==="link"?n.push(i.createElement("a",{key:o++,href:d[2],target:"_blank",rel:gr,onClick:h=>{h.preventDefault();const _=d[2];_&&(t==null||t({url:_}))}},d[1])):m==="bold"&&n.push(i.createElement("strong",{key:o++},d[1])),r=r.slice(f+d[0].length)}return n.filter(s=>s!=="")}catch{return[e]}},Jg=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Li=({options:e,value:t,disabled:n,hasError:r=!1,errorId:o,onChange:s})=>{const a=u.useRef([]),l=e.findIndex(f=>f.value===t),c=l>=0?l:0,d=f=>{requestAnimationFrame(()=>{var h;(h=a.current[f])==null||h.focus()})},m=f=>{const h=e[f];!h||n||(s==null||s(h.value),d(f))};return{radioGroupProps:f=>({role:"radiogroup","aria-label":f,...r&&o?{"aria-invalid":!0,"aria-errormessage":o}:{}}),getRadioProps:f=>({ref:h=>{a.current[f]=h},tabIndex:n?-1:f===c?0:-1,describedBy:r&&o?o:void 0,onArrowNavigate:h=>{m(Jg({direction:h,currentIndex:f,totalCount:e.length}))}})}},Qg=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},ep=({event:e,onClick:t,onArrowNavigate:n})=>{if(tp(e))return;const r=Qg(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},tp=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Ar=u.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:o=0,labelVariant:s="caption2",describedBy:a,onArrowNavigate:l},c)=>{const d=t?g.themedColor.primary:r?g.themedColor.textDisabled:g.themedColor.textLowEmphasis,m=t?g.themedColor.textHighEmphasis:r?g.themedColor.textLowEmphasis:g.themedColor.textHighEmphasis;return i.createElement(op,{ref:c,role:"radio",tabIndex:r?-1:o,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":a,onClick:r?void 0:e,onKeyDown:f=>ep({event:f,onClick:e,onArrowNavigate:l})},i.createElement(np,{"aria-hidden":"true"},i.createElement(Q,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(rp,{"aria-hidden":"true",variant:s,color:m},n))});Ar.displayName="Radio";const np=p.default.div`width:20px;height:20px;`,rp=p.default(P)`line-height:20px;word-break:break-word;`,op=p.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Ae}&[aria-disabled='false']{cursor:pointer;}`,sp=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:o})=>{var c,d;const s=[{label:((c=e.cre)==null?void 0:c.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],a=Li({options:s,value:r,disabled:t,onChange:o});if(u.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(o==null||o(n))},[r,n]),!e.cre)return null;const l=e.cre;return i.createElement(ip,null,i.createElement(Te.Label,{required:l.required,"aria-hidden":!0},l.question),i.createElement(ap,{...a.radioGroupProps(l.question)},s.map((m,f)=>i.createElement(Ar,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(f),onClick:()=>o==null?void 0:o(m.value)}))))},ip=p.default.div`display:flex;flex-direction:column;gap:8px;`,ap=p.default.div`display:flex;flex-direction:column;gap:8px;`,lp=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:s}=se(),{conversation:a}=oe(),l=u.useId(),c=e.response_type!=="free_text",d=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],m=Li({options:d,value:n,disabled:t,hasError:o,errorId:l,onChange:r});return i.createElement(cp,null,i.createElement(Te.Label,{required:e.required,"aria-hidden":c},e.question),e.response_type==="free_text"&&i.createElement(Te.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:o,...a.form.textInput(s.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t).props,"aria-invalid":o,"aria-errormessage":o?l:void 0}),e.response_type==="single_choice"&&i.createElement(up,{...m.radioGroupProps(e.question)},d.map((f,h)=>i.createElement(Ar,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...m.getRadioProps(h),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),o&&i.createElement(dp,{role:"alert",id:l},s.FORM_VALIDATION_REQUIRED))},cp=p.default.div`display:flex;flex-direction:column;gap:8px;`,up=p.default.div`display:flex;flex-direction:column;gap:8px;`,dp=p.default(Te.ErrorLabel)``,mp=({value:e,selected:t})=>i.createElement(fp,{$selected:t,"aria-hidden":"true"},hp[e-1]),fp=p.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,hp=[i.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},i.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)"}),i.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"}),i.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"}),i.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"}),i.createElement("defs",null,i.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},i.createElement("stop",{stopColor:"#FF2D1D"}),i.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.createElement("g",{clipPath:"url(#clip0_159_173224)"},i.createElement("g",{clipPath:"url(#clip1_159_173224)"},i.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"})),i.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},i.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"})),i.createElement("g",{mask:"url(#mask0_159_173224)"},i.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"}))),i.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"}),i.createElement("defs",null,i.createElement("clipPath",{id:"clip0_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),i.createElement("clipPath",{id:"clip1_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],gp=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",{conversation:s}=oe(),a=s.csat.scoresContainer(e.csat_question);return i.createElement(_p,null,i.createElement(P,{variant:"caption3",color:g.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(Ep,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:c},d)=>{const m=d+1,f=n===m,h=e.csat_scores.length,_=s.csat.scoreItem({score:m,label:l,selected:f,disabled:t,currentIndex:d,totalCount:h,hasSelection:!o,onChange:r});return i.createElement(bp,{key:d,type:"button",..._.props},i.createElement(pp,{value:m,selected:o||f,src:c}),!!l&&i.createElement(P,{"aria-hidden":"true",color:f?g.themedColor.textHighEmphasis:g.themedColor.textLowEmphasis,variant:"caption3"},l),_.descriptionNode)})))},pp=({value:e,src:t,selected:n})=>{const[r,o]=u.useState(!1),s=r?i.createElement(mp,{value:e,selected:n}):i.createElement(vp,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>o(!0)});return i.createElement(Cp,null,s)},_p=p.default.div`display:flex;flex-direction:column;gap:8px;`,Ep=p.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,bp=p.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;${Ae}&:not(:disabled):hover span{color:${g.themedColor.textHighEmphasis};}`,Cp=p.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${g.color.background200};${J.dark`
369
369
  background-color: ${g.color.background500};
370
370
  `}
371
371
  }
372
- `,fp=p.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,gp=({csatPayload:e})=>i.createElement($,{variant:"button",color:g.themedColor.textHighEmphasis},e.title),Ln=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:a,setParams:l,error:c,setError:d,followUpItem:m,state:h,validateParams:f,itemProps:E}=Gc({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return i.createElement(i.Fragment,null,i.createElement(pp,null,i.createElement(gp,{...E}),t===Ve.AI_AGENT_CSAT_5_WITH_CRE&&i.createElement(Jg,{...E,defaultValue:o,value:a.isResolved,onChange:v=>l({isResolved:v})}),i.createElement(lp,{...E,value:a.csat,onChange:v=>l({csat:v})}),m&&i.createElement(tp,{...E,followUpItem:m,value:a.csatReason,onChange:v=>{l({csatReason:v}),d({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&i.createElement(i.Fragment,null,i.createElement(Ae.Separator,null),n({state:h,params:a,validateParams:f})))},pp=p.default.div`display:flex;flex-direction:column;gap:12px;`,_p=e=>{const{stringSet:t}=oe();return Ya(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})},Ep=()=>{const{stringSet:e}=oe();return i.createElement($,{variant:"body2",color:g.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},bp=({onMount:e,children:t})=>(u.useEffect(()=>{e&&Re(e)},[]),t),Cp=e=>{const{conversation:t}=se(),{announceError:n,announceStatus:r}=qe();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:s,onSubmitCSAT:o,onScrollToBottom:a}=e,{csat:l,csatReason:c,csatExpireAt:d,isResolvedWhenDeterminedByUser:m}=e,h=cn(),f=_p(s==null?void 0:s.csat),E=u.useRef(null),v=u.useRef(null),[y,C]=u.useState(!1),_=u.useRef(!1),b=u.useCallback(()=>{Re(()=>{var I;return(I=v.current)==null?void 0:I.focus()})},[]),{isExpiredNow:A,isRenderableCSAT:T}=Uc({csat:l,csatExpireAt:d,csatPayload:f,announceStatus:r,onSubmittedAnnounced:b,isSubmitInFlight:y});if(!T||!f)return null;const L=()=>{var w;const I=(w=E.current)==null?void 0:w.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},k=f.type===Ve.AI_AGENT_CSAT_5||f.type===Ve.AI_AGENT_CSAT_5_WITH_CRE||f.type===Ve.HELPDESK_CSAT_5?Ln:()=>null;return i.createElement(vp,{ref:E},!l&&A?i.createElement(Ep,null):i.createElement(k,{csatPayload:f,type:f.type,initialCsat:l,initialCsatReason:c,initialIsResolved:m,renderSubmitButton:({state:I,params:w,validateParams:O})=>I==="submitted"?i.createElement(Sp,{ref:v,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":f.csat_submitted_label,tabIndex:-1},i.createElement($,{variant:"button","aria-hidden":"true"},f.csat_submitted_label)):i.createElement(bp,{onMount:a},i.createElement(yp,{type:"button",...t.csat.submitButton(f.csat_submit_label).props,onClick:async()=>{if(_.current)return;const U=_o(d);if(!U&&O()){_.current=!0,C(!0);try{await o(w)}catch(Y){throw _.current=!1,C(!1),Y}}else h(),U||Re(()=>{n({type:"csatFormError"},L())})}},i.createElement($,{variant:"button"},f.csat_submit_label)))}))},vp=p.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,yp=p.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;${Se}&:hover{background-color:${g.color.primary.dark};}`,Sp=p.default.div`width:100%;box-sizing:border-box;color:${g.themedColor.textHighEmphasis};background-color:${g.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${J.dark`
372
+ `,vp=p.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,yp=({csatPayload:e})=>i.createElement(P,{variant:"button",color:g.themedColor.textHighEmphasis},e.title),Nn=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:s})=>{const{params:a,setParams:l,error:c,setError:d,followUpItem:m,state:f,validateParams:h,itemProps:_}=Wc({csatPayload:e,type:t,initialCsat:r,initialCsatReason:o,initialIsResolved:s});return i.createElement(i.Fragment,null,i.createElement(Sp,null,i.createElement(yp,{..._}),t===Ye.AI_AGENT_CSAT_5_WITH_CRE&&i.createElement(sp,{..._,defaultValue:s,value:a.isResolved,onChange:y=>l({isResolved:y})}),i.createElement(gp,{..._,value:a.csat,onChange:y=>l({csat:y})}),m&&i.createElement(lp,{..._,followUpItem:m,value:a.csatReason,onChange:y=>{l({csatReason:y}),d({followUpItem:!1})},hasError:c.followUpItem})),f!=="unsubmittable"&&i.createElement(i.Fragment,null,i.createElement(Te.Separator,null),n({state:f,params:a,validateParams:h})))},Sp=p.default.div`display:flex;flex-direction:column;gap:12px;`,Ap=e=>{const{stringSet:t}=se();return ja(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})},xp=()=>{const{stringSet:e}=se();return i.createElement(P,{variant:"body2",color:g.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},Tp=({onMount:e,children:t})=>(u.useEffect(()=>{e&&Le(e)},[]),t),Ip=e=>{const{conversation:t}=oe(),{announceError:n,announceStatus:r}=Ke();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:o,onSubmitCSAT:s,onScrollToBottom:a}=e,{csat:l,csatReason:c,csatExpireAt:d,isResolvedWhenDeterminedByUser:m}=e,f=dn(),h=Ap(o==null?void 0:o.csat),_=u.useRef(null),y=u.useRef(null),[C,v]=u.useState(!1),b=u.useRef(!1),E=u.useCallback(()=>{Le(()=>{var I;return(I=y.current)==null?void 0:I.focus()})},[]),{isExpiredNow:A,isRenderableCSAT:x}=Vc({csat:l,csatExpireAt:d,csatPayload:h,announceStatus:r,onSubmittedAnnounced:E,isSubmitInFlight:C});if(!x||!h)return null;const k=()=>{var w;const I=(w=_.current)==null?void 0:w.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},R=h.type===Ye.AI_AGENT_CSAT_5||h.type===Ye.AI_AGENT_CSAT_5_WITH_CRE||h.type===Ye.HELPDESK_CSAT_5?Nn:()=>null;return i.createElement(wp,{ref:_},!l&&A?i.createElement(xp,null):i.createElement(R,{csatPayload:h,type:h.type,initialCsat:l,initialCsatReason:c,initialIsResolved:m,renderSubmitButton:({state:I,params:w,validateParams:O})=>I==="submitted"?i.createElement(kp,{ref:y,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":h.csat_submitted_label,tabIndex:-1},i.createElement(P,{variant:"button","aria-hidden":"true"},h.csat_submitted_label)):i.createElement(Tp,{onMount:a},i.createElement(Mp,{type:"button",...t.csat.submitButton(h.csat_submit_label).props,onClick:async()=>{if(b.current)return;const $=Es(d);if(!$&&O()){b.current=!0,v(!0);try{await s(w)}catch(V){throw b.current=!1,v(!1),V}}else f(),$||Le(()=>{n({type:"csatFormError"},k())})}},i.createElement(P,{variant:"button"},h.csat_submit_label)))}))},wp=p.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,Mp=p.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;${Ae}&:hover{background-color:${g.color.primary.dark};}`,kp=p.default.div`width:100%;box-sizing:border-box;color:${g.themedColor.textHighEmphasis};background-color:${g.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${J.dark`
373
373
  background-color: ${g.color.onlight.textDisabled};
374
374
  `}
375
- `,Ap=e=>{const{components:t}=gn.useContext(),n=e.messageType==="admin"?i.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?i.createElement(t.CSATMessage,{...e}):null;return i.createElement(xp,{$marginBottom:ln(e.groupType)},n)},gn=Ue({template:Ap,components:{AdminMessage:Gg,CSATMessage:Cp}}),xp=p.default.div`padding-inline:${te.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Hs={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Ri=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,onClickActionbook:s,onClickFunctionCall:o,onClickFunctionCallDetail:a,onClickGroundedness:l,onClickAgentMessageTemplate:c,bottomContent:d,renderCustomGroundednessIcon:m=f=>f.default,style:h={}})=>{const{iconColor:f="#000000",textColor:E="#000000",highlightColor:v=It.DEFAULT_PRIMARY}=h;return i.createElement(Gs,null,e&&i.createElement(Gs,null,i.createElement(an,null,i.createElement(Yt,null,i.createElement(Q,{size:16,type:"actionbook",color:f})),i.createElement(zt,{$clickable:!!s,$highlightColor:v,variant:"body2",color:E,onClick:()=>s==null?void 0:s(e),maxTextLines:1},e.name))),t==null?void 0:t.map(y=>i.createElement(Nn,{key:y.key},i.createElement(Yt,null,i.createElement(Q,{size:16,type:"function",color:f})),i.createElement(an,null,i.createElement(zt,{$clickable:!!o,$highlightColor:v,variant:"body2",color:E,onClick:()=>o==null?void 0:o(y),maxTextLines:1},y.name),a&&i.createElement(Ip,{role:"button",onClick:()=>a==null?void 0:a(y)},i.createElement($,{variant:"body2",color:v},"View details"),i.createElement(Q,{type:"chevron-right",size:16,color:v}))))),n==null?void 0:n.map(y=>i.createElement(Nn,{key:y.id},i.createElement(Yt,null,m({default:i.createElement(Q,{size:16,type:Hs[y.source_type]??Hs.snippet,color:f}),sourceType:y.source_type})),i.createElement(zt,{$clickable:!!l,$highlightColor:v,variant:"body2",color:E,onClick:()=>l==null?void 0:l(y),maxTextLines:1},y.preview_title))),r==null?void 0:r.map(y=>i.createElement(Nn,{key:y.key},i.createElement(Yt,null,i.createElement(Q,{size:16,type:"template",color:f})),i.createElement(zt,{$clickable:!!c,$highlightColor:v,variant:"body2",color:E,onClick:()=>c==null?void 0:c(y),maxTextLines:1},y.name))),d)},Tp=p.default($)`font-weight:400;`,zt=p.default(Tp)`${({$clickable:e,$highlightColor:t})=>e&&D.css`
375
+ `,Rp=e=>{const{components:t}=pn.useContext(),n=e.messageType==="admin"?i.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?i.createElement(t.CSATMessage,{...e}):null;return i.createElement(Lp,{$marginBottom:un(e.groupType)},n)},pn=Ue({template:Rp,components:{AdminMessage:jg,CSATMessage:Ip}}),Lp=p.default.div`padding-inline:${ne.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Ho={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Oi=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,onClickActionbook:o,onClickFunctionCall:s,onClickFunctionCallDetail:a,onClickGroundedness:l,onClickAgentMessageTemplate:c,bottomContent:d,renderCustomGroundednessIcon:m=h=>h.default,style:f={}})=>{const{iconColor:h="#000000",textColor:_="#000000",highlightColor:y=It.DEFAULT_PRIMARY}=f;return i.createElement(Go,null,e&&i.createElement(Go,null,i.createElement(ln,null,i.createElement(Wt,null,i.createElement(Q,{size:16,type:"actionbook",color:h})),i.createElement(Yt,{$clickable:!!o,$highlightColor:y,variant:"body2",color:_,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(C=>i.createElement(Dn,{key:C.key},i.createElement(Wt,null,i.createElement(Q,{size:16,type:"function",color:h})),i.createElement(ln,null,i.createElement(Yt,{$clickable:!!s,$highlightColor:y,variant:"body2",color:_,onClick:()=>s==null?void 0:s(C),maxTextLines:1},C.name),a&&i.createElement(Np,{role:"button",onClick:()=>a==null?void 0:a(C)},i.createElement(P,{variant:"body2",color:y},"View details"),i.createElement(Q,{type:"chevron-right",size:16,color:y}))))),n==null?void 0:n.map(C=>i.createElement(Dn,{key:C.id},i.createElement(Wt,null,m({default:i.createElement(Q,{size:16,type:Ho[C.source_type]??Ho.snippet,color:h}),sourceType:C.source_type})),i.createElement(Yt,{$clickable:!!l,$highlightColor:y,variant:"body2",color:_,onClick:()=>l==null?void 0:l(C),maxTextLines:1},C.preview_title))),r==null?void 0:r.map(C=>i.createElement(Dn,{key:C.key},i.createElement(Wt,null,i.createElement(Q,{size:16,type:"template",color:h})),i.createElement(Yt,{$clickable:!!c,$highlightColor:y,variant:"body2",color:_,onClick:()=>c==null?void 0:c(C),maxTextLines:1},C.name))),d)},Op=p.default(P)`font-weight:400;`,Yt=p.default(Op)`${({$clickable:e,$highlightColor:t})=>e&&D.css`
376
376
  cursor: pointer;
377
377
  text-decoration: underline;
378
378
  &:hover {
379
379
  color: ${t};
380
380
  }
381
381
  `}
382
- `,Yt=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,an=p.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Ip=p.default(an)`cursor:pointer;gap:4px;`,Nn=p.default(an)`flex-direction:row;align-items:center;`,Gs=p.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Oi=u.createContext(null);function wp({testerType:e,origin:t,children:n}){return i.createElement(Oi.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(Mp,null),n)}const ft=()=>{const e=u.useContext(Oi);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},Mp=()=>{const{isActionbookTester:e}=ft();return i.createElement(tt.Template,{template:e?kp:void 0},i.createElement(tt.MessageLogs,{component:Rp}))},kp=e=>i.createElement(wi,{...e,testerMode:!0,maxBodyWidth:te.WIDE_BODY_MAX_WIDTH}),Rp=({extendedMessagePayload:e={}})=>{const{handlers:t}=ge(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:o,is_thinking:a}=e;return a||!n&&!(r!=null&&r.length)&&!(s!=null&&s.length)&&!(o!=null&&o.length)?i.createElement(i.Fragment,null):i.createElement(Op,null,i.createElement(Lp,{$width:4}),i.createElement(Ri,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:g.themedColor.textHighEmphasis,textColor:g.themedColor.textHighEmphasis,barColor:g.themedColor.textDisabled},bottomContent:i.createElement(Np,{variant:"caption2",color:g.themedColor.textLowEmphasis},"Only visible in the tester")}))},Op=p.default.div`display:flex;gap:16px;margin:16px ${te.HORIZONTAL_PADDING}px 0;align-self:stretch;`,Lp=p.default.div`width:${({$width:e})=>e}px;background-color:${g.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Np=p.default($)`margin-top:5px;`,Vs=40,zs=.9,Dp="[data-message-listitem]",$p='input, textarea, select, [role="textbox"], [contenteditable="true"]',Pp=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*zs;case"PageUp":return t.clientHeight*-zs;case"ArrowDown":return n?Vs:void 0;case"ArrowUp":return n?Vs*-1:void 0;default:return}},Fp=({listRef:e,syncScrollPosition:t})=>u.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($p))return;const o=s===r||s.matches(Dp),a=Pp({event:n,list:r,isMessageAnchor:o});if(a==null||a===0)return;const l=Math.max(0,r.scrollHeight-r.clientHeight),c=Math.min(l,Math.max(0,r.scrollTop+a));c!==r.scrollTop&&(n.preventDefault(),t(c))},[e,t]),Bp="[data-message-listitem]",Up=e=>Math.min(Math.max(0,e),1),Hp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Bp),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})},Vp=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:a})=>{const l=u.useRef(!1),c=u.useRef(void 0),d=u.useRef(0),m=u.useRef(0),h=u.useRef(null),f=u.useRef(null),E=u.useRef(null);u.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),u.useLayoutEffect(()=>{const _=t.current;_&&(c.current==="top"&&(_.scrollTop=_.scrollHeight-m.current,Gp({list:_,focusRestoreTarget:h.current}),h.current=null),c.current==="bottom"&&(_.scrollTop=d.current),c.current=void 0)},[t,r]);const v=u.useCallback(async _=>{const b=t.current;if(!b||(a==null||a(_),m.current=b.scrollHeight-b.scrollTop,d.current=b.scrollTop,l.current))return;const A=b.clientHeight*Up(n);if(b.scrollTop<=A){l.current=!0,c.current="top",h.current=Hp(b),await o(),l.current=!1;return}if(b.scrollHeight-b.scrollTop-b.clientHeight<=A){l.current=!0,c.current="bottom",await s(),l.current=!1;return}c.current=void 0},[t,n,s,o,a]),y=u.useCallback(_=>{const b=t.current;if(!b)return;const A=E.current;if(A!=null){if(A===b.scrollTop){E.current=null;return}E.current=null}const T=f.current;if(T!=null&&T===b.scrollTop){f.current=null,E.current=b.scrollTop,v(_);return}f.current=null,v(_)},[v,t]),C=u.useCallback(_=>{const b=t.current;b&&(f.current=_,E.current=null,b.scrollTop=_,b.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return u.useLayoutEffect(()=>()=>{f.current=null,E.current=null},[]),{handleScroll:y,syncScrollPosition:C}},zp=u.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:a,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:E,onLoadPrev:v,onLoadNext:y,loadThreshold:C=.05,onScroll:_=he,depsForResetScrollPositionToBottom:b,stackDirection:A="top",bottomSpacerHeight:T=0,"aria-label":L}=t,k=u.useRef(null),I=u.useCallback(Y=>{k.current=Y,n&&(typeof n=="function"?n(Y):n.current=Y)},[n]),{handleScroll:w,syncScrollPosition:O}=Vp({depsForResetScrollPositionToBottom:b,listRef:k,loadThreshold:C,messagesLength:r.length,onLoadNext:y,onLoadPrev:v,onScroll:_}),U=Fp({listRef:k,syncScrollPosition:O});return l?i.createElement(i.Fragment,null,c):o?i.createElement(i.Fragment,null,a):i.createElement(Yp,{id:"infinite-list-container"},i.createElement(Wp,{id:"infinite-list-inner",ref:I,onScroll:w,onKeyDown:U,role:"list","aria-label":L,tabIndex:0},A==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((Y,V)=>s({message:Y,index:V})),f,T>0&&i.createElement("div",{style:{minHeight:T}})),i.createElement(qp,{id:"infinite-list-overlay-container"},i.createElement(Kp,{id:"infinite-list-overlay"},E)))}),Yp=p.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Wp=p.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${g.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,qp=p.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,Kp=p.default.div`pointer-events:auto;`,Ke=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...a})=>{const l=s?g.themedColor.textDisabled:g.themedColor.textHighEmphasis;return i.createElement(jp,{as:e,disabled:s,...a},i.createElement(Q,{type:t,size:n,color:r??l}),o)},jp=p.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Se}&:disabled{cursor:not-allowed;}`,Xp=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=u.useState(t),[a,l]=u.useState(!1),{stringSet:c,format:d}=oe(),{config:m}=ge(),h=e.length,f=e[s],E=m.conversation.fileViewer.downloadEnabled,v=h>1,y=(f==null?void 0:f.type)||"",C=je(y),_=tr(y),b=!Im(y);u.useEffect(()=>{r&&(o(t),l(!1))},[r,t]);const A=u.useCallback(()=>{s>0&&(o(L=>L-1),l(!1))},[s]),T=u.useCallback(()=>{s<h-1&&(o(L=>L+1),l(!1))},[s,h]);return u.useEffect(()=>{if(!r)return;const L=k=>{k.key==="ArrowLeft"?A():k.key==="ArrowRight"&&T()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,A,T]),!r||!f?null:i.createElement(nt,{onClose:n,visible:r,portalContainerId:Ee.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(Zp,null,i.createElement(Jp,null,i.createElement(Qp,null,i.createElement(e_,null,i.createElement($,{variant:"button",maxTextLines:1,color:g.color.ondark.textHighEmphasis},f.name||c.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&i.createElement($,{variant:"caption2",color:g.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),i.createElement(t_,{type:"close",size:18,color:g.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(n_,{onClick:L=>L.currentTarget===L.target&&n()},v&&i.createElement(Ys,{$position:"left",type:"chevron-right",size:22,color:g.color.ondark.textHighEmphasis,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),i.createElement(r_,null,C&&i.createElement(i.Fragment,null,!a&&i.createElement(s_,null,i.createElement(it,{size:32},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(o_,{src:f.url,alt:f.name||"Image",$loaded:a,onLoad:()=>l(!0)})),_&&i.createElement(i_,{controls:!0},i.createElement("source",{src:f.url,type:y})),b&&i.createElement(a_,null,i.createElement($,{variant:"h1",color:g.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),v&&i.createElement(Ys,{$position:"right",type:"chevron-right",size:22,color:g.color.ondark.textHighEmphasis,onClick:T,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),i.createElement(l_,null,v&&i.createElement($,{variant:"body2",color:g.color.ondark.textHighEmphasis},s+1,"/",h),E&&!b&&i.createElement(c_,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:g.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},Zp=p.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${g.themedColor.bg_50_600};`,Jp=p.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 12px 12px 16px;min-height:56px;background-color:${g.color.overlay.dark};`,Qp=p.default.div`flex:1;min-width:0;padding-right:8px;`,e_=p.default.div`display:flex;flex-direction:column;gap:2px;`,t_=p.default(Ke)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,pn=p.default.div`display:flex;align-items:center;justify-content:center;`,n_=p.default(pn)`flex:1;min-height:0;position:relative;`,r_=p.default(pn)`position:relative;max-width:100%;max-height:100%;`,s_=p.default(pn)`position:absolute;inset:0;`,o_=p.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;`,i_=p.default.video`max-width:100%;max-height:100%;object-fit:contain;`,a_=p.default(pn)`flex-direction:column;gap:16px;`,Ys=p.default(Ke)`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:${g.color.overlay.dark};&:disabled{opacity:0.3;}`,l_=p.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding:16px;min-height:56px;background-color:${g.color.overlay.dark};`,c_=p.default(Ke)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,xr=({title:e,titleId:t,description:n,descriptionId:r,negativeText:s,positiveText:o,onCancel:a,onConfirm:l,buttonLayout:c="horizontal",styles:d})=>{const m=s!==void 0&&a!==void 0,h=o!==void 0&&l!==void 0,f=m?i.createElement(f_,{type:"button",onClick:a,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},i.createElement($,{variant:"button",color:(d==null?void 0:d.negativeText)??g.themedColor.textHighEmphasis},s)):null,E=h?i.createElement(g_,{type:"button",onClick:l,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},i.createElement($,{variant:"button",color:(d==null?void 0:d.positiveText)??g.themedColor.textHighEmphasisInverse},o)):null;return i.createElement(u_,null,i.createElement(d_,null,i.createElement($,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??g.themedColor.textHighEmphasis},e)),i.createElement(m_,null,i.createElement($,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??g.themedColor.textMidEmphasis},n)),i.createElement(h_,{$buttonLayout:c},c==="horizontal"?i.createElement(i.Fragment,null,f,E):i.createElement(i.Fragment,null,E,f)))},u_=p.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,d_=p.default.div`padding:24px 24px 16px;`,m_=p.default.div`padding-inline:24px;`,h_=p.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;`,f_=p.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;}`,g_=p.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??g.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,Wt=16,p_=({status:e})=>e===Xt.COMPLETED?i.createElement(Q,{type:"done-circle",size:Wt,color:g.themedColor.textHighEmphasis}):e===Xt.CANCELED?i.createElement(Q,{type:"stop-circle",size:Wt,color:g.themedColor.textLowEmphasis}):i.createElement(it,{size:Wt},i.createElement(Q,{type:"spinner",size:Wt,color:g.themedColor.textHighEmphasis})),Li=24,__=8,E_=40,b_=({task:e,isFirst:t,isLast:n})=>i.createElement(C_,{role:"listitem"},i.createElement(v_,null,i.createElement(Ws,{$hidden:t}),i.createElement(y_,null,i.createElement(p_,{status:e.status})),i.createElement(Ws,{$hidden:n})),i.createElement(S_,null,i.createElement($,{as:"div",variant:"body3",color:e.status===Xt.CANCELED?g.themedColor.textLowEmphasis:g.themedColor.textHighEmphasis},e.user_facing_title))),C_=p.default.div`display:flex;gap:4px;`,v_=p.default.div`display:flex;flex-direction:column;align-items:center;width:${Li}px;flex-shrink:0;`,Ws=p.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${g.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,y_=p.default.div`display:flex;height:${Li}px;align-items:center;justify-content:center;`,S_=p.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${E_}px;padding-block:${__}px;`,A_=({steward:e,onCancelSteward:t})=>{const{logger:n}=ge(),[r,s]=u.useState(!1),[o,a]=u.useState(!1),l=!!e.cancellation_option,c=ma(e.status);return i.createElement(x_,{$marginBottom:ln("single")},i.createElement(T_,null,i.createElement(I_,null,i.createElement(w_,null,i.createElement($,{as:"div",variant:"caption1",color:g.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement($,{as:"div",variant:"caption4",color:g.themedColor.textLowEmphasis},e.description)),l&&i.createElement(O_,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},i.createElement(Q,{type:"stop",size:16,color:o?g.themedColor.textDisabled:g.themedColor.textHighEmphasis}))),i.createElement(M_,null),e.tasks.length===0?c!==xt.IN_PROGRESS?null:i.createElement(R_,null,i.createElement(it,{size:16},i.createElement(Q,{type:"spinner",size:16,color:g.themedColor.textHighEmphasis}))):i.createElement(k_,{role:"list"},e.tasks.map((d,m)=>i.createElement(b_,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(nt,{portalContainerId:Ee.WINDOW,visible:r,onClose:()=>s(!1)},i.createElement(xr,{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),a(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{a(!1)}}})))},x_=p.default.div`display:flex;flex-direction:column;margin:0 ${te.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
383
- `,T_=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${g.themedColor.bg_300_500};background-color:${g.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,I_=p.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,w_=p.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,M_=p.default.div`height:1px;margin-block:12px;background-color:${g.themedColor.bg_200_400};`,k_=p.default.div`display:flex;flex-direction:column;`,R_=p.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,O_=p.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:${g.themedColor.textHighEmphasis};background-color:${g.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,L_=({className:e,label:t,onClick:n})=>{const{colors:r}=D.useTheme(),{conversation:s}=se(),o={newMessages:s.newMessagesButton()};return i.createElement(N_,{className:e,onClick:n,...o.newMessages.props},i.createElement($,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(Q,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},N_=p.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;}${Se}`,Tr=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>i.createElement($_,{className:n},t&&i.createElement(Q,{type:t,size:e,color:g.themedColor.textLowEmphasis}),r&&i.createElement($,{variant:"body1",color:g.themedColor.textMidEmphasis},r),s),D_=p.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,$_=p.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,P_=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(Tr,{icon:t,label:e,...r},n&&i.createElement(F_,{onClick:n.onClick,label:n.label??"Retry"})),F_=({label:e,onClick:t})=>{const{conversation:n}=se();return i.createElement(B_,{tabIndex:0,...n.retryButton(e).props,onClick:t},i.createElement(Q,{type:"refresh",size:20}),i.createElement($,{variant:"button",color:g.color.primary.main},e))},B_=p.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Se}`,U_=({iconSize:e=48,className:t})=>i.createElement(it,{size:e,className:t}),H_=({label:e="No channels",icon:t="chat",...n})=>i.createElement(Tr,{icon:t,label:e,...n}),G_=({label:e="No messages",icon:t="message",...n})=>i.createElement(Tr,{icon:t,label:e,...n}),V_=e=>{const{components:t}=_n.useContext(),n=e.type==="loading"?i.createElement(t.Loading,{...e}):e.type==="error"?i.createElement(t.Error,{...e}):e.type==="noChannels"?i.createElement(t.NoChannels,{...e}):e.type==="noMessages"?i.createElement(t.NoMessages,{...e}):null;return n&&i.createElement(D_,null,n)},_n=Ue({template:V_,components:{Loading:U_,Error:P_,NoChannels:H_,NoMessages:G_}}),Tt=e=>{const{Template:t}=_n.useContext();return i.createElement(t,{...e})},z_=[0,150,450];function Y_({enabled:e}){const{state:t,actions:n}=ai(),r=u.useRef(0),s=u.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,u.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const a=z_.map(l=>setTimeout(()=>{Re(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const W_=({className:e,date:t=Date.now(),style:n})=>{const{format:r,stringSet:s}=oe();return i.createElement(q_,{id:`${Ne}-date-separator`,style:n,className:e},i.createElement($,{variant:"caption4",color:g.themedColor.textMidEmphasis},r(t,s.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},q_=p.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,K_=({className:e,style:t,onClick:n})=>{const{conversation:r}=se(),s={scrollToBottom:r.scrollToBottomButton()};return i.createElement(j_,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},i.createElement(Q,{size:24,type:"chevron-down",color:g.color.primary.main}),s.scrollToBottom.descriptionNode??null)},j_=p.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);${J.light`
382
+ `,Wt=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,ln=p.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Np=p.default(ln)`cursor:pointer;gap:4px;`,Dn=p.default(ln)`flex-direction:row;align-items:center;`,Go=p.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ni=u.createContext(null);function Dp({testerType:e,origin:t,children:n}){return i.createElement(Ni.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement($p,null),n)}const pt=()=>{const e=u.useContext(Ni);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},$p=()=>{const{isActionbookTester:e}=pt();return i.createElement(tt.Template,{template:e?Pp:void 0},i.createElement(tt.MessageLogs,{component:Fp}))},Pp=e=>i.createElement(ki,{...e,testerMode:!0,maxBodyWidth:ne.WIDE_BODY_MAX_WIDTH}),Fp=({extendedMessagePayload:e={}})=>{const{handlers:t}=me(),{manual:n,groundedness:r,function_calls:o,agent_message_templates:s,is_thinking:a}=e;return a||!n&&!(r!=null&&r.length)&&!(o!=null&&o.length)&&!(s!=null&&s.length)?i.createElement(i.Fragment,null):i.createElement(Bp,null,i.createElement(Up,{$width:4}),i.createElement(Oi,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:g.themedColor.textHighEmphasis,textColor:g.themedColor.textHighEmphasis,barColor:g.themedColor.textDisabled},bottomContent:i.createElement(Hp,{variant:"caption2",color:g.themedColor.textLowEmphasis},"Only visible in the tester")}))},Bp=p.default.div`display:flex;gap:16px;margin:16px ${ne.HORIZONTAL_PADDING}px 0;align-self:stretch;`,Up=p.default.div`width:${({$width:e})=>e}px;background-color:${g.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Hp=p.default(P)`margin-top:5px;`,zo=40,Vo=.9,Gp="[data-message-listitem]",zp='input, textarea, select, [role="textbox"], [contenteditable="true"]',Vp=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Vo;case"PageUp":return t.clientHeight*-Vo;case"ArrowDown":return n?zo:void 0;case"ArrowUp":return n?zo*-1:void 0;default:return}},Yp=({listRef:e,syncScrollPosition:t})=>u.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const o=n.target;if(!o||!r.contains(o)||o.closest(zp))return;const s=o===r||o.matches(Gp),a=Vp({event:n,list:r,isMessageAnchor:s});if(a==null||a===0)return;const l=Math.max(0,r.scrollHeight-r.clientHeight),c=Math.min(l,Math.max(0,r.scrollTop+a));c!==r.scrollTop&&(n.preventDefault(),t(c))},[e,t]),Wp="[data-message-listitem]",qp=e=>Math.min(Math.max(0,e),1),Kp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Wp),o=n===e||n===r;return!n||!e.contains(n)?null:o?e:n},jp=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,o=r===e||e.contains(r),s=t===e||e.contains(t);o&&s&&t.focus({preventScroll:!0})},Xp=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:o,onLoadPrev:s,onScroll:a})=>{const l=u.useRef(!1),c=u.useRef(void 0),d=u.useRef(0),m=u.useRef(0),f=u.useRef(null),h=u.useRef(null),_=u.useRef(null);u.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),u.useLayoutEffect(()=>{const b=t.current;b&&(c.current==="top"&&(b.scrollTop=b.scrollHeight-m.current,jp({list:b,focusRestoreTarget:f.current}),f.current=null),c.current==="bottom"&&(b.scrollTop=d.current),c.current=void 0)},[t,r]);const y=u.useCallback(async b=>{const E=t.current;if(!E||(a==null||a(b),m.current=E.scrollHeight-E.scrollTop,d.current=E.scrollTop,l.current))return;const A=E.clientHeight*qp(n);if(E.scrollTop<=A){l.current=!0,c.current="top",f.current=Kp(E),await s(),l.current=!1;return}if(E.scrollHeight-E.scrollTop-E.clientHeight<=A){l.current=!0,c.current="bottom",await o(),l.current=!1;return}c.current=void 0},[t,n,o,s,a]),C=u.useCallback(b=>{const E=t.current;if(!E)return;const A=_.current;if(A!=null){if(A===E.scrollTop){_.current=null;return}_.current=null}const x=h.current;if(x!=null&&x===E.scrollTop){h.current=null,_.current=E.scrollTop,y(b);return}h.current=null,y(b)},[y,t]),v=u.useCallback(b=>{const E=t.current;E&&(h.current=b,_.current=null,E.scrollTop=b,E.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return u.useLayoutEffect(()=>()=>{h.current=null,_.current=null},[]),{handleScroll:C,syncScrollPosition:v}},Zp=u.forwardRef(function(t,n){const{messages:r,renderMessage:o,loading:s,LoadingComponent:a,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:f,messageBottomArea:h,overlayArea:_,onLoadPrev:y,onLoadNext:C,loadThreshold:v=.05,onScroll:b=he,depsForResetScrollPositionToBottom:E,stackDirection:A="top",bottomSpacerHeight:x=0,"aria-label":k}=t,R=u.useRef(null),I=u.useCallback(V=>{R.current=V,n&&(typeof n=="function"?n(V):n.current=V)},[n]),{handleScroll:w,syncScrollPosition:O}=Xp({depsForResetScrollPositionToBottom:E,listRef:R,loadThreshold:v,messagesLength:r.length,onLoadNext:C,onLoadPrev:y,onScroll:b}),$=Yp({listRef:R,syncScrollPosition:O});return l?i.createElement(i.Fragment,null,c):s?i.createElement(i.Fragment,null,a):i.createElement(Jp,{id:"infinite-list-container"},i.createElement(Qp,{id:"infinite-list-inner",ref:I,onScroll:w,onKeyDown:$,role:"list","aria-label":k,tabIndex:0},A==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),f,d?m:r.map((V,H)=>o({message:V,index:H})),h,x>0&&i.createElement("div",{style:{minHeight:x}})),i.createElement(e_,{id:"infinite-list-overlay-container"},i.createElement(t_,{id:"infinite-list-overlay"},_)))}),Jp=p.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Qp=p.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${g.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,e_=p.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,t_=p.default.div`pointer-events:auto;`,je=({as:e,type:t,size:n=16,color:r,disabled:o,children:s,...a})=>{const l=o?g.themedColor.textDisabled:g.themedColor.textHighEmphasis;return i.createElement(n_,{as:e,disabled:o,...a},i.createElement(Q,{type:t,size:n,color:r??l}),s)},n_=p.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Ae}&:disabled{cursor:not-allowed;}`,r_=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[o,s]=u.useState(t),[a,l]=u.useState(!1),{stringSet:c,format:d}=se(),{config:m}=me(),f=e.length,h=e[o],_=m.conversation.fileViewer.downloadEnabled,y=f>1,C=(h==null?void 0:h.type)||"",v=He(C),b=cn(C),E=!Om(C);u.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const A=u.useCallback(()=>{o>0&&(s(k=>k-1),l(!1))},[o]),x=u.useCallback(()=>{o<f-1&&(s(k=>k+1),l(!1))},[o,f]);return u.useEffect(()=>{if(!r)return;const k=R=>{R.key==="ArrowLeft"?A():R.key==="ArrowRight"&&x()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[r,A,x]),!r||!h?null:i.createElement(nt,{onClose:n,visible:r,portalContainerId:Ce.MODAL_ROOT,"aria-label":(h==null?void 0:h.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(o_,null,i.createElement(s_,null,i.createElement(i_,null,i.createElement(a_,null,i.createElement(P,{variant:"button",maxTextLines:1,color:g.color.ondark.textHighEmphasis},h.name||c.IMAGE_VIEWER__DEFAULT_TITLE),h.timestamp&&i.createElement(P,{variant:"caption2",color:g.color.ondark.textHighEmphasis},d(new Date(h.timestamp),"h:mm a")))),i.createElement(l_,{type:"close",size:18,color:g.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(c_,{onClick:k=>k.currentTarget===k.target&&n()},y&&i.createElement(Yo,{$position:"left",type:"chevron-right",size:22,color:g.color.ondark.textHighEmphasis,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(u_,null,v&&i.createElement(i.Fragment,null,!a&&i.createElement(d_,null,i.createElement(at,{size:32},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(m_,{src:h.url,alt:h.name||"Image",$loaded:a,onLoad:()=>l(!0)})),b&&i.createElement(f_,{controls:!0},i.createElement("source",{src:h.url,type:C})),E&&i.createElement(h_,null,i.createElement(P,{variant:"h1",color:g.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),y&&i.createElement(Yo,{$position:"right",type:"chevron-right",size:22,color:g.color.ondark.textHighEmphasis,onClick:x,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===f-1})),i.createElement(g_,null,y&&i.createElement(P,{variant:"body2",color:g.color.ondark.textHighEmphasis},o+1,"/",f),_&&!E&&i.createElement(p_,{forwardedAs:"a",href:h.url,download:h.name||"file",type:"download",size:24,color:g.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},o_=p.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${g.themedColor.bg_50_600};`,s_=p.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 12px 12px 16px;min-height:56px;background-color:${g.color.overlay.dark};`,i_=p.default.div`flex:1;min-width:0;padding-right:8px;`,a_=p.default.div`display:flex;flex-direction:column;gap:2px;`,l_=p.default(je)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,_n=p.default.div`display:flex;align-items:center;justify-content:center;`,c_=p.default(_n)`flex:1;min-height:0;position:relative;`,u_=p.default(_n)`position:relative;max-width:100%;max-height:100%;`,d_=p.default(_n)`position:absolute;inset:0;`,m_=p.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;`,f_=p.default.video`max-width:100%;max-height:100%;object-fit:contain;`,h_=p.default(_n)`flex-direction:column;gap:16px;`,Yo=p.default(je)`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:${g.color.overlay.dark};&:disabled{opacity:0.3;}`,g_=p.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding:16px;min-height:56px;background-color:${g.color.overlay.dark};`,p_=p.default(je)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,xr=({title:e,titleId:t,description:n,descriptionId:r,negativeText:o,positiveText:s,onCancel:a,onConfirm:l,buttonLayout:c="horizontal",styles:d})=>{const m=o!==void 0&&a!==void 0,f=s!==void 0&&l!==void 0,h=m?i.createElement(v_,{type:"button",onClick:a,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},i.createElement(P,{variant:"button",color:(d==null?void 0:d.negativeText)??g.themedColor.textHighEmphasis},o)):null,_=f?i.createElement(y_,{type:"button",onClick:l,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},i.createElement(P,{variant:"button",color:(d==null?void 0:d.positiveText)??g.themedColor.textHighEmphasisInverse},s)):null;return i.createElement(__,null,i.createElement(E_,null,i.createElement(P,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??g.themedColor.textHighEmphasis},e)),i.createElement(b_,null,i.createElement(P,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??g.themedColor.textMidEmphasis},n)),i.createElement(C_,{$buttonLayout:c},c==="horizontal"?i.createElement(i.Fragment,null,h,_):i.createElement(i.Fragment,null,_,h)))},__=p.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,E_=p.default.div`padding:24px 24px 16px;`,b_=p.default.div`padding-inline:24px;`,C_=p.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;`,v_=p.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;}`,y_=p.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??g.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,qt=16,S_=({status:e})=>e===Zt.COMPLETED?i.createElement(Q,{type:"done-circle",size:qt,color:g.themedColor.textHighEmphasis}):e===Zt.CANCELED?i.createElement(Q,{type:"stop-circle",size:qt,color:g.themedColor.textLowEmphasis}):i.createElement(at,{size:qt},i.createElement(Q,{type:"spinner",size:qt,color:g.themedColor.textHighEmphasis})),Di=24,A_=8,x_=40,T_=({task:e,isFirst:t,isLast:n})=>i.createElement(I_,{role:"listitem"},i.createElement(w_,null,i.createElement(Wo,{$hidden:t}),i.createElement(M_,null,i.createElement(S_,{status:e.status})),i.createElement(Wo,{$hidden:n})),i.createElement(k_,null,i.createElement(P,{as:"div",variant:"body3",color:e.status===Zt.CANCELED?g.themedColor.textLowEmphasis:g.themedColor.textHighEmphasis},e.user_facing_title))),I_=p.default.div`display:flex;gap:4px;`,w_=p.default.div`display:flex;flex-direction:column;align-items:center;width:${Di}px;flex-shrink:0;`,Wo=p.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${g.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,M_=p.default.div`display:flex;height:${Di}px;align-items:center;justify-content:center;`,k_=p.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${x_}px;padding-block:${A_}px;`,R_=({steward:e,onCancelSteward:t})=>{const{logger:n}=me(),[r,o]=u.useState(!1),[s,a]=u.useState(!1),l=!!e.cancellation_option,c=ha(e.status);return i.createElement(L_,{$marginBottom:un("single")},i.createElement(O_,null,i.createElement(N_,null,i.createElement(D_,null,i.createElement(P,{as:"div",variant:"caption1",color:g.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement(P,{as:"div",variant:"caption4",color:g.themedColor.textLowEmphasis},e.description)),l&&i.createElement(B_,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(Q,{type:"stop",size:16,color:s?g.themedColor.textDisabled:g.themedColor.textHighEmphasis}))),i.createElement($_,null),e.tasks.length===0?c!==xt.IN_PROGRESS?null:i.createElement(F_,null,i.createElement(at,{size:16},i.createElement(Q,{type:"spinner",size:16,color:g.themedColor.textHighEmphasis}))):i.createElement(P_,{role:"list"},e.tasks.map((d,m)=>i.createElement(T_,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(xr,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>o(!1),onConfirm:async()=>{o(!1),a(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{a(!1)}}})))},L_=p.default.div`display:flex;flex-direction:column;margin:0 ${ne.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
383
+ `,O_=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${g.themedColor.bg_300_500};background-color:${g.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,N_=p.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,D_=p.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,$_=p.default.div`height:1px;margin-block:12px;background-color:${g.themedColor.bg_200_400};`,P_=p.default.div`display:flex;flex-direction:column;`,F_=p.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,B_=p.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:${g.themedColor.textHighEmphasis};background-color:${g.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,U_=({className:e,label:t,onClick:n})=>{const{colors:r}=D.useTheme(),{conversation:o}=oe(),s={newMessages:o.newMessagesButton()};return i.createElement(H_,{className:e,onClick:n,...s.newMessages.props},i.createElement(P,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(Q,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),s.newMessages.descriptionNode)},H_=p.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;}${Ae}`,Tr=({iconSize:e=64,icon:t,className:n,label:r,children:o})=>i.createElement(z_,{className:n},t&&i.createElement(Q,{type:t,size:e,color:g.themedColor.textLowEmphasis}),r&&i.createElement(P,{variant:"body1",color:g.themedColor.textMidEmphasis},r),o),G_=p.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,z_=p.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,V_=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(Tr,{icon:t,label:e,...r},n&&i.createElement(Y_,{onClick:n.onClick,label:n.label??"Retry"})),Y_=({label:e,onClick:t})=>{const{conversation:n}=oe();return i.createElement(W_,{tabIndex:0,...n.retryButton(e).props,onClick:t},i.createElement(Q,{type:"refresh",size:20}),i.createElement(P,{variant:"button",color:g.color.primary.main},e))},W_=p.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Ae}`,q_=({iconSize:e=48,className:t})=>i.createElement(at,{size:e,className:t}),K_=({label:e="No channels",icon:t="chat",...n})=>i.createElement(Tr,{icon:t,label:e,...n}),j_=({label:e="No messages",icon:t="message",...n})=>i.createElement(Tr,{icon:t,label:e,...n}),X_=e=>{const{components:t}=En.useContext(),n=e.type==="loading"?i.createElement(t.Loading,{...e}):e.type==="error"?i.createElement(t.Error,{...e}):e.type==="noChannels"?i.createElement(t.NoChannels,{...e}):e.type==="noMessages"?i.createElement(t.NoMessages,{...e}):null;return n&&i.createElement(G_,null,n)},En=Ue({template:X_,components:{Loading:q_,Error:V_,NoChannels:K_,NoMessages:j_}}),Tt=e=>{const{Template:t}=En.useContext();return i.createElement(t,{...e})},Z_=[0,150,450];function J_({enabled:e}){const{state:t,actions:n}=ci(),r=u.useRef(0),o=u.useRef(t.isAwayFromBottom);o.current=t.isAwayFromBottom,u.useEffect(()=>{if(!e){r.current+=1;return}const s=r.current+1;r.current=s;const a=Z_.map(l=>setTimeout(()=>{Le(()=>{r.current===s&&(o.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const Q_=({className:e,date:t=Date.now(),style:n})=>{const{format:r,stringSet:o}=se();return i.createElement(eE,{id:`${Ne}-date-separator`,style:n,className:e},i.createElement(P,{variant:"caption4",color:g.themedColor.textMidEmphasis},r(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},eE=p.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,tE=({className:e,style:t,onClick:n})=>{const{conversation:r}=oe(),o={scrollToBottom:r.scrollToBottomButton()};return i.createElement(nE,{className:e,style:t,onClick:n,tabIndex:0,...o.scrollToBottom.props},i.createElement(Q,{size:24,type:"chevron-down",color:g.color.primary.main}),o.scrollToBottom.descriptionNode??null)},nE=p.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);${J.light`
384
384
  background-color: ${g.color.background50};
385
385
  &:hover {
386
386
  background-color: ${g.color.background100};
@@ -403,12 +403,12 @@
403
403
  outline: none;
404
404
  }
405
405
 
406
- ${Se}
407
- `,X_=()=>null,En=Ue({template:X_,components:{DateSeparator:W_,ScrollToBottomButton:K_}}),Z_=()=>{const{stringSet:e,format:t}=oe(),{agentPreviewConfigs:n={},aiAgentId:r}=ge(),{aiAgentInfo:s}=Te(),{messageSource:o}=ve(),{Template:a}=tt.useContext(),{components:l}=En.useContext(),c=n.welcomeMessages??[],d=o.messages,m=Mm(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:ui(d,{previewWelcomeMessages:c,aiAgentUserId:r}),shouldShowOriginalDate:E=>E>0||c.length===0?!0:h&&!Xe.isSameDay(h.createdAt,(f==null?void 0:f.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>c.length===0?null:i.createElement(i.Fragment,null,i.createElement(l.DateSeparator,{style:{margin:"16px 0"},date:f==null?void 0:f.createdAt}),c.map((E,v)=>{const y=v===c.length-1,C=m.length!==d.length,_=c.length===1?"single":v===0?"top":y||C?"bottom":"middle",b=(f==null?void 0:f.createdAt)??Date.now();return i.createElement("div",{key:v,role:"listitem",tabIndex:-1,"aria-label":yt({sender:(s==null?void 0:s.nickname)||"",message:E.message,messageFormat:"markdown",time:t(b,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},i.createElement(a,{messageType:"user",message:E.message,sender:s,groupType:_,createdAt:b,extendedMessagePayload:{suggested_replies:E.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:y&&!C,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{o.sendUserMessage({message:A})}}))}))}},J_=()=>{const{messageSource:e,scrollSource:t}=ve();u.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Q_=({style:e})=>{const{stringSet:t}=oe(),{conversation:n}=se(),{isActionbookTester:r}=ft();return!dr("powered-by")||r?null:i.createElement(eE,{variant:"caption2",style:e},t.POWERED_BY+" ",i.createElement(tE,{variant:"caption2",forwardedAs:"a",href:"https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",...n.poweredByLink().props,rel:gr,target:"_blank"},"Sendbird"))},eE=p.default($)`color:${g.themedColor.textLowEmphasis};text-align:center;`,tE=p.default($)`color:${g.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,nE=()=>{var l;const{stringSet:e}=oe(),{conversation:t}=se(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=ve(),o=ke(n.channel),a=u.useRef(o);return u.useEffect(()=>{if(!a.current&&o){const m=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(m)}a.current=o},[o,s.actions.scrollToBottom]),!((l=n.channel)!=null&&l.isAIAgent)||!o?null:i.createElement(rE,null,i.createElement(sE,{variant:"button",color:g.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},rE=p.default.div`display:flex;justify-content:center;margin-bottom:16px;`,sE=p.default($)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${g.color.background50};border:1px solid ${g.color.onlight.textDisabled};${J.dark`
406
+ ${Ae}
407
+ `,rE=()=>null,bn=Ue({template:rE,components:{DateSeparator:Q_,ScrollToBottomButton:tE}}),oE=()=>{const{stringSet:e,format:t}=se(),{agentPreviewConfigs:n={},aiAgentId:r}=me(),{aiAgentInfo:o}=we(),{messageSource:s}=Se(),{Template:a}=tt.useContext(),{components:l}=bn.useContext(),c=n.welcomeMessages??[],d=s.messages,m=Dm(d,r),f=d[m.length+1],h=m[0]??f;return{filteredMessages:mi(d,{previewWelcomeMessages:c,aiAgentUserId:r}),shouldShowOriginalDate:_=>_>0||c.length===0?!0:f&&!Xe.isSameDay(f.createdAt,(h==null?void 0:h.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>c.length===0?null:i.createElement(i.Fragment,null,i.createElement(l.DateSeparator,{style:{margin:"16px 0"},date:h==null?void 0:h.createdAt}),c.map((_,y)=>{const C=y===c.length-1,v=m.length!==d.length,b=c.length===1?"single":y===0?"top":C||v?"bottom":"middle",E=(h==null?void 0:h.createdAt)??Date.now();return i.createElement("div",{key:y,role:"listitem",tabIndex:-1,"aria-label":yt({sender:(o==null?void 0:o.nickname)||"",message:_.message,messageFormat:"markdown",time:t(E,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},i.createElement(a,{messageType:"user",message:_.message,sender:o,groupType:b,createdAt:E,extendedMessagePayload:{suggested_replies:_.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:C&&!v,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{s.sendUserMessage({message:A})}}))}))}},sE=()=>{const{messageSource:e,scrollSource:t}=Se();u.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},qo="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",iE=({style:e})=>{const{stringSet:t}=se(),{handlers:n}=me(),{conversation:r}=oe(),{isActionbookTester:o}=pt();return!dr("powered-by")||o?null:i.createElement(aE,{variant:"caption2",style:e},t.POWERED_BY+" ",i.createElement(lE,{variant:"caption2",forwardedAs:"a",href:qo,...r.poweredByLink().props,rel:gr,target:"_blank",onClick:a=>{a.preventDefault(),n.onClickLink({url:qo})}},"Sendbird"))},aE=p.default(P)`color:${g.themedColor.textLowEmphasis};text-align:center;`,lE=p.default(P)`color:${g.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,cE=()=>{var l;const{stringSet:e}=se(),{conversation:t}=oe(),{channelSource:n,goToActiveConversation:r,scrollSource:o}=Se(),s=Re(n.channel),a=u.useRef(s);return u.useEffect(()=>{if(!a.current&&s){const m=setTimeout(()=>{o.actions.scrollToBottom()},100);return()=>clearTimeout(m)}a.current=s},[s,o.actions.scrollToBottom]),!((l=n.channel)!=null&&l.isAIAgent)||!s?null:i.createElement(uE,null,i.createElement(dE,{variant:"button",color:g.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},uE=p.default.div`display:flex;justify-content:center;margin-bottom:16px;`,dE=p.default(P)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${g.color.background50};border:1px solid ${g.color.onlight.textDisabled};${J.dark`
408
408
  background-color: ${g.color.background700};
409
409
  border-color: ${g.color.ondark.textLowEmphasis};
410
410
  `}
411
- `,oE=()=>{var ae;const{Template:e}=Nt.useContext(),{Template:t}=tt.useContext(),{Template:n}=gn.useContext(),{components:r}=En.useContext(),{stringSet:s,format:o}=oe(),{file:a}=se().conversation,{config:l,cache:c,agentPreviewConfigs:d,chatSDK:m,state:h}=ge(),{userSession:f,aiAgentInfo:E,connectionError:v}=Te(),{conversation:y,channelSource:C,messageSource:_,scrollSource:b,state:{input:A,streamAnimation:T}}=ve(),{isActionbookTester:L}=ft(),{filteredMessages:k,shouldShowOriginalDate:I,renderAgentPreviewWelcomeMessages:w}=Z_(),O=Mo(C.channel),[U,Y]=u.useState(null),[V,z]=u.useState(null);u.useEffect(()=>{b.actions.onTypingIndicatorUpdate(!!O)},[!!O,b.actions.onTypingIndicatorUpdate]),J_(),Y_({enabled:_.initialized&&_.messages.length>0});const H=(M,ye=!1)=>{var X;return ye?E:((X=C.channel)==null?void 0:X.members.find(q=>q.userId===M.sender.userId))??M.sender},W=M=>{if(M.sendingStatus==="failed"&&!A.disabled)return()=>z(M)},K=({message:M,index:ye})=>{const X=ha(M),q=k[ye-1],G=k[ye+1],ee=k[k.length-1],de=M===ee,le=dt(M,E.userId),we=!(E.isUserFeedbackEnabled&&le&&!Ge.isWelcomeMessage(M)),Le=fa(M,q,G,we),Me=!la.isSameDay((q==null?void 0:q.createdAt)??0,M.createdAt)&&I(ye)&&!L,x=re=>{Y({files:re.files.map(ie=>({...ie,timestamp:M.createdAt})),index:re.index})},R=re=>{x({files:[re],index:0})},N=()=>{M.isFileMessage()&&Er(M.url)},j=Me?i.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:M.createdAt}):null,P={data:M.data,maxBodyWidth:h.expanded?te.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:M.extendedMessagePayload,createdAt:M.createdAt,groupType:Le,onClickMedia:R,onClickMediaFiles:x,onClickFile:N},B=()=>{if(xe.isOutgoing(M,f.userId))return"outgoingmessage";if(xe.isIncoming(M,f.userId))return"incomingmessage"},F=M.createdAt!=null&&M.createdAt!==0?o(M.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ue=(()=>{var ie,ne,Z,me,pe,_t;const re=(ie=M.message)==null?void 0:ie.trim();if(M.isFileMessage()){const rt=((ne=M.name)==null?void 0:ne.trim())||"";return Tn({markdownText:re,comparisonText:rt,plainText:a.label(rt,M.type)})}if(M.isMultipleFilesMessage()){const rt=((pe=(me=(Z=M.fileInfoList)==null?void 0:Z[0])==null?void 0:me.fileName)==null?void 0:pe.trim())||"",Fr=((_t=M.fileInfoList)==null?void 0:_t.length)??0;return Tn({markdownText:re,comparisonText:rt,plainText:Fr>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Fr):""})}return re?Tn({markdownText:re}):Do("")})(),$e=(()=>{if(xe.isAdmin(M))return yt({message:ue.text,messageFormat:ue.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(xe.isOutgoing(M,f.userId))return yt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:ue.text,messageFormat:"plain",time:F,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(xe.isIncoming(M,f.userId))return yt({sender:H(M,le).nickname,message:ue.text,messageFormat:ue.format,time:F,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),ce=(()=>{var re,ie;if(xe.isAdmin(M))return xe.isCSAT(M)?y?i.createElement(n,{...P,...y,isResolvedWhenDeterminedByUser:Va(y),messageType:"admin.csat",onSubmitCSAT:async ne=>{var Z;await((Z=C.channel)==null?void 0:Z.submitCSAT(ne))},onScrollToBottom:()=>b.actions.scrollToBottom()}):null:i.createElement(n,{...P,messageType:"admin",message:M.message});if(xe.isSteward(M))return i.createElement(A_,{steward:M.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:M.channelUrl,messageId:M.messageId})}});if(xe.isOutgoing(M,f.userId)){const ne={...P,message:M.message,sender:H(M),sendingStatus:M.sendingStatus,onClickFailedMessage:W(M)};if(M.isUserMessage())return i.createElement(e,{messageType:"user",...ne});if(M.isFileMessage()){const[Z,me]=((re=M.metaArrays.find(pe=>pe.key===oo))==null?void 0:re.value)??[];return i.createElement(e,{messageType:"file",file:M,metadata:{aspectRatio:Z&&me?`${Z}/${me}`:"1/1",localFile:(ie=M.messageParams)==null?void 0:ie.file},...ne})}if(M.isMultipleFilesMessage()){const{files:Z,metadata:me}=Rs(M);return i.createElement(e,{messageType:"multipleFiles",files:Z,metadata:me,...ne})}}if(xe.isIncoming(M,f.userId)){const ne={...P,sender:H(M,le),message:M.message,suggestedRepliesVisible:de,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:le,isStreaming:Ge.isStreaming(M),isHandedOff:et(C.channel),isConversationClosed:ke(C.channel),isFeedbackEnabled:E.isUserFeedbackEnabled,isFeedbackCommentEnabled:E.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled,markdownImageRenderMode:l.conversation.list.markdownImageRenderMode,onClickSuggestedReply:async({reply:Z})=>{_.sendUserMessage({message:Z})},onRequestMessageTemplate:async Z=>{const{template:me}=await m.aiAgent.getMessageTemplate(Z);return c.template.set(Z,me),me},onGetCachedMessageTemplate:Z=>c.template.get(Z),onHandleTemplateInternalAction:Z=>{if(Z.type==="internal"&&Z.internalData){const{method:me,payload:pe}=Z.internalData;me==="message.send"&&(pe!=null&&pe.message)&&_.sendUserMessage({message:pe.message})}},onFeedbackUpdate:Z=>{const me={messageId:M.messageId,channelUrl:M.channelUrl};if(!Z)return m.aiAgent.deleteMessageFeedback(me);const pe={...me,rating:ef(Z.rating),comment:Z.comment};return Ge.hasFeedback(M)?m.aiAgent.updateMessageFeedback(pe):m.aiAgent.createMessageFeedback(pe)},onSubmitForm:({key:Z,data:me})=>m.aiAgent.submitForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:Z,formData:me}),onCancelForm:({key:Z})=>m.aiAgent.cancelForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:Z}),onStreamAnimationStart:()=>{T.start(M.messageId)},onStreamAnimationProgress:()=>{b.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{T.stop(M.messageId),b.actions.onStreamingUpdate(!1)}};if(M.isUserMessage())return i.createElement(t,{messageType:"user",...ne});if(M.isFileMessage())return i.createElement(t,{messageType:"file",file:M,...ne});if(M.isMultipleFilesMessage()){const{files:Z}=Rs(M);return i.createElement(t,{messageType:"multipleFiles",files:Z,...ne})}}})();return i.createElement("div",{key:X,id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":$e,"data-message-listitem":"","data-layout-id":B()},j,ce)};return i.createElement(iE,{id:`${Ne}-message-list`},i.createElement(zp,{ref:b.ref,onScroll:b.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:k,renderMessage:K,onLoadPrev:_.loadPrevious,onLoadNext:_.loadNext,depsForResetScrollPositionToBottom:[_.initialized,_.messages.length!==0],bottomSpacerHeight:b.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!_.initialized||!C.channel,empty:k.length===0&&!O,error:!!(v||C.error),LoadingComponent:i.createElement(Tt,{type:"loading"}),EmptyComponent:(()=>{const M=w();return M?i.createElement("div",{style:{width:"100%"}},M):i.createElement(Tt,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(Tt,{type:"error",label:(v==null?void 0:v.message)??((ae=C.error)==null?void 0:ae.message),action:C.error?{label:s.RETRY,onClick:()=>C.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(Q_,{style:{marginTop:16}}),w()),messageBottomArea:i.createElement(i.Fragment,null,O&&i.createElement("div",{id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":yt({sender:O.user.nickname,message:s.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:k.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:O.isBot,sender:O.user,thinkingMessage:O.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled})),l.conversation.list.isTalkToAgentViewEnabled&&i.createElement(nE,null)),overlayArea:i.createElement(i.Fragment,null,l.conversation.list.newMessageIndicatorEnabled&&b.state.isAwayFromBottom&&_.newMessages.length>0&&i.createElement(aE,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(_.newMessages),onClick:()=>b.actions.scrollToBottom()}),b.state.isAwayFromBottom&&_.newMessages.length===0&&!O&&i.createElement(r.ScrollToBottomButton,{onClick:()=>b.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),U&&i.createElement(Xp,{files:U.files,initialIndex:U.index,onClose:()=>Y(null),visible:!0}),V&&i.createElement(Je,{visible:!0,onClose:()=>z(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(Je.ActionItem,{onClick:()=>{_.resendMessage(V),z(null)}},s.FAILED_MESSAGE_RESEND),i.createElement(Je.ActionItem,{destructive:!0,onClick:()=>{_.deleteMessage(V),z(null)}},s.FAILED_MESSAGE_REMOVE)))},iE=p.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,aE=p.default(L_)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,lE=()=>i.createElement(oE,null),cE=()=>{var s;const{origin:e}=ft(),{appId:t,aiAgentId:n}=Oe(),{channelSource:r}=ve();return(s=r.channel)!=null&&s.conversation?i.createElement(uE,null,i.createElement(Zn,{style:{gap:4}},i.createElement(Q,{color:g.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement($,{as:"i",color:g.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(Zn,{role:"button",style:{gap:4},onClick:()=>{var c,d;const o=e??window.location.origin,a=(d=(c=r.channel)==null?void 0:c.conversation)==null?void 0:d.id,l=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},i.createElement($,{variant:"body3",color:g.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:g.themedColor.primary}},"conversation link")),i.createElement(Q,{color:g.themedColor.primary,size:14,type:"copy"}))):null},Zn=p.default.div`display:flex;justify-content:center;align-items:center;`,uE=p.default(Zn)`flex-direction:column;padding-block:16px;background-color:${g.themedColor.bg_100_500};gap:8px;`,dE=(e,t)=>{const n=[],r=[],s=[];for(const o of e){const a=t.isSupportedMimeType(o.type),l=o.size<=t.getUploadSizeLimit(o.type);a&&l?n.push(o):a?r.push(o):s.push(o)}return{passed:n,failedBySize:r,failedByType:s}},Ni=u.createContext(void 0),mE=({children:e})=>{var V,z;const{chatSDK:t}=ge(),{createAttachmentRules:n}=Te(),{stringSet:r}=oe(),{channelSource:s,state:o}=ve(),[a,l]=u.useState([]),{announceError:c}=_r(),[d,m]=u.useState(null),h=n({channel:s.channel,uploadSizeLimit:(V=t.appInfo)==null?void 0:V.uploadSizeLimit}),f=((z=o==null?void 0:o.input)==null?void 0:z.disabled)??!1,E=h.isEnabled(),v=h.maxAttachmentCount,y=()=>m(null),C=H=>m(H),_=()=>{C({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",v.toString())})},b=H=>{C({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",H.toString())}),c({type:"fileSizeExceeded",maxSizeMB:H})},A=H=>{C({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",H.toString())})},T=H=>H.map(W=>({file:W,preview:{url:URL.createObjectURL(W),type:W.type,name:W.name}})),L=H=>{l(W=>[...W,...T(H)])},k=H=>{l(W=>(W.forEach(K=>URL.revokeObjectURL(K.preview.url)),T(H)))},I=H=>{const{passed:W,failedBySize:K,failedByType:ae}=dE(H,h),M=K.length+ae.length,ye=H.length===1?K[0]:void 0;return ye?b(h.getUploadSizeLimitInMB(ye.type)):M>0&&A(M),W},w=H=>{const W=I(H.files);W.length!==0&&(H.type==="append"?L(W):k(W))},O=H=>{if(!E||f||!_l(H))return;const W=bl({currentFiles:a.map(({file:K})=>K),incomingFiles:H,maxAttachmentCount:v});switch(W.type){case"reject":_();return;case"confirm_replace":C({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>w(W.action)});return;case"apply":w(W.action);return}},U=H=>{l(W=>{var ae;const K=(ae=W[H])==null?void 0:ae.preview;return K&&URL.revokeObjectURL(K.url),W.filter((M,ye)=>ye!==H)})},Y=()=>{l(H=>(H.forEach(W=>URL.revokeObjectURL(W.preview.url)),[]))};return i.createElement(Ni.Provider,{value:{files:a,addFiles:O,removeFile:U,clearFiles:Y,isFileUploadEnabled:E,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:C}},e,i.createElement(fn,{visible:!!d,...d??{},onClose:y}))},Ir=()=>{const e=u.useContext(Ni);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function hE({elementRef:e,ready:t,onRestore:n}){const r=u.useRef(!1);u.useEffect(()=>{var a;!t||!r.current||(n==null||n(),(a=e.current)==null||a.focus(),r.current=!1)},[t,n]);const s=u.useCallback(()=>{r.current=!0},[]),o=u.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function fE({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=u.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),u.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const gE=()=>{const{announceError:e}=qe();return u.useCallback(t=>{e({type:"sendFailed"},t)},[e])},pE=1e3,_E=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=qe(),o=n??!0,a=u.useRef(!1),l=u.useRef(void 0),c=u.useCallback(d=>{var m;d&&o&&(a.current=!0,l.current=e,e==null||e.startTyping()),d||(a.current&&o&&((m=l.current)==null||m.endTyping()),a.current=!1,l.current=void 0),s(d)},[e,s,o]);u.useLayoutEffect(()=>{s(a.current)},[r,s]),$c(t,c,{enabled:o,idleMs:pE})},EE=({enabled:e=!0,focusRoot:t})=>{const[n,r]=u.useState(!1),s=u.useRef(!1),o=u.useRef(!1);u.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 a=u.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),l=u.useCallback(()=>{r(!1)},[]),c=u.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:c,focusHandlers:{onFocus:a,onBlur:l}}},bE=p.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,CE=p.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;}`,vE=p.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;${J.light`
411
+ `,mE=()=>{var _e;const{Template:e}=Dt.useContext(),{Template:t}=tt.useContext(),{Template:n}=pn.useContext(),{components:r}=bn.useContext(),{stringSet:o,format:s}=se(),{file:a}=oe().conversation,{config:l,cache:c,agentPreviewConfigs:d,chatSDK:m,handlers:f,state:h}=me(),{userSession:_,aiAgentInfo:y,connectionError:C}=we(),{conversation:v,channelSource:b,messageSource:E,scrollSource:A,state:{input:x,streamAnimation:k}}=Se(),{isActionbookTester:R}=pt(),{filteredMessages:I,shouldShowOriginalDate:w,renderAgentPreviewWelcomeMessages:O}=oE(),$=Rs(b.channel),[V,H]=u.useState(null),[Y,G]=u.useState(null);u.useEffect(()=>{A.actions.onTypingIndicatorUpdate(!!$)},[!!$,A.actions.onTypingIndicatorUpdate]),sE(),J_({enabled:E.initialized&&E.messages.length>0});const W=(L,X=!1)=>{var K;return X?y:((K=b.channel)==null?void 0:K.members.find(F=>F.userId===L.sender.userId))??L.sender},q=L=>{if(L.sendingStatus==="failed"&&!x.disabled)return()=>G(L)},ce=({message:L,index:X})=>{const K=ga(L),F=I[X-1],ee=I[X+1],de=I[I.length-1],fe=L===de,xe=ft(L,y.userId),Oe=!(y.isUserFeedbackEnabled&&xe&&!Ve.isWelcomeMessage(L)),ke=pa(L,F,ee,Oe),T=!ua.isSameDay((F==null?void 0:F.createdAt)??0,L.createdAt)&&w(X)&&!R,M=te=>{H({files:te.files.map(ie=>({...ie,timestamp:L.createdAt})),index:te.index})},N=te=>{M({files:[te],index:0})},j=T?i.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:L.createdAt}):null,B={data:L.data,maxBodyWidth:h.expanded?ne.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:L.extendedMessagePayload,createdAt:L.createdAt,groupType:ke,onClickMedia:N,onClickMediaFiles:M,onClickFile:f.onClickLink,onClickCTA:f.onClickLink,onClickCitation:te=>f.onClickLink({url:te.link}),onClickLink:f.onClickLink},z=()=>{if(Ie.isOutgoing(L,_.userId))return"outgoingmessage";if(Ie.isIncoming(L,_.userId))return"incomingmessage"},U=L.createdAt!=null&&L.createdAt!==0?s(L.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ue=(()=>{var ie,re,Z,le,pe,rt;const te=(ie=L.message)==null?void 0:ie.trim();if(L.isFileMessage()){const ot=((re=L.name)==null?void 0:re.trim())||"";return In({markdownText:te,comparisonText:ot,plainText:a.label(ot,L.type)})}if(L.isMultipleFilesMessage()){const ot=((pe=(le=(Z=L.fileInfoList)==null?void 0:Z[0])==null?void 0:le.fileName)==null?void 0:pe.trim())||"",Fr=((rt=L.fileInfoList)==null?void 0:rt.length)??0;return In({markdownText:te,comparisonText:ot,plainText:Fr>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Fr):""})}return te?In({markdownText:te}):Ps("")})(),$e=(()=>{if(Ie.isAdmin(L))return yt({message:ue.text,messageFormat:ue.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ie.isOutgoing(L,_.userId))return yt({sender:o.A11Y_MESSAGE_SENDER_YOU,message:ue.text,messageFormat:"plain",time:U,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ie.isIncoming(L,_.userId))return yt({sender:W(L,xe).nickname,message:ue.text,messageFormat:ue.format,time:U,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),ae=(()=>{var te,ie;if(Ie.isAdmin(L))return Ie.isCSAT(L)?v?i.createElement(n,{...B,...v,isResolvedWhenDeterminedByUser:qa(v),messageType:"admin.csat",onSubmitCSAT:async re=>{var Z;await((Z=b.channel)==null?void 0:Z.submitCSAT(re))},onScrollToBottom:()=>A.actions.scrollToBottom()}):null:i.createElement(n,{...B,messageType:"admin",message:L.message});if(Ie.isSteward(L))return i.createElement(R_,{steward:L.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:L.channelUrl,messageId:L.messageId})}});if(Ie.isOutgoing(L,_.userId)){const re={...B,message:L.message,sender:W(L),sendingStatus:L.sendingStatus,onClickFailedMessage:q(L)};if(L.isUserMessage())return i.createElement(e,{messageType:"user",...re});if(L.isFileMessage()){const[Z,le]=((te=L.metaArrays.find(pe=>pe.key===as))==null?void 0:te.value)??[];return i.createElement(e,{messageType:"file",file:L,metadata:{aspectRatio:Z&&le?`${Z}/${le}`:"1/1",localFile:(ie=L.messageParams)==null?void 0:ie.file},...re})}if(L.isMultipleFilesMessage()){const{files:Z,metadata:le}=Ro(L);return i.createElement(e,{messageType:"multipleFiles",files:Z,metadata:le,...re})}}if(Ie.isIncoming(L,_.userId)){const re={...B,sender:W(L,xe),message:L.message,suggestedRepliesVisible:fe,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:xe,isStreaming:Ve.isStreaming(L),isHandedOff:et(b.channel),isConversationClosed:Re(b.channel),isFeedbackEnabled:y.isUserFeedbackEnabled,isFeedbackCommentEnabled:y.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled,markdownImageRenderMode:l.conversation.list.markdownImageRenderMode,onClickSuggestedReply:async({reply:Z})=>{E.sendUserMessage({message:Z})},onRequestMessageTemplate:async Z=>{const{template:le}=await m.aiAgent.getMessageTemplate(Z);return c.template.set(Z,le),le},onGetCachedMessageTemplate:Z=>c.template.get(Z),onHandleTemplateInternalAction:Z=>{if(Z.type==="internal"&&Z.internalData){const{method:le,payload:pe}=Z.internalData;le==="message.send"&&(pe!=null&&pe.message)&&E.sendUserMessage({message:pe.message})}},onFeedbackUpdate:Z=>{const le={messageId:L.messageId,channelUrl:L.channelUrl};if(!Z)return m.aiAgent.deleteMessageFeedback(le);const pe={...le,rating:lh(Z.rating),comment:Z.comment};return Ve.hasFeedback(L)?m.aiAgent.updateMessageFeedback(pe):m.aiAgent.createMessageFeedback(pe)},onSubmitForm:({key:Z,data:le})=>m.aiAgent.submitForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:Z,formData:le}),onCancelForm:({key:Z})=>m.aiAgent.cancelForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:Z}),onSendChallengeAction:({key:Z,requestId:le,action:pe,data:rt})=>m.aiAgent.sendChallengeAction({channelUrl:L.channelUrl,key:Z,requestId:le,action:pe,data:rt}),onStreamAnimationStart:()=>{k.start(L.messageId)},onStreamAnimationProgress:()=>{A.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{k.stop(L.messageId),A.actions.onStreamingUpdate(!1)}};if(L.isUserMessage())return i.createElement(t,{messageType:"user",...re});if(L.isFileMessage())return i.createElement(t,{messageType:"file",file:L,...re});if(L.isMultipleFilesMessage()){const{files:Z}=Ro(L);return i.createElement(t,{messageType:"multipleFiles",files:Z,...re})}}})();return i.createElement("div",{key:K,id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":$e,"data-message-listitem":"","data-layout-id":z()},j,ae)};return i.createElement(fE,{id:`${Ne}-message-list`},i.createElement(Zp,{ref:A.ref,onScroll:A.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:I,renderMessage:ce,onLoadPrev:E.loadPrevious,onLoadNext:E.loadNext,depsForResetScrollPositionToBottom:[E.initialized,E.messages.length!==0],bottomSpacerHeight:A.state.bottomSpace,"aria-label":o.A11Y_MESSAGE_LIST,loading:!E.initialized||!b.channel,empty:I.length===0&&!$,error:!!(C||b.error),LoadingComponent:i.createElement(Tt,{type:"loading"}),EmptyComponent:(()=>{const L=O();return L?i.createElement("div",{style:{width:"100%"}},L):i.createElement(Tt,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(Tt,{type:"error",label:(C==null?void 0:C.message)??((_e=b.error)==null?void 0:_e.message),action:b.error?{label:o.RETRY,onClick:()=>b.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(iE,{style:{marginTop:16}}),O()),messageBottomArea:i.createElement(i.Fragment,null,$&&i.createElement("div",{id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":yt({sender:$.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:I.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:$.isBot,sender:$.user,thinkingMessage:$.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled})),l.conversation.list.isTalkToAgentViewEnabled&&i.createElement(cE,null)),overlayArea:i.createElement(i.Fragment,null,l.conversation.list.newMessageIndicatorEnabled&&A.state.isAwayFromBottom&&E.newMessages.length>0&&i.createElement(hE,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(E.newMessages),onClick:()=>A.actions.scrollToBottom()}),A.state.isAwayFromBottom&&E.newMessages.length===0&&!$&&i.createElement(r.ScrollToBottomButton,{onClick:()=>A.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),V&&i.createElement(r_,{files:V.files,initialIndex:V.index,onClose:()=>H(null),visible:!0}),Y&&i.createElement(Je,{visible:!0,onClose:()=>G(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(Je.ActionItem,{onClick:()=>{E.resendMessage(Y),G(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(Je.ActionItem,{destructive:!0,onClick:()=>{E.deleteMessage(Y),G(null)}},o.FAILED_MESSAGE_REMOVE)))},fE=p.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,hE=p.default(U_)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,gE=()=>i.createElement(mE,null),pE=()=>{var o;const{origin:e}=pt(),{appId:t,aiAgentId:n}=Me(),{channelSource:r}=Se();return(o=r.channel)!=null&&o.conversation?i.createElement(_E,null,i.createElement(Zn,{style:{gap:4}},i.createElement(Q,{color:g.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement(P,{as:"i",color:g.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(Zn,{role:"button",style:{gap:4},onClick:()=>{var c,d;const s=e??window.location.origin,a=(d=(c=r.channel)==null?void 0:c.conversation)==null?void 0:d.id,l=`${s}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},i.createElement(P,{variant:"body3",color:g.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:g.themedColor.primary}},"conversation link")),i.createElement(Q,{color:g.themedColor.primary,size:14,type:"copy"}))):null},Zn=p.default.div`display:flex;justify-content:center;align-items:center;`,_E=p.default(Zn)`flex-direction:column;padding-block:16px;background-color:${g.themedColor.bg_100_500};gap:8px;`,EE=(e,t)=>{const n=[],r=[],o=[];for(const s of e){const a=t.isSupportedMimeType(s.type),l=s.size<=t.getUploadSizeLimit(s.type);a&&l?n.push(s):a?r.push(s):o.push(s)}return{passed:n,failedBySize:r,failedByType:o}},$i=u.createContext(void 0),bE=({children:e})=>{var H,Y;const{chatSDK:t}=me(),{createAttachmentRules:n}=we(),{stringSet:r}=se(),{channelSource:o,state:s}=Se(),[a,l]=u.useState([]),{announceError:c}=_r(),[d,m]=u.useState(null),f=n({channel:o.channel,uploadSizeLimit:(H=t.appInfo)==null?void 0:H.uploadSizeLimit}),h=((Y=s==null?void 0:s.input)==null?void 0:Y.disabled)??!1,_=f.isEnabled(),y=f.maxAttachmentCount,C=()=>m(null),v=G=>m(G),b=()=>{v({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",y.toString())})},E=G=>{v({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",G.toString())}),c({type:"fileSizeExceeded",maxSizeMB:G})},A=G=>{v({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",G.toString())})},x=G=>G.map(W=>({file:W,preview:{url:URL.createObjectURL(W),type:W.type,name:W.name}})),k=G=>{l(W=>[...W,...x(G)])},R=G=>{l(W=>(W.forEach(q=>URL.revokeObjectURL(q.preview.url)),x(G)))},I=G=>{const{passed:W,failedBySize:q,failedByType:ce}=EE(G,f),_e=q.length+ce.length,L=G.length===1?q[0]:void 0;return L?E(f.getUploadSizeLimitInMB(L.type)):_e>0&&A(_e),W},w=G=>{const W=I(G.files);W.length!==0&&(G.type==="append"?k(W):R(W))},O=G=>{if(!_||h||!vl(G))return;const W=Sl({currentFiles:a.map(({file:q})=>q),incomingFiles:G,maxAttachmentCount:y});switch(W.type){case"reject":b();return;case"confirm_replace":v({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>w(W.action)});return;case"apply":w(W.action);return}},$=G=>{l(W=>{var ce;const q=(ce=W[G])==null?void 0:ce.preview;return q&&URL.revokeObjectURL(q.url),W.filter((_e,L)=>L!==G)})},V=()=>{l(G=>(G.forEach(W=>URL.revokeObjectURL(W.preview.url)),[]))};return i.createElement($i.Provider,{value:{files:a,addFiles:O,removeFile:$,clearFiles:V,isFileUploadEnabled:_,acceptableMimeTypes:f.supportedMimeTypes,maxAttachmentCount:f.maxAttachmentCount,showFileUploadAlert:v}},e,i.createElement(gn,{visible:!!d,...d??{},onClose:C}))},Ir=()=>{const e=u.useContext($i);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function CE({elementRef:e,ready:t,onRestore:n}){const r=u.useRef(!1);u.useEffect(()=>{var a;!t||!r.current||(n==null||n(),(a=e.current)==null||a.focus(),r.current=!1)},[t,n]);const o=u.useCallback(()=>{r.current=!0},[]),s=u.useCallback(()=>{r.current=!1},[]);return{requestRestore:o,cancelRestore:s}}function vE({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const o=u.useRef(!1);e&&t.current&&n.activeElement===t.current&&(o.current=!0),u.useLayoutEffect(()=>{var s;!e&&o.current&&(r==null||r(),(s=t.current)==null||s.focus(),o.current=!1)},[e,r])}const yE=()=>{const{announceError:e}=Ke();return u.useCallback(t=>{e({type:"sendFailed"},t)},[e])},SE=1e3,AE=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:o}=Ke(),s=n??!0,a=u.useRef(!1),l=u.useRef(void 0),c=u.useCallback(d=>{var m;d&&s&&(a.current=!0,l.current=e,e==null||e.startTyping()),d||(a.current&&s&&((m=l.current)==null||m.endTyping()),a.current=!1,l.current=void 0),o(d)},[e,o,s]);u.useLayoutEffect(()=>{o(a.current)},[r,o]),Uc(t,c,{enabled:s,idleMs:SE})},xE=({enabled:e=!0,focusRoot:t})=>{const[n,r]=u.useState(!1),o=u.useRef(!1),s=u.useRef(!1);u.useEffect(()=>{if(!e){r(!1);return}const d=f=>{const h=f;h.metaKey||h.altKey||h.ctrlKey||(o.current=!0)},m=()=>{o.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const a=u.useCallback(()=>{if(s.current){s.current=!1,r(!1);return}r(o.current)},[]),l=u.useCallback(()=>{r(!1)},[]),c=u.useCallback(()=>{s.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:c,focusHandlers:{onFocus:a,onBlur:l}}},TE=p.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,IE=p.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;}`,wE=p.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;${J.light`
412
412
  background-color: ${g.color.background50};
413
413
  `}
414
414
  ${J.dark`
@@ -433,7 +433,7 @@
433
433
  circle {
434
434
  stroke: ${g.themedColor.bg_50_600};
435
435
  }
436
- `,yE=()=>{const e=Ot(),{conversation:t}=se(),{files:n,removeFile:r,isFileUploadEnabled:s}=Ir();return s&&n.length>0?i.createElement(bE,null,n.map(({preview:{type:a,name:l,url:c}},d)=>{let m=i.createElement(vr,{name:l,mimeType:a,type:nr(l,a),selected:!0});return a.startsWith("image/")&&(m=i.createElement("img",{alt:t.file.label(l,a,!0),src:c})),i.createElement(CE,{key:c},i.createElement(vE,{type:"button",...t.file.removeButton(l).props,$mobile:e,onClick:()=>r(d)},i.createElement(Q,{type:"close-filled",color:g.themedColor.textMidEmphasis})),m)})):null},SE={textArea:D.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Di=p.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Se}`,qs=p.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,Ks=p.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,js=p.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:${Vo}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${si&&SE.textArea};${({$focusVisible:e})=>e&&D.css`
436
+ `,ME=()=>{const e=Ot(),{conversation:t}=oe(),{files:n,removeFile:r,isFileUploadEnabled:o}=Ir();return o&&n.length>0?i.createElement(TE,null,n.map(({preview:{type:a,name:l,url:c}},d)=>{let m=i.createElement(vr,{name:l,mimeType:a,type:tr(l,a),selected:!0});return a.startsWith("image/")&&(m=i.createElement("img",{alt:t.file.label(l,a,!0),src:c})),i.createElement(IE,{key:c},i.createElement(wE,{type:"button",...t.file.removeButton(l).props,$mobile:e,onClick:()=>r(d)},i.createElement(Q,{type:"close-filled",color:g.themedColor.textMidEmphasis})),m)})):null},kE={textArea:D.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Pi=p.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Ae}`,Ko=p.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,jo=p.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Xo=p.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:${Ys}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${ii&&kE.textArea};${({$focusVisible:e})=>e&&D.css`
437
437
  outline: 2px solid ${g.themedColor.primary};
438
438
  outline-offset: 2px;
439
439
  `}
@@ -450,17 +450,17 @@
450
450
  }
451
451
 
452
452
  ${({$blocked:e})=>e&&D.css`cursor:not-allowed;&::placeholder{color:${g.themedColor.textDisabled};}`}
453
- `,AE=p.default.input`display:none;`;p.default.div`display:flex;align-items:center;gap:24px;`;const xE=p.default(Di)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${g.themedColor.bg_100_500};path{fill:${g.themedColor.textHighEmphasis};}}&:active{background-color:${g.themedColor.bg_200_400};}}`,Xs=p.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Zs=e=>e.startsWith("image/"),Js=({disabled:e})=>{const{stringSet:t}=oe(),{conversation:n}=se(),{config:r}=ge(),s=u.useRef(null),o=u.useRef(null),[a,l]=u.useState(!1),{addFiles:c,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=Ir(),f=m.includes(Pn),E=f?["image/*"]:m.filter(Zs),v=f?[Pn]:m.filter(I=>!Zs(I)),y=r.conversation.input.gallery.photoEnabled,C=r.conversation.input.fileEnabled,_=()=>f||E.length>0,b=()=>f||v.length>0,A=I=>{const w=I.currentTarget.files;w&&c(Array.from(w)),I.target.value=""},T=()=>{l(!0)},L=u.useMemo(()=>{const I=[];return y&&I.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:E.join(","),inputRef:s,onSelect:()=>{if(!_()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var w;return(w=s.current)==null?void 0:w.click()},100)}}),C&&I.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!b()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var w;return(w=o.current)==null?void 0:w.click()},100)}}),I},[E,m,t,y,C]);if(!d)return null;const k={attach:n.messageInput.attachFileButton()};return i.createElement(i.Fragment,null,i.createElement(xE,{...k.attach.props,disabled:e,onClick:T},i.createElement(Q,{type:"add",color:e?g.themedColor.textDisabled:g.color.primary.main,size:20}),k.attach.descriptionNode),L.map(I=>i.createElement(AE,{key:I.type,type:"file",ref:I.inputRef,multiple:I.type==="image",onChange:A,accept:I.accept})),i.createElement(Je,{visible:a,onClose:()=>l(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},L.map(I=>i.createElement(Je.ActionItem,{key:I.type,onClick:I.onSelect,icon:I.icon},I.label))))},TE=()=>{const e=u.useRef(null),[t,n]=u.useState(""),{stringSet:r}=oe(),{conversation:s}=se(),{rootElement:o}=ge(),a=st(o),{focusHandlers:l,isFocusVisible:c,suppressNextFocusVisible:d}=EE({focusRoot:a}),{channelSource:m,messageSource:h,state:f}=ve(),{files:E,addFiles:v,clearFiles:y}=Ir(),C=gE(),{focusPolicy:_,disabled:b,disabledBy:A}=f.input,T=_==="preserve",L=_==="release",k=(()=>{if(!b)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}})();Am({onDropFiles:G=>{v(G)}}),fE({blurred:L,elementRef:e,document:a,onRecoverFocus:()=>{d()}}),_E(m.channel,t,!b);const I=t.trim().length>0,w=E.length>0,O=!b&&(I||w),U={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},Y=()=>{e.current&&(e.current.value="",e.current.style.height=""),y(),n("")},V=()=>{var G;d(),(G=e.current)==null||G.focus()},{requestRestore:z,cancelRestore:H}=hE({elementRef:e,ready:T,onRestore:d}),W=G=>{H(),C(G)},K=()=>{H()},ae=async G=>{try{await G(),K()}catch{W(e.current)}},M=async()=>{if(b)return;const G=t.trim();if(!G&&!E.length)return;const ee=[...E];if(z(),Y(),V(),ee.length===0){await ae(()=>h.sendUserMessage({message:G}));return}if(ee.length===1)await ae(()=>h.sendFileMessage({message:G,file:ee[0].file}));else{const de=ee.map(({file:le})=>({file:le}));await ae(()=>h.sendMultipleFilesMessage({message:G,fileInfoList:de}))}},ye=G=>{const ee=Array.from(G.clipboardData.files);ee.length>0&&(G.preventDefault(),v(ee))},X=G=>{G.key!=="Enter"||G.nativeEvent.isComposing||G.shiftKey||(G.preventDefault(),M())},q=G=>{if(b){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const ee=Math.min(Fu,e.current.scrollHeight);Vo<ee&&(e.current.style.height=`${ee}px`)}n(G.target.value)};return L?i.createElement(Xs,null,i.createElement(Js,{disabled:!0}),i.createElement(qs,null,i.createElement(Ks,null,i.createElement(js,{rows:1,...U.input.props,disabled:!0,placeholder:k,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):i.createElement(Xs,{"data-message-composer":""},i.createElement(Js,{disabled:b}),i.createElement(qs,null,i.createElement(yE,null),i.createElement(Ks,null,i.createElement(js,{ref:e,rows:1,...U.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:k,maxLength:5e3,$blocked:b,$focusVisible:c,"data-focus-visible":c?"true":"false",onKeyDown:X,onChange:q,onFocus:l.onFocus,onBlur:l.onBlur,onPaste:ye}))),O&&i.createElement(Di,{...U.send.props,onClick:()=>M()},i.createElement(Q,{type:"send",color:g.color.primary.main,size:20}),U.send.descriptionNode))},IE=p.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:${g.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${J.light`
453
+ `,RE=p.default.input`display:none;`;p.default.div`display:flex;align-items:center;gap:24px;`;const LE=p.default(Pi)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${g.themedColor.bg_100_500};path{fill:${g.themedColor.textHighEmphasis};}}&:active{background-color:${g.themedColor.bg_200_400};}}`,Zo=p.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Jo=e=>e.startsWith("image/"),Qo=({disabled:e})=>{const{stringSet:t}=se(),{conversation:n}=oe(),{config:r}=me(),o=u.useRef(null),s=u.useRef(null),[a,l]=u.useState(!1),{addFiles:c,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:f}=Ir(),h=m.includes(Fn),_=h?["image/*"]:m.filter(Jo),y=h?[Fn]:m.filter(I=>!Jo(I)),C=r.conversation.input.gallery.photoEnabled,v=r.conversation.input.fileEnabled,b=()=>h||_.length>0,E=()=>h||y.length>0,A=I=>{const w=I.currentTarget.files;w&&c(Array.from(w)),I.target.value=""},x=()=>{l(!0)},k=u.useMemo(()=>{const I=[];return C&&I.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:_.join(","),inputRef:o,onSelect:()=>{if(!b()){f({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var w;return(w=o.current)==null?void 0:w.click()},100)}}),v&&I.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:s,onSelect:()=>{if(!E()){f({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var w;return(w=s.current)==null?void 0:w.click()},100)}}),I},[_,m,t,C,v]);if(!d)return null;const R={attach:n.messageInput.attachFileButton()};return i.createElement(i.Fragment,null,i.createElement(LE,{...R.attach.props,disabled:e,onClick:x},i.createElement(Q,{type:"add",color:e?g.themedColor.textDisabled:g.color.primary.main,size:20}),R.attach.descriptionNode),k.map(I=>i.createElement(RE,{key:I.type,type:"file",ref:I.inputRef,multiple:I.type==="image",onChange:A,accept:I.accept})),i.createElement(Je,{visible:a,onClose:()=>l(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},k.map(I=>i.createElement(Je.ActionItem,{key:I.type,onClick:I.onSelect,icon:I.icon},I.label))))},OE=()=>{const e=u.useRef(null),[t,n]=u.useState(""),{stringSet:r}=se(),{conversation:o}=oe(),{rootElement:s}=me(),a=st(s),{focusHandlers:l,isFocusVisible:c,suppressNextFocusVisible:d}=xE({focusRoot:a}),{channelSource:m,messageSource:f,state:h}=Se(),{files:_,addFiles:y,clearFiles:C}=Ir(),v=yE(),{focusPolicy:b,disabled:E,disabledBy:A}=h.input,x=b==="preserve",k=b==="release",R=(()=>{if(!E)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}})();km({onDropFiles:F=>{y(F)}}),vE({blurred:k,elementRef:e,document:a,onRecoverFocus:()=>{d()}}),AE(m.channel,t,!E);const I=t.trim().length>0,w=_.length>0,O=!E&&(I||w),$={input:o.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:o.messageInput.sendButton()},V=()=>{e.current&&(e.current.value="",e.current.style.height=""),C(),n("")},H=()=>{var F;d(),(F=e.current)==null||F.focus()},{requestRestore:Y,cancelRestore:G}=CE({elementRef:e,ready:x,onRestore:d}),W=F=>{G(),v(F)},q=()=>{G()},ce=async F=>{try{await F(),q()}catch{W(e.current)}},_e=async()=>{if(E)return;const F=t.trim();if(!F&&!_.length)return;const ee=[..._];if(Y(),V(),H(),ee.length===0){await ce(()=>f.sendUserMessage({message:F}));return}if(ee.length===1)await ce(()=>f.sendFileMessage({message:F,file:ee[0].file}));else{const de=ee.map(({file:fe})=>({file:fe}));await ce(()=>f.sendMultipleFilesMessage({message:F,fileInfoList:de}))}},L=F=>{const ee=Array.from(F.clipboardData.files);ee.length>0&&(F.preventDefault(),y(ee))},X=F=>{F.key!=="Enter"||F.nativeEvent.isComposing||F.shiftKey||(F.preventDefault(),_e())},K=F=>{if(E){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const ee=Math.min(zu,e.current.scrollHeight);Ys<ee&&(e.current.style.height=`${ee}px`)}n(F.target.value)};return k?i.createElement(Zo,null,i.createElement(Qo,{disabled:!0}),i.createElement(Ko,null,i.createElement(jo,null,i.createElement(Xo,{rows:1,...$.input.props,disabled:!0,placeholder:R,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):i.createElement(Zo,{"data-message-composer":""},i.createElement(Qo,{disabled:E}),i.createElement(Ko,null,i.createElement(ME,null),i.createElement(jo,null,i.createElement(Xo,{ref:e,rows:1,...$.input.props,readOnly:x,"aria-disabled":x?"true":void 0,placeholder:R,maxLength:5e3,$blocked:E,$focusVisible:c,"data-focus-visible":c?"true":"false",onKeyDown:X,onChange:K,onFocus:l.onFocus,onBlur:l.onBlur,onPaste:L}))),O&&i.createElement(Pi,{...$.send.props,onClick:()=>_e()},i.createElement(Q,{type:"send",color:g.color.primary.main,size:20}),$.send.descriptionNode))},NE=p.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:${g.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${J.light`
454
454
  color: ${g.color.information.light};
455
455
  `};
456
456
  ${J.dark`
457
457
  color: ${g.color.information.main};
458
458
  `};
459
459
  }
460
- `,wE=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),ME=()=>{const{aiAgentInfo:e,userSession:t}=Te(),{messageSource:n,channelSource:r}=ve(),[s,o]=u.useState(null),a=dr("special-notice",r.channel),l=u.useCallback(()=>r.channel?a?n.messages.some(c=>dt(c,(t==null?void 0:t.userId)??"")):!0:null,[r.channel,a,n.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{s||o(l())},[l,s]),s||!e.specialNotice?null:i.createElement(IE,null,i.createElement(wE,null,e.specialNotice))},kE=()=>i.createElement(RE,null,i.createElement(ME,null),i.createElement(mE,null,i.createElement(TE,null))),RE=p.default.div`z-index:0;border:none;width:100%;`,OE=()=>{var s;const{testerType:e}=ft(),{channelSource:t}=ve(),n=ke(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?i.createElement(cE,null):i.createElement(kE,null)},$i=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=u.useRef(null),a=u.useRef(null),[l,c]=u.useState(0),[d,m]=u.useState(0);return u.useLayoutEffect(()=>{o.current&&c(o.current.offsetWidth),a.current&&m(a.current.offsetWidth)},[e,r]),i.createElement(LE,{...s},i.createElement(NE,null,n==="center"&&t&&i.createElement(DE,{$sideWidth:Math.max(l,d)},i.createElement($E,null,t)),i.createElement(PE,null,i.createElement(FE,{ref:o},e),(n==="start"||n==="end")&&t&&i.createElement(UE,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(BE,{ref:a},r))))},LE=p.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${g.themedColor.textDisabled};`,NE=p.default.div`position:relative;height:56px;padding:11px 12px;`,DE=p.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;`,$E=p.default.div`max-width:100%;overflow:hidden;`,PE=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,FE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,BE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,UE=p.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;`,gt=(e=16)=>Ot()?e*1.5:e,HE=()=>{const{state:e}=ge(),{messenger:t}=se(),n=gt(),r=()=>{e.setOpened(!1)};return i.createElement(Ke,{...t.closeButton().props,type:"close",size:n,onClick:r})},GE=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ge(),{channelSource:n}=ve(),{conversation:r}=se(),s=n.channel,o=gt(),a=(s==null?void 0:s.isAIAgent)&&e,l=!sr(s);if(!a)return null;const c={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(Ze.CloseConversation({channelUrl:s.url}))};return i.createElement(i.Fragment,null,i.createElement(Ke,{...c.close.props,type:"mute",size:o,disabled:l,onClick:d}),c.close.descriptionNode)},VE=()=>{const{state:e,enableExpandButton:t}=ge(),{messenger:n}=se(),r=gt();return t?i.createElement(Ke,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},zE=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(Jn,null,t,i.createElement(qE,{$position:n},i.createElement(KE,{variant:"caption1"},e),i.createElement(YE,{$position:n}))),YE=({$position:e})=>i.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"},i.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:g.themedColor.textHighEmphasis})),WE={top:D.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:D.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Jn=p.default.div`position:relative;`,qE=p.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${ot.TOOLTIP};${({$position:e})=>WE[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Jn}:hover &,${Jn}:focus-within &{opacity:1;}`,KE=p.default($)`padding:6px 8px;background:${g.themedColor.textHighEmphasis};color:${g.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,jE=2e3,Qs=0,XE=1500,qt=Symbol("header-focus-status-pause"),eo="data-sb-header-focus-protected",ZE="[data-message-composer]",to=new WeakMap,Dn=e=>{const t=to.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return to.set(e,n),n},$n=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},Kt=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},JE=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),Kt(e)},QE=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)})},eb=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(ZE),!1),wr=()=>{const{setStatusPauseState:e}=qe(),t=u.useRef(Symbol("header-focus-target")),n=u.useRef(!1),r=u.useRef(0),s=u.useRef(null),o=u.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),a=u.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+XE,o();const c=Dn(e);$n(c,t.current),c.focusedTargetIds.add(t.current),c.focusedTargetIds.size===1&&e(qt,!0),Kt(c),c.maxPauseTimeout=setTimeout(()=>{JE(c),e(qt,!1)},jE)},[o,e]),l=u.useCallback(c=>{if(!n.current)return;n.current=!1;const d=c.currentTarget,m=Dn(e),h=d instanceof HTMLElement&&Date.now()<=r.current;$n(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const E=d.ownerDocument.activeElement,v=E instanceof HTMLElement&&E.hasAttribute(eo);if(E===d||v||!eb(E))return;const y=QE(d);d.focus({preventScroll:!0}),y()},Qs)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(Kt(m),e(qt,!1))},Qs))},[o,e]);return u.useEffect(()=>()=>{const c=Dn(e);n.current=!1,o(),$n(c,t.current),c.focusedTargetIds.delete(t.current)&&c.focusedTargetIds.size===0&&(Kt(c),e(qt,!1))},[o,e]),{[eo]:"true",onFocus:a,onBlur:l}},tb=()=>{const{logger:e}=ge(),{stringSet:t}=oe(),{channelSource:n}=ve(),{conversation:r}=se(),s=n.channel,o=gt(),a=dr("handoff-button",s),l=!sr(s)||et(s),[c,d]=u.useState(!1),m=wr(),h=async()=>{d(!1);try{const E=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",E)}catch(E){e.error("conversation.handleAgentHandoff: error",E)}};if(!a)return null;const f={handoff:r.header.handoffButton()};return i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(zE,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(Ke,{...f.handoff.props,type:"agent",size:o,disabled:l,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),i.createElement(nt,{portalContainerId:Ee.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(xr,{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})))},nb=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),rb=()=>{const{logger:e}=ge(),{stringSet:t}=oe(),{memoryInfo:n,sdkUser:r}=Te(),{actions:s}=ve(),{conversation:o}=se(),a=gt(20),l=wr(),[c,d]=u.useState(null),[m,h]=u.useState(!1),f=u.useRef(!1);if(u.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const E=o.header.memoryIndicator(n.enabled),v=async y=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:y}),d(null)}catch(C){e.error("memoryIndicator.setUserMemoryState: error",C),h(!0)}finally{f.current=!1}}};return i.createElement(i.Fragment,null,n.showIndicator&&i.createElement(i.Fragment,null,i.createElement(ab,{...E.props,as:"button",type:"button",onClick:()=>d({...n}),...l,$size:a},i.createElement(Q,{type:"memory",size:a,color:g.themedColor.textHighEmphasis}),i.createElement(lb,{$enabled:n.enabled})),E.descriptionNode),c&&i.createElement(sb,{memoryInfo:c,onClose:()=>d(null),onSetEnabled:v}),i.createElement(fn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},sb=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=oe(),{colors:s}=D.useTheme(),o=u.useId(),a=u.useId(),l=pl(e),c=l==="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}}[l],m=s.memoryDialog;return i.createElement(nt,{visible:!0,portalContainerId:Ee.WINDOW,onClose:t,cancelable:!c,"aria-labelledby":o,"aria-describedby":a},i.createElement(xr,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:i.createElement(ob,null,d.body),descriptionId:a,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:c?"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}}))},ob=({children:e})=>i.createElement(cb,null,i.createElement(wt,{fallback:e},i.createElement(nb,null,e))),ib=D.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;`,ab=p.default.button`${ib};cursor:pointer;${Se}`,lb=p.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?g.themedColor.secondary:g.color.background300};box-shadow:0 0 0 2px ${g.color.background50};${J.dark`
460
+ `,DE=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),$E=()=>{const{aiAgentInfo:e,userSession:t}=we(),{handlers:n}=me(),{messageSource:r,channelSource:o}=Se(),[s,a]=u.useState(null),l=dr("special-notice",o.channel),c=u.useCallback(()=>o.channel?l?r.messages.some(d=>ft(d,(t==null?void 0:t.userId)??"")):!0:null,[o.channel,l,r.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{s||a(c())},[c,s]),s||!e.specialNotice?null:i.createElement(NE,null,i.createElement(DE,{onClickLink:n.onClickLink},e.specialNotice))},PE=()=>i.createElement(FE,null,i.createElement($E,null),i.createElement(bE,null,i.createElement(OE,null))),FE=p.default.div`z-index:0;border:none;width:100%;`,BE=()=>{var o;const{testerType:e}=pt(),{channelSource:t}=Se(),n=Re(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(pE,null):i.createElement(PE,null)},Fi=({start:e,title:t,titleAlign:n="start",end:r,containerProps:o})=>{const s=u.useRef(null),a=u.useRef(null),[l,c]=u.useState(0),[d,m]=u.useState(0);return u.useLayoutEffect(()=>{s.current&&c(s.current.offsetWidth),a.current&&m(a.current.offsetWidth)},[e,r]),i.createElement(UE,{...o},i.createElement(HE,null,n==="center"&&t&&i.createElement(GE,{$sideWidth:Math.max(l,d)},i.createElement(zE,null,t)),i.createElement(VE,null,i.createElement(YE,{ref:s},e),(n==="start"||n==="end")&&t&&i.createElement(qE,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(WE,{ref:a},r))))},UE=p.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${g.themedColor.textDisabled};`,HE=p.default.div`position:relative;height:56px;padding:11px 12px;`,GE=p.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;`,zE=p.default.div`max-width:100%;overflow:hidden;`,VE=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,YE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,WE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,qE=p.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;`,_t=(e=16)=>Ot()?e*1.5:e,KE=()=>{const{state:e}=me(),{messenger:t}=oe(),n=_t(),r=()=>{e.setOpened(!1)};return i.createElement(je,{...t.closeButton().props,type:"close",size:n,onClick:r})},jE=()=>{const{enableCloseConversationButton:e,dispatcher:t}=me(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=_t(),a=(o==null?void 0:o.isAIAgent)&&e,l=!or(o);if(!a)return null;const c={close:r.header.closeConversationButton()},d=async()=>{o&&await t.send(Ze.CloseConversation({channelUrl:o.url}))};return i.createElement(i.Fragment,null,i.createElement(je,{...c.close.props,type:"mute",size:s,disabled:l,onClick:d}),c.close.descriptionNode)},XE=()=>{const{state:e,enableExpandButton:t}=me(),{messenger:n}=oe(),r=_t();return t?i.createElement(je,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},ZE=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(Jn,null,t,i.createElement(eb,{$position:n},i.createElement(tb,{variant:"caption1"},e),i.createElement(JE,{$position:n}))),JE=({$position:e})=>i.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"},i.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:g.themedColor.textHighEmphasis})),QE={top:D.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:D.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Jn=p.default.div`position:relative;`,eb=p.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${it.TOOLTIP};${({$position:e})=>QE[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Jn}:hover &,${Jn}:focus-within &{opacity:1;}`,tb=p.default(P)`padding:6px 8px;background:${g.themedColor.textHighEmphasis};color:${g.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,nb=2e3,es=0,rb=1500,Kt=Symbol("header-focus-status-pause"),ts="data-sb-header-focus-protected",ob="[data-message-composer]",ns=new WeakMap,$n=e=>{const t=ns.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return ns.set(e,n),n},Pn=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},jt=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},sb=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),jt(e)},ib=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)})},ab=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(ob),!1),wr=()=>{const{setStatusPauseState:e}=Ke(),t=u.useRef(Symbol("header-focus-target")),n=u.useRef(!1),r=u.useRef(0),o=u.useRef(null),s=u.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),a=u.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+rb,s();const c=$n(e);Pn(c,t.current),c.focusedTargetIds.add(t.current),c.focusedTargetIds.size===1&&e(Kt,!0),jt(c),c.maxPauseTimeout=setTimeout(()=>{sb(c),e(Kt,!1)},nb)},[s,e]),l=u.useCallback(c=>{if(!n.current)return;n.current=!1;const d=c.currentTarget,m=$n(e),f=d instanceof HTMLElement&&Date.now()<=r.current;Pn(m,t.current),f&&(s(),o.current=setTimeout(()=>{if(o.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const _=d.ownerDocument.activeElement,y=_ instanceof HTMLElement&&_.hasAttribute(ts);if(_===d||y||!ab(_))return;const C=ib(d);d.focus({preventScroll:!0}),C()},es)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(jt(m),e(Kt,!1))},es))},[s,e]);return u.useEffect(()=>()=>{const c=$n(e);n.current=!1,s(),Pn(c,t.current),c.focusedTargetIds.delete(t.current)&&c.focusedTargetIds.size===0&&(jt(c),e(Kt,!1))},[s,e]),{[ts]:"true",onFocus:a,onBlur:l}},lb=()=>{const{logger:e}=me(),{stringSet:t}=se(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=_t(),a=dr("handoff-button",o),l=!or(o)||et(o),[c,d]=u.useState(!1),m=wr(),f=async()=>{d(!1);try{const _=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",_)}catch(_){e.error("conversation.handleAgentHandoff: error",_)}};if(!a)return null;const h={handoff:r.header.handoffButton()};return i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(ZE,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(je,{...h.handoff.props,type:"agent",size:s,disabled:l,...m,onClick:()=>d(!0)})),h.handoff.descriptionNode),i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(xr,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:f})))},cb=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),ub=()=>{const{logger:e}=me(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=we(),{actions:o}=Se(),{conversation:s}=oe(),a=_t(20),l=wr(),[c,d]=u.useState(null),[m,f]=u.useState(!1),h=u.useRef(!1);if(u.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const _=s.header.memoryIndicator(n.enabled),y=async C=>{if(!h.current){h.current=!0,f(!1);try{await o.setUserMemoryState({enabled:C}),d(null)}catch(v){e.error("memoryIndicator.setUserMemoryState: error",v),f(!0)}finally{h.current=!1}}};return i.createElement(i.Fragment,null,n.showIndicator&&i.createElement(i.Fragment,null,i.createElement(hb,{..._.props,as:"button",type:"button",onClick:()=>d({...n}),...l,$size:a},i.createElement(Q,{type:"memory",size:a,color:g.themedColor.textHighEmphasis}),i.createElement(gb,{$enabled:n.enabled})),_.descriptionNode),c&&i.createElement(db,{memoryInfo:c,onClose:()=>d(null),onSetEnabled:y}),i.createElement(gn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},db=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var f;const{stringSet:r}=se(),{colors:o}=D.useTheme(),s=u.useId(),a=u.useId(),l=Cl(e),c=l==="consent",d={consent:{body:((f=e.consentDialog)==null?void 0:f.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}}[l],m=o.memoryDialog;return i.createElement(nt,{visible:!0,portalContainerId:Ce.WINDOW,onClose:t,cancelable:!c,"aria-labelledby":s,"aria-describedby":a},i.createElement(xr,{title:r.MEMORY__DIALOG_TITLE,titleId:s,description:i.createElement(mb,null,d.body),descriptionId:a,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:c?"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}}))},mb=({children:e})=>{const{handlers:t}=me();return i.createElement(pb,null,i.createElement(wt,{fallback:e},i.createElement(cb,{onClickLink:t.onClickLink},e)))},fb=D.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;`,hb=p.default.button`${fb};cursor:pointer;${Ae}`,gb=p.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?g.themedColor.secondary:g.color.background300};box-shadow:0 0 0 2px ${g.color.background50};${J.dark`
461
461
  box-shadow: 0 0 0 2px ${g.color.background500};
462
462
  `}
463
- `,cb=p.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;}`,ub=()=>{const{conversation:e}=se(),{onNavigateToConversationList:t}=ve();if(!t)return null;const n={menu:e.header.menuButton()};return i.createElement(i.Fragment,null,i.createElement(Ke,{...n.menu.props,...Bo,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Pi=_e("WindowTitle",{hasWindowTitleReference:!1,registerWindowTitleReference:()=>he}),db=Pi.Provider,Fi=Pi.useContext,Mr=({children:e})=>{const t=u.useRef(0),[n,r]=u.useState(!1),s=u.useCallback(()=>{let a=!0;return t.current+=1,t.current===1&&r(!0),()=>{a&&(a=!1,t.current=Math.max(0,t.current-1),t.current===0&&r(!1))}},[]),o=u.useMemo(()=>({hasWindowTitleReference:n,registerWindowTitleReference:s}),[n,s]);return i.createElement(db,{value:o},e)},kr=Fi,Bi=({enabled:e,label:t})=>{const{registerWindowTitleReference:n}=Fi(),r=e&&t.trim().length>0;return u.useLayoutEffect(()=>{if(r)return n()},[n,r]),{enabled:r,id:r?Ee.WINDOW_TITLE:void 0}},Ui=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Te(),{fallbackIcon:s,url:o}=mr({channel:e,aiAgentInfo:r,userSession:n}),a=D.useTheme();return o?i.createElement(Ei,{src:o,size:t,"aria-hidden":"true"}):i.createElement(mb,{"aria-hidden":"true",$size:t,$bgColor:a.colors.base.primary},i.createElement(Q,{type:s,size:t*.55,color:a.colors.base.primaryContrastContent}))},mb=p.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;`,hb=()=>{const{channelSource:e}=ve(),{aiAgentInfo:t,userSession:n}=Te(),{conversation:r}=se(),{config:s}=Oe(),{announcementsEnabled:o}=qe(),a=e.channel,l=mr({channel:a,userSession:n,aiAgentInfo:t}),c=s.conversation.header.avatarEnabled,d=wr(),m=Bi({enabled:o,label:l.title}),h={title:r.header.title(l.title,{active:m.enabled,titleId:m.id})};return i.createElement(fb,null,c&&i.createElement(Ui,{channel:a,size:34}),i.createElement(gb,{...h.title.props,...d},l.title))},fb=p.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,gb=p.default($).attrs({variant:"h2",color:g.themedColor.textHighEmphasis})`
463
+ `,pb=p.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;}`,_b=()=>{const{conversation:e}=oe(),{onNavigateToConversationList:t}=Se();if(!t)return null;const n={menu:e.header.menuButton()};return i.createElement(i.Fragment,null,i.createElement(je,{...n.menu.props,...Hs,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Bi=Ee("WindowTitle",{hasWindowTitleReference:!1,registerWindowTitleReference:()=>he}),Eb=Bi.Provider,Ui=Bi.useContext,Mr=({children:e})=>{const t=u.useRef(0),[n,r]=u.useState(!1),o=u.useCallback(()=>{let a=!0;return t.current+=1,t.current===1&&r(!0),()=>{a&&(a=!1,t.current=Math.max(0,t.current-1),t.current===0&&r(!1))}},[]),s=u.useMemo(()=>({hasWindowTitleReference:n,registerWindowTitleReference:o}),[n,o]);return i.createElement(Eb,{value:s},e)},kr=Ui,Hi=({enabled:e,label:t})=>{const{registerWindowTitleReference:n}=Ui(),r=e&&t.trim().length>0;return u.useLayoutEffect(()=>{if(r)return n()},[n,r]),{enabled:r,id:r?Ce.WINDOW_TITLE:void 0}},Gi=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=we(),{fallbackIcon:o,url:s}=mr({channel:e,aiAgentInfo:r,userSession:n}),a=D.useTheme();return s?i.createElement(Ci,{src:s,size:t,"aria-hidden":"true"}):i.createElement(bb,{"aria-hidden":"true",$size:t,$bgColor:a.colors.base.primary},i.createElement(Q,{type:o,size:t*.55,color:a.colors.base.primaryContrastContent}))},bb=p.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;`,Cb=()=>{const{channelSource:e}=Se(),{aiAgentInfo:t,userSession:n}=we(),{conversation:r}=oe(),{config:o}=Me(),{announcementsEnabled:s}=Ke(),a=e.channel,l=mr({channel:a,userSession:n,aiAgentInfo:t}),c=o.conversation.header.avatarEnabled,d=wr(),m=Hi({enabled:s,label:l.title}),f={title:r.header.title(l.title,{active:m.enabled,titleId:m.id})};return i.createElement(vb,null,c&&i.createElement(Gi,{channel:a,size:34}),i.createElement(yb,{...f.title.props,...d},l.title))},vb=p.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,yb=p.default(P).attrs({variant:"h2",color:g.themedColor.textHighEmphasis})`
464
464
  margin: 0;
465
465
  flex: 1;
466
466
  min-width: 0;
@@ -472,10 +472,10 @@
472
472
  &:focus {
473
473
  outline: none;
474
474
  }
475
- `,pb=e=>{const{components:t}=at.useContext();return i.createElement($i,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:Go})},_b=()=>{const{components:e}=at.useContext();return i.createElement(e.MenuButton,null)},Eb=()=>{const{components:e}=at.useContext();return i.createElement(e.Title,null)},bb=()=>{const{components:e}=at.useContext();return i.createElement(vb,null,i.createElement(e.MemoryIndicator,null),i.createElement(e.HandoffButton,null),i.createElement(e.ConversationCloseButton,null),i.createElement(e.ExpandButton,null),i.createElement(e.CloseButton,null))},at=Ue({template:pb,components:{StartArea:_b,TitleArea:Eb,EndArea:bb,MenuButton:ub,Title:hb,MemoryIndicator:rb,HandoffButton:tb,ConversationCloseButton:GE,ExpandButton:VE,CloseButton:HE}}),Cb=()=>{const{isActionbookTester:e}=ft(),{Template:t}=at.useContext();return e?null:i.createElement(t,{titleAlign:"start"})},vb=p.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Hi=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,announcementsEnabled:o,style:a,closedChannelUrl:l,onClearClosedChannelUrl:c})=>{const{Template:d}=bn.useContext();return i.createElement(li,{onNavigateToConversationList:t,channelUrl:n??l,onClearChannelUrl:r??c,shouldMarkAsRead:s},i.createElement(qn,null,i.createElement(qn.Consumer,null,m=>i.createElement(Md,{announcementsEnabled:o},i.createElement(yb,null),i.createElement(Sb,{style:a,dragHandlers:m},i.createElement(d,null)),e))))},yb=()=>(Gm(),Om(),Bm(),null),Sb=({style:e,dragHandlers:t,children:n})=>{const r=u.useRef(null);return Tm(r),i.createElement(xb,{ref:r,style:e,...t},n)},Ab=e=>{const{components:t}=bn.useContext();return i.createElement(i.Fragment,null,i.createElement(t.Header,null),i.createElement(t.Body,null),i.createElement(t.Footer,null))},bn=Ue({template:Ab,components:{Header:Cb,Body:lE,Footer:OE}}),xb=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Gi=_e("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:he}),Tb=Gi.Provider,Rr=Gi.useContext,Ib=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=_r(),r=u.useCallback(o=>{t&&n(o)},[n,t]),s=u.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return i.createElement(Tb,{value:s},e)},{Provider:wb,Context:Mb,useContext:Dt}=_e("ConversationList");function Vi({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=he,children:r}){return i.createElement(bc,{conversationListLimit:e,conversationListFilter:t},s=>i.createElement(wb,{value:{...s,onOpenConversationView:n}},r))}const kb=e=>{const{announcementsEnabled:t}=Rr(),{listSource:n}=Dt();ci(e,{enabled:t,ready:n.initialized})},Rb=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=Rr(),{listSource:n}=Dt(),r=u.useRef(!1);u.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])},Ob=({channel:e})=>i.createElement(Ui,{channel:e}),Qn=99,Lb=e=>{var C,_;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=oe(),{userSession:o,aiAgentInfo:a}=Te(),{conversationList:l}=se(),c=mr({channel:t,userSession:o,aiAgentInfo:a}),d=ml(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=hl(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=(C=t.lastMessage)!=null&&C.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:c.title,E=ke(t)?r.CONVERSATION_LIST__ENDED:So(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),v=n?()=>n():void 0,y=l.item({agent:f,status:E,time:m,unreadCount:h,onActivate:v});return i.createElement(Nb,{"data-testid":"sb-conversation-list-item",$clickable:!!v,...y.props},i.createElement(Db,null,i.createElement(Ob,{...e})),i.createElement($b,null,i.createElement(Pb,null,(_=t.lastMessage)!=null&&_.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?i.createElement(fi,{variant:"subtitle1",color:g.themedColor.textHighEmphasis},d):i.createElement($,{variant:"subtitle1",color:g.themedColor.textHighEmphasis,maxTextLines:1},d),i.createElement(Fb,null,ke(t)&&i.createElement(i.Fragment,null,i.createElement($,{variant:"caption1",color:g.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),i.createElement(Bb,null)),i.createElement($,{variant:"caption2",color:g.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&i.createElement(Ub,{$count:h},i.createElement($,{variant:"caption3",color:g.themedColor.textHighEmphasisInverse},h<=Qn?h:`${Qn}+`))),y.descriptionNode)},Or=Ue({template:Lb,components:{}}),Nb=p.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"};`,Db=p.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,$b=p.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 ${g.themedColor.textDisabled};`,Pb=p.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;`,Fb=p.default.div`display:flex;align-items:center;gap:6px;`,Bb=p.default.div`width:2px;height:2px;border-radius:1px;background-color:${g.themedColor.textLowEmphasis};`,Ub=p.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${g.themedColor.error};${({$count:e})=>e<=Qn&&D.css`
475
+ `,Sb=e=>{const{components:t}=lt.useContext();return i.createElement(Fi,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:Vs})},Ab=()=>{const{components:e}=lt.useContext();return i.createElement(e.MenuButton,null)},xb=()=>{const{components:e}=lt.useContext();return i.createElement(e.Title,null)},Tb=()=>{const{components:e}=lt.useContext();return i.createElement(wb,null,i.createElement(e.MemoryIndicator,null),i.createElement(e.HandoffButton,null),i.createElement(e.ConversationCloseButton,null),i.createElement(e.ExpandButton,null),i.createElement(e.CloseButton,null))},lt=Ue({template:Sb,components:{StartArea:Ab,TitleArea:xb,EndArea:Tb,MenuButton:_b,Title:Cb,MemoryIndicator:ub,HandoffButton:lb,ConversationCloseButton:jE,ExpandButton:XE,CloseButton:KE}}),Ib=()=>{const{isActionbookTester:e}=pt(),{Template:t}=lt.useContext();return e?null:i.createElement(t,{titleAlign:"start"})},wb=p.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,zi=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:o,announcementsEnabled:s,style:a,closedChannelUrl:l,onClearClosedChannelUrl:c})=>{const{Template:d}=Cn.useContext();return i.createElement(ui,{onNavigateToConversationList:t,channelUrl:n??l,onClearChannelUrl:r??c,shouldMarkAsRead:o},i.createElement(qn,null,i.createElement(qn.Consumer,null,m=>i.createElement(Nd,{announcementsEnabled:s},i.createElement(Mb,null),i.createElement(kb,{style:a,dragHandlers:m},i.createElement(d,null)),e))))},Mb=()=>(Km(),Fm(),Ym(),null),kb=({style:e,dragHandlers:t,children:n})=>{const r=u.useRef(null);return Lm(r),i.createElement(Lb,{ref:r,style:e,...t},n)},Rb=e=>{const{components:t}=Cn.useContext();return i.createElement(i.Fragment,null,i.createElement(t.Header,null),i.createElement(t.Body,null),i.createElement(t.Footer,null))},Cn=Ue({template:Rb,components:{Header:Ib,Body:gE,Footer:BE}}),Lb=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Vi=Ee("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:he}),Ob=Vi.Provider,Rr=Vi.useContext,Nb=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=_r(),r=u.useCallback(s=>{t&&n(s)},[n,t]),o=u.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return i.createElement(Ob,{value:o},e)},{Provider:Db,Context:$b,useContext:$t}=Ee("ConversationList");function Yi({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=he,children:r}){return i.createElement(Sc,{conversationListLimit:e,conversationListFilter:t},o=>i.createElement(Db,{value:{...o,onOpenConversationView:n}},r))}const Pb=e=>{const{announcementsEnabled:t}=Rr(),{listSource:n}=$t();di(e,{enabled:t,ready:n.initialized})},Fb=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=Rr(),{listSource:n}=$t(),r=u.useRef(!1);u.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const o=n.channels.length,s=setTimeout(()=>{e({screen:"conversationList",conversationCount:o}),r.current=!0},0);return()=>clearTimeout(s)},[e,t,n.initialized])},Bb=({channel:e})=>i.createElement(Gi,{channel:e}),Qn=99,Ub=e=>{var v,b;const{channel:t,onClick:n}=e,{stringSet:r,format:o}=se(),{userSession:s,aiAgentInfo:a}=we(),{conversationList:l}=oe(),c=mr({channel:t,userSession:s,aiAgentInfo:a}),d=pl(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=_l(t,o,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),f=t.unreadMessageCount,h=(v=t.lastMessage)!=null&&v.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:c.title,_=Re(t)?r.CONVERSATION_LIST__ENDED:As(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),y=n?()=>n():void 0,C=l.item({agent:h,status:_,time:m,unreadCount:f,onActivate:y});return i.createElement(Hb,{"data-testid":"sb-conversation-list-item",$clickable:!!y,...C.props},i.createElement(Gb,null,i.createElement(Bb,{...e})),i.createElement(zb,null,i.createElement(Vb,null,(b=t.lastMessage)!=null&&b.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?i.createElement(pi,{variant:"subtitle1",color:g.themedColor.textHighEmphasis},d):i.createElement(P,{variant:"subtitle1",color:g.themedColor.textHighEmphasis,maxTextLines:1},d),i.createElement(Yb,null,Re(t)&&i.createElement(i.Fragment,null,i.createElement(P,{variant:"caption1",color:g.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),i.createElement(Wb,null)),i.createElement(P,{variant:"caption2",color:g.themedColor.textLowEmphasis,maxTextLines:1},m))),f>0&&i.createElement(qb,{$count:f},i.createElement(P,{variant:"caption3",color:g.themedColor.textHighEmphasisInverse},f<=Qn?f:`${Qn}+`))),C.descriptionNode)},Lr=Ue({template:Ub,components:{}}),Hb=p.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"};`,Gb=p.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,zb=p.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 ${g.themedColor.textDisabled};`,Vb=p.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;`,Yb=p.default.div`display:flex;align-items:center;gap:6px;`,Wb=p.default.div`width:2px;height:2px;border-radius:1px;background-color:${g.themedColor.textLowEmphasis};`,qb=p.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${g.themedColor.error};${({$count:e})=>e<=Qn&&D.css`
476
476
  width: 20px;
477
477
  `}
478
- `,Hb=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=a=>{const l=a.target;l.scrollHeight-l.scrollTop===l.clientHeight&&(n==null||n())};return i.createElement(Gb,{role:r,"aria-label":s,onScroll:a=>o(a)},e.map((a,l)=>{const c=t(a,l);if(r!=="list")return c;const d=u.isValidElement(c)&&c.key!=null?c.key:l;return i.createElement(Vb,{key:d,role:"listitem"},c)}))},Gb=p.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,Vb=p.default.div`flex-shrink:0;`,zb=()=>{const{stringSet:e}=oe(),{listSource:t,onOpenConversationView:n}=Dt(),{Template:r}=Or.useContext();return t.initialized?t.channels.length===0?i.createElement(Tt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):i.createElement(Hb,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:s=>{var o,a,l;return i.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,ke(s)?"closed":"open"),channelUrl:s.url,title:(a=(o=s.conversation)==null?void 0:o.topics)==null?void 0:a.join(", "),lastMessageTimestamp:(l=s.lastMessage)==null?void 0:l.createdAt})},onEndReached:()=>{t.loadMore()}}):i.createElement(Tt,{type:"loading"})},Yb=()=>{const{stringSet:e}=oe(),{_aiAgentSDK:t}=Oe(),{language:n,countryCode:r,context:s}=ge(),{aiAgentInfo:o,refreshActiveChannel:a,createConversation:l}=Te(),{onOpenConversationView:c}=Dt(),{conversationList:d}=se(),m=async()=>{var h;if(o.isMultipleActiveConversationsEnabled){const f=await l({aiAgentId:o.userId,language:n,country:r,context:s});(h=t.session)==null||h._updateActiveChannel({url:f,status:"open"}),c(f,"open")}else{const f=await a();c(f,"open")}};return i.createElement(Wb,{...d.footer.button({onActivate:m}).props},i.createElement(qb,{variant:"h1"},e.TALK_TO_AGENT))},Wb=p.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,qb=p.default($)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Kb=()=>{const{state:e}=ge(),{messenger:t}=se(),n=gt(),r=()=>{e.setOpened(!1)};return i.createElement(Ke,{...t.closeButton().props,type:"close",size:n,onClick:r})},jb=()=>{const{stringSet:e}=oe(),{announcementsEnabled:t}=Rr(),{conversationList:n}=se(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=Bi({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return i.createElement(Xb,{forwardedAs:"h2",variant:"h2",color:g.themedColor.textHighEmphasis,...o.title.props},r)},Xb=p.default($)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,Zb=e=>{const{components:t}=pt.useContext();return i.createElement($i,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:Go})},Jb=()=>null,Qb=()=>{const{components:e}=pt.useContext();return i.createElement(e.Title,null)},eC=()=>{const{components:e}=pt.useContext();return i.createElement(e.CloseButton,null)},pt=Ue({template:Zb,components:{StartArea:Jb,TitleArea:Qb,EndArea:eC,Title:jb,CloseButton:Kb}}),tC=()=>{const{Template:e}=pt.useContext();return i.createElement(e,{titleAlign:"start"})},nC=()=>(Rb(),null),zi=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,style:o})=>{const{Template:a}=Cn.useContext();return i.createElement(Vi,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},i.createElement(Ib,{announcementsEnabled:s},i.createElement(nC,null),i.createElement(rC,{style:o},i.createElement(a,null)),n))},rC=({style:e,children:t})=>{const n=u.useRef(null);return kb(n),i.createElement(oC,{ref:n,style:e},t)},sC=()=>{const{components:e}=Cn.useContext();return i.createElement(i.Fragment,null,i.createElement(e.Header,null),i.createElement(e.Body,null),i.createElement(e.Footer,null))},Cn=Ue({template:sC,components:{Header:tC,Body:zb,Footer:Yb}}),oC=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,iC=D.css`:where(#${Ee.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,aC=[iC,nd,rd],lC=(e,...t)=>D.createGlobalStyle(e,...aC,...t),cC=lC``,uC=dl(bn,tt,Nt,gn,En,Cn,at,Or,pt,_n,hn),dC=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Yi({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:a,messageTemplate:l,icons:c,theme:d,entryElement:m,modalRootElement:h}){yd(dC?Vu:"",t);const[f,E]=u.useState(null),v=u.useCallback(_=>{E(b=>b===_?b:_)},[]),y=m??f,C=i.createElement(D.StyleSheetManager,{target:t},i.createElement(bd,{rootElement:t,logger:n,appearance:e,theme:d},i.createElement(qu,{rootElement:t,boundaryElement:y},i.createElement(Sc,{internalVariables:l==null?void 0:l.__internalVariables},i.createElement(td,{stringSet:o,logger:n,language:r,languageCode:s},i.createElement(_d,{icons:c},i.createElement(uC,null,i.createElement(Yu,{entryElement:y,modalRootElement:h,rootElement:t},a),i.createElement(cC,null))))))));return m?C:i.createElement("div",{ref:v,style:{display:"contents"}},C)}const mC=()=>{const[e,t]=u.useState(null),[n,r]=u.useState(null),s=u.useCallback(a=>{t(l=>l===a?l:a)},[]),o=u.useCallback(a=>{r(l=>l===a?l:a)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},Lr=u.forwardRef(function({rootElement:t=document.body,logLevel:n=fe.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:a,icons:l,...c},d){var C,_,b;At.level!==n&&(At.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:E}=mC();vd("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const v=Yo(r),y=Wo.has(v)?v:Rt;return i.createElement("div",{ref:f,id:Ee.ENTRY,lang:y,style:{width:"fit-content",height:"fit-content",...c.entryStyle}},m&&h&&i.createElement(Yi,{logger:At,rootElement:t,appearance:(C=c.agentPreviewConfigs)==null?void 0:C.appearance,stringSet:c.stringSet,language:y,messageTemplate:c.messageTemplate,icons:l,theme:c.theme,entryElement:m,modalRootElement:h},i.createElement(em,{rootElement:t,language:r,logger:At,dispatcher:Wi,chatParams:{...a,...c.customApiHost&&{customApiHost:c.customApiHost},...c.customWebSocketHost&&{customWebSocketHost:c.customWebSocketHost}},chatSDK:c.customChatSDK,_forceCreateChannel:(_=c.agentPreviewConfigs)==null?void 0:_.forceCreateChannel,_agentVersion:(b=c.agentPreviewConfigs)==null?void 0:b.agentVersion,...c},i.createElement(lm,{ref:d,userSessionInfo:s},i.createElement(wp,{...c._UNSAFE_INTERNAL_dashboardTester},i.createElement(Id,null,o))))),i.createElement("div",{ref:E,id:Ee.MODAL_ROOT,dir:c.dir}))}),At=new mo(fe.LogLevel.WARN),Wi=new uo(At),{Provider:hC,useContext:Nr}=_e("PageChildren"),qi=({children:e})=>{const[t,n]=u.useState(null),[r,s]=u.useState(null);return i.createElement(hC,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:s}},e)},Dr=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Ee.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Ki=({children:e,isOpened:t,zIndex:n=ot.WINDOW})=>i.createElement(Mr,null,i.createElement(fC,{isOpened:t,zIndex:n},e)),fC=({children:e,isOpened:t,zIndex:n=ot.WINDOW})=>{const{dir:r,rootElement:s}=ge(),o=st(s,!0),a=u.useRef(null),{hasWindowTitleReference:l}=kr();return mn(t,a),u.useEffect(()=>{const c="sb-agent-block-scroll";return t?o.body.classList.add(c):o.body.classList.remove(c),()=>{o.body.classList.remove(c)}},[o,t]),i.createElement(gC,{ref:a,id:Ee.WINDOW,dir:r,...Dr(t,l),$visible:t,$zIndex:n},e)},gC=p.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,pC=48,_C=2/3;function ji({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:a,imageUrl:l,dir:c,animated:d=!0,backgroundColor:m,size:h=pC}){const f=Ci(),E=d&&!f,v=Vn(m),y=Math.round(h*_C);return i.createElement(CC,{dir:c,id:Ee.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:E,$backgroundColor:m,$prefersReducedMotion:f,$size:h},i.createElement(vC,{$isOpened:n,$animated:E,$fillColor:v,$iconSize:y,$prefersReducedMotion:f},i.createElement(no.Open,{url:l,isDefaultIcon:a==="default_icon",size:y})),i.createElement(yC,{$isOpened:n,$animated:E,$fillColor:v,$iconSize:y,$prefersReducedMotion:f},i.createElement(no.Close,{size:y})),t)}const EC=D.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,bC=D.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===It.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Xi=D.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>D.css`
478
+ `,Kb=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":o})=>{const s=a=>{const l=a.target;l.scrollHeight-l.scrollTop-l.clientHeight<=2&&(n==null||n())};return i.createElement(jb,{role:r,"aria-label":o,onScroll:a=>s(a)},e.map((a,l)=>{const c=t(a,l);if(r!=="list")return c;const d=u.isValidElement(c)&&c.key!=null?c.key:l;return i.createElement(Xb,{key:d,role:"listitem"},c)}))},jb=p.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,Xb=p.default.div`flex-shrink:0;`,Zb=()=>{const{stringSet:e}=se(),{listSource:t,onOpenConversationView:n}=$t(),{Template:r}=Lr.useContext();return t.initialized?t.channels.length===0?i.createElement(Tt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):i.createElement(Kb,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:o=>{var s,a,l;return i.createElement(r,{key:o.url,channel:o,onClick:()=>n(o.url,Re(o)?"closed":"open"),channelUrl:o.url,title:(a=(s=o.conversation)==null?void 0:s.topics)==null?void 0:a.join(", "),lastMessageTimestamp:(l=o.lastMessage)==null?void 0:l.createdAt})},onEndReached:()=>{t.loadMore()}}):i.createElement(Tt,{type:"loading"})},Jb=()=>{const{stringSet:e}=se(),{_aiAgentSDK:t}=Me(),{language:n,countryCode:r,context:o}=me(),{aiAgentInfo:s,refreshActiveChannel:a,createConversation:l}=we(),{onOpenConversationView:c}=$t(),{conversationList:d}=oe(),m=async()=>{var f;if(s.isMultipleActiveConversationsEnabled){const h=await l({aiAgentId:s.userId,language:n,country:r,context:o});(f=t.session)==null||f._updateActiveChannel({url:h,status:"open"}),c(h,"open")}else{const h=await a();c(h,"open")}};return i.createElement(Qb,{...d.footer.button({onActivate:m}).props},i.createElement(eC,{variant:"h1"},e.TALK_TO_AGENT))},Qb=p.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,eC=p.default(P)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,tC=()=>{const{state:e}=me(),{messenger:t}=oe(),n=_t(),r=()=>{e.setOpened(!1)};return i.createElement(je,{...t.closeButton().props,type:"close",size:n,onClick:r})},nC=()=>{const{stringSet:e}=se(),{announcementsEnabled:t}=Rr(),{conversationList:n}=oe(),r=e.CONVERSATION_LIST__HEADER_TITLE,o=Hi({enabled:t,label:r}),s={title:n.headerTitle(r,{active:o.enabled,titleId:o.id})};return i.createElement(rC,{forwardedAs:"h2",variant:"h2",color:g.themedColor.textHighEmphasis,...s.title.props},r)},rC=p.default(P)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,oC=e=>{const{components:t}=Et.useContext();return i.createElement(Fi,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:Vs})},sC=()=>null,iC=()=>{const{components:e}=Et.useContext();return i.createElement(e.Title,null)},aC=()=>{const{components:e}=Et.useContext();return i.createElement(e.CloseButton,null)},Et=Ue({template:oC,components:{StartArea:sC,TitleArea:iC,EndArea:aC,Title:nC,CloseButton:tC}}),lC=()=>{const{Template:e}=Et.useContext();return i.createElement(e,{titleAlign:"start"})},cC=()=>(Fb(),null),Wi=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:o=!0,style:s})=>{const{Template:a}=vn.useContext();return i.createElement(Yi,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},i.createElement(Nb,{announcementsEnabled:o},i.createElement(cC,null),i.createElement(uC,{style:s},i.createElement(a,null)),n))},uC=({style:e,children:t})=>{const n=u.useRef(null);return Pb(n),i.createElement(mC,{ref:n,style:e},t)},dC=()=>{const{components:e}=vn.useContext();return i.createElement(i.Fragment,null,i.createElement(e.Header,null),i.createElement(e.Body,null),i.createElement(e.Footer,null))},vn=Ue({template:dC,components:{Header:lC,Body:Zb,Footer:Jb}}),mC=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,fC=D.css`:where(#${Ce.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,hC=[fC,ad,ld],gC=(e,...t)=>D.createGlobalStyle(e,...hC,...t),pC=gC``,_C=gl(Cn,tt,Dt,pn,bn,vn,lt,Lr,Et,En,hn),EC=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function qi({appearance:e,rootElement:t,logger:n,language:r,languageCode:o,stringSet:s,children:a,messageTemplate:l,icons:c,theme:d,entryElement:m,modalRootElement:f}){Id(EC?Ku:"",t);const[h,_]=u.useState(null),y=u.useCallback(b=>{_(E=>E===b?E:b)},[]),C=m??h,v=i.createElement(D.StyleSheetManager,{target:t},i.createElement(Ad,{rootElement:t,logger:n,appearance:e,theme:d},i.createElement(Ju,{rootElement:t,boundaryElement:C},i.createElement(Ic,{internalVariables:l==null?void 0:l.__internalVariables},i.createElement(id,{stringSet:s,logger:n,language:r,languageCode:o},i.createElement(yd,{icons:c},i.createElement(_C,null,i.createElement(Xu,{entryElement:C,modalRootElement:f,rootElement:t},a),i.createElement(pC,null))))))));return m?v:i.createElement("div",{ref:y,style:{display:"contents"}},v)}const bC=()=>{const[e,t]=u.useState(null),[n,r]=u.useState(null),o=u.useCallback(a=>{t(l=>l===a?l:a)},[]),s=u.useCallback(a=>{r(l=>l===a?l:a)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:o,setModalRootElement:s}},Or=u.forwardRef(function({rootElement:t=document.body,logLevel:n=ge.LogLevel.WARN,language:r=navigator.language,userSessionInfo:o,children:s,chatParams:a,icons:l,...c},d){var v,b,E;At.level!==n&&(At.level=n);const{entryElement:m,modalRootElement:f,setEntryElement:h,setModalRootElement:_}=bC();Td("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const y=qs(r),C=Ks.has(y)?y:Lt;return i.createElement("div",{ref:h,id:Ce.ENTRY,lang:C,style:{width:"fit-content",height:"fit-content",...c.entryStyle}},m&&f&&i.createElement(qi,{logger:At,rootElement:t,appearance:(v=c.agentPreviewConfigs)==null?void 0:v.appearance,stringSet:c.stringSet,language:C,messageTemplate:c.messageTemplate,icons:l,theme:c.theme,entryElement:m,modalRootElement:f},i.createElement(im,{rootElement:t,language:r,logger:At,dispatcher:Ki,chatParams:{...a,...c.customApiHost&&{customApiHost:c.customApiHost},...c.customWebSocketHost&&{customWebSocketHost:c.customWebSocketHost}},chatSDK:c.customChatSDK,_forceCreateChannel:(b=c.agentPreviewConfigs)==null?void 0:b.forceCreateChannel,_agentVersion:(E=c.agentPreviewConfigs)==null?void 0:E.agentVersion,...c},i.createElement(hm,{ref:d,userSessionInfo:o},i.createElement(Dp,{...c._UNSAFE_INTERNAL_dashboardTester},i.createElement(Ld,null,s))))),i.createElement("div",{ref:_,id:Ce.MODAL_ROOT,dir:c.dir}))}),At=new hs(ge.LogLevel.WARN),Ki=new fs(At),{Provider:CC,useContext:Nr}=Ee("PageChildren"),ji=({children:e})=>{const[t,n]=u.useState(null),[r,o]=u.useState(null);return i.createElement(CC,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:o}},e)},Dr=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Ce.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Xi=({children:e,isOpened:t,zIndex:n=it.WINDOW})=>i.createElement(Mr,null,i.createElement(vC,{isOpened:t,zIndex:n},e)),vC=({children:e,isOpened:t,zIndex:n=it.WINDOW})=>{const{dir:r,rootElement:o}=me(),s=st(o,!0),a=u.useRef(null),{hasWindowTitleReference:l}=kr();return fn(t,a),u.useEffect(()=>{const c="sb-agent-block-scroll";return t?s.body.classList.add(c):s.body.classList.remove(c),()=>{s.body.classList.remove(c)}},[s,t]),i.createElement(yC,{ref:a,id:Ce.WINDOW,dir:r,...Dr(t,l),$visible:t,$zIndex:n},e)},yC=p.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,SC=48,AC=2/3,rs=12;function Zi({className:e,children:t,isOpened:n,onClick:r,"aria-label":o,"aria-describedby":s,type:a,imageUrl:l,dir:c,animated:d=!0,backgroundColor:m,size:f=SC,hasUnread:h=!1}){const _=yi(),y=d&&!_,C=zn(m),v=Math.round(f*AC);return i.createElement(IC,{dir:c,id:Ce.LAUNCHER,className:e,"aria-label":o,"aria-describedby":s,onClick:r,$animated:y,$backgroundColor:m,$prefersReducedMotion:_,$size:f},i.createElement(wC,{$isOpened:n,$animated:y,$fillColor:C,$iconSize:v,$prefersReducedMotion:_},i.createElement(os.Open,{url:l,isDefaultIcon:a==="default_icon",size:v})),i.createElement(MC,{$isOpened:n,$animated:y,$fillColor:C,$iconSize:v,$prefersReducedMotion:_},i.createElement(os.Close,{size:v})),h&&i.createElement(kC,null),t)}const xC=D.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,TC=D.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===It.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Ji=D.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>D.css`
479
479
  ellipse,
480
480
  path {
481
481
  fill: ${e};
@@ -485,7 +485,7 @@
485
485
  }
486
486
  `}
487
487
  }
488
- `,CC=p.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&&EC}`,Zi=p.default.span.attrs({"aria-hidden":"true"})`
488
+ `,IC=p.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&&xC}`,Qi=p.default.span.attrs({"aria-hidden":"true"})`
489
489
  position: absolute;
490
490
  width: 100%;
491
491
  height: 100%;
@@ -495,15 +495,23 @@
495
495
  display: flex;
496
496
  justify-content: center;
497
497
  align-items: center;
498
- `,vC=p.default(Zi)`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)")};${bC}${Xi}`,yC=p.default(Zi)`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)")};${Xi}`,no={Open:e=>e.url?i.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):i.createElement(Q,{size:e.size,type:"delight"}),Close:({size:e})=>i.createElement(Q,{size:e,type:"chevron-down"})};function Ji({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=D.useTheme(),{dir:o,state:a}=ge(),{resolveElement:l}=pr(),{launcher:c}=se(),{launcherInfo:d,statsTrackers:m}=Te(),h=(r??n)==="ConversationList",f={launcher:c.button({isOpened:a.opened,opensConversationList:h})};u.useLayoutEffect(()=>{m.initialRender.setPresentMethod("launcher_toggle")},[m]),AC();const E=()=>{Re(()=>{const C=l(Ee.WINDOW),_=C?ti(C):null;_==null||_.focus()})},v=()=>{Re(()=>{var C;(C=l(Ee.LAUNCHER))==null||C.focus()})},y=()=>{const C=!a.opened;a.setOpened(C),C?E():v()};return i.createElement(ji,{dir:o,className:e,isOpened:a.opened,onClick:y,type:d.type,imageUrl:d.imageUrl,backgroundColor:s.base.primary,size:t,...f.launcher.props},f.launcher.descriptionNode)}const SC=1e3*60;function AC(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ge(),s=u.useRef(null);u.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function a(){e.connectionState===fe.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),o(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function l(){o(),s.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},SC)}t.opened?a():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const Qi=u.createContext(null);function $r(){const e=u.useContext(Qi);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function ea({children:e}){const t=$r();return typeof e=="function"?e(t):i.createElement(i.Fragment,null,e)}const xC=D.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,TC=D.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,IC=D.css`animation-name:${xC};animation-duration:0.3s;animation-fill-mode:forwards;`,wC=D.css``,MC=D.css`animation-name:${TC};animation-duration:0.3s;animation-fill-mode:forwards;`,kC=D.css`visibility:hidden;`,RC=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return IC;case"entered":return wC;case"exiting":return MC;case"exited":return kC;default:return""}}}${({$active:e})=>e?D.css`
498
+ `,wC=p.default(Qi)`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)")};${TC}${Ji}`,MC=p.default(Qi)`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)")};${Ji}`,kC=p.default.span.attrs({"aria-hidden":"true"})`
499
+ position: absolute;
500
+ top: 1px;
501
+ inset-inline-end: 1px;
502
+ width: ${rs}px;
503
+ height: ${rs}px;
504
+ border-radius: 50%;
505
+ background-color: ${g.themedColor.error};
506
+ `,os={Open:e=>e.url?i.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):i.createElement(Q,{size:e.size,type:"delight"}),Close:({size:e})=>i.createElement(Q,{size:e,type:"chevron-down"})};function ea({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:o}=D.useTheme(),{chatSDK:s,config:a,dir:l,state:c}=me(),{resolveElement:d}=pr(),{launcher:m}=oe(),{launcherInfo:f,statsTrackers:h}=we(),_=a.launcher.unreadBadgeEnabled,y=Ms(),C=ru(s,{enabled:_,opened:c.opened,filter:y}),v=(r??n)==="ConversationList",b={launcher:m.button({isOpened:c.opened,opensConversationList:v})};u.useLayoutEffect(()=>{h.initialRender.setPresentMethod("launcher_toggle")},[h]),LC();const E=()=>{Le(()=>{const k=d(Ce.WINDOW),R=k?ri(k):null;R==null||R.focus()})},A=()=>{Le(()=>{var k;(k=d(Ce.LAUNCHER))==null||k.focus()})},x=()=>{const k=!c.opened;c.setOpened(k),k?E():A()};return i.createElement(Zi,{dir:l,className:e,isOpened:c.opened,onClick:x,type:f.type,imageUrl:f.imageUrl,backgroundColor:o.base.primary,size:t,hasUnread:_&&!c.opened&&C,...b.launcher.props},b.launcher.descriptionNode)}const RC=1e3*60;function LC(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=me(),o=u.useRef(null);u.useEffect(()=>{if(!r)return;function s(){o.current&&(clearTimeout(o.current),o.current=null)}function a(){e.connectionState===ge.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),s(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function l(){s(),o.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},RC)}t.opened?a():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const ta=u.createContext(null);function $r(){const e=u.useContext(ta);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function na({children:e}){const t=$r();return typeof e=="function"?e(t):i.createElement(i.Fragment,null,e)}const OC=D.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,NC=D.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,DC=D.css`animation-name:${OC};animation-duration:0.3s;animation-fill-mode:forwards;`,$C=D.css``,PC=D.css`animation-name:${NC};animation-duration:0.3s;animation-fill-mode:forwards;`,FC=D.css`visibility:hidden;`,BC=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return DC;case"entered":return $C;case"exiting":return PC;case"exited":return FC;default:return""}}}${({$active:e})=>e?D.css`
499
507
  z-index: 999;
500
508
  `:D.css`z-index:1;pointer-events:none;`}
501
- `;function jt({initialId:e,children:t}){const[n,r]=u.useState([e]),s=n[n.length-1],o=u.useCallback((C,_)=>{r(b=>[...b,C]),h(b=>({...b,[C]:!0})),_!=null&&_.reset&&y(b=>({...b,[C]:(b[C]||0)+1})),E(b=>({...b,[C]:"entering"})),setTimeout(()=>{E(b=>({...b,[C]:"entered"}))},300)},[]),a=u.useCallback(()=>{r(C=>{if(C.length<=1)return C;const _=C[C.length-1];return E(b=>({...b,[_]:"exiting"})),setTimeout(()=>{E(b=>({...b,[_]:"exited"})),r(b=>b.slice(0,-1))},300),C})},[]),l=u.useMemo(()=>({navigation:{navigate:o,pop:a},activeScreenId:s}),[o,a,s]),c=u.useMemo(()=>u.Children.toArray(t).filter(C=>C.type===ea),[t]),d=u.useMemo(()=>{const C={};return c.forEach(_=>{const{id:b,lazy:A,children:T}=_.props;C[b]={lazy:A,element:typeof T=="function"?T(l):T}}),C},[c,l]),[m,h]=u.useState(()=>{const C={};return Object.entries(d).forEach(([_,{lazy:b}])=>{b===!1&&(C[_]=!0)}),C[e]=!0,C}),[f,E]=u.useState(()=>{const C={};return Object.keys(d).forEach(_=>{_===e?C[_]="entered":C[_]="exited"}),C}),[v,y]=u.useState({});return i.createElement(Qi.Provider,{value:l},i.createElement(OC,null,Object.keys(d).map(C=>{var T;if(!m[C])return null;const _=f[C]||"exited",b=C===s,A=`${C}-${v[C]||0}`;return i.createElement(RC,{key:A,$transitionState:_,$active:b,"aria-hidden":b?void 0:!0,inert:b?void 0:!0},(T=d[C])==null?void 0:T.element)})))}const OC=p.default.div`position:relative;width:100%;height:100%;`;jt.Screen=ea;const Pe={conv:"conv",convList:"conv-list"},LC=e=>e===Pe.convList?"ConversationList":"Conversation",ro=({isOpened:e,activeScreenId:t})=>e&&t===Pe.conv,ta=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:s})=>{const{conversationChildren:o,conversationListChildren:a}=Nr(),l=(()=>{switch(t){case"Conversation":return Pe.conv;case"ConversationList":return Pe.convList;default:return Pe.conv}})(),c=i.createElement(i.Fragment,null,i.createElement(NC,{onOpenConversationView:(d,m)=>{r(m),d.navigate(Pe.conv)}}),i.createElement(DC,{onActiveRouteChange:s}));return i.createElement(jt,{initialId:l},i.createElement(jt.Screen,{id:Pe.conv},({navigation:d,activeScreenId:m})=>i.createElement(Hi,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>d.navigate(Pe.convList),announcementsEnabled:ro({isOpened:e,activeScreenId:m}),shouldMarkAsRead:ro({isOpened:e,activeScreenId:m})},c,o)),i.createElement(jt.Screen,{id:Pe.convList,lazy:!0},({navigation:d,activeScreenId:m})=>{const h=e&&m===Pe.convList;return i.createElement(zi,{announcementsEnabled:h,onOpenConversationView:f=>{r(f),d.navigate(Pe.conv)}},c,a)}))},NC=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Te(),{navigation:n}=$r();return t(({channel:r})=>{e(n,r.url)}),null},DC=({onActiveRouteChange:e})=>{const{activeScreenId:t}=$r();return u.useEffect(()=>{e==null||e(LC(t))},[t,e]),null},$C=({isExpanded:e,isOpened:t,children:n,launcher:r})=>i.createElement(Mr,null,i.createElement(PC,{isExpanded:e,isOpened:t,launcher:r},n)),PC=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=ge(),o=u.useRef(null),{hasWindowTitleReference:a}=kr();return mn(t,o),i.createElement(FC,null,i.createElement(BC,{ref:o,dir:s,id:Ee.WINDOW,...Dr(t,a),$isExpanded:e,$isOpened:t},n),r)},FC=p.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,BC=p.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&&HC};${({$isExpanded:e})=>e&&UC};`,UC=D.css`width:743px;height:723px;`,HC=D.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;`,GC=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=Ot(),[o,a]=u.useState(t),[l,c]=u.useState(n.entryPoint??"Conversation"),d=s?Ki:$C;return i.createElement(Lr,{enableExpandButton:!s,ref:r,...n},i.createElement(ri,null,({state:m})=>i.createElement(qi,null,i.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...s&&{zIndex:"auto"},launcher:i.createElement(Ji,{entryPoint:n.entryPoint,activeRoute:l})},i.createElement(ta,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:a,onActiveRouteChange:c})),e)))}),{Provider:VC,useContext:Pr}=_e("FixedMessengerStyle");function na(e,t,n,r=0){const{top:s,bottom:o,start:a,end:l}=n;let c="",d="";switch(e){case"start":d=`inset-inline-start: ${He(a)}`;break;case"end":d=`inset-inline-end: ${He(l)}`;break}switch(t){case"top":c=`top: calc(${He(s)} + ${r}px)`;break;case"bottom":c=`bottom: calc(${He(o)} + ${r}px)`;break}return D.css`${c};${d};`}function zC(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Pr();return i.createElement(YC,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const YC=p.default(Ji)`position:fixed;z-index:${ot.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>na(e,t,n)};`,WC=({isExpanded:e,isOpened:t,children:n})=>i.createElement(Mr,null,i.createElement(qC,{isExpanded:e,isOpened:t},n)),qC=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=ge(),{horizontal:s,vertical:o,margin:a,launcherSize:l}=Pr(),c=u.useRef(null),{hasWindowTitleReference:d}=kr();return mn(t,c),i.createElement(KC,{ref:c,dir:r,id:Ee.WINDOW,...Dr(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:a,$launcherSize:l},n)},KC=p.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})=>na(e,t,n,r+12)};height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 150ms;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
509
+ `;function Xt({initialId:e,children:t}){const[n,r]=u.useState([e]),o=n[n.length-1],s=u.useCallback((v,b)=>{r(E=>[...E,v]),f(E=>({...E,[v]:!0})),b!=null&&b.reset&&C(E=>({...E,[v]:(E[v]||0)+1})),_(E=>({...E,[v]:"entering"})),setTimeout(()=>{_(E=>({...E,[v]:"entered"}))},300)},[]),a=u.useCallback(()=>{r(v=>{if(v.length<=1)return v;const b=v[v.length-1];return _(E=>({...E,[b]:"exiting"})),setTimeout(()=>{_(E=>({...E,[b]:"exited"})),r(E=>E.slice(0,-1))},300),v})},[]),l=u.useMemo(()=>({navigation:{navigate:s,pop:a},activeScreenId:o}),[s,a,o]),c=u.useMemo(()=>u.Children.toArray(t).filter(v=>v.type===na),[t]),d=u.useMemo(()=>{const v={};return c.forEach(b=>{const{id:E,lazy:A,children:x}=b.props;v[E]={lazy:A,element:typeof x=="function"?x(l):x}}),v},[c,l]),[m,f]=u.useState(()=>{const v={};return Object.entries(d).forEach(([b,{lazy:E}])=>{E===!1&&(v[b]=!0)}),v[e]=!0,v}),[h,_]=u.useState(()=>{const v={};return Object.keys(d).forEach(b=>{b===e?v[b]="entered":v[b]="exited"}),v}),[y,C]=u.useState({});return i.createElement(ta.Provider,{value:l},i.createElement(UC,null,Object.keys(d).map(v=>{var x;if(!m[v])return null;const b=h[v]||"exited",E=v===o,A=`${v}-${y[v]||0}`;return i.createElement(BC,{key:A,$transitionState:b,$active:E,"aria-hidden":E?void 0:!0,inert:E?void 0:!0},(x=d[v])==null?void 0:x.element)})))}const UC=p.default.div`position:relative;width:100%;height:100%;`;Xt.Screen=na;const Pe={conv:"conv",convList:"conv-list"},HC=e=>e===Pe.convList?"ConversationList":"Conversation",ss=({isOpened:e,activeScreenId:t})=>e&&t===Pe.conv,ra=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:o})=>{const{conversationChildren:s,conversationListChildren:a}=Nr(),l=(()=>{switch(t){case"Conversation":return Pe.conv;case"ConversationList":return Pe.convList;default:return Pe.conv}})(),c=i.createElement(i.Fragment,null,i.createElement(GC,{onOpenConversationView:(d,m)=>{r(m),d.navigate(Pe.conv)}}),i.createElement(zC,{onActiveRouteChange:o}));return i.createElement(Xt,{initialId:l},i.createElement(Xt.Screen,{id:Pe.conv},({navigation:d,activeScreenId:m})=>i.createElement(zi,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>d.navigate(Pe.convList),announcementsEnabled:ss({isOpened:e,activeScreenId:m}),shouldMarkAsRead:ss({isOpened:e,activeScreenId:m})},c,s)),i.createElement(Xt.Screen,{id:Pe.convList,lazy:!0},({navigation:d,activeScreenId:m})=>{const f=e&&m===Pe.convList;return i.createElement(Wi,{announcementsEnabled:f,onOpenConversationView:h=>{r(h),d.navigate(Pe.conv)}},c,a)}))},GC=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=we(),{navigation:n}=$r();return t(({channel:r})=>{e(n,r.url)}),null},zC=({onActiveRouteChange:e})=>{const{activeScreenId:t}=$r();return u.useEffect(()=>{e==null||e(HC(t))},[t,e]),null},VC=({isExpanded:e,isOpened:t,children:n,launcher:r})=>i.createElement(Mr,null,i.createElement(YC,{isExpanded:e,isOpened:t,launcher:r},n)),YC=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:o}=me(),s=u.useRef(null),{hasWindowTitleReference:a}=kr();return fn(t,s),i.createElement(WC,null,i.createElement(qC,{ref:s,dir:o,id:Ce.WINDOW,...Dr(t,a),$isExpanded:e,$isOpened:t},n),r)},WC=p.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,qC=p.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&&jC};${({$isExpanded:e})=>e&&KC};`,KC=D.css`width:743px;height:723px;`,jC=D.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;`,XC=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const o=Ot(),[s,a]=u.useState(t),[l,c]=u.useState(n.entryPoint??"Conversation"),d=o?Xi:VC;return i.createElement(Or,{enableExpandButton:!o,ref:r,...n},i.createElement(si,null,({state:m})=>i.createElement(ji,null,i.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...o&&{zIndex:"auto"},launcher:i.createElement(ea,{entryPoint:n.entryPoint,activeRoute:l})},i.createElement(ra,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:a,onActiveRouteChange:c})),e)))}),{Provider:ZC,useContext:Pr}=Ee("FixedMessengerStyle");function oa(e,t,n,r=0){const{top:o,bottom:s,start:a,end:l}=n;let c="",d="";switch(e){case"start":d=`inset-inline-start: ${Ge(a)}`;break;case"end":d=`inset-inline-end: ${Ge(l)}`;break}switch(t){case"top":c=`top: calc(${Ge(o)} + ${r}px)`;break;case"bottom":c=`bottom: calc(${Ge(s)} + ${r}px)`;break}return D.css`${c};${d};`}function JC(e){const{horizontal:t,vertical:n,margin:r,launcherSize:o}=Pr();return i.createElement(QC,{...e,size:o,$horizontal:t,$vertical:n,$margin:r})}const QC=p.default(ea)`position:fixed;z-index:${it.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>oa(e,t,n)};`,ev=({isExpanded:e,isOpened:t,children:n})=>i.createElement(Mr,null,i.createElement(tv,{isExpanded:e,isOpened:t},n)),tv=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=me(),{horizontal:o,vertical:s,margin:a,launcherSize:l}=Pr(),c=u.useRef(null),{hasWindowTitleReference:d}=kr();return fn(t,c),i.createElement(nv,{ref:c,dir:r,id:Ce.WINDOW,...Dr(t,d),$isExpanded:e,$isOpened:t,$horizontal:o,$vertical:s,$margin:a,$launcherSize:l},n)},nv=p.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})=>oa(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}`};
502
510
  [dir='rtl'] &:not([dir='ltr']),
503
511
  &[dir='rtl'] {
504
512
  transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
505
513
  }
506
514
 
507
- ${({$isOpened:e})=>e&&XC};
508
- ${({$isExpanded:e})=>e&&jC};
509
- `,jC=D.css`width:743px;height:723px;`,XC=D.css`z-index:${ot.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;`,ra={top:24,bottom:24,start:24,end:24},ZC=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=u.useState(t),[a,l]=u.useState(n.entryPoint??"Conversation"),[c,d]=u.useState("end-bottom"),[m,h]=u.useState(ra),[f,E]=u.useState(48),v=Ot(),y=v?Ki:WC,{horizontal:C,vertical:_}=u.useMemo(()=>{const[b,A]=c.split("-");return{horizontal:b==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[c]);return i.createElement(Lr,{enableExpandButton:!v,ref:r,...n},i.createElement(ri,null,({state:b})=>i.createElement(VC,{value:{horizontal:C,vertical:_,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:E}},i.createElement(qi,null,i.createElement(y,{isExpanded:b.expanded,isOpened:b.opened},i.createElement(ta,{isOpened:b.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,onActiveRouteChange:l})),i.createElement(zC,{entryPoint:n.entryPoint,activeRoute:a}),e))))}),JC=e=>{var s,o,a,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=Pr();return u.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...ra,...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,(a=e.margin)==null?void 0:a.start,(l=e.margin)==null?void 0:l.end,e.launcherSize]),null},QC=({children:e})=>{const{setConversationChildren:t}=Nr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},ev=({children:e})=>{const{setConversationListChildren:t}=Nr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},tv=Object.assign(ZC,{Style:JC,ConversationChildren:QC,ConversationListChildren:ev}),nv=e=>{const{refreshActiveChannel:t}=Te(),[n,r]=u.useState(!1),s=u.useRef(null),o=u.useRef(null);return u.useEffect(()=>{n&&t().then(()=>{var a;(a=s.current)==null||a.call(s),r(!1)}).catch(a=>{var l;(l=o.current)==null||l.call(o,a),r(!1)})},[n]),u.useCallback(()=>new Promise((a,l)=>{s.current=a,o.current=l,e().then(()=>r(!0)).catch(l)}),[e])};vo.set(fe.SendbirdPlatform.JS,{deviceOSPlatform:va()?fe.DeviceOsPlatform.MOBILE_WEB:fe.DeviceOsPlatform.WEB,messengerVersion:Bu,keyValueStorage:Hu(),networkStateAdapter:Uu()});exports.ANCHOR_REL=gr;exports.AgentProviderContainer=Lr;exports.AgentUIProviderContainer=Yi;exports.AnonymousSessionInfo=Un;exports.CSATType=Ve;exports.Commands=Ze;exports.ConnectionDelayLayout=hn;exports.Conversation=Hi;exports.ConversationContext=vm;exports.ConversationContextProvider=li;exports.ConversationHeaderLayout=at;exports.ConversationLayout=bn;exports.ConversationList=zi;exports.ConversationListContext=Mb;exports.ConversationListContextProvider=Vi;exports.ConversationListHeaderLayout=pt;exports.ConversationListItemLayout=Or;exports.ConversationListLayout=Cn;exports.DefaultMessenger=GC;exports.DeskTicketPriority=ar;exports.DeskTicketStatus=ir;exports.FixedMessenger=tv;exports.ID_INCOMING=Ye;exports.IncomingMessageLayout=tt;exports.LauncherBase=ji;exports.LogLevel=rr;exports.ManualSessionInfo=ho;exports.MessageListUILayout=En;exports.MessageLogs=Ri;exports.OutgoingMessageLayout=Nt;exports.PlaceholderLayout=_n;exports.SystemMessageLayout=gn;exports.cssVars=g;exports.escapeMarkdownSyntax=ba;exports.flattenObject=Xa;exports.mapCommonStringsToReactFormat=zo;exports.messengerDispatcher=Wi;exports.noop=he;exports.parseToMessageTemplate=bo;exports.parseToUITemplate=Ka;exports.pickColorByTheme=ja;exports.replaceVariablesAsync=Ja;exports.replaceVariablesSync=Za;exports.useAIAgentContext=Oe;exports.useConversationContext=ve;exports.useConversationListContext=Dt;exports.useLocalizationContext=oe;exports.useMessageTemplateFetchingContext=yc;exports.useMessengerContext=ge;exports.useMessengerSessionContext=Te;exports.useMessengerThemeContext=Xo;exports.useRefreshActiveChannel=nv;
515
+ ${({$isOpened:e})=>e&&ov};
516
+ ${({$isExpanded:e})=>e&&rv};
517
+ `,rv=D.css`width:743px;height:723px;`,ov=D.css`z-index:${it.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;`,sa={top:24,bottom:24,start:24,end:24},sv=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[o,s]=u.useState(t),[a,l]=u.useState(n.entryPoint??"Conversation"),[c,d]=u.useState("end-bottom"),[m,f]=u.useState(sa),[h,_]=u.useState(48),y=Ot(),C=y?Xi:ev,{horizontal:v,vertical:b}=u.useMemo(()=>{const[E,A]=c.split("-");return{horizontal:E==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[c]);return i.createElement(Or,{enableExpandButton:!y,ref:r,...n},i.createElement(si,null,({state:E})=>i.createElement(ZC,{value:{horizontal:v,vertical:b,margin:m,launcherSize:h,setPosition:d,setMargin:f,setLauncherSize:_}},i.createElement(ji,null,i.createElement(C,{isExpanded:E.expanded,isOpened:E.opened},i.createElement(ra,{isOpened:E.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:s,onActiveRouteChange:l})),i.createElement(JC,{entryPoint:n.entryPoint,activeRoute:a}),e))))}),iv=e=>{var o,s,a,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=Pr();return u.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...sa,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(o=e.margin)==null?void 0:o.top,(s=e.margin)==null?void 0:s.bottom,(a=e.margin)==null?void 0:a.start,(l=e.margin)==null?void 0:l.end,e.launcherSize]),null},av=({children:e})=>{const{setConversationChildren:t}=Nr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},lv=({children:e})=>{const{setConversationListChildren:t}=Nr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},cv=Object.assign(sv,{Style:iv,ConversationChildren:av,ConversationListChildren:lv}),uv=e=>{const{refreshActiveChannel:t}=we(),[n,r]=u.useState(!1),o=u.useRef(null),s=u.useRef(null);return u.useEffect(()=>{n&&t().then(()=>{var a;(a=o.current)==null||a.call(o),r(!1)}).catch(a=>{var l;(l=s.current)==null||l.call(s,a),r(!1)})},[n]),u.useCallback(()=>new Promise((a,l)=>{o.current=a,s.current=l,e().then(()=>r(!0)).catch(l)}),[e])};ys.set(ge.SendbirdPlatform.JS,{deviceOSPlatform:Sa()?ge.DeviceOsPlatform.MOBILE_WEB:ge.DeviceOsPlatform.WEB,messengerVersion:Vu,keyValueStorage:Wu(),networkStateAdapter:Yu()});exports.ANCHOR_REL=gr;exports.AgentProviderContainer=Or;exports.AgentUIProviderContainer=qi;exports.AnonymousSessionInfo=Un;exports.CSATType=Ye;exports.Commands=Ze;exports.ConnectionDelayLayout=hn;exports.Conversation=zi;exports.ConversationContext=Im;exports.ConversationContextProvider=ui;exports.ConversationHeaderLayout=lt;exports.ConversationLayout=Cn;exports.ConversationList=Wi;exports.ConversationListContext=$b;exports.ConversationListContextProvider=Yi;exports.ConversationListHeaderLayout=Et;exports.ConversationListItemLayout=Lr;exports.ConversationListLayout=vn;exports.DefaultMessenger=XC;exports.DeskTicketPriority=ar;exports.DeskTicketStatus=ir;exports.FixedMessenger=cv;exports.ID_INCOMING=We;exports.IncomingMessageLayout=tt;exports.LauncherBase=Zi;exports.LogLevel=nr;exports.ManualSessionInfo=gs;exports.MessageListUILayout=bn;exports.MessageLogs=Oi;exports.OutgoingMessageLayout=Dt;exports.PlaceholderLayout=En;exports.SystemMessageLayout=pn;exports.cssVars=g;exports.escapeMarkdownSyntax=va;exports.flattenObject=el;exports.mapCommonStringsToReactFormat=Ws;exports.messengerDispatcher=Ki;exports.noop=he;exports.parseToMessageTemplate=Cs;exports.parseToUITemplate=Ja;exports.pickColorByTheme=Qa;exports.replaceVariablesAsync=nl;exports.replaceVariablesSync=tl;exports.useAIAgentContext=Me;exports.useConversationContext=Se;exports.useConversationListContext=$t;exports.useLocalizationContext=se;exports.useMessageTemplateFetchingContext=Tc;exports.useMessengerContext=me;exports.useMessengerSessionContext=we;exports.useMessengerThemeContext=Js;exports.useRefreshActiveChannel=uv;