@sendbird/ai-agent-messenger-react 1.24.0 → 1.25.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 Si=Object.defineProperty;var Ai=(e,t,n)=>t in e?Si(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var A=(e,t,n)=>Ai(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("@sendbird/chat"),u=require("react"),O=require("styled-components"),We=require("date-fns"),xi=require("date-fns/locale/en-US"),qe=require("@sendbird/chat/message"),be=require("@sendbird/chat/aiAgent"),ht=require("@sendbird/chat/groupChannel"),Ye=require("@sendbird/uikit-tools"),Ti=require("react-dom"),Ii=require("date-fns/isSameDay"),Bn=require("@sendbird/react-uikit-message-template-view"),wi=require("@sendbird/uikit-message-template"),ki=require("dompurify"),Li=require("@emotion/is-prop-valid"),mn=e=>e&&e.__esModule?e:{default:e};function Mi(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 Ri=mn(ie),i=Mi(u),_=mn(O),Fo=mn(ki),Oi=mn(Li),ct="sb-agent",Bo="KEY_IMG_ASPECT_RATIO",Hn="*/*",K={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 en=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(en||{}),St=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(St||{});const Ho=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Ni=e=>e===St.COMPLETED||e===St.CANCELED?e:St.IN_PROGRESS,An=e=>Re(e)&&!Ho(e),Re=e=>!!e&&"sender"in e,$i=e=>Re(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Mr=(e,t)=>!e||!t?!1:Re(e)&&Re(t)?e.messageId>0&&t.messageId>0?e.messageId===t.messageId:e.reqId.length>0&&e.reqId===t.reqId:e.messageId>0&&e.messageId===t.messageId,Di=(e,t,n,r=!0)=>{if(!r||!An(e))return"single";const o=()=>{if(!An(t))return!1;const c=t.sender.userId===e.sender.userId,d=We.isSameMinute(t.createdAt,e.createdAt);return c&&d},s=()=>{if(!An(n))return!1;const c=n.sender.userId===e.sender.userId,d=We.isSameMinute(n.createdAt,e.createdAt);return c&&d},a=o(),l=s();return a&&l?"middle":a?"bottom":l?"top":"single"},Tt=(e,t)=>(()=>{var r;return Re(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,pe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Ho(e),isIncoming:(e,t)=>Re(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Re(e)&&(e.sender.userId===t||e.sendingStatus===qe.SendingStatus.PENDING)},ze=e=>e.startsWith("image/"),Uo=e=>e.startsWith("video/"),er=(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"},Vo=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},hn=e=>{switch(e){case"top":case"middle":return K.GAP_GROUPED;default:return K.GAP_UNGROUPED}},Pi=(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},Fi=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Bi=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Hi=e=>e.replace(/~~/g,"\\~\\~"),Ui=e=>{let t=e;return t=Fi(t),t=Bi(t),t=Hi(t),t},Vi=typeof navigator<"u"&&navigator.product==="ReactNative",Rr=(e,t)=>{const n=r=>!t||t.length===0?!0:Re(r)&&t.includes(r.sendingStatus);return Vi?e.find(n):e.findLast(n)};function oe(){}function Gi(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function zi(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 Un=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},De={isStreaming(e){const t=Un(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(Tt(e,t)){const r=Un(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)}},xn=`@${ct}`,Wi=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${xn}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const s=zi(`${e}/${t}/${o}`);return`${xn}-udata/${s}`},anonUserSession:()=>`${xn}-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}}}}},Go=(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 h=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},h)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},c};class zo{constructor(t,{filter:n,limit:r=20}){A(this,"filter");A(this,"_sdk");A(this,"_pinnedChannels");A(this,"_channels");A(this,"_isDisposed",!1);A(this,"_handlerId",`handler-id-${Date.now()}`);A(this,"_order",ht.GroupChannelListOrder.LATEST_LAST_MESSAGE);A(this,"_limit");A(this,"_query");A(this,"_token");A(this,"_timestamp");A(this,"_isSyncing");A(this,"_channelHandler");A(this,"_connectionHandler");A(this,"_collectionEventHandler");A(this,"_throttledOnChannelChanged");var o,s,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:(o=this.filter)==null?void 0:o.aiAgentChannelFilter,aiAgentConversationStatusFilter:(s=this.filter)==null?void 0:s.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=Go(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new ht.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new ie.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 s,a;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let o;r?o=((a=r.lastMessage)==null?void 0:a.createdAt)??r.createdAt:o=this._query.lastResponseAt,this._timestamp>o&&(this._timestamp=o)}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])),o=[],s=[],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=Vn(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),s.push(c)):o.push(c);const g=this._pinnedChannels.findIndex(b=>(r.get(b.url)??1/0)>d),C=g===-1?this._pinnedChannels.length:g;this._pinnedChannels.splice(C,0,c)}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:a}}_upsertRegularChannelsToArray(t,n=!1){const r=[],o=[],s=[];for(const a of t){if(!this._query.belongsTo(a)){r.push(a.url);continue}const l=Vn(this._channels,a),c=l<0;!c&&this._channels.splice(l,1);const m=qi(this._channels,a,this._order).place,h=m===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(a),o.push(a)):(this._channels.splice(m,0,a),o.push(a)):(this._channels.splice(m,0,a),s.push(a))}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var h,g,C,b,v;const r=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),o=[],s=[];for(const f of t)r.has(f.url)?o.push(f):s.push(f);const a=this._upsertPinnedChannelsToArray(o),l=this._upsertRegularChannelsToArray(s,n),c=a.addedChannels.concat(l.addedChannels),d=a.updatedChannels.concat(l.updatedChannels),m=a.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((C=(g=this._collectionEventHandler)==null?void 0:g.onChannelsAdded)==null||C.call(g,{},c)),d.length>0&&((v=(b=this._collectionEventHandler)==null?void 0:b.onChannelsUpdated)==null||v.call(b,{},d)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var o,s,a;const n=new Set(((o=this.filter)==null?void 0:o.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=(s=this._collectionEventHandler)==null?void 0:s.onChannelsDeleted)==null||a.call(s,{},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 Vn=(e,t)=>e.findIndex(n=>n.isIdentical(t)),qi=(e,t,n)=>{if(e.length>0){const r=Vn(e,t);let o=0,s=e.length-1,a=Math.floor((o+s)/2);for(;o<s;){const c=Or(e[a],t,n);if(c>0)s=a,a=Math.floor((o+s)/2);else if(c<0)o=a+1,a=Math.floor((o+s)/2);else return{place:a,oldPosition:r}}return{place:Or(e[a],t,n)>=0?a:a+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},Or=(e,t,n)=>{switch(n){case ht.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 Wo{constructor(t){A(this,"subscribers",{});this.logger=t}async send(t){const n=Ki(),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 Ki=()=>{let e=oe,t=oe;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var Me=(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))(Me||{});class It{constructor(t={}){A(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const rt={CloseConversation:e=>new Yi(e),MessengerSettingsUpdated:e=>new ji(e),ActiveChannelUpdated:e=>new Xi(e),AnonymousSessionTokenExpired:()=>new Zi,AuthTokenRefreshed:()=>new Ji};class Yi extends It{constructor(){super(...arguments);A(this,"type","conv.close")}}class ji extends It{constructor(){super(...arguments);A(this,"type","messenger.settings.updated")}}class Xi extends It{constructor(){super(...arguments);A(this,"type","active.channel.updated")}}class Zi extends It{constructor(){super(...arguments);A(this,"type","anon.token.expired")}}class Ji extends It{constructor(){super(...arguments);A(this,"type","auth.token.refreshed")}}var tr=(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))(tr||{});class qo{constructor(t){A(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 Ko{constructor({userId:t,authToken:n,sessionHandler:r}){A(this,"userId");A(this,"authToken");A(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class Gn{constructor(){A(this,"userId");A(this,"authToken");A(this,"sessionHandler")}}const Qi=e=>({onSessionTokenRequired:t=>{t(null),e.send(rt.AnonymousSessionTokenExpired())}}),ea="ai_agent:stats",ta="conversation_initial_render",na=800220;var ae=(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))(ae||{});class ra{constructor(){A(this,"timers",new Map);A(this,"committed",!1);A(this,"commitCallback",null);A(this,"conversationId",null);A(this,"channelUrl",null);A(this,"errorCode",null);A(this,"errorDescription",null);A(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(ea,t)):!1}}class oa extends ra{constructor(){super(...arguments);A(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return ta}buildPayload(){const n=this.getDuration(ae.AUTH),r=this.getDuration(ae.GET_CHANNEL),o=this.getDuration(ae.GET_MESSAGES),s=this.getDuration(ae.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(ae.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 sa{constructor(t){A(this,"commitCallback");A(this,"presentMethod","direct_present");A(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new oa().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(ae.TOTAL_DURATION).startTimer(ae.TOTAL_DURATION_FROM_CACHE).startTimer(ae.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(ae.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ae.AUTH).setError(t instanceof ie.SendbirdError?t.code:void 0,t.message).stopTimer(ae.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(ae.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(ae.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(ae.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ae.GET_CHANNEL).setError(t instanceof ie.SendbirdError?t.code:void 0,t.message).stopTimer(ae.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ie.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ae.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ie.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ae.TOTAL_DURATION).stopTimer(ae.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 ia(){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 Ge={conversation:{isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0,messageAlertSoundEnabled:!1,header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Nr=e=>{var t,n,r,o,s,a,l,c,d,m,h,g,C,b;return e?{...Ge,...e,conversation:{...Ge.conversation,...e==null?void 0:e.conversation,header:{...(t=Ge.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=Ge.conversation)==null?void 0:r.input,...(o=e==null?void 0:e.conversation)==null?void 0:o.input,camera:{...(a=(s=Ge.conversation)==null?void 0:s.input)==null?void 0:a.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(m=(d=Ge.conversation)==null?void 0:d.input)==null?void 0:m.gallery,...(g=(h=e==null?void 0:e.conversation)==null?void 0:h.input)==null?void 0:g.gallery}},fileViewer:{...(C=Ge.conversation)==null?void 0:C.fileViewer,...(b=e==null?void 0:e.conversation)==null?void 0:b.fileViewer}}}:Ge},Ce=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")},nr=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 je(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 aa(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!je(e):!1}function la(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function $r(e){return!!e&&e<Date.now()}function ca(e){return!e.title}function ua(e,t){var n;if(e)return ca(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 da{constructor(){A(this,"_channelHandlerId",null);A(this,"_connectionHandlerId",null);A(this,"_handleActiveChannelChangedThrottled",null);A(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Go(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:Ce(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 ht.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 ie.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})});A(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")});A(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:Ce(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)}});A(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)}});A(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Me.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Me.MessengerSettingsUpdated,t)}));A(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Me.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Me.ActiveChannelUpdated,t)}));A(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Me.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Me.AuthTokenRefreshed,t)}))}}class ma{constructor(t){A(this,"_sdkUser");A(this,"_userSession");A(this,"_dispatcher");A(this,"_activeChannel");A(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(rt.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});A(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(rt.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 Yo=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)}},wt=e=>JSON.parse(e),gn=e=>JSON.parse(e);function ha(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function ga(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 rr({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,Yo(l))},e)}async function fa({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,Yo(l)),e)}var zn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(zn||{});const jo=e=>typeof e=="object"&&e!==null,Dr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",pa=e=>!jo(e)||!Dr(e,"channel_url")||!Dr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},_a={1:pa};function Ea(e){if(!jo(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=_a[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function ba(e,t,n,r){const o=Ri.default.init({appId:e,modules:[new ht.GroupChannelModule,new be.AIAgentModule],localCacheEnabled:!0,options:new ie.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:ie.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function Ca(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 va=[400300,400301,400302,400310];class or{constructor(t,n,r){A(this,"chatSDK");A(this,"_logger");A(this,"_cache");A(this,"connect",async(t,n,r,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const s=new ie.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(s),this.chatSDK.aiAgent.addEventHandler(zn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=Ea(a);(l==null?void 0:l.category)===zn.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}});A(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")});A(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));A(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));A(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));A(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});A(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)})}});A(this,"_isCacheRestrictedError",t=>va.some(n=>t.code===n));A(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}=wt(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?(Ca(t.chatSDK),n=t.chatSDK):n=ba(t.appId,t.extensions,t.messengerVersion,t.chatParams),new or(n,t.logger,t.cache)}}const Pt=new Map,Xo={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]}}},ya=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class Pr extends Error{constructor(n,r){const o=(r==null?void 0:r.detail)??"";super(o||`Desk API error (${n})`);A(this,"status");A(this,"code");A(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=o}}var sr=(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))(sr||{}),ir=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(ir||{}),Zo=(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))(Zo||{});const Sa=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Aa{constructor(t){A(this,"_appId");A(this,"_apiHost");A(this,"_logger");A(this,"_credential",null);A(this,"_authRefreshPromise",null);A(this,"_onDeskTokenRefreshRequired",async()=>!1);A(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)});A(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});A(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});A(this,"_handleUnauthorized",async(t,n,r)=>{const o=await this._parseErrorCode(t);if(!Sa(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)});A(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}});A(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))}:{}}));A(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));A(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));A(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));A(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Pr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Pr(t.status,{})}});A(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 tn{constructor(t,n){A(this,"id");A(this,"title");A(this,"status");A(this,"agent");A(this,"priority");A(this,"group");A(this,"firstResponseTime");A(this,"issuedAt");A(this,"customFields");A(this,"_client");A(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 tn({id:t.id,title:t.channelName??null,status:t.status2??sr.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??ir.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 ar{constructor(t){A(this,"_logger");A(this,"_apiClient");A(this,"_onDeskTokenRefreshRequired");A(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);A(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}});A(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});A(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")});A(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return tn._fromResponse(n,this)});A(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:ya({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 tn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Aa(t)}static init(t){return new ar(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function xa(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 Ta=1440*60*1e3;function tt(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Ia(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class nn extends da{constructor(n){super();A(this,"appId");A(this,"aiAgentId");A(this,"_chatClient");A(this,"_deskClient");A(this,"_cache");A(this,"_logger");A(this,"_dispatcher");A(this,"_session",null);A(this,"language");A(this,"countryCode");A(this,"context");A(this,"queryParams");A(this,"_config");A(this,"_networkStateAdapter");A(this,"_forceCreateChannel");A(this,"_agentVersion");A(this,"_statsTrackers");A(this,"_operationQueue",ia());A(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"))});A(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));A(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(rt.MessengerSettingsUpdated({settings:s,source:"cache"}));try{const h=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 g;if(h.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."),g={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:v,session_token:f,expire_at:y}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:f,expireAt:y}),g={userId:v,authToken:f},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else g={userId:((d=o.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=o.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,h),this._dispatcher.send(rt.MessengerSettingsUpdated({settings:h,source:"server"}));const C=(()=>{var v;return o.type==="anonymous"?Qi(this._dispatcher):(v=o.userSessionCandidate)==null?void 0:v.sessionHandler})(),b=await this._chatClient.connect(g,C,v=>{var f;this._logger.debug("AIAgent: session token refreshed"),(f=this._session)==null||f._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:g.userId,accessToken:g.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var f;if(v===Zo.ERR_SESSION_KEY_EXPIRED){await new Promise(E=>setTimeout(E,2e3));const y=(f=this._session)==null?void 0:f.userSession.authToken;return y?await this._deskClient.refreshDeskAuthToken(y):!1}return!1}}),(s==null?void 0:s.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new ma({sdkUser:b,userSession:g,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:g.userId}),h}catch(h){throw this._statsTrackers.initialRender.onAuthError(h),h}})});A(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")}));A(this,"createConversation",async n=>{tt(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});A(this,"searchConversation",async n=>{if(tt(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)Ia(a.context??{},n.context)&&o.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:o.length}),o});A(this,"closeConversation",async n=>{var o;tt(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")});A(this,"createConversationListCollection",n=>new zo(this.chatSDK,n??{}));A(this,"patchContext",async(n,r)=>{tt(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??{}}});A(this,"updateContext",async(n,r)=>{tt(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??{}}});A(this,"getContextObject",async n=>{tt(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??{}}});A(this,"refreshActiveChannel",async n=>{var l,c,d;tt(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});A(this,"_getSessionCandidate",n=>n instanceof Ko?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Gn?{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});A(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Ta<=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});A(this,"_getManualSessionInfo",n=>{if(!n||n instanceof Gn)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=Nr(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 sa((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var h;const r=Xo.get(n.platform),o=n.logger??new qo(n.logLevel??tr.WARN),s=n.dispatcher??new Wo(o),a=n.useMMKVStorage?xa(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=Wi({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:o,cache:c}),m=ar.init({appId:n.appId,logger:o,customApiHost:(h=n.deskParams)==null?void 0:h.customApiHost});return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new nn({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=Nr(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 ue=(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 Pe(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:h=>l(()=>h),components:c,updateComponent:(h,g)=>d(C=>({...C,[h]:g}))};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 wa(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function ka(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Jo(e,t)}function Jo(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 La(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=We.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):We.isToday(o)?n.hoursAgo(We.differenceInHours(r,o)):t(o,n.dateShortFormat)}const Ma=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"),Fr=(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=Ma(e);return r?`#${Ft(r[0])}${Ft(r[1])}${Ft(r[2])}${n}`:e},Ra=(e,t)=>{if(!t)return e;const n={...e};for(const[r,o]of Object.entries(t))o&&(n[r]=o);return n},Qo=ue("AIAgent"),Oa=Qo.Provider,ke=Qo.useContext;function Na(e){const t=$a(e);return i.createElement(Oa,{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}},e.children)}function $a(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=nn.init(e);else{const o=Da(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=nn.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 Da(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 Br=Symbol("conversationMessageEventBridge"),bt=Symbol("conversationMessageEventPublisher"),Pa=(e,t)=>{const n=e;if(n[bt]=t,n[Br])return e;n[Br]=!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,h)=>{var g;d(m,h),(g=n[bt])==null||g.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),a.onApiResult=d=>c((m,h)=>{var g;d(m,h),(g=n[bt])==null||g.call(n,{kind:"initialized",source:"api",messages:h??[]})}),a},e},Fa=(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(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 ht.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return Pa(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=Ye.useGroupChannelMessages(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},xt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function es(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Ba(e){const t=es(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Ha(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Ua(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 Va(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const a=function(m,h,g){return g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(h-m)*6*g:g<.5?h:g<.6666666666666666?m+(h-m)*(.6666666666666666-g)*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]=Ba(e),[a,l,c]=Ua(r,o,s),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,g,C]=Va(a,m,d);return Ha([Math.round(h),Math.round(g),Math.round(C)])}function Ga(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 Wn(e){const t=es(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?xt.BLACK:xt.WHITE}function za(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}}}const Wa=(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}}),Ht={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)"}},Tn={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 Hr(e){const t=qa(e),n=Ka(e,t),r=ja(n,e.colors,e.selectedTheme),o=Za(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 qa({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ht.primary.main?Ht.primary:Ga(n,e):Ht.primary;return{...Ht,primary:r,...t}}function Ka({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??Wn(s),l=n??xt.DEFAULT_BOT_MSG_BG,c=r??Wn(l);return(e==="light"?za:Wa)(o,s,a,l,c)}function Ya(e,t,n){return typeof e=="string"?e:e[t]??n}function ja(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 h=((a=s[l])==null?void 0:a[d])??"";o[l][d]=Ya(m,n,h)}}}return r}function Xa(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function Za({typography:e}){if(!e)return Tn;const t={...Tn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=Tn[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Xa(o,r,s)}}),t}const{Provider:Ja,useContext:lr}=ue("AIAgentTheme");function Qa({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=u.useRef(null),[l,c]=u.useState(()=>Hr({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,h)=>{h&&(a.current=h);const g=(o==null?void 0:o.theme)??m,C=a.current?a.current.themes[g]:null,b={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!b.primary&&(C!=null&&C.primary_color)&&(b.primary=C.primary_color,b.primaryContrast=C.primary_contrast_color),!b.botMessageBackground&&(C!=null&&C.bot_message_bg_color)&&(b.botMessageBackground=C.bot_message_bg_color,b.botMessageBackgroundContrast=C.bot_message_bg_contrast_color);const v=Hr({selectedTheme:g,palette:t,typography:n,colors:r,...b});c(v),e==null||e.info("theme.update:",g)},[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(Ja,{value:{theme:l,updateTheme:d}},s)}const In=25*1024*1024,Ur=1,Vr=new Set(["image/png","image/jpeg","image/jpg"]),Gr=new Set(["application/pdf"]),el={off:"off",always:"always",handed_off_only:"handed_off_only"},tl=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:Ur,attachmentMode:"handed_off_only",defaultUploadSizeLimit:In,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Vr,supportedFileMimeTypes:Gr})),n=u.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??Ur,attachmentMode:el[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??In,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)??Vr),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??Gr)})},[]),r=u.useCallback(o=>{const{channel:s,uploadSizeLimit:a=In}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?je(s):!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 je(s);default:return!0}},get supportedMimeTypes(){return l()?[Hn]:[...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}},zr=(...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:nl,useContext:kt}=ue("AIAgentMessengerSession"),rl=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=ke(),{updateTheme:l}=lr(),[c,d]=u.useState(void 0),[m,h]=u.useState(void 0),[g,C]=u.useState(null),[b,v]=u.useState(null),[f,y]=u.useState(null),[E,x]=u.useState(null),{updateBaseAttachmentRules:S,createAttachmentRules:I}=tl();u.useEffect(()=>{const L=r.onMessengerSettingsUpdated(({settings:w})=>{const{appearance:D,bot:R,launcher:Y}=w;l(D.selected_theme,D),y({userId:R.bot_userid,profileUrl:R.bot_profile_url,nickname:R.bot_nickname,replyToFile:R.reply_to_file,specialNotice:R.special_notice,specialNoticeEnabled:R.is_special_notice_enabled,showHandoffButton:R.show_handoff_button??!0,isMultipleActiveConversationsEnabled:R.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:R.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:R.is_user_feedback_comment_option_enabled??!1}),x({type:Y.image_type||"default_icon",imageUrl:Y.image_url}),S(w)}),P=r.onActiveChannelUpdated(({channelUrl:w,status:D,conversationStatus:R})=>{h({url:w,status:D,conversationStatus:R})}),N=r.onAuthTokenRefreshed(()=>{var D;const w=(D=r.session)==null?void 0:D.userSession.authToken;w&&v(R=>R?{...R,authToken:w}:null)});return()=>{L(),P(),N()}},[r,l,S]);const k=u.useCallback(async()=>{try{const L=await r.authenticate(e),P=r.session;return C(P.sdkUser),v(P.userSession),h(P.activeChannel),d(void 0),L}catch(L){throw C(null),v(null),h(void 0),d(L),L}},[r,e]),M=u.useCallback(async()=>{await r.deauthenticate(),C(null),h(void 0),v(null),y(null),x(null)},[r]),U=u.useCallback(async()=>{if(!r.session){if(b)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!==(b==null?void 0:b.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,a,b]),F=u.useCallback(async L=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(L)},[r]),z=u.useCallback(async L=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(L)},[r]);return u.useImperativeHandle(n,()=>{const L=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:k,deauthenticate:M,updateContext:async(...P)=>{const N=zr(...P);if(N.type==="active"){const R=await(await L()).updateContext(s,N.context);return Ct(R)}const w=await o.aiAgent.updateContext(N.aiAgentId,N.channelUrl,N.context);return Ct(w)},patchContext:async(...P)=>{const N=zr(...P);if(N.type==="active"){const R=await(await L()).patchContext(s,N.context);return Ct(R)}const w=await o.aiAgent.patchContext(N.aiAgentId,N.channelUrl,N.context);return Ct(w)},getContextObject:async()=>{const N=await(await L()).getContextObject(s);return Ct(N)}}},[k,M,m,o,s,a]),i.createElement(nl,{value:{sdkUser:g,userSessionInfo:e,userSession:b,activeChannel:m,setActiveChannel:h,refreshActiveChannel:U,createConversation:F,searchConversation:z,connectionError:c,aiAgentInfo:f,launcherInfo:E,authenticate:k,deauthenticate:M,createAttachmentRules:I,statsTrackers:r.statsTrackers}},t)}),cr=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useEffect(()=>{const o=new ie.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 ol(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=ke(),{sdkUser:s,statsTrackers:a}=kt(),l=Ye.useForceUpdate(),[c,d]=u.useState(void 0),[m,h]=u.useState(void 0),[g,C]=u.useState(!1);function b(f){f.isAIAgent&&!f.conversation&&(C(!0),o.initConversationIfNeeded(f).finally(()=>C(!1)))}async function v(){var f,y,E;if(!s){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),h(void 0),C(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const x=await t.groupChannel.getChannel(e);b(x),d(x),a.initialRender.onGetChannelComplete((f=x.conversation)==null?void 0:f.id),x.url===((y=o.session)==null?void 0:y.activeChannel.url)&&o.session._updateActiveChannel({url:x.url,status:Ce(x)?"closed":"open",conversationStatus:(E=x.conversation)==null?void 0:E.status}),n.debug("useChannel.getChannel: fetched channel",x)}catch(x){a.initialRender.onGetChannelError(x),x instanceof ie.SendbirdError&&h(x),n.error("useChannel.getChannel: error",x)}}}return u.useEffect(()=>{v()},[t,s,e,r]),cr(t,{async onReconnectSucceeded(){if(!c)return;const f=await c.refresh();b(f),d(f)}}),Ye.useGroupChannelHandler(t,{onChannelChanged:f=>{f.isGroupChannel()&&f.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",f.url),d(f),l())}}),{channel:c,channelFetchError:m,getChannel:v,isInitializingConversation:g}}const sl=new Set(["suggested_replies","steward","system"]),il=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||!sl.has(r)))return r},al=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},ll=()=>{const{chatSDK:e,networkStateAdapter:t}=ke(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return cr(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===ie.ConnectionState.OPEN?"connected":s)})},[t,e]),n},cl=3e4,ul=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,s]=u.useState(!1),a=u.useRef(null),l=t&&Tt(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),s(!1)},d=g=>{a.current&&clearTimeout(a.current),s(!0),a.current=setTimeout(()=>{s(!1),a.current=null},g)},m=Date.now()-l,h=cl-m;return n||h<=0?c():d(h),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},ts=e=>{const{chatSDK:t}=ke(),[n,r]=u.useState([]);return Ye.useGroupChannelHandler(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},dl=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=u.useState(!1),a=ts(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=Tt(t,n)&&(De.isStreaming(t)||r);s(c||l)},[a,t,n,r]),o},ml=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=kt(),a=ll(),l=dl({channel:e,lastMessage:Rr(t,[qe.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=ul({shouldApply:!!(e!=null&&e.isAIAgent)&&!je(e),isBlockedWhileAIResponding:l,lastMessage:Rr(t,[qe.SendingStatus.PENDING,qe.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""}),d=(h,g)=>({_mode:h,disabled:h!=="enabled",disabledBy:g});if(!e||a==="disconnected")return d("disabled","unavailable");if(a==="reconnecting")return d("disabled","reconnecting");if(Ce(e))return d("disabled","conversation_closed");if(aa(e))return d("disabled","handoff_pending");if(al(e))return d("disabled","form_active");const m=il(e);return m?d("disabled",m):l||c||r?d("readOnly","ai_responding"):d("enabled","")},hl=()=>{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:gl}=ue("AIAgentConversation");function fl({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=oe,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var z;const g=()=>d&&(f==null?void 0:f.markAsRead()),{chatSDK:C,logger:b,dispatcher:v}=ke(),{channel:f,channelFetchError:y,getChannel:E,isInitializingConversation:x}=ol(t),{statsTrackers:S}=kt();u.useEffect(()=>{if(t)return S.initialRender.setChannelUrl(t),()=>{S.initialRender.cleanup()}},[t,S]);const I=Fa(C,f,{replyType:qe.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:L=>r==null?void 0:r(L),onMessagesUpdated:L=>o==null?void 0:o(L),onCacheResult:L=>S.initialRender.onCacheResult(L),onApiResult:L=>S.initialRender.onApiResult(L),logger:b,markAsRead:g,sortComparator:h}),k=hl(),M=ml({channel:f,messages:I.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:x});u.useEffect(()=>{g()},[d,f]);const U=Ce(f);u.useEffect(()=>{s==null||s(U)},[U,s]),u.useEffect(()=>{const L=async P=>{const N=typeof(P==null?void 0:P.channelUrl)=="string";f&&N&&P.channelUrl!==f.url||(b.debug("conversation.dispatcher: try to close conversation",f),f!=null&&f.conversation&&f.conversation.status===be.ConversationStatus.OPEN&&(await f.closeConversation(),a==null||a()))};return v.subscribe(Me.ConversationClose,L),()=>{v.unsubscribe(Me.ConversationClose,L)}},[v,f,b,(z=f==null?void 0:f.conversation)==null?void 0:z.status,a]);const F={conversation:(f==null?void 0:f.conversation)??void 0,channelSource:{channel:f,error:y,refetch:()=>E(),closeConversation:async()=>{Ce(f)||await(f==null?void 0:f.closeConversation())}},messageSource:{messages:I.messages,newMessages:I.newMessages,initialized:I.initialized,subscribeMessageEvents:I.subscribeMessageEvents,loadPrevious:()=>I.loadPrevious(),loadNext:()=>I.loadNext(),deleteMessage:L=>I.deleteMessage(L),resendMessage:L=>I.resendMessage(L),resetNewMessages:()=>I.resetNewMessages(),sendUserMessage:async L=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const P=await I.sendUserMessage(L,c);return c==null||c(P),P},sendFileMessage:async L=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const P=await I.sendFileMessage(L,c);return c==null||c(P),P},sendMultipleFilesMessage:async L=>{var N;if(((N=f==null?void 0:f.conversation)==null?void 0:N.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const P=await I.sendMultipleFilesMessage(L,c);return c==null||c(P),P}},state:{streamAnimation:k,input:M}};return i.createElement(gl,{value:F},e)}function pl(e,t){var C,b,v,f,y,E,x,S,I,k;const[n,r]=u.useState(!1),[o,s]=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),s(null),l([]);try{c==null||c.dispose();const M=new zo(e,t);M.setConversationListCollectionHandler({onChannelsAdded:()=>{l(M.channels)},onChannelsUpdated:()=>{l(M.channels)},onChannelsDeleted:()=>{l(M.channels)}}),await M.loadMore(),d(M),s(null)}catch(M){d(null),s(M)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(C=t.filter)==null?void 0:C.aiAgentChannelFilter,(v=(b=t.filter)==null?void 0:b.aiAgentConversationStatusFilter)==null?void 0:v.join(),(y=(f=t.filter)==null?void 0:f.aiAgentIds)==null?void 0:y.join(),(E=t.filter)==null?void 0:E.deskChannelFilter,(S=(x=t.filter)==null?void 0:x.pinnedChannelUrls)==null?void 0:S.join(),(I=t.filter)==null?void 0:I.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),g=u.useCallback(async()=>{if(c)try{await c.loadMore()}catch(M){s(M)}},[c]);return cr(e,{onConnected:()=>h()}),u.useEffect(()=>{h()},[h]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:o,channels:a,loadMore:g}}const{Provider:_l}=ue("AIAgentConversationList");function El({conversationListLimit:e,conversationListFilter:t,children:n}){var h,g;const{chatSDK:r,aiAgentId:o,queryParams:s}=ke(),a={aiAgentIds:[o],aiAgentConversationStatusFilter:[be.ConversationStatus.CLOSED,be.ConversationStatus.OPEN]},l=e??((h=s==null?void 0:s.conversationListParams)==null?void 0:h.limit),c={...a,...(g=s==null?void 0:s.conversationListParams)==null?void 0:g.filter,...t},d=pl(r,{limit:l,filter:c}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return i.createElement(_l,{value:m},n)}function bl(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:Cl,useContext:ns}=ue("MessageTemplateFetching");function vl({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[o,s]=u.useState({}),a=u.useCallback((d,m)=>{s(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const C=m(h);if(C)return C;const b=r.current[h];if(b)return b;g||a(h,{fetching:!0});const v=d(h).catch(f=>{throw g||a(h,{error:!0}),f}).finally(()=>{g||a(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=bl(m());return n.current[d]=h,h},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(Cl,{value:c},e)}const fn={VARIABLE:e=>new RegExp(`\\{${e}\\}`,"g"),VIEW_VARIABLE:e=>new RegExp(`"{@${e}}"`,"g")};function Xe({uiTemplateString:e,variables:t={}}){const n=ga(t);return rr({template:e,variables:n,variableKeyPattern:r=>fn.VARIABLE(r)})}function Ze({theme:e,uiTemplateString:t,colorVariables:n={}}){return rr({template:t,variables:n,variableKeyPattern:r=>fn.VARIABLE(r),variableValueTransformer:r=>ha(e,r)})}function yl({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:o,onRequestTemplate:s}){const l=Object.values(n).flat().map(d=>d.key);return[...new Set(l)].some(d=>!s(d))?null:rr({template:t,variables:n,variableKeyPattern:d=>fn.VIEW_VARIABLE(d),variableValueTransformer:d=>{const m=d.map(({key:h,variables:g})=>{const C=s(h),{ui_template:b,color_variables:v}=wt(C);let f=JSON.stringify(b);return f=Xe({uiTemplateString:f,variables:o}),f=Ze({theme:e,uiTemplateString:f,colorVariables:v}),f=Ze({theme:e,uiTemplateString:f,colorVariables:r}),f=Xe({uiTemplateString:f,variables:g}),gn(f)});return JSON.stringify(m)}})}async function Sl({theme:e,uiTemplateString:t,viewVariables:n={},aiAgentColorVariables:r,internalVariables:o,onRequestTemplate:s}){return fa({template:t,variables:n,variableKeyPattern:a=>fn.VIEW_VARIABLE(a),variableValueTransformer:async a=>{const l=a.map(async({key:d,variables:m})=>{const h=await s(d),{ui_template:g,color_variables:C}=wt(h);let b=JSON.stringify(g);return b=Xe({uiTemplateString:b,variables:o}),b=Ze({theme:e,uiTemplateString:b,colorVariables:C}),b=Ze({theme:e,uiTemplateString:b,colorVariables:r}),b=Xe({uiTemplateString:b,variables:m}),gn(b)}),c=await Promise.all(l);return JSON.stringify(c)}})}const Al=({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:o,color_variables:s}=wt(e);let a=JSON.stringify(o);if(Object.keys(r.viewVariables??{}).length>0){const c=yl({...r,uiTemplateString:a,aiAgentColorVariables:t,internalVariables:n});if(c===null)return null;a=c}return a=Xe({...r,uiTemplateString:a,variables:n}),a=Ze({...r,uiTemplateString:a,colorVariables:s}),a=Ze({...r,uiTemplateString:a,colorVariables:t}),a=Xe({...r,uiTemplateString:a}),gn(a)},xl=async({rawTemplate:e,aiAgentColorVariables:t,internalVariables:n,...r})=>{const{ui_template:o,color_variables:s}=wt(e);let a=JSON.stringify(o);return Object.keys(r.viewVariables??{}).length>0&&(a=await Sl({...r,uiTemplateString:a,aiAgentColorVariables:t,internalVariables:n})),a=Xe({...r,uiTemplateString:a,variables:n}),a=Ze({...r,uiTemplateString:a,colorVariables:s}),a=Ze({...r,uiTemplateString:a,colorVariables:t}),a=Xe({...r,uiTemplateString:a}),gn(a)},Tl=e=>{const{aiAgentColorVariables:t={}}=e,{internalVariables:n}=ns();return u.useState(()=>{const r=e.onGetCachedTemplate(e.templateKey);return r?Al({...e,rawTemplate:r,aiAgentColorVariables:t,internalVariables:n,onRequestTemplate:e.onGetCachedTemplate}):null})},Il=e=>{const[t]=Tl(e);if(t)return t;const{aiAgentColorVariables:n={}}=e,{internalVariables:r,fetchTemplate:o,suspend:s}=ns();return s(e.templateKey,async()=>{const l=await o({...e,suspense:!0});return await xl({...e,rawTemplate:l,aiAgentColorVariables:n,internalVariables:r})}).value},wl="remove_powered_by",ur=(e,t)=>{var o,s;const{chatSDK:n}=ke(),{aiAgentInfo:r}=kt();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&&nr(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(wl)),[a])}throw new Error("Unsupported feature")},kl={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"},Ll={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}}},Ml={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}}},Rl={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}}},Ol={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}}},Nl={text:Ll,number:Ml,"single-select":Rl,"multi-select":Ol},$l={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function rs(e){return Nl[e.type]||$l}function Wr(e){return rs(e).getValueOrDefault(e)}function Dl(e,t,n={}){const r={...kl,...n};return rs(e).validate(e,t,r)}const Pl=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=u.useState({}),[l,c]=u.useState(()=>{const v={};return e.fields.forEach(f=>{v[f.key]=Wr(f)}),v}),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 v={};let f=!1;e.fields.forEach(y=>{const E=Wr(y);JSON.stringify(l[y.key])!==JSON.stringify(E)&&(f=!0),v[y.key]=E}),f&&c(v)}},[d]);const m=(v,f)=>{c(y=>({...y,[v]:f})),a(y=>({...y,[v]:void 0}))},h=e.fields.map(v=>{var E,x,S;const f=l[v.key]??null,y={key:v.key,label:v.label,error:s[v.key],required:v.required};return v.type==="text"?{...y,type:"text",layout:v.layout,value:f,...v.placeholder&&{placeholder:v.placeholder},...((E=v.rules)==null?void 0:E.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...y,type:"number",layout:v.layout,value:f,...v.placeholder&&{placeholder:v.placeholder},...((x=v.rules)==null?void 0:x.max)&&{max:v.rules.max}}:v.type==="single-select"?{...y,type:"single-select",layout:v.layout,value:f,options:v.options}:v.type==="multi-select"?{...y,type:"multi-select",layout:v.layout,value:f,options:v.options,...((S=v.rules)==null?void 0:S.max_select)&&{maxSelect:v.rules.max_select}}:{...y,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(f=>f.key===v),updateFieldValue:m,submit:async()=>{const v={};let f=!1;for(const y of e.fields){const E=l[y.key]??null,x=Dl(y,E,n);x.isValid||(v[y.key]=x.error,f=!0)}if(a(v),!f&&r){const y={};e.fields.forEach(E=>{y[E.key]=l[E.key]??null}),await r(y)}},cancel:async()=>{await(o==null?void 0:o())}}},Fl=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},os=e=>{const{aiAgentInfo:t}=kt(),n=ts(e);if(Ce(e))return null;const r=n[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?Fl(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},Bl=(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},[])},Hl=(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()}}},Ul=(e,t,n=1e4,r=!0)=>{const o=u.useRef(null),s=u.useRef(null),a=u.useRef(!1);o.current||(o.current=Hl(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 h;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)&&(h=o.current)!=null&&h.shouldAnnounce(c)&&t(l)},[c,l,r,t])},dr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=e.members.filter(s=>s.userId!==t.userId).sort((s,a)=>a.joinedAt-s.joinedAt)[0],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?je(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},qr=e=>u.useReducer((t,n)=>({...t,...n}),e);var Ne=(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))(Ne||{});const Vl=new Set(["free_text","single_choice"]),Gl=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=qr({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=qr({followUpItem:!1}),d=u.useMemo(()=>{var f;const C=s.csat,b=typeof C=="number",v=(f=e.follow_up)==null?void 0:f.find(y=>b?y.scores.includes(C):y.always_visible??!1);if(Vl.has(v==null?void 0:v.response_type))return v},[s.csat,e.follow_up]),m=(()=>{var C;if(typeof n=="number")return"submitted";if((t===Ne.AI_AGENT_CSAT_5||t===Ne.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===Ne.AI_AGENT_CSAT_5_WITH_CRE){const b=typeof s.csat=="number",v=!((C=e.cre)!=null&&C.required)||typeof s.isResolved=="boolean";if(b&&v)return"submittable"}return"unsubmittable"})(),h=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:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},wn=5,zl=250,Wl=50,Kr=e=>Math.max(0,e-Wl),ql=e=>e<1e3?{speed:wn*.5,chunkSize:2}:e<2e3?{speed:wn*.8,chunkSize:2}:{speed:wn*.6,chunkSize:3},Kl=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:o,onAnimationComplete:s}=e,[a,l]=u.useState(()=>Kr(t.length)),c=u.useRef(null),d=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=u.useRef({onStart:r,onProgress:o,onComplete:s}).current,h=u.useRef({startCalled:!1,completeCalled:!1}).current,g=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,C=n,b=a<t.length,v=g.initialEnabled&&(C||b);return u.useLayoutEffect(()=>{m.onStart=r,m.onProgress=o,m.onComplete=s,g.textLength=t.length,g.enabled=n}),u.useLayoutEffect(()=>{var f;g.initialEnabled&&(h.startCalled||(h.startCalled=!0,(f=m.onStart)==null||f.call(m)),l(y=>t.length<y?t.length:y))},[t]),u.useEffect(()=>{if(!g.initialEnabled)return;let f=Kr(t.length);d.lastUpdate=0,d.startTime=0,d.lastProgressCall=0;const y=E=>{var z;d.lastUpdate===0&&(d.lastUpdate=E,d.startTime=E,d.lastProgressCall=E);const x=g.textLength,S=E-d.lastUpdate,I=E-d.startTime,{speed:k,chunkSize:M}=ql(I),U=k*M;S>=U&&f<x&&(f=Math.min(f+M,x),l(f),d.lastUpdate=E),E-d.lastProgressCall>=zl&&(d.lastProgressCall=E,(z=m.onProgress)==null||z.call(m)),(f<x||g.enabled)&&(c.current=requestAnimationFrame(y))};return c.current=requestAnimationFrame(y),()=>{var E;c.current&&cancelAnimationFrame(c.current),h.startCalled&&!h.completeCalled&&(h.completeCalled=!0,(E=m.onComplete)==null||E.call(m))}},[]),u.useEffect(()=>{var x;const f=g.initialEnabled&&h.startCalled,y=!n,E=a>=t.length&&t.length>0;f&&y&&E&&!h.completeCalled&&(h.completeCalled=!0,(x=m.onComplete)==null||x.call(m))},[n,a,t.length]),{streamText:g.initialEnabled?t.slice(0,a):t,isAnimating:v}},ss=e=>e.replace(/\s+/g," ").trim(),Yl="Code block",is=e=>`A11Y_INLINE_CODE_${e}`,as=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}},ls=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}},jl=e=>{const{blockquotePrefix:t,content:n}=as(e),{content:r}=ls(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}},Xl=(e,t)=>{const{blockquotePrefix:n,content:r}=as(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=ls(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)},Zl=(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},Jl=(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},Ql=(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},ec=e=>{let t=0,n="";for(;t<e.length;){const r=Zl(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=Jl(e,r+1);if(o===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&rn(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]==="!"&&!rn(e,r-1)?r-1:r;n+=e.slice(t,s);const a=e.slice(r+1,o),l=Ql(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},cs=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},tc=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return cs(n,r,a)?t:`${n}${r}`}),nc=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),rc=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),oc=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 cs(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},sc=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),ic=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},Yr=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))},jr=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},ac=e=>{const t=e.split(`
2
- `),n=[];let r=0;for(;r<t.length;){const o=t[r],s=t[r+1],a=jr(o);if(a.length>0&&s&&Yr(s)){for(n.push(a.join(" ")),r+=2;r<t.length;){const l=t[r],c=jr(l);if(c.length===0||Yr(l))break;n.push(c.join(" ")),r+=1}continue}n.push(o),r+=1}return n.join(`
3
- `)},lc=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),cc=(e,t)=>{const n=e.split(`
4
- `),r=[];let o=0;for(;o<n.length;){const s=n[o],a=jl(s);if(!a){r.push(s),o+=1;continue}let l=-1;for(let c=o+1;c<n.length;c++)if(Xl(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
- `)},rn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},uc=e=>{const t=[];let n=0,r="";for(;n<e.length;){const o=e[n];if(o!=="`"||rn(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]==="`"&&!rn(e,l)&&e.startsWith(a,l)){const d=e.slice(s,l),m=t.push(d)-1;r+=is(m),n=l+a.length,c=!0;break}l+=1}c||(r+=a,n=s)}return{text:r,inlineCodes:t}},dc=(e,{codeBlockPlaceholder:t=Yl}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
7
- `);if(!n)return;const r=[];let o=n;o=cc(o,t),o=ic(o);const s=uc(o);o=s.text,r.push(...s.inlineCodes),o=ec(o),o=tc(o),o=nc(o),o=rc(o),o=oc(o),o=ac(o),o=lc(o),o=sc(o);for(let l=0;l<r.length;l++)o=o.replaceAll(is(l),r[l]);return ss(o)||void 0},on=e=>(e==null?void 0:e.trim())||"",mc=e=>(e?ss(e):void 0)||void 0,mr=e=>({text:on(e),format:"plain"}),hc=e=>({text:on(e),format:"markdown"}),mt=({markdownText:e,plainText:t,comparisonText:n})=>{const r=on(e);return r&&r!==on(n)?hc(r):mr(t)},dt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?dc(t,{codeBlockPlaceholder:o}):mc(t);if(e&&s.push(e),a&&s.push(a),r&&s.push(r),s.length!==0)return s.join(", ")},gc=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r}=t;let o=null;const s=[];let a=null,l=null,c=!1,d=0;const m=(S,I)=>({text:S,ignoreSuppression:I,queueOrder:d++}),h=()=>{const S=s[0]??null,I=o;return S&&I?I.queueOrder<S.queueOrder?(o=null,I):s.shift()??null:S?s.shift()??null:I!==null?(o=null,I):null},g=()=>{for(;;){const S=h();if(!S)return null;if(!(!S.ignoreSuppression&&(r!=null&&r())))return S}},C=S=>{a=S,c=!0,e(S),l=setTimeout(()=>{l=null,c=!1;const I=g();I&&C(I.text)},n)},b=S=>{a=S,e(S)},v=(S,I,k)=>{if(S&&!(!I&&(r!=null&&r()))&&!(S===a&&c))if(c){if(((k==null?void 0:k.mode)??"latestOnly")==="ordered"){const U=s[s.length-1];if((U==null?void 0:U.text)===S)return;s.push(m(S,I));return}o=m(S,I)}else o=null,C(S)};return{announce:(S,I)=>{v(S,!1,I)},announceIgnoringSuppression:(S,I)=>{v(S,!0,I)},flush:()=>{const S=[];let I=h();for(;I!==null;)S.push(I),I=h();if(l!==null&&(clearTimeout(l),l=null),c=!1,S.length!==0)for(const k of S)b(k.text)},destroy:()=>{l!==null&&(clearTimeout(l),l=null),o=null,s.length=0,a=null,c=!1}}},fc=e=>{switch(e){case"conversationClosed":case"csatDisplayed":return"ordered";default:return"latestOnly"}},pc=(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(". "),_c=(e,t)=>{switch(e.event){case"newMessage":return 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"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},Ec=(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}},bc=(e,t)=>!t||!Re(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Xr=(e,t)=>pe.isAdmin(e)?pe.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Cc=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,vc=e=>e===ie.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===ie.CollectionEventSource.EVENT_MESSAGE_UPDATED,Zr=(e,t,n,r)=>{const{newestFirst:o=!1}={};if(o){for(const s of e)if(s&&Xr(s,n)&&t.some(a=>Mr(s,a)))return s;return}for(let s=e.length-1;s>=0;s-=1){const a=e[s];if(a&&Xr(a,n)&&t.some(l=>Mr(a,l)))return a}},yc=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Sc=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Ac=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},xc=({intent:e,strings:t})=>({label:Sc(e,t),hint:Ac(e,t)}),Tc="1.24.0",we="sb-agent",ce={ENTRY:`${we}-entry`,MODAL_ROOT:`${we}-modal-root`,WINDOW:`${we}-window`,LAUNCHER:`${we}-launcher`},us="data-sb-initial-focus",ds="true",Ic=`[${us}="${ds}"]`,wc={[us]:ds},Ut=2147483647,gt={MODAL:Ut-1,TOOLTIP:Ut-2,WINDOW:Ut-3,LAUNCHER:Ut-4},ms=36,kc=100,Lc=Tc,hr="noopener noreferrer nofollow";function Mc(){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 Vt={};function Rc(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Vt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Vt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Vt[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(Vt).filter(t=>t.startsWith(e))}}}}const Oc={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",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:"Connect with an 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_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_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"},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} 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_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"}},qn={language:"en",strings:Oc,dateLocale:xi.enUS},hs=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,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_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_RATING_LABEL:e.csat.a11y_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,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}),gs=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Lt},Lt="en",fs=new Set([Lt,"ko","es","pt","fr","hi","it","de","tr","ja"]),Nc='@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}',$c=(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.":""))))})},Jr=hs(qn.strings),Dc={...Jr,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_UPLOAD_FILES:"Files",FILE_VIEWER__UNSUPPORT:"Unsupported message",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",A11Y_ATTACH_FILE:"Attach file",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_CSAT_RATING_LABEL:(e,t)=>`${e} — ${t}`,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",A11Y_CONNECT_AGENT:"Talk to human agent",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:Jr.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},sn={language:qn.language,dateLocale:qn.dateLocale,stringSet:Dc},Pc=Object.freeze(Object.defineProperty({__proto__:null,default:sn},Symbol.toStringTag,{value:"Module"})),Kn=new Map([[Lt,sn]]);async function Fc(e){const t=Kn.get(e);if(t)return t;try{if(fs.has(e)){const{default:n}=await $c(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/RKaCusvu.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Pc),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/CfhYXtgc.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/BCDZXq61.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BBssumix.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/Jlh8RyJW.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/Sz9ta-fi.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/Bz2jHC-Z.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/CFY_588Z.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/CHz4H01e.cjs"))}),`./languages/${e}.ts`,3);return Kn.set(e,n),n}return sn}catch{return sn}}const{Provider:Bc,useContext:Q}=ue("Localization"),Hc=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=u.useState(Kn.get(Lt));return u.useEffect(()=>{const l=t??gs(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),Fc(l).then(a))},[e,t,n]),i.createElement(Bc,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,c,d)=>We.format(l,c,{locale:s.dateLocale,...d})}},o)},an="data-sb-agent-theme",Qr=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${an}='${e}'] & { ${r} }`},G={light:Qr("light"),dark:Qr("dark")},Uc=O.css(({theme:e})=>{const{palette:t}=e;return`
1
+ "use strict";var Hi=Object.defineProperty;var Gi=(e,t,n)=>t in e?Hi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>Gi(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const le=require("@sendbird/chat"),c=require("react"),P=require("styled-components"),et=require("date-fns"),Vi=require("date-fns/locale/en-US"),ze=require("@sendbird/chat/message"),zi=require("react-dom"),Re=require("@sendbird/chat/aiAgent"),je=require("@sendbird/chat/groupChannel"),qi=require("date-fns/isSameDay"),Wi=require("dompurify"),tr=e=>e&&e.__esModule?e:{default:e};function Yi(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 Ki=tr(le),i=Yi(c),_=tr(P),Js=tr(Wi),ht="sb-agent",Qs="KEY_IMG_ASPECT_RATIO",Hn="*/*",ee={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var rn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(rn||{}),kt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(kt||{});const eo=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},ji=e=>e===kt.COMPLETED||e===kt.CANCELED?e:kt.IN_PROGRESS,Tn=e=>Xe(e)&&!eo(e),Xe=e=>!!e&&"sender"in e,Xi=e=>Xe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Nr=(e,t)=>!e||!t?!1:Xe(e)&&Xe(t)?e.messageId>0&&t.messageId>0?e.messageId===t.messageId:e.reqId.length>0&&e.reqId===t.reqId:e.messageId>0&&e.messageId===t.messageId,Zi=(e,t,n,r=!0)=>{if(!r||!Tn(e))return"single";const s=()=>{if(!Tn(t))return!1;const u=t.sender.userId===e.sender.userId,d=et.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Tn(n))return!1;const u=n.sender.userId===e.sender.userId,d=et.isSameMinute(n.createdAt,e.createdAt);return u&&d},a=s(),l=o();return a&&l?"middle":a?"bottom":l?"top":"single"},Et=(e,t)=>(()=>{var r;return Xe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Te={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>eo(e),isIncoming:(e,t)=>Xe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Xe(e)&&(e.sender.userId===t||e.sendingStatus===ze.SendingStatus.PENDING)},at=e=>e.startsWith("image/"),to=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"},no=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},gn=e=>{switch(e){case"top":case"middle":return ee.GAP_GROUPED;default:return ee.GAP_UNGROUPED}},Ji=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...a)=>{const[l,u,d]=a;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:u.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},Qi=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),ea=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),ta=e=>e.replace(/~~/g,"\\~\\~"),na=e=>{let t=e;return t=Qi(t),t=ea(t),t=ta(t),t},ra=typeof navigator<"u"&&navigator.product==="ReactNative",Dr=(e,t)=>{const n=r=>!t||t.length===0?!0:Xe(r)&&t.includes(r.sendingStatus);return ra?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 oa(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 Gn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ke={isStreaming(e){const t=Gn(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(Et(e,t)){const r=Gn(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)}},In=`@${ht}`,ia=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${In}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=oa(`${e}/${t}/${s}`);return`${In}-udata/${o}`},anonUserSession:()=>`${In}-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}}}}},ro=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:a=!0,trailing:l=!0}=n,u=(...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 u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u};class so{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",je.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,u,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:(u=this.filter)==null?void 0:u.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=ro(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new je.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new le.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((u,d)=>[u,d])),s=[],o=[],a=[];for(const u of t){if(!this._query.belongsTo(u)){a.push(u.url);continue}const d=r.get(u.url);if(d===void 0)continue;const m=Vn(this._pinnedChannels,u);m>=0?(this._pinnedChannels.splice(m,1),o.push(u)):s.push(u);const f=this._pinnedChannels.findIndex(b=>(r.get(b.url)??1/0)>d),v=f===-1?this._pinnedChannels.length:f;this._pinnedChannels.splice(v,0,u)}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=Vn(this._channels,a),u=l<0;!u&&this._channels.splice(l,1);const m=aa(this._channels,a,this._order).place,h=m===this._channels.length;u?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,v,b,C;const r=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),s=[],o=[];for(const g of t)r.has(g.url)?s.push(g):o.push(g);const a=this._upsertPinnedChannelsToArray(s),l=this._upsertRegularChannelsToArray(o,n),u=a.addedChannels.concat(l.addedChannels),d=a.updatedChannels.concat(l.updatedChannels),m=a.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);u.length>0&&((v=(f=this._collectionEventHandler)==null?void 0:f.onChannelsAdded)==null||v.call(f,{},u)),d.length>0&&((C=(b=this._collectionEventHandler)==null?void 0:b.onChannelsUpdated)==null||C.call(b,{},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 u=this._pinnedChannels.findIndex(d=>d.url===l);u>=0&&(r.push(l),this._pinnedChannels.splice(u,1))}else{const u=this._channels.findIndex(d=>d.url===l);u>=0&&(r.push(l),this._channels.splice(u,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 Vn=(e,t)=>e.findIndex(n=>n.isIdentical(t)),aa=(e,t,n)=>{if(e.length>0){const r=Vn(e,t);let s=0,o=e.length-1,a=Math.floor((s+o)/2);for(;s<o;){const u=$r(e[a],t,n);if(u>0)o=a,a=Math.floor((s+o)/2);else if(u<0)s=a+1,a=Math.floor((s+o)/2);else return{place:a,oldPosition:r}}return{place:$r(e[a],t,n)>=0?a:a+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},$r=(e,t,n)=>{switch(n){case je.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 oo{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=la(),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 la=()=>{let e=he,t=he;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Ve=(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))(Ve||{});class Ot{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const lt={CloseConversation:e=>new ca(e),MessengerSettingsUpdated:e=>new ua(e),ActiveChannelUpdated:e=>new da(e),AnonymousSessionTokenExpired:()=>new ma,AuthTokenRefreshed:()=>new ha};class ca extends Ot{constructor(){super(...arguments);S(this,"type","conv.close")}}class ua extends Ot{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class da extends Ot{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class ma extends Ot{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class ha extends Ot{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 io{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${ht}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${ht}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${ht}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${ht}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${ht}/error]`,...t)}}class ao{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 zn{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const fa=e=>({onSessionTokenRequired:t=>{t(null),e.send(lt.AnonymousSessionTokenExpired())}}),ga="ai_agent:stats",pa="conversation_initial_render",_a=800220;var _e=(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))(_e||{});class Ea{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??_a,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(ga,t)):!1}}class ba extends Ea{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return pa}buildPayload(){const n=this.getDuration(_e.AUTH),r=this.getDuration(_e.GET_CHANNEL),s=this.getDuration(_e.GET_MESSAGES),o=this.getDuration(_e.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(_e.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}},u={key:this.getMetricKey(),value:a!==null?String(a):"0"};return this.conversationId!==null&&(u.conversation_id=this.conversationId),this.errorCode!==null&&(u.error_code=this.errorCode),this.errorDescription!==null&&(u.error_description=this.errorDescription),Object.keys(l).length>0&&(u.extra=l),u}}class Ca{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(_e.TOTAL_DURATION).startTimer(_e.TOTAL_DURATION_FROM_CACHE).startTimer(_e.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(_e.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(_e.AUTH).setError(t instanceof le.SendbirdError?t.code:void 0,t.message).stopTimer(_e.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(_e.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(_e.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(_e.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(_e.GET_CHANNEL).setError(t instanceof le.SendbirdError?t.code:void 0,t.message).stopTimer(_e.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof le.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(_e.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof le.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(_e.TOTAL_DURATION).stopTimer(_e.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 va(){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 Qe={conversation:{isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0,messageAlertSoundEnabled:!1,header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Pr=e=>{var t,n,r,s,o,a,l,u,d,m,h,f,v,b;return e?{...Qe,...e,conversation:{...Qe.conversation,...e==null?void 0:e.conversation,header:{...(t=Qe.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=Qe.conversation)==null?void 0:r.input,...(s=e==null?void 0:e.conversation)==null?void 0:s.input,camera:{...(a=(o=Qe.conversation)==null?void 0:o.input)==null?void 0:a.camera,...(u=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:u.camera},gallery:{...(m=(d=Qe.conversation)==null?void 0:d.input)==null?void 0:m.gallery,...(f=(h=e==null?void 0:e.conversation)==null?void 0:h.input)==null?void 0:f.gallery}},fileViewer:{...(v=Qe.conversation)==null?void 0:v.fileViewer,...(b=e==null?void 0:e.conversation)==null?void 0:b.fileViewer}}}:Qe},lo=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},De=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Re.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)===Re.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function nt(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 ya(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!nt(e):!1}function Sa(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Fr(e){return!!e&&e<Date.now()}function Aa(e){return!e.title}function xa(e,t){var n;if(e)return Aa(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 Ta{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=ro(s=>{var o,a;(a=this._session)==null||a._updateActiveChannel({url:s.url,status:De(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new je.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 le.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});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:De(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(Ve.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Ve.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Ve.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Ve.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Ve.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Ve.AuthTokenRefreshed,t)}))}}class Ia{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(lt.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(lt.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 co=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)}},uo=e=>JSON.parse(e),wa=e=>JSON.parse(e);function Ma(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function ka(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 La({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),u=n(o);return s.replace(u,co(l))},e)}async function Ra({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,co(l)),e)}var qn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(qn||{});const mo=e=>typeof e=="object"&&e!==null,Br=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Oa=e=>!mo(e)||!Br(e,"channel_url")||!Br(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Na={1:Oa};function Da(e){if(!mo(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Na[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function $a(e,t,n,r){const s=Ki.default.init({appId:e,modules:[new je.GroupChannelModule,new Re.AIAgentModule],localCacheEnabled:!0,options:new le.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:le.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Pa(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 Fa=[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 le.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(o),this.chatSDK.aiAgent.addEventHandler(qn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var u;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=Da(a);(l==null?void 0:l.category)===qn.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(u=n==null?void 0:n.onExternalAuthTokenExpired)==null||u.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,"_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=>Fa.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:u}=uo(l);this._cache.template.set(u,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?(Pa(t.chatSDK),n=t.chatSDK):n=$a(t.appId,t.extensions,t.messengerVersion,t.chatParams),new or(n,t.logger,t.cache)}}const Ut=new Map,ho={set:(e,t)=>{Ut.set(e,t)},get:e=>{if(Ut.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=Ut.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Ut.entries().next().value;return{platform:t[0],...t[1]}}},Ba=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class Ur 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||{}),fo=(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))(fo||{});const Ua=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Ha{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(!Ua(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 Ur(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Ur(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 sn{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 sn({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 sn._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Ba({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return sn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Ha(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 Ga(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 Va=1440*60*1e3,za=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function ot(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function qa(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class on extends Ta{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",va());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,u,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(lt.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:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:C,session_token:g,expire_at:y}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:C,authToken:g,expireAt:y}),f={userId:C,authToken:g},this._logger.debug("AIAgent.authenticate: anonymous user created",C)}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(lt.MessengerSettingsUpdated({settings:h,source:"server"}));const v=(()=>{var C;return s.type==="anonymous"?fa(this._dispatcher):(C=s.userSessionCandidate)==null?void 0:C.sessionHandler})(),b=await this._chatClient.connect(f,v,C=>{var g;this._logger.debug("AIAgent: session token refreshed"),(g=this._session)==null||g._updateAuthToken(C),this._deskClient.refreshDeskAuthToken(C)},()=>{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:C})=>{var g;if(C===fo.ERR_SESSION_KEY_EXPIRED){await new Promise(E=>setTimeout(E,2e3));const y=(g=this._session)==null?void 0:g.userSession.authToken;return y?await this._deskClient.refreshDeskAuthToken(y):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Ia({sdkUser:b,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=>{ot(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(ot(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:Re.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const a of o)qa(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;ot(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===Re.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Re.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 so(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{ot(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)=>{ot(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=>{ot(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,"refreshActiveChannel",async n=>{var l,u,d;ot(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const 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 ao?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof zn?{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-Va<=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 zn)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=Pr(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 Ca((r,s)=>this._chatClient.chatSDK.aiAgent.appendStat(r,s))}}static init(n){var h;const r=ho.get(n.platform),s=n.logger??new io(n.logLevel??rr.WARN),o=n.dispatcher??new oo(s),a=n.useMMKVStorage?Ga(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=ia({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:u}),m=za?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 on({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:u,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=Pr(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=c.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=c.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 qe(e){const t=c.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[a,l]=c.useState(()=>e.template),[u,d]=c.useState(e.components),m={Template:a,updateTemplate:h=>l(()=>h),components:u,updateComponent:(h,f)=>d(v=>({...v,[h]:f}))};return i.createElement(t.Provider,{value:m},o)}function r({template:o,children:a}){const{updateTemplate:l}=c.useContext(t);return c.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=()=>c.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:l}){const{updateComponent:u}=c.useContext(t);return c.useLayoutEffect(()=>{l&&u(o,l)},[l]),null}}),s}function Wa(...e){return function({children:n}){return e.reduce((r,s)=>i.createElement(s,null,r),n)}}function Ya(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":go(e,t)}function go(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 Ka(e,t,n){var a;const r=new Date,s=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),o=et.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):et.isToday(s)?n.hoursAgo(et.differenceInHours(r,s)):t(s,n.dateShortFormat)}const ja=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},Ht=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Hr=(e,t)=>{const n=Ht(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=ja(e);return r?`#${Ht(r[0])}${Ht(r[1])}${Ht(r[2])}${n}`:e},Xa=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Za=e=>e.length>0,Ja=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>at(s.type)),r=e.some(s=>!at(s.type));return n&&r?at(t.type)?e.filter(s=>at(s.type)):[t]:r?[t]:e},Gr=e=>e.length===0?"empty":e.every(t=>at(t.type))?"images":"non_images",Qa=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Ja(t),s=Gr(e),o=Gr(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}},gt=3,po=6,el=e=>e%gt===0?gt:po,tl=({index:e,itemCount:t})=>{const n=t%gt,r=n>0,s=r?t-n:t,o=r&&e>=s,a=o?n:gt,l=o?e-s:e%gt,u=!r&&e>=t-gt;return{columnSpan:r?po/a:1,rowItemCount:a,isLastInRow:l===a-1,isLastRow:o||u}},_o=Ee("AIAgent"),nl=_o.Provider,$e=_o.useContext;function rl(e){const t=sl(e);return i.createElement(nl,{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 sl(e){const t=c.useRef(null),n=c.useRef(null);if(!t.current||!n.current)t.current=on.init(e);else{const s=ol(n.current,e);(s.appId||s.aiAgentId||s.chatSDK)&&(t.current.dispose(),t.current=on.init({...e,chatParams:s.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,c.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 ol(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 Vr=Symbol("conversationMessageEventBridge"),xt=Symbol("conversationMessageEventPublisher"),il=(e,t)=>{const n=e;if(n[xt]=t,n[Vr])return e;n[Vr]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=o=>{r({...o,onMessagesAdded:(a,l,u)=>{var d,m;(d=o.onMessagesAdded)==null||d.call(o,a,l,u),(m=n[xt])==null||m.call(n,{kind:"messagesAdded",source:a.source,messages:u})},onMessagesUpdated:(a,l,u)=>{var d,m;(d=o.onMessagesUpdated)==null||d.call(o,a,l,u),(m=n[xt])==null||m.call(n,{kind:"messagesUpdated",source:a.source,messages:u})}})};const s=e.initialize.bind(e);return e.initialize=o=>{const a=s(o),l=a.onCacheResult.bind(a),u=a.onApiResult.bind(a);return a.onCacheResult=d=>l((m,h)=>{var f;d(m,h),(f=n[xt])==null||f.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),a.onApiResult=d=>u((m,h)=>{var f;d(m,h),(f=n[xt])==null||f.call(n,{kind:"initialized",source:"api",messages:h??[]})}),a},e},ur=()=>{const[,e]=c.useState(0);return c.useCallback(()=>e(t=>t+1),[])};let al=0;function ll(){return c.useState(()=>`${al++}`)[0]}const bt=(e,t,n)=>{const r=c.useRef(t),o=ll();r.current=t,c.useEffect(()=>{var l;const a=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var b;const v=r.current;(b=v[h])==null||b.call(v,...f)}}),d};return(l=e==null?void 0:e.groupChannel)==null||l.addGroupChannelHandler(o,a(new je.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function cl(e,t){return!e||!t?!0:e.url!==t.url}function Ue(e){return e!=null&&"sendingStatus"in e}function ul(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return Ue(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function dl(e,t){return ul(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function zr(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const an={collection:{groupChannel:{defaultOrder:je.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function qr(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Wr(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const ml=({...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=hl(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const a=Ue(o)?o.reqId:void 0,l=o.messageId||void 0;[a,l].forEach(u=>{if(!u)return;const d=n[u];fl(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=>{Ue(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{Ue(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=>dl(s,n));return t.value.clearBeforeAction?e.newMessageMap=Wr(r,zr):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Wr(r,zr)}),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&&(Ue(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(Ue(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},hl=e=>e.reduce((t,n)=>(Ue(n)?(t[n.reqId]=n,n.sendingStatus===ze.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),fl=(e,t,n=!1)=>{var r,s;if(!Ue(e)||!Ue(t))return!0;if(n&&e&&Kr(e)&&Kr(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===ze.SendingStatus.SUCCEEDED?t.sendingStatus===ze.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},gl=(e=pl)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},a]=c.useReducer(ml,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),l=(g,y,E,I)=>{a({type:"update_messages",value:{messages:g,clearBeforeAction:y,currentUserId:E,strictStreamingOrder:I}})},u=(g,y)=>{a({type:"delete_messages",value:{messageIds:g,reqIds:y}})},d=(g,y,E)=>{a({type:"update_new_messages",value:{messages:g,clearBeforeAction:y,currentUserId:E}})},m=(g,y)=>{a({type:"delete_new_messages",value:{messageIds:g,reqIds:y}})},h=g=>{a({type:"update_initialized",value:{status:g}})},f=g=>{a({type:"update_loading",value:{status:g}})},v=g=>{a({type:"update_refreshing",value:{status:g}})},b=Object.values(o),C=c.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:v,updateMessages:l,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:C,newMessages:b,updateNewMessages:d,deleteNewMessages:m}},Yr=Math.floor(Number.MAX_SAFE_INTEGER/10);function pl(e,t){let n=0,r=0;return Ue(e)&&e.sendingStatus!=="succeeded"&&(n=Yr),Ue(t)&&t.sendingStatus!=="succeeded"&&(r=Yr),e.createdAt+n-(t.createdAt+r)}function Kr(e){try{const t=JSON.parse(e.data||"{}");return typeof t=="object"&&!!t.stream}catch{return!1}}function Ce(e){const t=c.useRef(e);return t.current=e,c.useCallback((...n)=>t.current(...n),[t])}const _l=(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 je.MessageFilter(r)})};function jr(e){return e<Date.now()?an.collection.message.searchLimit:an.collection.message.defaultLimit}const El=(e,t,n={})=>{var Pe,Me;const r=c.useRef(n);r.current=n;const s=c.useRef(t);s.current=t;const o=r.current.logger,a=r.current.startingPoint??Number.MAX_SAFE_INTEGER,l=jr(a),u=r.current.strictStreamingOrder??!1,d=c.useRef({prev:!1,next:!1}),m=ur(),h=c.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:v,refreshing:b,messages:C,newMessages:g,updateMessages:y,updateNewMessages:E,deleteNewMessages:I,deleteMessages:A,updateInitialized:w,updateLoading:k,updateRefreshing:N}=gl(n==null?void 0:n.sortComparator),W=Ce(M=>{var R,O,j,q;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(M){case le.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case le.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case le.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(j=(O=r.current).markAsRead)==null||j.call(O,[s.current]);break}}catch(U){(q=o==null?void 0:o.warn)==null||q.call(o,"[useGroupChannelMessages/markAsReadBySource]",U)}}),G=Ce((M,R)=>{var O,j,q,U,H;if(R.length>0)switch(M){case le.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case le.CollectionEventSource.SYNC_MESSAGE_FILL:{(j=(O=r.current).shouldCountNewMessages)!=null&&j.call(O)&&E(R,!1,(q=e.currentUser)==null?void 0:q.userId),(H=(U=r.current).onMessagesReceived)==null||H.call(U,R);break}}}),K=Ce(M=>{var R,O;(O=(R=r.current).onCollectionEvent)==null||O.call(R,M)}),L=Ce(async(M,R,O)=>new Promise((j,q)=>{var Ge;h.current.instance&&h.current.instance.dispose(),W(),E([],!0,(Ge=e.currentUser)==null?void 0:Ge.userId);const U=()=>{var ce,ue;const{pendingMessages:ne,failedMessages:ie}=h.current.instance??{};qr(ne)&&y(ne,!1,(ce=e.currentUser)==null?void 0:ce.userId),qr(ie)&&y(ie,!1,(ue=e.currentUser)==null?void 0:ue.userId)},H=_l(M,O,{...r.current,startingPoint:R});h.current={apiInitialized:!1,initialized:!1,instance:H},H.setMessageCollectionHandler({onMessagesAdded:(ne,ie,ce)=>{var ue;W(ne.source),G(ne.source,ce),y(ce,!1,(ue=e.currentUser)==null?void 0:ue.userId,u),K({kind:"messagesAdded",source:ne.source,messages:ce})},onMessagesUpdated:(ne,ie,ce)=>{var ue,ge,be;W(ne.source),G(ne.source,ce),y(ce,!1,(ue=e.currentUser)==null?void 0:ue.userId,u),ne.source===le.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((be=(ge=r.current).onMessagesUpdated)==null||be.call(ge,ce)),K({kind:"messagesUpdated",source:ne.source,messages:ce})},onMessagesDeleted:(ne,ie,ce,ue)=>{const ge=ue.map(ke=>ke.messageId),be=ue.filter(Ue).map(ke=>ke.reqId);A(ge,be),I(ge,be),K({kind:"messagesDeleted",source:ne.source,messages:ue})},onChannelDeleted:(ne,ie)=>{var ce,ue;(ue=(ce=r.current).onChannelDeleted)==null||ue.call(ce,ie)},onChannelUpdated:(ne,ie)=>{var ce,ue;m(),(ue=(ce=r.current).onChannelUpdated)==null||ue.call(ce,ie,ne)},onHugeGapDetected:()=>{L(M,Number.MAX_SAFE_INTEGER,an.collection.message.defaultLimit)}});let oe=!1;H.initialize(je.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ne,ie)=>{var ce,ue,ge,be,ke;(ue=(ce=r.current).onCacheResult)==null||ue.call(ce,ne,ie??[]),ne?(e.isCacheEnabled&&((ge=o==null?void 0:o.error)==null||ge.call(o,"[useGroupChannelMessages/onCacheResult]",ne)),oe=!0):ie&&((be=o==null?void 0:o.debug)==null||be.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",ie.length),y(H.succeededMessages,!0,(ke=e.currentUser)==null?void 0:ke.userId),U(),ie.length>0&&(h.current.initialized=!0,j())),K({kind:"initialized",source:"cache",messages:ie??[]})}).onApiResult((ne,ie)=>{var ce,ue,ge,be,ke,Le,te;(ue=(ce=r.current).onApiResult)==null||ue.call(ce,ne,ie??[]),h.current.initialized=!0,h.current.apiInitialized=!0,ne?((ge=o==null?void 0:o.warn)==null||ge.call(o,"[useGroupChannelMessages/onApiResult]",ne),oe?q(ne):j()):ie&&((be=o==null?void 0:o.debug)==null||be.call(o,"[useGroupChannelMessages/onApiResult]","message length:",ie.length),y(H.succeededMessages,!0,(ke=e.currentUser)==null?void 0:ke.userId),r.current.startingPoint||(te=(Le=r.current).onMessagesReceived)==null||te.call(Le,ie),e.isCacheEnabled&&U(),j()),K({kind:"initialized",source:"api",messages:ie??[]})})}));bt(e,{onUserBanned(M,R){var O,j,q;M.isGroupChannel()&&!cl(M,s.current)&&(R.userId===((O=e.currentUser)==null?void 0:O.userId)?(q=(j=r.current).onCurrentUserBanned)==null||q.call(j):m())}}),c.useLayoutEffect(()=>{const M=setTimeout(async()=>{e.currentUser&&s.current&&(w(!1),k(!0),await L(s.current,a,l),k(!1),w(!0))});return()=>clearTimeout(M)},[e,(Pe=e.currentUser)==null?void 0:Pe.userId,(Me=s.current)==null?void 0:Me.url,r.current.replyType]),c.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const V=Ce(async()=>{e.currentUser&&s.current&&(N(!0),await L(s.current,Number.MAX_SAFE_INTEGER,an.collection.message.defaultLimit),N(!1))}),Y=Ce(async()=>{var R;const M=h.current.instance;if(M!=null&&M.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const O=await M.loadPrevious();y(O,!1,(R=e.currentUser)==null?void 0:R.userId)}catch{}finally{d.current.prev=!1}}),x=Ce(()=>{const{initialized:M,instance:R}=h.current;return M&&R?R.hasPrevious:!1}),D=Ce(async()=>{var R;const M=h.current.instance;if(M!=null&&M.hasNext&&!d.current.next)try{d.current.next=!0;const O=await M.loadNext();y(O,!1,(R=e.currentUser)==null?void 0:R.userId)}catch{}finally{d.current.next=!1}}),$=Ce(()=>{const{initialized:M,apiInitialized:R,instance:O}=h.current;return R&&M&&O?O.hasNext:!1}),Q=Ce((M,R)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,q)=>{s.current.sendUserMessage(M).onPending(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId),R==null||R(U)}).onSucceeded(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId),j(U)}).onFailed((U,H)=>{var oe;H&&H.channelUrl===s.current.url&&y([H],!1,(oe=e.currentUser)==null?void 0:oe.userId),q(U)})})}),ae=Ce((M,R)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,q)=>{s.current.sendFileMessage(M).onPending(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId),R==null||R(U)}).onSucceeded(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId),j(U)}).onFailed((U,H)=>{var oe;H&&H.channelUrl===s.current.url&&y([H],!1,(oe=e.currentUser)==null?void 0:oe.userId),q(U)})})}),de=Ce(async(M,R)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise(j=>{const q=[];s.current.sendFileMessages(M).onPending(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId),R==null||R(U)}).onSucceeded(U=>{var H;U.isFileMessage()&&U.channelUrl===s.current.url&&(y([U],!1,(H=e.currentUser)==null?void 0:H.userId),q.push(U)),q.length===M.length&&j(q)}).onFailed((U,H)=>{var oe;H&&H.channelUrl===s.current.url?(y([H],!1,(oe=e.currentUser)==null?void 0:oe.userId),q.push(H)):q.push(null),q.length===M.length&&j(q)})})}),we=Ce((M,R)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,q)=>{s.current.sendMultipleFilesMessage(M).onPending(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId),R==null||R(U)}).onFileUploaded(()=>{m()}).onSucceeded(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId),j(U)}).onFailed((U,H)=>{var oe;H&&H.channelUrl===s.current.url&&y([H],!1,(oe=e.currentUser)==null?void 0:oe.userId),q(U)})})}),T=Ce(async(M,R)=>{var j,q;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 O=await s.current.updateUserMessage(M,R);return O.channelUrl===s.current.url&&y([O],!1,(q=e.currentUser)==null?void 0:q.userId),O}),F=Ce(async(M,R)=>{var j,q;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 O=await s.current.updateFileMessage(M,R);return O.channelUrl===s.current.url&&y([O],!1,(q=e.currentUser)==null?void 0:q.userId),O}),z=Ce(async M=>{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((O,j)=>{let q;M.isUserMessage()&&(q=s.current.resendMessage(M)),M.isFileMessage()&&(q=s.current.resendMessage(M)),M.isMultipleFilesMessage()&&(q=s.current.resendMessage(M)),q&&("onPending"in q&&q.onPending(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId)}),"onFileUploaded"in q&&q.onFileUploaded(()=>{m()}),"onSucceeded"in q&&q.onSucceeded(U=>{var H;U.channelUrl===s.current.url&&y([U],!1,(H=e.currentUser)==null?void 0:H.userId),O(U)}),"onFailed"in q&&q.onFailed((U,H)=>{var oe;H&&H.channelUrl===s.current.url&&y([H],!1,(oe=e.currentUser)==null?void 0:oe.userId),j(U)}))})}),J=Ce(async M=>{var R,O;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(M.sendingStatus==="succeeded")M.isUserMessage()&&await s.current.deleteMessage(M),M.isFileMessage()&&await s.current.deleteMessage(M),M.isMultipleFilesMessage()&&await s.current.deleteMessage(M);else try{await((O=h.current.instance)==null?void 0:O.removeFailedMessage(M.reqId))}finally{A([],[M.reqId])}}),me=Ce(()=>{var M;E([],!0,(M=e.currentUser)==null?void 0:M.userId)}),pe=Ce(async M=>{var R;if(e.currentUser&&s.current){const O=jr(M);k(!0),y([],!0,(R=e.currentUser)==null?void 0:R.userId),await L(s.current,M,O),k(!1)}});return{initialized:f,loading:v,refreshing:b,messages:C,newMessages:g,resetNewMessages:me,refresh:V,loadPrevious:Y,hasPrevious:x,loadNext:D,hasNext:$,sendUserMessage:Q,sendFileMessage:ae,sendFileMessages:de,sendMultipleFilesMessage:we,updateUserMessage:T,updateFileMessage:F,resendMessage:z,deleteMessage:J,resetWithStartingPoint:pe,_dangerous_reducer_updateMessages:y,_dangerous_reducer_deleteMessages:A}},bl=(e,t,n)=>{const r=c.useRef(0),s=c.useRef(new Set),o=c.useCallback(d=>{const m={id:r.current+=1,...d};s.current.forEach(h=>{h(m)})},[]),a=c.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 je.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return il(m,o)},[t,n==null?void 0:n.collectionCreator,o]),l=El(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),u=c.useCallback(d=>(s.current.add(d),()=>{s.current.delete(d)}),[]);return{...l,subscribeMessageEvents:u}},Rt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Eo(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Cl(e){const t=Eo(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function vl(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function yl(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 u=(r+s)/2;return r!==s&&(l=u>.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,u]}function Sl(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,u=2*n-l;r=a(u,l,e+1/3),s=a(u,l,e),o=a(u,l,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function Gt(e,t,n){const[r,s,o]=Cl(e),[a,l,u]=yl(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,l*n)),[h,f,v]=Sl(a,m,d);return vl([Math.round(h),Math.round(f),Math.round(v)])}function Al(e,t="light"){return{extraDark:Gt(e,.6,1.2),dark:Gt(e,.85,1.1),main:e,light:Gt(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Gt(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Wn(e){const t=Eo(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?Rt.BLACK:Rt.WHITE}function xl(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}}}const Tl=(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}}),Vt={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},wn={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function Xr(e){const t=Il(e),n=wl(e,t),r=kl(n,e.colors,e.selectedTheme),s=Rl(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 Il({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Vt.primary.main?Vt.primary:Al(n,e):Vt.primary;return{...Vt,primary:r,...t}}function wl({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,a=t??Wn(o),l=n??Rt.DEFAULT_BOT_MSG_BG,u=r??Wn(l);return(e==="light"?xl:Tl)(s,o,a,l,u)}function Ml(e,t,n){return typeof e=="string"?e:e[t]??n}function kl(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 u=t[l];if(u){s[l]={...s[l]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((a=o[l])==null?void 0:a[d])??"";s[l][d]=Ml(m,n,h)}}}return r}function Ll(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Rl({typography:e}){if(!e)return wn;const t={...wn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=wn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Ll(s,r,o)}}),t}const{Provider:Ol,useContext:dr}=Ee("AIAgentTheme");function Nl({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const a=c.useRef(null),[l,u]=c.useState(()=>Xr({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=c.useCallback((m,h)=>{h&&(a.current=h);const f=(s==null?void 0:s.theme)??m,v=a.current?a.current.themes[f]:null,b={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!b.primary&&(v!=null&&v.primary_color)&&(b.primary=v.primary_color,b.primaryContrast=v.primary_contrast_color),!b.botMessageBackground&&(v!=null&&v.bot_message_bg_color)&&(b.botMessageBackground=v.bot_message_bg_color,b.botMessageBackgroundContrast=v.bot_message_bg_contrast_color);const C=Xr({selectedTheme:f,palette:t,typography:n,colors:r,...b});u(C),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 c.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(Ol,{value:{theme:l,updateTheme:d}},o)}const Mn=25*1024*1024,Zr=1,Jr=new Set(["image/png","image/jpeg","image/jpg"]),Qr=new Set(["application/pdf"]),Dl={off:"off",always:"always",handed_off_only:"handed_off_only"},$l=()=>{const[e,t]=c.useState(()=>({maxAttachmentCount:Zr,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Mn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:Jr,supportedFileMimeTypes:Qr})),n=c.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Zr,attachmentMode:Dl[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Mn,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)??Jr),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Qr)})},[]),r=c.useCallback(s=>{const{channel:o,uploadSizeLimit:a=Mn}=s,l=(d=!0)=>o!=null&&o.isAIAgent?d?nt(o):!1:!0,u=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 nt(o);default:return!0}},get supportedMimeTypes(){return l()?[Hn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},es=(...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)")},Tt=e=>({...e,context:e.context??{}}),{Provider:Pl,useContext:Ct}=Ee("AIAgentMessengerSession"),Fl=c.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:a}=$e(),{updateTheme:l}=dr(),[u,d]=c.useState(void 0),[m,h]=c.useState(void 0),[f,v]=c.useState(null),[b,C]=c.useState(null),[g,y]=c.useState(null),[E,I]=c.useState(null),{updateBaseAttachmentRules:A,createAttachmentRules:w}=$l();c.useEffect(()=>{const L=r.onMessengerSettingsUpdated(({settings:x})=>{const{appearance:D,bot:$,launcher:Q}=x;l(D.selected_theme,D),y({userId:$.bot_userid,profileUrl:$.bot_profile_url,nickname:$.bot_nickname,replyToFile:$.reply_to_file,specialNotice:$.special_notice,specialNoticeEnabled:$.is_special_notice_enabled,showHandoffButton:$.show_handoff_button??!0,isMultipleActiveConversationsEnabled:$.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:$.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:$.is_user_feedback_comment_option_enabled??!1}),I({type:Q.image_type||"default_icon",imageUrl:Q.image_url}),A(x)}),V=r.onActiveChannelUpdated(({channelUrl:x,status:D,conversationStatus:$})=>{h({url:x,status:D,conversationStatus:$})}),Y=r.onAuthTokenRefreshed(()=>{var D;const x=(D=r.session)==null?void 0:D.userSession.authToken;x&&C($=>$?{...$,authToken:x}:null)});return()=>{L(),V(),Y()}},[r,l,A]);const k=c.useCallback(async()=>{try{const L=await r.authenticate(e),V=r.session;return v(V.sdkUser),C(V.userSession),h(V.activeChannel),d(void 0),L}catch(L){throw v(null),C(null),h(void 0),d(L),L}},[r,e]),N=c.useCallback(async()=>{await r.deauthenticate(),v(null),h(void 0),C(null),y(null),I(null)},[r]),W=c.useCallback(async()=>{if(!r.session){if(b)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!==(b==null?void 0:b.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,a,b]),G=c.useCallback(async L=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(L)},[r]),K=c.useCallback(async L=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(L)},[r]);return c.useImperativeHandle(n,()=>{const L=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:k,deauthenticate:N,updateContext:async(...V)=>{const Y=es(...V);if(Y.type==="active"){const $=await(await L()).updateContext(o,Y.context);return Tt($)}const x=await s.aiAgent.updateContext(Y.aiAgentId,Y.channelUrl,Y.context);return Tt(x)},patchContext:async(...V)=>{const Y=es(...V);if(Y.type==="active"){const $=await(await L()).patchContext(o,Y.context);return Tt($)}const x=await s.aiAgent.patchContext(Y.aiAgentId,Y.channelUrl,Y.context);return Tt(x)},getContextObject:async()=>{const Y=await(await L()).getContextObject(o);return Tt(Y)}}},[k,N,m,s,o,a]),i.createElement(Pl,{value:{sdkUser:f,userSessionInfo:e,userSession:b,activeChannel:m,setActiveChannel:h,refreshActiveChannel:W,createConversation:G,searchConversation:K,connectionError:u,aiAgentInfo:g,launcherInfo:E,authenticate:k,deauthenticate:N,createAttachmentRules:w,statsTrackers:r.statsTrackers}},t)}),pn=(e,t)=>{const n=c.useId(),r=c.useRef(t);c.useLayoutEffect(()=>{r.current=t}),c.useLayoutEffect(()=>{const s=new le.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 Bl(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:s}=$e(),{sdkUser:o,statsTrackers:a}=Ct(),l=ur(),[u,d]=c.useState(void 0),[m,h]=c.useState(void 0),[f,v]=c.useState(!1);function b(g){g.isAIAgent&&!g.conversation&&(v(!0),s.initConversationIfNeeded(g).finally(()=>v(!1)))}async function C(){var g,y,E;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),v(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const I=await t.groupChannel.getChannel(e);b(I),d(I),a.initialRender.onGetChannelComplete((g=I.conversation)==null?void 0:g.id),I.url===((y=s.session)==null?void 0:y.activeChannel.url)&&s.session._updateActiveChannel({url:I.url,status:De(I)?"closed":"open",conversationStatus:(E=I.conversation)==null?void 0:E.status}),n.debug("useChannel.getChannel: fetched channel",I)}catch(I){a.initialRender.onGetChannelError(I),I instanceof le.SendbirdError&&h(I),n.error("useChannel.getChannel: error",I)}}}return c.useEffect(()=>{C()},[t,o,e,r]),pn(t,{async onReconnectSucceeded(){if(!u)return;const g=await u.refresh();b(g),d(g)}}),bt(t,{onChannelChanged:g=>{g.isGroupChannel()&&g.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",g.url),d(g),l())}}),{channel:u,channelFetchError:m,getChannel:C,isInitializingConversation:f}}const Ul=new Set(["suggested_replies","steward","system"]),Hl=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||!Ul.has(r)))return r},Gl=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},Vl=()=>{const{chatSDK:e,networkStateAdapter:t}=$e(),[n,r]=c.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return pn(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),c.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===le.ConnectionState.OPEN?"connected":o)})},[t,e]),n},zl=3e4,ql=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=c.useState(!1),a=c.useRef(null),l=t&&Et(t,r)?t.createdAt:0;return c.useEffect(()=>{const u=()=>{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=zl-m;return n||h<=0?u():d(h),()=>{a.current&&clearTimeout(a.current)}},[n,l]),s&&e},bo=e=>{const{chatSDK:t}=$e(),[n,r]=c.useState([]);return bt(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Wl=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=c.useState(!1),a=bo(e);return c.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),u=Et(t,n)&&(Ke.isStreaming(t)||r);o(u||l)},[a,t,n,r]),s},Yl=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=Ct(),a=Vl(),l=Wl({channel:e,lastMessage:Dr(t,[ze.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=ql({shouldApply:!!(e!=null&&e.isAIAgent)&&!nt(e),isBlockedWhileAIResponding:l,lastMessage:Dr(t,[ze.SendingStatus.PENDING,ze.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(De(e))return d("conversation_closed");if(ya(e))return d("handoff_pending");if(Gl(e))return d("form_active");const m=Hl(e);return d(m||(l||u||r?"ai_responding":""))},Kl=()=>{const[e,t]=c.useState(new Set),n=c.useCallback(s=>{t(o=>{if(o.has(s))return o;const a=new Set(o);return a.add(s),a})},[]),r=c.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:jl}=Ee("AIAgentConversation");function Xl({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:o,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:u=he,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var K;const f=()=>d&&(g==null?void 0:g.markAsRead()),{chatSDK:v,logger:b,dispatcher:C}=$e(),{channel:g,channelFetchError:y,getChannel:E,isInitializingConversation:I}=Bl(t),{statsTrackers:A}=Ct();c.useEffect(()=>{if(t)return A.initialRender.setChannelUrl(t),()=>{A.initialRender.cleanup()}},[t,A]);const w=bl(v,g,{replyType:ze.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:L=>r==null?void 0:r(L),onMessagesUpdated:L=>s==null?void 0:s(L),onCacheResult:L=>A.initialRender.onCacheResult(L),onApiResult:L=>A.initialRender.onApiResult(L),logger:b,markAsRead:f,sortComparator:h}),k=Kl(),N=Yl({channel:g,messages:w.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:I});c.useEffect(()=>{f()},[d,g]);const W=De(g);c.useEffect(()=>{o==null||o(W)},[W,o]),c.useEffect(()=>{const L=async V=>{const Y=typeof(V==null?void 0:V.channelUrl)=="string";g&&Y&&V.channelUrl!==g.url||(b.debug("conversation.dispatcher: try to close conversation",g),g!=null&&g.conversation&&g.conversation.status===Re.ConversationStatus.OPEN&&(await g.closeConversation(),a==null||a()))};return C.subscribe(Ve.ConversationClose,L),()=>{C.unsubscribe(Ve.ConversationClose,L)}},[C,g,b,(K=g==null?void 0:g.conversation)==null?void 0:K.status,a]);const G={conversation:(g==null?void 0:g.conversation)??void 0,channelSource:{channel:g,error:y,refetch:()=>E(),closeConversation:async()=>{De(g)||await(g==null?void 0:g.closeConversation())}},messageSource:{messages:w.messages,newMessages:w.newMessages,initialized:w.initialized,subscribeMessageEvents:w.subscribeMessageEvents,loadPrevious:()=>w.loadPrevious(),loadNext:()=>w.loadNext(),deleteMessage:L=>w.deleteMessage(L),resendMessage:L=>w.resendMessage(L),resetNewMessages:()=>w.resetNewMessages(),sendUserMessage:async L=>{var Y;if(((Y=g==null?void 0:g.conversation)==null?void 0:Y.status)===Re.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const V=await w.sendUserMessage(L,u);return u==null||u(V),V},sendFileMessage:async L=>{var Y;if(((Y=g==null?void 0:g.conversation)==null?void 0:Y.status)===Re.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const V=await w.sendFileMessage(L,u);return u==null||u(V),V},sendMultipleFilesMessage:async L=>{var Y;if(((Y=g==null?void 0:g.conversation)==null?void 0:Y.status)===Re.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(L=await l(L));const V=await w.sendMultipleFilesMessage(L,u);return u==null||u(V),V}},state:{streamAnimation:k,input:N}};return i.createElement(jl,{value:G},e)}function Zl(e,t){var v,b,C,g,y,E,I,A,w,k;const[n,r]=c.useState(!1),[s,o]=c.useState(null),[a,l]=c.useState([]),[u,d]=c.useState(null),m=c.useRef(!1),h=c.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),o(null),l([]);try{u==null||u.dispose();const N=new so(e,t);N.setConversationListCollectionHandler({onChannelsAdded:()=>{l(N.channels)},onChannelsUpdated:()=>{l(N.channels)},onChannelsDeleted:()=>{l(N.channels)}}),await N.loadMore(),d(N),o(null)}catch(N){d(null),o(N)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(v=t.filter)==null?void 0:v.aiAgentChannelFilter,(C=(b=t.filter)==null?void 0:b.aiAgentConversationStatusFilter)==null?void 0:C.join(),(y=(g=t.filter)==null?void 0:g.aiAgentIds)==null?void 0:y.join(),(E=t.filter)==null?void 0:E.deskChannelFilter,(A=(I=t.filter)==null?void 0:I.pinnedChannelUrls)==null?void 0:A.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),f=c.useCallback(async()=>{if(u)try{await u.loadMore()}catch(N){o(N)}},[u]);return pn(e,{onConnected:()=>h()}),c.useEffect(()=>{h()},[h]),c.useEffect(()=>()=>{m.current=!1,u==null||u.dispose()},[u]),{initialized:n,error:s,channels:a,loadMore:f}}const{Provider:Jl}=Ee("AIAgentConversationList");function Ql({conversationListLimit:e,conversationListFilter:t,children:n}){var h,f;const{chatSDK:r,aiAgentId:s,queryParams:o}=$e(),a={aiAgentIds:[s],aiAgentConversationStatusFilter:[Re.ConversationStatus.CLOSED,Re.ConversationStatus.OPEN]},l=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),u={...a,...(f=o==null?void 0:o.conversationListParams)==null?void 0:f.filter,...t},d=Zl(r,{limit:l,filter:u}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return i.createElement(Jl,{value:m},n)}function ec(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:tc,useContext:nc}=Ee("MessageTemplateFetching");function rc({children:e,internalVariables:t}){const n=c.useRef({}),r=c.useRef({}),[s,o]=c.useState({}),a=c.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),l=c.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const v=m(h);if(v)return v;const b=r.current[h];if(b)return b;f||a(h,{fetching:!0});const C=d(h).catch(g=>{throw f||a(h,{error:!0}),g}).finally(()=>{f||a(h,{fetching:!1}),delete r.current[h]});return r.current[h]=C,C},[a]),u={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=ec(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(tc,{value:u},e)}const sc="remove_powered_by",mr=(e,t)=>{var s,o;const{chatSDK:n}=$e(),{aiAgentInfo:r}=Ct();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 c.useMemo(()=>!(Array.isArray(a)&&a.includes(sc)),[a])}throw new Error("Unsupported feature")},oc={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"},ic={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}}},ac={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}}},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}}},cc={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}}},uc={text:ic,number:ac,"single-select":lc,"multi-select":cc},dc={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Co(e){return uc[e.type]||dc}function ts(e){return Co(e).getValueOrDefault(e)}function mc(e,t,n={}){const r={...oc,...n};return Co(e).validate(e,t,r)}const hc=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,a]=c.useState({}),[l,u]=c.useState(()=>{const C={};return e.fields.forEach(g=>{C[g.key]=ts(g)}),C}),d=c.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);c.useEffect(()=>{if(d==="submitted"||d==="canceled"){const C={};let g=!1;e.fields.forEach(y=>{const E=ts(y);JSON.stringify(l[y.key])!==JSON.stringify(E)&&(g=!0),C[y.key]=E}),g&&u(C)}},[d]);const m=(C,g)=>{u(y=>({...y,[C]:g})),a(y=>({...y,[C]:void 0}))},h=e.fields.map(C=>{var E,I,A;const g=l[C.key]??null,y={key:C.key,label:C.label,error:o[C.key],required:C.required};return C.type==="text"?{...y,type:"text",layout:C.layout,value:g,...C.placeholder&&{placeholder:C.placeholder},...((E=C.rules)==null?void 0:E.max_length)&&{maxLength:C.rules.max_length}}:C.type==="number"?{...y,type:"number",layout:C.layout,value:g,...C.placeholder&&{placeholder:C.placeholder},...((I=C.rules)==null?void 0:I.max)&&{max:C.rules.max}}:C.type==="single-select"?{...y,type:"single-select",layout:C.layout,value:g,options:C.options}:C.type==="multi-select"?{...y,type:"multi-select",layout:C.layout,value:g,options:C.options,...((A=C.rules)==null?void 0:A.max_select)&&{maxSelect:C.rules.max_select}}:{...y,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:C=>h.find(g=>g.key===C),updateFieldValue:m,submit:async()=>{const C={};let g=!1;for(const y of e.fields){const E=l[y.key]??null,I=mc(y,E,n);I.isValid||(C[y.key]=I.error,g=!0)}if(a(C),!g&&r){const y={};e.fields.forEach(E=>{y[E.key]=l[E.key]??null}),await r(y)}},cancel:async()=>{await(s==null?void 0:s())}}},fc=e=>{const{chatSDK:t,handlers:n,logger:r}=$e(),{aiAgentInfo:s}=Ct(),o=c.useRef(new Set),a=c.useRef(new Set),l=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!Et(m,s.userId))return;const f=m.messageId;if(Ke.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))},u=c.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=Gn(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),u(h))};return bt(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},gc=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},vo=e=>{const{aiAgentInfo:t}=Ct(),n=bo(e);if(De(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?gc(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},pc=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=c.useRef(null),o=c.useRef(t),a=c.useRef(t),l=c.useRef(!1);o.current=t,c.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]),c.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(l.current?a.current:o.current)(!1),l.current=!1,a.current=o.current},[])},_c=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:l=>{const u=Date.now(),d=t.get(l);return d!==void 0&&u-d<n?!1:(t.set(l,u),!0)},setInterval:l=>{n=l},reset:()=>{t.clear()}}},Ec=(e,t,n=1e4,r=!0)=>{const s=c.useRef(null),o=c.useRef(null),a=c.useRef(!1);s.current||(s.current=_c(n));const l=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??l;c.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),c.useEffect(()=>{var h;if(!r){a.current=!1,o.current=u;return}if(!u||!l){a.current=!1,o.current=null;return}const d=!a.current,m=o.current!==u;a.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(l)},[u,l,r,t])},hr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=lo(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?nt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},ns=e=>c.useReducer((t,n)=>({...t,...n}),e);var We=(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))(We||{});const bc=new Set(["free_text","single_choice"]),Cc=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,a]=ns({csatType:t,csat:n,csatReason:r,isResolved:s}),[l,u]=ns({followUpItem:!1}),d=c.useMemo(()=>{var g;const v=o.csat,b=typeof v=="number",C=(g=e.follow_up)==null?void 0:g.find(y=>b?y.scores.includes(v):y.always_visible??!1);if(bc.has(C==null?void 0:C.response_type))return C},[o.csat,e.follow_up]),m=(()=>{var v;if(typeof n=="number")return"submitted";if((t===We.AI_AGENT_CSAT_5||t===We.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===We.AI_AGENT_CSAT_5_WITH_CRE){const b=typeof o.csat=="number",C=!((v=e.cre)!=null&&v.required)||typeof o.isResolved=="boolean";if(b&&C)return"submittable"}return"unsubmittable"})(),h=c.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return c.useEffect(()=>{r||(a({csatReason:""}),u({followUpItem:!1}))},[r,d,a,u]),{params:o,setParams:a,error:l,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},kn=5,vc=250,yc=50,rs=e=>Math.max(0,e-yc),Sc=e=>e<1e3?{speed:kn*.5,chunkSize:2}:e<2e3?{speed:kn*.8,chunkSize:2}:{speed:kn*.6,chunkSize:3},Ac=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:s,onAnimationComplete:o}=e,[a,l]=c.useState(()=>rs(t.length)),u=c.useRef(null),d=c.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=c.useRef({onStart:r,onProgress:s,onComplete:o}).current,h=c.useRef({startCalled:!1,completeCalled:!1}).current,f=c.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,v=n,b=a<t.length,C=f.initialEnabled&&(v||b);return c.useLayoutEffect(()=>{m.onStart=r,m.onProgress=s,m.onComplete=o,f.textLength=t.length,f.enabled=n}),c.useLayoutEffect(()=>{var g;f.initialEnabled&&(h.startCalled||(h.startCalled=!0,(g=m.onStart)==null||g.call(m)),l(y=>t.length<y?t.length:y))},[t]),c.useEffect(()=>{if(!f.initialEnabled)return;let g=rs(t.length);d.lastUpdate=0,d.startTime=0,d.lastProgressCall=0;const y=E=>{var K;d.lastUpdate===0&&(d.lastUpdate=E,d.startTime=E,d.lastProgressCall=E);const I=f.textLength,A=E-d.lastUpdate,w=E-d.startTime,{speed:k,chunkSize:N}=Sc(w),W=k*N;A>=W&&g<I&&(g=Math.min(g+N,I),l(g),d.lastUpdate=E),E-d.lastProgressCall>=vc&&(d.lastProgressCall=E,(K=m.onProgress)==null||K.call(m)),(g<I||f.enabled)&&(u.current=requestAnimationFrame(y))};return u.current=requestAnimationFrame(y),()=>{var E;u.current&&cancelAnimationFrame(u.current),h.startCalled&&!h.completeCalled&&(h.completeCalled=!0,(E=m.onComplete)==null||E.call(m))}},[]),c.useEffect(()=>{var I;const g=f.initialEnabled&&h.startCalled,y=!n,E=a>=t.length&&t.length>0;g&&y&&E&&!h.completeCalled&&(h.completeCalled=!0,(I=m.onComplete)==null||I.call(m))},[n,a,t.length]),{streamText:f.initialEnabled?t.slice(0,a):t,isAnimating:C}},ss={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},xc=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Tc=(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}},Ic=()=>{const{chatSDK:e}=$e(),[t,n]=c.useState(ss),r=()=>n(ss);return pn(e,{onConnectionDelayed:s=>{s>0?n(xc(s)):r()},onReconnectSucceeded:r,onConnected:r}),c.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Tc(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},wc=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Mc=(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)}},yo=e=>e.replace(/\s+/g," ").trim(),kc="Code block",So=e=>`A11Y_INLINE_CODE_${e}`,Ao=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}},xo=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}},Lc=e=>{const{blockquotePrefix:t,content:n}=Ao(e),{content:r}=xo(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(u=>u===l))&&!(l==="`"&&a.includes("`")))return{char:l,blockquotePrefix:t,length:o.length}},Rc=(e,t)=>{const{blockquotePrefix:n,content:r}=Ao(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=xo(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(u=>u===t.char)},Oc=(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},Nc=(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},Dc=(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},$c=e=>{let t=0,n="";for(;t<e.length;){const r=Oc(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Nc(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&ln(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]==="!"&&!ln(e,r-1)?r-1:r;n+=e.slice(t,o);const a=e.slice(r+1,s),l=Dc(e,s+2);if(l===-1){n+=e.slice(o);break}n+=a,t=l}return n},To=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Pc=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const a=o[s+t.length]??"";return To(n,r,a)?t:`${n}${r}`}),Fc=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Bc=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Uc=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 To(r,s,l)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Hc=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Gc=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},os=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))},is=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},Vc=e=>{const t=e.split(`
2
+ `),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],a=is(s);if(a.length>0&&o&&os(o)){for(n.push(a.join(" ")),r+=2;r<t.length;){const l=t[r],u=is(l);if(u.length===0||os(l))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
3
+ `)},zc=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),qc=(e,t)=>{const n=e.split(`
4
+ `),r=[];let s=0;for(;s<n.length;){const o=n[s],a=Lc(o);if(!a){r.push(o),s+=1;continue}let l=-1;for(let u=s+1;u<n.length;u++)if(Rc(n[u],a)){l=u;break}if(l===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=l+1}return r.join(`
5
+ `)},ln=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},Wc=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||ln(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,u=!1;for(;l<e.length&&e[l]!==`
6
+ `;){if(e[l]==="`"&&!ln(e,l)&&e.startsWith(a,l)){const d=e.slice(o,l),m=t.push(d)-1;r+=So(m),n=l+a.length,u=!0;break}l+=1}u||(r+=a,n=o)}return{text:r,inlineCodes:t}},Yc=(e,{codeBlockPlaceholder:t=kc}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
7
+ `);if(!n)return;const r=[];let s=n;s=qc(s,t),s=Gc(s);const o=Wc(s);s=o.text,r.push(...o.inlineCodes),s=$c(s),s=Pc(s),s=Fc(s),s=Bc(s),s=Uc(s),s=Vc(s),s=zc(s),s=Hc(s);for(let l=0;l<r.length;l++)s=s.replaceAll(So(l),r[l]);return yo(s)||void 0},cn=e=>(e==null?void 0:e.trim())||"",Kc=e=>(e?yo(e):void 0)||void 0,fr=e=>({text:cn(e),format:"plain"}),jc=e=>({text:cn(e),format:"markdown"}),_t=({markdownText:e,plainText:t,comparisonText:n})=>{const r=cn(e);return r&&r!==cn(n)?jc(r):fr(t)},pt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],a=n==="markdown"?Yc(t,{codeBlockPlaceholder:s}):Kc(t);if(e&&o.push(e),a&&o.push(a),r&&o.push(r),o.length!==0)return o.join(", ")},Xc=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r}=t;let s=null;const o=[];let a=null,l=null,u=!1,d=0;const m=(A,w)=>({text:A,ignoreSuppression:w,queueOrder:d++}),h=()=>{const A=o[0]??null,w=s;return A&&w?w.queueOrder<A.queueOrder?(s=null,w):o.shift()??null:A?o.shift()??null:w!==null?(s=null,w):null},f=()=>{for(;;){const A=h();if(!A)return null;if(!(!A.ignoreSuppression&&(r!=null&&r())))return A}},v=A=>{a=A,u=!0,e(A),l=setTimeout(()=>{l=null,u=!1;const w=f();w&&v(w.text)},n)},b=A=>{a=A,e(A)},C=(A,w,k)=>{if(A&&!(!w&&(r!=null&&r()))&&!(A===a&&u))if(u){if(((k==null?void 0:k.mode)??"latestOnly")==="ordered"){const W=o[o.length-1];if((W==null?void 0:W.text)===A)return;o.push(m(A,w));return}s=m(A,w)}else s=null,v(A)};return{announce:(A,w)=>{C(A,!1,w)},announceIgnoringSuppression:(A,w)=>{C(A,!0,w)},flush:()=>{const A=[];let w=h();for(;w!==null;)A.push(w),w=h();if(l!==null&&(clearTimeout(l),l=null),u=!1,A.length!==0)for(const k of A)b(k.text)},destroy:()=>{l!==null&&(clearTimeout(l),l=null),s=null,o.length=0,a=null,u=!1}}},Zc=e=>{switch(e){case"conversationClosed":case"csatDisplayed":return"ordered";default:return"latestOnly"}},Jc=(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(". "),Qc=(e,t)=>{switch(e.event){case"newMessage":return 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"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},eu=(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||!Xe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),as=(e,t)=>Te.isAdmin(e)?Te.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,nu=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,ru=e=>e===le.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===le.CollectionEventSource.EVENT_MESSAGE_UPDATED,ls=(e,t,n,r)=>{const{newestFirst:s=!1}={};if(s){for(const o of e)if(o&&as(o,n)&&t.some(a=>Nr(o,a)))return o;return}for(let o=e.length-1;o>=0;o-=1){const a=e[o];if(a&&as(a,n)&&t.some(l=>Nr(a,l)))return a}},su=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",ou=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},iu=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},au=({intent:e,strings:t})=>({label:ou(e,t),hint:iu(e,t)}),lu="1.25.0",He="sb-agent",ve={ENTRY:`${He}-entry`,MODAL_ROOT:`${He}-modal-root`,WINDOW:`${He}-window`,LAUNCHER:`${He}-launcher`},Io="data-sb-initial-focus",wo="true",gr=`[${Io}="${wo}"]`,cu={[Io]:wo},Mo="data-sb-conversation-header",ko="true",uu=`[${Mo}="${ko}"]`,du={[Mo]:ko},zt=2147483647,vt={MODAL:zt-1,TOOLTIP:zt-2,WINDOW:zt-3,LAUNCHER:zt-4},Lo=36,mu=100,hu=lu,pr="noopener noreferrer nofollow";function fu(){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 qt={};function gu(){return{get:e=>{try{return localStorage.getItem(e)}catch{return qt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{qt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete qt[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(qt).filter(t=>t.startsWith(e))}}}}const pu={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",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:"Connect with an 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_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_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} 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_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"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`}},Yn={language:"en",strings:pu,dateLocale:Vi.enUS},Ro=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_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_RATING_LABEL:e.csat.a11y_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,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),Oo=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Nt},Nt="en",No=new Set([Nt,"ko","es","pt","fr","hi","it","de","tr","ja"]),_u='@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:Eu,useContext:_r}=Ee("AgentUIElementResolver"),bu=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=c.useMemo(()=>{const o=n??document.body,a=e??o,l=t??o,u=d=>d===ve.MODAL_ROOT?l:a.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??l}},[e,t,n]);return i.createElement(Eu,{value:s},r)};function ct(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const cs=()=>{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:Cu,useContext:Do}=Ee("EscapeDismissStack"),us=e=>{e.stopPropagation(),e.stopImmediatePropagation()},vu=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=c.useRef(null),s=c.useRef(null);r.current||(r.current=cs()),s.current||(s.current=cs());const o=r.current,a=s.current;c.useLayoutEffect(()=>{const u=t??ct(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){us(m);return}a.dismissTopmost()&&us(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,a,o]);const l=c.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:a.register}),[a,o]);return i.createElement(Cu,{value:l},n)},$o=(e,t,n)=>{const r=c.useRef(t);c.useLayoutEffect(()=>{r.current=t},[t]),c.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},yu=(e,t)=>{const{register:n}=Do();$o(e,t,n)},Su=(e,t)=>{const{registerShellDismissHandler:n}=Do();$o(e,t,n)},Au=(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.":""))))})},ds=Ro(Yn.strings),xu={...ds,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_ATTACH_FILE:"Attach file",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_CSAT_RATING_LABEL:(e,t)=>`${e} — ${t}`,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",A11Y_CONNECT_AGENT:"Talk to human agent",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:ds.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"},un={language:Yn.language,dateLocale:Yn.dateLocale,stringSet:xu},Tu=Object.freeze(Object.defineProperty({__proto__:null,default:un},Symbol.toStringTag,{value:"Module"})),Kn=new Map([[Nt,un]]);async function Iu(e){const t=Kn.get(e);if(t)return t;try{if(No.has(e)){const{default:n}=await Au(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/KpILxsy5.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Tu),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/C9Y_myeI.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/Bb7tPFDH.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/1RttGdBR.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/DYr6MsyB.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/Xd5FCJlT.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/COfoIob1.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/CY5jZKJU.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/B8O63u6F.cjs"))}),`./languages/${e}.ts`,3);return Kn.set(e,n),n}return un}catch{return un}}const{Provider:wu,useContext:re}=Ee("Localization"),Mu=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,a]=c.useState(Kn.get(Nt));return c.useEffect(()=>{const l=t??Oo(e);o.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:l}),Iu(l).then(a))},[e,t,n]),i.createElement(wu,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(l,u,d)=>et.format(l,u,{locale:o.dateLocale,...d})}},s)},dn="data-sb-agent-theme",ms=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${dn}='${e}'] & { ${r} }`},X={light:ms("light"),dark:ms("dark")},ku=P.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
- `}),Vc=O.css`[${an}='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);}[${an}='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);}`,p={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)",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:{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 ln 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 $e=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Gc=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"})),zc=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"})),Wc=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"})),qc=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"})),Kc=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"})),Yc=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),jc={close:Gc,send:Kc,menu:qc,expand:Wc,collapse:zc,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")))},Xc=e=>({size:t=24,color:n=p.color.primary.main,flipInRtl:r=!1})=>i.createElement(Jc,{$size:t,$color:n,$rtlFlip:r},i.createElement(ln,{errorFallback:i.createElement(Qc,null)},i.createElement(e,null))),ps=Object.fromEntries(Object.entries(jc).map(([e,t])=>[e,Xc(t)])),Zc=O.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Jc=_.default.span.attrs({"aria-hidden":"true"})`
57
- width: ${({$size:e})=>$e(e)};
58
- height: ${({$size:e})=>$e(e)};
56
+ `}),Lu=P.css`[${dn}='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);}[${dn}='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);}`,p={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)",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 mn extends c.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(c.Suspense,{fallback:r},s)}}const Ye=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Ru=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"})),Ou=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"})),Nu=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"})),Du=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"})),$u=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"})),Pu=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Fu={close:Ru,send:$u,menu:Du,expand:Nu,collapse:Ou,spinner:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":c.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:c.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs")))},Bu=e=>({size:t=24,color:n=p.color.primary.main,flipInRtl:r=!1})=>i.createElement(Hu,{$size:t,$color:n,$rtlFlip:r},i.createElement(mn,{errorFallback:i.createElement(Gu,null)},i.createElement(e,null))),Po=Object.fromEntries(Object.entries(Fu).map(([e,t])=>[e,Bu(t)])),Uu=P.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Hu=_.default.span.attrs({"aria-hidden":"true"})`
57
+ width: ${({$size:e})=>Ye(e)};
58
+ height: ${({$size:e})=>Ye(e)};
59
59
  display: inline-block;
60
60
 
61
61
  svg {
@@ -74,24 +74,24 @@
74
74
  stroke-linejoin: round;
75
75
  }
76
76
 
77
- ${({$rtlFlip:e})=>e&&Zc};
78
- `,Qc=()=>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:eu,useContext:tu}=ue("MessengerIcon",{icons:ps}),nu=({icons:e,children:t})=>{const n=u.useMemo(()=>({icons:Ra(ps,e)}),[e]);return i.createElement(eu,{value:n},t)},{Provider:ru,useContext:gr}=ue("MessengerTheme");function ou(e){const{theme:t,appearance:n,logger:r}=e;return i.createElement(Qa,{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(su,{...e}))}function su({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=lr();return u.useLayoutEffect(()=>{e.setAttribute(an,n.selectedTheme)},[e,n.selectedTheme]),i.createElement(O.ThemeProvider,{theme:n},i.createElement(ru,{value:{theme:n,updateTheme:r,rootElement:e}},t))}function He(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const iu=(e,t)=>{u.useEffect(()=>{const n=He(t)instanceof ShadowRoot,r=He(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])},au=(e,t=document.body)=>{u.useEffect(()=>{const n=He(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])},lu=80,cu=()=>{const{stringSet:e}=Q(),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,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},_s=ue("AriaLiveRegion",{announce:oe,announceScreenEntry:oe,announceStatus:oe,announceError:oe,flush:oe,setSuppressionState:oe}),uu=_s.Provider,fr=_s.useContext,du={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},mu=({children:e})=>{const t=u.useRef(null),n=u.useRef(new Set),r=u.useRef(oe),o=cu(),[s]=u.useState(()=>gc(C=>{r.current(C)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=C=>{const b=t.current;b&&(b.textContent="",requestAnimationFrame(()=>{b.textContent=C}))},u.useEffect(()=>()=>{s.destroy()},[s]);const a=s.announce,l=s.flush,c=u.useCallback(C=>{const b=pc(C,o.current);a(b)},[a]),d=u.useCallback(C=>{const b=_c(C,o.current);a(b,{mode:fc(C.event)})},[a]),m=u.useCallback((C,b)=>{const v=Ec(C,o.current);s.announceIgnoringSuppression(v),b&&setTimeout(()=>{b.focus()},lu)},[s]),h=u.useCallback((C,b)=>{if(b){n.current.add(C);return}n.current.delete(C)},[]),g=u.useMemo(()=>({announce:a,announceScreenEntry:c,announceStatus:d,announceError:m,flush:l,setSuppressionState:h}),[a,m,c,d,l,h]);return i.createElement(uu,{value:g},e,i.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:du}))},Es=ue("ConversationAnnouncements",{announcementsActive:!0,announce:oe,announceStatusText:oe,announceScreenEntry:oe,announceStatus:oe,announceError:oe,setIsSuppressed:oe,setStatusPauseState:oe,flush:oe}),hu=Es.Provider,ot=Es.useContext,gu=({children:e,announcementsActive:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:o,announceError:s,flush:a,setSuppressionState:l}=fr(),c=u.useRef([]),d=u.useRef(new Set),m=u.useRef(Symbol("conversation-announcements")),h=u.useCallback(I=>{if(!t||!I){l(m.current,!1);return}l(m.current,!0)},[t,l]),g=u.useCallback(()=>{c.current=[]},[]),C=u.useCallback(()=>{if(c.current.length===0)return;if(!t){g();return}const I=[...c.current];g(),I.forEach(k=>{if(a(),k.type==="status"){o(k.params);return}n(k.text)})},[n,o,t,g,a]),b=u.useCallback((I,k)=>{if(k){d.current.add(I);return}d.current.delete(I),d.current.size===0&&C()},[C]),v=u.useCallback(I=>{t&&n(I)},[n,t]),f=u.useCallback(I=>{if(t){if(d.current.size>0){c.current.push({type:"text",text:I});return}a(),n(I)}},[n,t,a]),y=u.useCallback(I=>{t&&r(I)},[r,t]),E=u.useCallback(I=>{if(t){if(d.current.size>0){c.current.push({type:"status",params:I});return}o(I)}},[o,t]),x=u.useCallback((I,k)=>{t&&s(I,k)},[s,t]);u.useLayoutEffect(()=>(t||(g(),l(m.current,!1)),()=>{g(),l(m.current,!1)}),[t,g,l]);const S=u.useMemo(()=>({announcementsActive:t,announce:v,announceStatusText:f,announceScreenEntry:y,announceStatus:E,announceError:x,setIsSuppressed:h,setStatusPauseState:b,flush:a}),[t,a,v,f,x,y,E,h,b]);return i.createElement(hu,{value:S},e)},{Provider:fu,Consumer:bs,useContext:ne}=ue("Messenger");function pu({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};return i.createElement(Na,{...s},h=>i.createElement(fu,{value:{...s,...h,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o}},e))}const Cs=/iPad|iPhone|iPod/.test(navigator.userAgent),_u=/Android/.test(navigator.userAgent),Mt=e=>Cs||_u;let vt=null,kn=null;const Eu=(e,t=5e3)=>{vt&&(clearInterval(vt),clearTimeout(kn));const n=document.title;vt=setInterval(()=>{document.title=document.title===e?n:e},750),kn=setTimeout(()=>{clearInterval(vt),vt=null,kn=null,document.title=n},t)},vs=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},_e=O.css`&:focus-visible{outline:2px solid ${p.themedColor.primary};outline-offset:2px;}`,$=({as:e,variant:t="body1",color:n,maxTextLines:r,className:o,...s})=>i.createElement(vu,{as:e,$variant:t,className:o,$color:n,$maxTextLines:r,...s}),eo=new WeakMap,bu=(e,t)=>{let n=eo.get(t);n||(n=new Map,eo.set(t,n));const r=n.get(e);if(r)return r;const o=t[e]??t.body1,s=O.css`font-size:${$e(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},Cu=e=>e?O.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",vu=_.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>bu(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Cu(e)}`,ys=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),Rt=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 pr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function ve(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const yu='[data-sb-initial-focus="true"]',Ss=e=>Array.from(e.querySelectorAll(ys)).filter(Rt),Su=e=>Array.from(e.querySelectorAll(yu)).find(Rt)??Ss(e)[0]??null,Au=e=>Array.from(e.ownerDocument.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e&&Rt(t)),xu=e=>{const t=Su(e)??e;t===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),t.focus()},Tu=(e,t,n)=>{const r=Ss(t);if(r.length===0){e.preventDefault(),t.focus();return}const o=r[0],s=r[r.length-1],a=n.activeElement;(e.shiftKey?a===o:a===s)&&(e.preventDefault(),(e.shiftKey?s:o).focus())},Iu=(e,t)=>{const n=u.useRef(null);u.useEffect(()=>{if(!e||!t.current)return;const r=t.current,o=r.getRootNode();n.current=o.activeElement instanceof HTMLElement?o.activeElement:null;let s=!1;return ve(()=>{s||!r.isConnected||xu(r)}),()=>{s=!0;const a=n.current;n.current=null,a&&ve(()=>{Au(r)||!a.isConnected||!Rt(a)||a.focus()})}},[e,t]),u.useEffect(()=>{if(!e||!t.current)return;const r=t.current,o=r.getRootNode(),s=a=>{a.key==="Tab"&&Tu(a,r,o)};return r.addEventListener("keydown",s),()=>r.removeEventListener("keydown",s)},[e,t])},wu=(e,t=!0,n)=>{const r=n==null?void 0:n.containerRef;u.useEffect(()=>{if(!t||!e)return;const o=a=>{a.key==="Escape"&&e()&&a.stopImmediatePropagation()},s=(r==null?void 0:r.current)??document;return s.addEventListener("keydown",o),()=>s.removeEventListener("keydown",o)},[r,e,t])},ft=({style:e,rootElementId:t,visible:n,onClose:r,children:o,"aria-label":s,"aria-labelledby":a,"aria-describedby":l})=>{const c=u.useRef(null),{rootElement:d}=gr();if(Iu(n,c),wu(u.useCallback(()=>(r(),!0),[r]),n,{containerRef:c}),!n)return null;const m=He(d),h=He(d,!0);return Ti.createPortal(i.createElement(ku,{onClick:r,style:e},i.createElement(Lu,{ref:c,role:"dialog","aria-modal":"true","aria-label":s,"aria-labelledby":a,"aria-describedby":l,onClick:g=>g.stopPropagation()},o)),m.getElementById(t)??m.getElementById(ce.MODAL_ROOT)??h.body)},ku=_.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${p.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${gt.MODAL};`,Lu=_.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${gt.MODAL};`,to=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},_r=({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(),h=c??to(t)??to(n),g=c?void 0:t?d:n?m:void 0,C=t&&n?m:void 0,b=()=>{l(),ve(()=>s==null?void 0:s())},v=()=>{l(),ve(()=>a==null?void 0:a())};return i.createElement(ft,{rootElementId:ce.WINDOW,visible:e,onClose:l,"aria-label":h,"aria-labelledby":g,"aria-describedby":C},i.createElement(Mu,null,i.createElement(Ru,null,t&&i.createElement("div",{id:d},i.createElement($,{variant:"h1",color:p.themedColor.textHighEmphasis},t)),n&&i.createElement(Ou,{id:m},i.createElement($,{variant:"subtitle2",color:p.themedColor.textHighEmphasis},n))),i.createElement(Nu,null,o&&i.createElement(no,{onClick:v},i.createElement($,{variant:"button",color:p.themedColor.textHighEmphasis},o)),i.createElement(no,{onClick:b},i.createElement($,{variant:"button",color:p.themedColor.primary},r)))))},Mu=_.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};`,Ru=_.default.div`margin-bottom:16px;`,Ou=_.default.div`margin-top:8px;`,Nu=_.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,no=_.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${_e}`,{Provider:$u,useContext:Ee}=ue("MessengerSession"),Du=u.forwardRef(function({children:e,...t},n){return i.createElement(rl,{ref:n,...t},r=>i.createElement(Pu,{...r},e))}),Pu=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=ne(),{userSessionInfo:h,authenticate:g,userSession:C,aiAgentInfo:b,launcherInfo:v}=t,[f,y]=u.useState(!1),E=u.useRef(null);Ye.useGroupChannelHandler(n,{async onUserJoined(S,I){var M,U,F,z;S.conversation&&S.conversation.type===be.ConversationType.PROACTIVE&&I.userId===((M=n.currentUser)==null?void 0:M.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",S.url),(F=m.session)==null||F._updateActiveChannel({url:S.url,status:"open",conversationStatus:(U=S.conversation)==null?void 0:U.status}),l.setOpened(!0),Fu({sound:document.hidden||!l.opened}),(z=E.current)==null||z.call(E,{channel:S}))}}),u.useEffect(()=>{g().then(({launcher:S})=>{S.auto_open&&!Mt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(S=>{var I;r.error("messengerSession: failed to initialize",S),(I=c==null?void 0:c.onInitializeFailed)==null||I.call(c,S)})},[n,o,s,h==null?void 0:h.userId]),u.useEffect(()=>{const S=()=>y(!0);return d.subscribe(Me.AnonymousSessionTokenExpired,S),()=>d.unsubscribe(Me.AnonymousSessionTokenExpired,S)},[d]);const x=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!C||!b||!v?null:i.createElement($u,{value:{...t,userSession:C,aiAgentInfo:{...b,...a==null?void 0:a.bot},launcherInfo:{...v,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:S=>E.current=S}},e,i.createElement(_r,{visible:f,title:"Session timed out",description:"Start a new conversation.",onConfirm:x,onClose:oe}))};function Fu({sound:e}){Eu("🔔You have received a new message"),e&&vs()}const Bu=e=>{const{chatSDK:t,handlers:n,logger:r}=ne(),{aiAgentInfo:o}=Ee(),s=u.useRef(new Set),a=m=>{if(!(n!=null&&n.onCustomEvent))return;Re(m)&&m.sender.userId===o.userId&&!De.isStreaming(m)&&!s.current.has(m.messageId)&&(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),s.current.add(m.messageId))},l=m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!s.current.has(m.messageId)){const h=Un(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}),s.current.add(m.messageId))}},c=(m,h)=>{m.url===e&&(a(h),l(h))},d=m=>{l(m)};return Ye.useGroupChannelHandler(t,{onMessageUpdated:c,onMessageReceived:c}),{checkForUserActionRequired:d}},cn=`@${we}-focused-channel`,As=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Hu=()=>{try{const e=localStorage.getItem(cn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},ro=e=>{try{localStorage.setItem(cn,JSON.stringify({channelUrl:e,tabId:As}))}catch{}},oo=()=>{try{const e=localStorage.getItem(cn);if(!e)return;JSON.parse(e).tabId===As&&localStorage.removeItem(cn)}catch{}},Uu=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>ro(e),r=()=>oo();return document.hasFocus()&&ro(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),oo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Hu()===e}),Vu=e=>{var a;const{config:t,chatSDK:n}=ne(),{sdkUser:r}=Ee(),o=!!((a=t==null?void 0:t.conversation)!=null&&a.messageAlertSoundEnabled),{isChannelViewedInAnyTab:s}=Uu(e,o);Ye.useGroupChannelHandler(n,{onMessageReceived(l,c){if(!o||l.url!==e||s())return;(Re(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&vs()}})};function Gu(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 zu(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Gu(e.file);return new qe.MessageMetaArray({key:Bo,value:[t,n]})}}const Wu=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ne(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await zu(o),a={...o,metaArrays:s?[s]:void 0},l=qu(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===qe.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===qe.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},qu=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},ut=50,Ln=ut-40,{Provider:Ku,useContext:xs}=ue("ConversationScroll"),so={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Mn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function Yu({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(so),h=u.useRef(!1),g=u.useRef(null),[C,b]=u.useState(0),[v,f]=u.useState(0),[y,E]=u.useState(!1),[x,S]=u.useState(!1),[I,k]=u.useState(!0),M=B=>{const Z=Mn(B);return s.current=Z,f(Z),Z},U=()=>{d.current&&(clearTimeout(d.current),d.current=null)},F=u.useMemo(()=>y||t==="bottom"?"auto":e,[y,t,e]),z=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},L=()=>{const B=r.current;!B||!m.current.shouldUpdate||b(Z=>{m.current.shouldUpdate=!1;const{contentHeight:X,contentSnapshotHeight:ge,shouldRecalc:ye}=m.current,Be=B.clientHeight;if(ge>X)return Z;const at=P(B,{messageType:"outgoing"});let Le=0;if(at){const Ve=at.message.offsetTop-Ln+Be;Le=Math.max(0,Ve-X)}else{const Ve=X-ge,lt=Be-Ln;Le=Math.max(0,Ve-lt)}return Z===0||Le!==Z||ye?(m.current.shouldRecalc=!1,Le):Z})},P=u.useCallback((B,Z)=>{const{messageType:X="all"}=Z??{},ge=Array.from(B.querySelectorAll(`#${we}-message-item`));let ye=ge;X==="outgoing"&&(ye=ge.filter(Qe=>Qe.getAttribute("data-layout-id")==="outgoingmessage"));const Be=ye[ye.length-1];if(!Be)return null;const at=B.getBoundingClientRect(),Le=Be.getBoundingClientRect(),Ve=B.scrollTop+(Le.top-at.top),lt=Ve+Be.offsetHeight;return{message:Be,scrollTop:Ve,lastMessageBottom:lt}},[]),N=u.useCallback(()=>{const B=r.current;if(!B||F!=="fixed")return;const Z=P(B);m.current.contentHeight=(Z==null?void 0:Z.lastMessageBottom)??B.scrollHeight,!h.current&&m.current.contentSnapshotHeight>0&&z(),c.current?s.current=Mn(B):M(B),L()},[F,P]),w=u.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),U(),m.current=so,b(0),f(0),k(!0),s.current=0,l.current=!1,a.current=0,c.current=!1},[]),D=u.useCallback((B=!0)=>{const Z=s.current>ut;if(l.current=!1,f(0),!Z){ve(()=>{const X=r.current;X&&!l.current&&X.scrollTo({top:X.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,k(!1),U()),ve(()=>{const X=r.current;if(!X){c.current=!1,k(!0);return}if(l.current){c.current=!1,M(X),k(!0);return}const ge=()=>{if(r.current!==X){c.current=!1,r.current&&M(r.current),k(!0);return}c.current=!1,M(X),k(!0)};if(B&&!d.current){const ye=setTimeout(ge,500);d.current=ye,X.addEventListener("scrollend",()=>{clearTimeout(ye),d.current=null,ge()},{once:!0})}X.scrollTo({top:X.scrollHeight,behavior:B?"smooth":"auto"}),B||ge()})},[]),R=u.useCallback(B=>{B&&(r.current=B,F==="fixed"&&(w(),m.current.viewport=B.clientHeight,o.current=new MutationObserver(()=>{N()}),o.current.observe(B,{childList:!0,subtree:!0})))},[F,N,w]),Y=u.useCallback(()=>{const B=r.current;if(!B)return;const Z=P(B,{messageType:"outgoing"});Z&&(B.scrollTo({top:Z.message.offsetTop-Ln,behavior:"smooth"}),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{S(!1)},500))},[P]),te=(B,Z,X)=>{const ge=Mn(B);if(X&&ge>ut){c.current=!1,l.current=!0,U(),M(B),k(!0),a.current=Z;return}s.current=ge},re=(B,Z,X)=>{const ye=M(B)<=ut;Z&&!ye&&(l.current=!0,U()),X&&ye&&(l.current=!1)},q=B=>{const{scrollTop:Z}=B.currentTarget,X=a.current;c.current?te(B.currentTarget,Z,Z<X):re(B.currentTarget,Z<X,Z>X),a.current=Z},T=u.useCallback(()=>{F==="fixed"&&(S(!0),z())},[F]),V=u.useCallback(()=>{F==="fixed"?setTimeout(()=>Y(),300):D()},[F,Y]),H=u.useCallback(B=>{h.current=B,F==="fixed"?z():l.current||D()},[F,D]),j=u.useCallback(B=>{E(B),B&&(b(0),o.current&&(o.current.disconnect(),o.current=null))},[]),se=u.useCallback(B=>{F==="auto"&&B&&!l.current&&D()},[F,D]),Oe=!(v<=ut)&&!x,Ae=u.useCallback(()=>s.current>ut,[]);return i.createElement(Ku,{value:{ref:R,state:{bottomSpace:C,isAwayFromBottom:Oe,isScrollPositionReconciled:I,shouldCountNewMessages:Ae},props:{onScroll:q},actions:{scrollToBottom:D,onBeforeMessageSend:T,onAfterMessageSend:V,onStreamingUpdate:H,onConversationClosed:j,onTypingIndicatorUpdate:se}}},n)}const{Provider:ju,Context:Xu,useContext:he}=ue("Conversation"),Zu=({children:e})=>{var o;const{channelSource:t}=he(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=Bu(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)},Ju=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=Ee(),l=xs(),c=e||(s==null?void 0:s.url);Vu(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=Wu({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),h=u.useCallback(b=>(l.actions.onBeforeMessageSend(),d(b)),[l.actions,d]),g=u.useCallback(b=>{const v=b.some(f=>De.isStreaming(f));l.actions.onStreamingUpdate(v)},[l.actions.onStreamingUpdate]),C=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(fl,{key:c,channelUrl:c,onBeforeSendMessage:h,onAfterSendMessage:m,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:C,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},b=>i.createElement(ju,{value:{...b,scrollSource:l,goToActiveConversation:C,onNavigateToConversationList:n}},i.createElement(Zu,null,o)))},Ts=({children:e,...t})=>{var a;const{config:n}=ke(),{agentPreviewConfigs:r}=ne(),o=((a=n==null?void 0:n.conversation)==null?void 0:a.scrollMode)??"auto",s=r==null?void 0:r.messageStackDirection;return i.createElement(Yu,{scrollMode:o,messageStackDirection:s},i.createElement(Ju,{...t},e))},Er=u.createContext({onDrop:oe,subscribe:()=>oe}),Yn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(Er.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)},Qu=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(Er);u.useEffect(()=>t(e),[e])};Yn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(Er);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const ed=e=>ze(e)||Uo(e);function td(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function nd(e,t){return e.filter(n=>De.isWelcomeMessage(n,t))}const Is=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>td(r)?!1:t.length>0?!De.isWelcomeMessage(r,n):!0),rd=[],ws=()=>{var b,v,f,y,E,x,S;const{agentPreviewConfigs:e={},aiAgentId:t}=ne(),{aiAgentInfo:n,userSession:r}=Ee(),{channelSource:o,messageSource:s,state:{input:a,streamAnimation:l}}=he(),c=e.welcomeMessages??rd,d=u.useMemo(()=>Is(s.messages,{previewWelcomeMessages:c,aiAgentUserId:t}),[t,s.messages,c]),m=je(o.channel),h=(f=(v=(b=o.channel)==null?void 0:b.members.find(I=>I.userId!==r.userId))==null?void 0:v.nickname)==null?void 0:f.trim(),g=m?(E=(y=o.channel)==null?void 0:y.name)==null?void 0:E.trim():(x=n==null?void 0:n.nickname)==null?void 0:x.trim(),C=h||g||void 0;return{initialized:s.initialized,channelUrl:(S=o.channel)==null?void 0:S.url,agentName:C,isClosed:Ce(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}},od=(e={})=>{const{announceScreenEntry:t,announcementsActive:n}=ot(),{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(g=>pe.isAdmin(g)&&pe.isCSAT(g)),[l]),h=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,...h?{isEmpty:!0}:{}}),d.current=o)},[s,t,n,o,m,r,a,h])},sd=()=>{const e=ws();od(e)},id=(e,t,n)=>t!=null&&t.startsWith("image")?n.A11Y_FILE_IMAGE(e):t!=null&&t.startsWith("video")?n.A11Y_FILE_VIDEO(e):n.A11Y_FILE_DOCUMENT(e),ad=(e,t)=>{var r,o,s,a,l,c;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const d=((o=e.name)==null?void 0:o.trim())||"";return mt({markdownText:n,comparisonText:d,plainText:id(d,e.type,t)})}if(e.isMultipleFilesMessage()){const d=((l=(a=(s=e.fileInfoList)==null?void 0:s[0])==null?void 0:a.fileName)==null?void 0:l.trim())||"",m=((c=e.fileInfoList)==null?void 0:c.length)??0;return mt({markdownText:n,comparisonText:d,plainText:m>0?t.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(m):""})}return n?mt({markdownText:n}):mr("")},io=(e,t,n=We.format)=>{const r=ad(e,t),o="sender"in e?e.sender:void 0,s=dt({message:r.text,messageFormat:r.format,codeBlockPlaceholder:t.A11Y_CODE_BLOCK_PLACEHOLDER}),a=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,l=typeof(o==null?void 0:o.nickname)=="string"&&o.nickname.trim()||void 0;return[t.SCROLL_TO_NEW_MESSAGES_LABEL([e]),a,l,s].filter(c=>!!c).join(", ")},ao=2e3,lo=400,Zt=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]},ks=e=>{if(!pe.isAdmin(e)||!pe.isCSAT(e))return null;const t=Cc(e);return t?`csat:${t}`:null},ld=e=>{const t=new Set;for(const n of e){const r=ks(n);r&&t.add(r)}return t},cd=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Zt(r).some(o=>t.includes(o)))return r}},Rn=(e,t)=>e.some(n=>t.includes(n)),co=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,On=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),ud=()=>{const{announceStatusText:e,announceStatus:t,announcementsActive:n}=ot(),{stringSet:r,format:o}=Q(),{channelUrl:s,messages:a,isClosed:l,isHandedOff:c,agentName:d,initialized:m,inputDisabled:h,inputDisabledBy:g,isStreamAnimating:C,subscribeMessageEvents:b,currentUserId:v}=ws(),{outgoingMessageStates:f,outgoingMessageStatusSignature:y}=u.useMemo(()=>{if(!v)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const T=a.flatMap(V=>{const H=bc(V,v);return!H||!("sendingStatus"in V)?[]:[{key:H,sendingStatus:V.sendingStatus}]});return{outgoingMessageStates:T,outgoingMessageStatusSignature:T.map(({key:V,sendingStatus:H})=>`${V}:${H}`).join(",")}},[v,a]),E=u.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:h,inputDisabledBy:g,outgoingMessageStatuses:On(f)}),x=u.useRef({messages:a,currentUserId:v,inputDisabledBy:g,isStreamAnimating:C,stringSet:r,format:o}),S=u.useRef([]),I=u.useRef(null),k=u.useRef({eventKeys:[],text:null,replaceableUntil:null}),M=u.useRef(new Set),U=u.useRef(new Set),F=u.useRef(!1),z=u.useRef(s);x.current={messages:a,currentUserId:v,inputDisabledBy:g,isStreamAnimating:C,stringSet:r,format:o};const L=()=>x.current.isStreamAnimating||x.current.inputDisabledBy==="ai_responding",P=()=>{I.current!=null&&(clearTimeout(I.current),I.current=null)},N=(T,V,H)=>{k.current={eventKeys:T,text:V,replaceableUntil:H!=null&&H.replaceableForMs?Date.now()+H.replaceableForMs:null}},w=()=>S.current.length>0,D=()=>{S.current=[]},R=()=>{const[T,...V]=S.current;if(!T)return!1;S.current=V;const{eventKeys:H,text:j}=T,se=Ae=>{N(H,Ae,{replaceableForMs:H.length>0?ao:void 0}),e(Ae)};if(H.length===0)return j&&se(j),!0;const le=x.current,Oe=cd(le.messages,H);return Oe?(se(io(Oe,le.stringSet,le.format)),!0):(j&&se(j),!0)},Y=()=>{for(P();R(););},te=(T=ao)=>{P(),I.current=setTimeout(()=>{if(I.current=null,L())return;const V=co(),[H]=S.current;if(!H)return;if(H.focusTarget!==V){S.current=[{...H,focusTarget:V},...S.current.slice(1)],te(lo);return}R()&&w()&&te(lo)},T)},re=(T,V)=>{const H={eventKeys:V,text:T,focusTarget:co()},j=V.length===0?-1:S.current.findIndex(({eventKeys:se})=>Rn(se,V));j>=0?S.current=S.current.map((se,le)=>le===j?H:se):S.current=[...S.current,H],te()},q=(T,V,H)=>{if(T!=="messagesUpdated"||V.length===0)return!1;const j=k.current;return!Rn(j.eventKeys,V)||j.text==null||j.replaceableUntil==null||Date.now()>j.replaceableUntil?!1:H!==j.text};u.useEffect(()=>{const T=z.current!==s;(!n||!m||T)&&(F.current=!1,U.current.clear(),D(),k.current={eventKeys:[],text:null,replaceableUntil:null},M.current.clear(),P(),T&&(z.current=s),!n||!m)||F.current||(F.current=!0,z.current=s,E.current={isClosed:l,isHandedOff:c,inputDisabled:h,inputDisabledBy:g,outgoingMessageStatuses:On(f)},M.current=new Set(a.flatMap(V=>{if(!De.isStreaming(V))return[];const H="sender"in V?V.sender:void 0;return(H==null?void 0:H.userId)===x.current.currentUserId?[]:Zt(V)})),U.current=ld(a))},[t,n,s,m,h,l,c,y]),u.useEffect(()=>b(T=>{if(!F.current||T.kind==="initialized"||!vc(T.source))return;const V=x.current,H=Zr(T.messages,T.messages,V.currentUserId)??Zr(V.messages,T.messages,V.currentUserId);if(!H)return;const j=Zt(H),se=ks(H);if(se!=null){if(U.current.has(se))return;U.current.add(se),t({event:"csatDisplayed"});return}if(De.isStreaming(H)){Zt(H).forEach(X=>{M.current.add(X)});return}const le=j.filter(X=>M.current.has(X)),Oe=T.kind==="messagesUpdated"&&le.length>0;Oe&&le.forEach(X=>{M.current.delete(X)});const Ae=T.kind==="messagesUpdated"&&S.current.some(({eventKeys:X})=>Rn(X,j)),B=io(H,V.stringSet,V.format),Z=q(T.kind,j,B);if(!(!Oe&&T.kind!=="messagesAdded"&&!Ae&&!Z)){if(Oe||L()||Ae){re(B,[...new Set([...le,...j])]);return}w()&&Y(),N(j,B),e(B)}}),[t,e,b]),u.useEffect(()=>{F.current&&(L()||w()&&te())},[g,C]),u.useEffect(()=>()=>{P()},[]),u.useEffect(()=>{if(!F.current)return;const T=E.current,V=T.outgoingMessageStatuses;T.outgoingMessageStatuses=On(f),f.some(({key:j,sendingStatus:se})=>{const le=V.get(j);return le!==void 0&&le!=="failed"&&se==="failed"})&&t({event:"sendFailed"})},[t,y]),u.useEffect(()=>{if(!F.current)return;const T=E.current;l&&!T.isClosed&&t({event:"conversationClosed"}),T.isClosed=l},[t,l]),u.useEffect(()=>{if(!F.current)return;const T=E.current;c&&!T.isHandedOff&&t({event:"agentConnected",agentName:d}),T.isHandedOff=c},[d,t,c]),u.useEffect(()=>{if(!F.current)return;const T=E.current;h&&g!=="ai_responding"&&(!T.inputDisabled||T.inputDisabledBy==="ai_responding")&&t({event:"inputDisabled"}),T.inputDisabled=h,T.inputDisabledBy=g},[t,h,g])},dd=()=>{const{channelSource:e}=he(),t=os(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},md=e=>{const{announceStatus:t,announcementsActive:n}=ot();Ul(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},hd=()=>{const e=dd();md(e)},W=({type:e,size:t=24,className:n,color:r})=>{const{icons:o}=tu(),s=o[e];return i.createElement(gd,{className:n},i.createElement(s,{size:t,color:r??p.color.primary.main,flipInRtl:Yc.has(e)}))},gd=_.default.span.attrs({"aria-hidden":"true"})`
77
+ ${({$rtlFlip:e})=>e&&Uu};
78
+ `,Gu=()=>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:Vu,useContext:zu}=Ee("MessengerIcon",{icons:Po}),qu=({icons:e,children:t})=>{const n=c.useMemo(()=>({icons:Xa(Po,e)}),[e]);return i.createElement(Vu,{value:n},t)},{Provider:Wu,useContext:Fo}=Ee("MessengerTheme");function Yu(e){const{theme:t,appearance:n,logger:r}=e;return i.createElement(Nl,{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(Ku,{...e}))}function Ku({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=dr();return c.useLayoutEffect(()=>{e.setAttribute(dn,n.selectedTheme)},[e,n.selectedTheme]),i.createElement(P.ThemeProvider,{theme:n},i.createElement(Wu,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const ju=(e,t)=>{c.useEffect(()=>{const n=ct(t)instanceof ShadowRoot,r=ct(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const o=r.createElement("link");o.rel="stylesheet",o.href=e,(n?t:r.head).appendChild(o)}},[e,t])},Xu=(e,t=document.body)=>{c.useEffect(()=>{if(!e)return;const n=ct(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let 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])},Zu=80,Ju=()=>{const{stringSet:e}=re(),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,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=c.useRef(t);return n.current=t,n},Bo=Ee("AriaLiveRegion",{announce:he,announceScreenEntry:he,announceStatus:he,announceError:he,flush:he,setSuppressionState:he}),Qu=Bo.Provider,Er=Bo.useContext,ed={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},td=({children:e})=>{const t=c.useRef(null),n=c.useRef(new Set),r=c.useRef(he),s=Ju(),[o]=c.useState(()=>Xc(v=>{r.current(v)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=v=>{const b=t.current;b&&(b.textContent="",requestAnimationFrame(()=>{b.textContent=v}))},c.useEffect(()=>()=>{o.destroy()},[o]);const a=o.announce,l=o.flush,u=c.useCallback(v=>{const b=Jc(v,s.current);a(b)},[a]),d=c.useCallback(v=>{const b=Qc(v,s.current);a(b,{mode:Zc(v.event)})},[a]),m=c.useCallback((v,b)=>{const C=eu(v,s.current);o.announceIgnoringSuppression(C),b&&setTimeout(()=>{b.focus()},Zu)},[o]),h=c.useCallback((v,b)=>{if(b){n.current.add(v);return}n.current.delete(v)},[]),f=c.useMemo(()=>({announce:a,announceScreenEntry:u,announceStatus:d,announceError:m,flush:l,setSuppressionState:h}),[a,m,u,d,l,h]);return i.createElement(Qu,{value:f},e,i.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:ed}))},Uo=Ee("ConversationAnnouncements",{announcementsActive:!0,announce:he,announceStatusText:he,announceScreenEntry:he,announceStatus:he,announceError:he,setIsSuppressed:he,setStatusPauseState:he,flush:he}),nd=Uo.Provider,st=Uo.useContext,rd=({children:e,announcementsActive:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:a,setSuppressionState:l}=Er(),u=c.useRef([]),d=c.useRef(new Set),m=c.useRef(Symbol("conversation-announcements")),h=c.useCallback(w=>{if(!t||!w){l(m.current,!1);return}l(m.current,!0)},[t,l]),f=c.useCallback(()=>{u.current=[]},[]),v=c.useCallback(()=>{if(u.current.length===0)return;if(!t){f();return}const w=[...u.current];f(),w.forEach(k=>{if(a(),k.type==="status"){s(k.params);return}n(k.text)})},[n,s,t,f,a]),b=c.useCallback((w,k)=>{if(k){d.current.add(w);return}d.current.delete(w),d.current.size===0&&v()},[v]),C=c.useCallback(w=>{t&&n(w)},[n,t]),g=c.useCallback(w=>{if(t){if(d.current.size>0){u.current.push({type:"text",text:w});return}a(),n(w)}},[n,t,a]),y=c.useCallback(w=>{t&&r(w)},[r,t]),E=c.useCallback(w=>{if(t){if(d.current.size>0){u.current.push({type:"status",params:w});return}s(w)}},[s,t]),I=c.useCallback((w,k)=>{t&&o(w,k)},[o,t]);c.useLayoutEffect(()=>(t||(f(),l(m.current,!1)),()=>{f(),l(m.current,!1)}),[t,f,l]);const A=c.useMemo(()=>({announcementsActive:t,announce:C,announceStatusText:g,announceScreenEntry:y,announceStatus:E,announceError:I,setIsSuppressed:h,setStatusPauseState:b,flush:a}),[t,a,C,g,I,y,E,h,b]);return i.createElement(nd,{value:A},e)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>i.createElement(id,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),hs=new WeakMap,sd=(e,t)=>{let n=hs.get(t);n||(n=new Map,hs.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=P.css`font-size:${Ye(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},od=e=>e?P.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",id=_.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>sd(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>od(e)}`,_n=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ad=`${_n}, [tabindex="-1"]`,yt=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 br(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Oe(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const ld='[data-sb-initial-focus="true"]',Ho=e=>Array.from(e.querySelectorAll(_n)).filter(yt),cd=e=>Array.from(e.querySelectorAll(ld)).find(yt)??Ho(e)[0]??null,ud=e=>Array.from(e.ownerDocument.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e&&yt(t)),dd=e=>{const t=cd(e)??e;t===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),t.focus()},md=(e,t,n)=>{const r=Ho(t);if(r.length===0){e.preventDefault(),t.focus();return}const s=r[0],o=r[r.length-1],a=n.activeElement;(e.shiftKey?a===s:a===o)&&(e.preventDefault(),(e.shiftKey?o:s).focus())},hd=(e,t)=>{const n=c.useRef(null);c.useEffect(()=>{if(!e||!t.current)return;const r=t.current,s=r.getRootNode();n.current=s.activeElement instanceof HTMLElement?s.activeElement:null;let o=!1;return Oe(()=>{o||!r.isConnected||dd(r)}),()=>{o=!0;const a=n.current;n.current=null,a&&Oe(()=>{ud(r)||!a.isConnected||!yt(a)||a.focus()})}},[e,t]),c.useEffect(()=>{if(!e||!t.current)return;const r=t.current,s=r.getRootNode(),o=a=>{a.key==="Tab"&&md(a,r,s)};return r.addEventListener("keydown",o),()=>r.removeEventListener("keydown",o)},[e,t])},ut=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,"aria-label":o,"aria-labelledby":a,"aria-describedby":l})=>{const u=c.useRef(null),{resolvePortalContainer:d}=_r();return hd(n,u),yu(n,r),n?zi.createPortal(i.createElement(fd,{onClick:r,style:e},i.createElement(gd,{ref:u,role:"dialog","aria-modal":"true","aria-label":o,"aria-labelledby":a,"aria-describedby":l,onClick:m=>m.stopPropagation()},s)),d(t)):null},fd=_.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${p.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${vt.MODAL};`,gd=_.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:${vt.MODAL};`,pd=({id:e,children:t})=>i.createElement(_d,{id:e},t),_d=_.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;`,Wt=(e,t)=>e!=null&&e.startsWith("image")?t.A11Y_HINT_OPEN_IMAGE:t.A11Y_HINT_OPEN_FILE,Yt=({name:e,mimeType:t,selected:n},r)=>{var o;const s=t!=null&&t.startsWith("image")?r.A11Y_FILE_IMAGE(e):t!=null&&t.startsWith("video")?r.A11Y_FILE_VIDEO(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},Ae=(e,t)=>t?{describedByProps:{"aria-describedby":e},descriptionNode:c.createElement(pd,{id:e,children:t})}:{describedByProps:{},descriptionNode:null},Ed=(e,t,n,r)=>{var o;const s=n.trim()||n;return((o=r.A11Y_CSAT_RATING_LABEL)==null?void 0:o.call(r,e,s))??`${e} / ${t} — ${s}`},bd=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},wt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:bd(e)}),se=()=>{const{stringSet:e}=re(),t=c.useId(),n=c.useId(),r=c.useId(),s=c.useId(),o=c.useId(),a=c.useId(),l=c.useId(),u=c.useId(),d=c.useId(),m=c.useId(),h=c.useId(),f=c.useId(),v=c.useId(),b=c.useId(),C=c.useId(),g=c.useId(),y=x=>x===e.A11Y_HINT_OPEN_CONVERSATION?Ae(t,x):x===e.A11Y_HINT_OPEN_CONVERSATIONS?Ae(n,x):(x===e.A11Y_HINT_CLOSE_CONVERSATION,Ae(r,x)),E=Ae(s,e.A11Y_HINT_OPEN_MENU),I=Ae(o,e.A11Y_HINT_CLOSE_CONVERSATION),A=Ae(a,e.A11Y_HINT_CONNECT_TO_AGENT),w=Ae(l,e.A11Y_HINT_ATTACH_FILE),k=Ae(u,e.A11Y_HINT_SEND_MESSAGE),N=Ae(d,e.A11Y_HINT_VIEW_NEW_MESSAGES),W=Ae(m,e.A11Y_HINT_VIEW_NEW_MESSAGES),G=Ae(h,e.A11Y_HINT_SEND_REPLY),K=Ae(f,e.A11Y_HINT_SELECT_RATING),L=Ae(v,e.A11Y_HINT_SELECT_RATING),V=Ae(b,e.A11Y_HINT_OPEN_CONVERSATION),Y=x=>{const D=Wt(x,e);return x!=null&&x.startsWith("image")?Ae(g,D):Ae(C,D)};return{launcher:{button:({isOpened:x,opensConversationList:D})=>{const $=au({intent:su({isOpened:x,opensConversationList:D}),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}}),Q=y($.hint);return{props:{"aria-label":$.label,...Q.describedByProps},hint:$.hint,descriptionNode:Q.descriptionNode}}},messenger:{closeButton:{"aria-label":e.A11Y_CLOSE_MESSENGER},expandButton:x=>({"aria-label":x?e.A11Y_COLLAPSE_MESSENGER:e.A11Y_EXPAND_MESSENGER}),connectionDelayDialog:{"aria-label":e.CONNECTION_DELAY__TITLE}},conversation:{header:{menuButton:{props:{"aria-label":e.A11Y_MENU,...E.describedByProps},hint:e.A11Y_HINT_OPEN_MENU,descriptionNode:E.descriptionNode},closeConversationButton:{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...I.describedByProps},hint:e.A11Y_HINT_CLOSE_CONVERSATION,descriptionNode:I.descriptionNode},handoffButton:{props:{"aria-label":e.A11Y_CONNECT_AGENT,...A.describedByProps},hint:e.A11Y_HINT_CONNECT_TO_AGENT,descriptionNode:A.descriptionNode},title:x=>({role:"heading","aria-level":2,"aria-label":x,tabIndex:-1})},messageInput:{attachFileButton:{props:{"aria-label":e.A11Y_ATTACH_FILE,...w.describedByProps},hint:e.A11Y_HINT_ATTACH_FILE,descriptionNode:w.descriptionNode},sendButton:{props:{"aria-label":e.A11Y_SEND_MESSAGE,...k.describedByProps},hint:e.A11Y_HINT_SEND_MESSAGE,descriptionNode:k.descriptionNode},textInput:x=>({role:"textbox","aria-label":x})},suggestedReplies:{hint:e.A11Y_HINT_SEND_REPLY,descriptionNode:G.descriptionNode,item:x=>({props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${x}`,...G.describedByProps}})},feedback:{hint:e.A11Y_HINT_SELECT_RATING,descriptionNode:K.descriptionNode,button:(x,D)=>({props:{"aria-label":x==="good"?e.FEEDBACK_GOOD:e.FEEDBACK_BAD,...K.describedByProps,"aria-pressed":D}}),optionsBottomSheet:{"aria-label":e.A11Y_FEEDBACK_OPTIONS}},newMessagesButton:{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...N.describedByProps},hint:e.A11Y_HINT_VIEW_NEW_MESSAGES,descriptionNode:N.descriptionNode},scrollToBottomButton:{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...W.describedByProps},hint:e.A11Y_HINT_VIEW_NEW_MESSAGES,descriptionNode:W.descriptionNode},startNewConversationButton:({onActivate:x})=>({...wt({onActivate:x}),"aria-label":e.TALK_TO_AGENT}),poweredByLink:{"aria-label":`${e.POWERED_BY} Sendbird`},retryButton:(x=e.RETRY)=>({"aria-label":x}),file:{label:(x,D)=>x?Yt({name:x,mimeType:D},e):"",preview:x=>({props:{"aria-label":Yt(x,e)}}),interactivePreview:x=>{const D=Y(x.mimeType);return{props:{"aria-label":Yt(x,e),...D.describedByProps},hint:Wt(x.mimeType,e),descriptionNode:D.descriptionNode}},openDescription:x=>{const D=Y(x);return{props:D.describedByProps,hint:Wt(x,e),descriptionNode:D.descriptionNode}},buttonLikeInteractivePreview:({onActivate:x,...D})=>{const $=Y(D.mimeType);return{props:{...wt({onActivate:x}),"aria-label":Yt(D,e),...$.describedByProps},hint:Wt(D.mimeType,e),descriptionNode:$.descriptionNode}},removeButton:x=>({"aria-label":e.A11Y_FILE_REMOVE_BUTTON(x)})},csat:{scoresContainer:x=>({props:{role:"radiogroup","aria-label":x},descriptionNode:L.descriptionNode}),scoreItem:({score:x,label:D,selected:$,disabled:Q,currentIndex:ae,totalCount:de,hasSelection:we,onChange:T})=>({props:{disabled:Q,onClick:()=>T(x),onKeyDown:F=>{var pe;if(Q)return;let z=null;switch(F.key){case"ArrowRight":case"ArrowDown":z=(ae+1)%de;break;case"ArrowLeft":case"ArrowUp":z=(ae-1+de)%de;break;default:return}F.preventDefault(),T(z+1);const J=F.currentTarget.parentElement,me=J==null?void 0:J.querySelectorAll('[role="radio"]');(pe=me==null?void 0:me[z])==null||pe.focus()},tabIndex:$||!we&&ae===0?0:-1,role:"radio","aria-checked":$,"aria-disabled":Q,...L.describedByProps,"aria-label":Ed(x,de,D,e)}}),submitButton:x=>({"aria-label":x})},form:{button:x=>({"aria-label":x}),textInput:(x,D,$)=>({"aria-label":x,"aria-required":D,"aria-disabled":$}),numberInput:(x,D,$)=>({"aria-label":x,"aria-required":D,"aria-disabled":$}),singleSelectGroup:x=>({role:"radiogroup",...x?{"aria-label":x}:{}}),singleSelectOption:(x,D,$)=>({role:"radio","aria-label":x,"aria-checked":D,"aria-disabled":$}),multiSelectOption:(x,D,$)=>({"aria-label":x,"aria-pressed":D,"aria-disabled":$})}},conversationList:{footer:{button:({onActivate:x})=>({...wt({onActivate:x}),"aria-label":e.TALK_TO_AGENT})},item:({agent:x,status:D,time:$,unreadCount:Q,onActivate:ae})=>{const de=typeof ae<"u",we=de?V:{describedByProps:{},descriptionNode:null};return{props:{...de?wt({onActivate:ae}):{},...we.describedByProps,"aria-label":e.A11Y_CONVERSATION_ITEM(x,D,$,Q)},hint:de?e.A11Y_HINT_OPEN_CONVERSATION:void 0,descriptionNode:de?we.descriptionNode:void 0}}}}},Cd=({title:e,description:t,highlightedText:n})=>{const r=Mc(t,n);return i.createElement(yd,null,i.createElement(Sd,null,i.createElement(B,{as:"div",variant:"h1",color:p.themedColor.textHighEmphasis},e),t&&i.createElement(Ad,null,i.createElement(B,{as:"div",variant:"body3",color:p.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?i.createElement(xd,null,r.highlightedText):null,r.afterText))))},vd=()=>{const{components:e}=En.useContext(),{stringSet:t}=re(),n=se(),r=Ic(),s=r.showDescription?wc(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return i.createElement(ut,{portalContainerId:ve.WINDOW,visible:r.visible,onClose:he,...n.messenger.connectionDelayDialog},i.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},En=qe({template:vd,components:{Dialog:Cd}}),yd=_.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Sd=_.default.div`display:flex;flex-direction:column;`,Ad=_.default.div`margin-top:16px;`,xd=_.default.strong`font-weight:700;`,{Provider:Td,Consumer:Go,useContext:fe}=Ee("Messenger");function Id({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[a,l]=c.useState(!1),[u,d]=c.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)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=_r(),f=c.useCallback(()=>{var b;m.setOpened(!1),(b=h(ve.LAUNCHER))==null||b.focus()},[m.setOpened,h]);Su(m.opened,f);const{Template:v}=En.useContext();return i.createElement(rl,{...o},b=>i.createElement(Td,{value:{...o,...b,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s}},i.createElement(v,null),e))}const Vo=/iPad|iPhone|iPod/.test(navigator.userAgent),wd=/Android/.test(navigator.userAgent),Dt=e=>Vo||wd;let It=null,Ln=null;const Md=(e,t=5e3)=>{It&&(clearInterval(It),clearTimeout(Ln));const n=document.title;It=setInterval(()=>{document.title=document.title===e?n:e},750),Ln=setTimeout(()=>{clearInterval(It),It=null,Ln=null,document.title=n},t)},zo=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Ie=P.css`&:focus-visible{outline:2px solid ${p.themedColor.primary};outline-offset:2px;}`,fs=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Cr=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:a,onClose:l,"aria-label":u})=>{const d=c.useId(),m=c.useId(),h=u??fs(t)??fs(n),f=u?void 0:t?d:n?m:void 0,v=t&&n?m:void 0,b=()=>{l(),Oe(()=>o==null?void 0:o())},C=()=>{l(),Oe(()=>a==null?void 0:a())};return i.createElement(ut,{portalContainerId:ve.WINDOW,visible:e,onClose:l,"aria-label":h,"aria-labelledby":f,"aria-describedby":v},i.createElement(kd,null,i.createElement(Ld,null,t&&i.createElement("div",{id:d},i.createElement(B,{variant:"h1",color:p.themedColor.textHighEmphasis},t)),n&&i.createElement(Rd,{id:m},i.createElement(B,{variant:"body3",color:p.themedColor.textMidEmphasis},n))),i.createElement(Od,null,s&&i.createElement(gs,{onClick:C},i.createElement(B,{variant:"button",color:p.themedColor.textHighEmphasis},s)),i.createElement(gs,{onClick:b},i.createElement(B,{variant:"button",color:p.themedColor.primary},r)))))},kd=_.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};`,Ld=_.default.div`margin-bottom:16px;`,Rd=_.default.div`margin-top:16px;`,Od=_.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,gs=_.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Ie}`,{Provider:Nd,useContext:Ne}=Ee("MessengerSession"),Dd=c.forwardRef(function({children:e,...t},n){return i.createElement(Fl,{ref:n,...t},r=>i.createElement($d,{...r},e))}),$d=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:a,state:l,handlers:u,dispatcher:d,_aiAgentSDK:m}=fe(),{userSessionInfo:h,authenticate:f,userSession:v,aiAgentInfo:b,launcherInfo:C}=t,[g,y]=c.useState(!1),E=c.useRef(null);bt(n,{async onUserJoined(A,w){var N,W,G,K;A.conversation&&A.conversation.type===Re.ConversationType.PROACTIVE&&w.userId===((N=n.currentUser)==null?void 0:N.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",A.url),(G=m.session)==null||G._updateActiveChannel({url:A.url,status:"open",conversationStatus:(W=A.conversation)==null?void 0:W.status}),l.setOpened(!0),Pd({sound:document.hidden||!l.opened}),(K=E.current)==null||K.call(E,{channel:A}))}}),c.useEffect(()=>{f().then(({launcher:A})=>{A.auto_open&&!Dt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(A=>{var w;r.error("messengerSession: failed to initialize",A),(w=u==null?void 0:u.onInitializeFailed)==null||w.call(u,A)})},[n,s,o,h==null?void 0:h.userId]),c.useEffect(()=>{const A=()=>y(!0);return d.subscribe(Ve.AnonymousSessionTokenExpired,A),()=>d.unsubscribe(Ve.AnonymousSessionTokenExpired,A)},[d]);const I=c.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!v||!b||!C?null:i.createElement(Nd,{value:{...t,userSession:v,aiAgentInfo:{...b,...a==null?void 0:a.bot},launcherInfo:{...C,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:A=>E.current=A}},e,i.createElement(Cr,{visible:g,title:"Session timed out",description:"Start a new conversation.",onConfirm:I,onClose:he}))};function Pd({sound:e}){Md("🔔You have received a new message"),e&&zo()}const hn=`@${He}-focused-channel`,qo=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Fd=()=>{try{const e=localStorage.getItem(hn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},ps=e=>{try{localStorage.setItem(hn,JSON.stringify({channelUrl:e,tabId:qo}))}catch{}},_s=()=>{try{const e=localStorage.getItem(hn);if(!e)return;JSON.parse(e).tabId===qo&&localStorage.removeItem(hn)}catch{}},Bd=(e,t)=>(c.useEffect(()=>{if(!t||!e)return;const n=()=>ps(e),r=()=>_s();return document.hasFocus()&&ps(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),_s()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Fd()===e}),Ud=e=>{var a;const{config:t,chatSDK:n}=fe(),{sdkUser:r}=Ne(),s=!!((a=t==null?void 0:t.conversation)!=null&&a.messageAlertSoundEnabled),{isChannelViewedInAnyTab:o}=Bd(e,s);bt(n,{onMessageReceived(l,u){if(!s||l.url!==e||o())return;(Xe(u)&&u.sender.userId!==(r==null?void 0:r.userId)||u.isAdminMessage()&&!u.silent)&&zo()}})};function Hd(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 Gd(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Hd(e.file);return new ze.MessageMetaArray({key:Qs,value:[t,n]})}}const Vd=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=fe(),r=c.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await Gd(s),a={...s,metaArrays:o?[o]:void 0},l=zd(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===ze.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===ze.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:s}}))}}},zd=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},ft=50,Rn=ft-40,{Provider:qd,useContext:Wo}=Ee("ConversationScroll"),Es={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},On=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function Wd({scrollMode:e,messageStackDirection:t,children:n}){const r=c.useRef(null),s=c.useRef(null),o=c.useRef(0),a=c.useRef(0),l=c.useRef(!1),u=c.useRef(!1),d=c.useRef(null),m=c.useRef(Es),h=c.useRef(!1),f=c.useRef(null),[v,b]=c.useState(0),[C,g]=c.useState(0),[y,E]=c.useState(!1),[I,A]=c.useState(!1),[w,k]=c.useState(!0),N=M=>{const R=On(M);return o.current=R,g(R),R},W=()=>{d.current&&(clearTimeout(d.current),d.current=null)},G=c.useMemo(()=>y||t==="bottom"?"auto":e,[y,t,e]),K=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},L=()=>{const M=r.current;!M||!m.current.shouldUpdate||b(R=>{m.current.shouldUpdate=!1;const{contentHeight:O,contentSnapshotHeight:j,shouldRecalc:q}=m.current,U=M.clientHeight;if(j>O)return R;const H=V(M,{messageType:"outgoing"});let oe=0;if(H){const Ge=H.message.offsetTop-Rn+U;oe=Math.max(0,Ge-O)}else{const Ge=O-j,ne=U-Rn;oe=Math.max(0,Ge-ne)}return R===0||oe!==R||q?(m.current.shouldRecalc=!1,oe):R})},V=c.useCallback((M,R)=>{const{messageType:O="all"}=R??{},j=Array.from(M.querySelectorAll(`#${He}-message-item`));let q=j;O==="outgoing"&&(q=j.filter(ie=>ie.getAttribute("data-layout-id")==="outgoingmessage"));const U=q[q.length-1];if(!U)return null;const H=M.getBoundingClientRect(),oe=U.getBoundingClientRect(),Ge=M.scrollTop+(oe.top-H.top),ne=Ge+U.offsetHeight;return{message:U,scrollTop:Ge,lastMessageBottom:ne}},[]),Y=c.useCallback(()=>{const M=r.current;if(!M||G!=="fixed")return;const R=V(M);m.current.contentHeight=(R==null?void 0:R.lastMessageBottom)??M.scrollHeight,!h.current&&m.current.contentSnapshotHeight>0&&K(),u.current?o.current=On(M):N(M),L()},[G,V]),x=c.useCallback(()=>{s.current&&(s.current.disconnect(),s.current=null),W(),m.current=Es,b(0),g(0),k(!0),o.current=0,l.current=!1,a.current=0,u.current=!1},[]),D=c.useCallback((M=!0)=>{const R=o.current>ft;if(l.current=!1,g(0),!R){Oe(()=>{const O=r.current;O&&!l.current&&O.scrollTo({top:O.scrollHeight,behavior:"auto"})});return}u.current||(u.current=!0,k(!1),W()),Oe(()=>{const O=r.current;if(!O){u.current=!1,k(!0);return}if(l.current){u.current=!1,N(O),k(!0);return}const j=()=>{if(r.current!==O){u.current=!1,r.current&&N(r.current),k(!0);return}u.current=!1,N(O),k(!0)};if(M&&!d.current){const q=setTimeout(j,500);d.current=q,O.addEventListener("scrollend",()=>{clearTimeout(q),d.current=null,j()},{once:!0})}O.scrollTo({top:O.scrollHeight,behavior:M?"smooth":"auto"}),M||j()})},[]),$=c.useCallback(M=>{M&&(r.current=M,G==="fixed"&&(x(),m.current.viewport=M.clientHeight,s.current=new MutationObserver(()=>{Y()}),s.current.observe(M,{childList:!0,subtree:!0})))},[G,Y,x]),Q=c.useCallback(()=>{const M=r.current;if(!M)return;const R=V(M,{messageType:"outgoing"});R&&(M.scrollTo({top:R.message.offsetTop-Rn,behavior:"smooth"}),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{A(!1)},500))},[V]),ae=(M,R,O)=>{const j=On(M);if(O&&j>ft){u.current=!1,l.current=!0,W(),N(M),k(!0),a.current=R;return}o.current=j},de=(M,R,O)=>{const q=N(M)<=ft;R&&!q&&(l.current=!0,W()),O&&q&&(l.current=!1)},we=M=>{const{scrollTop:R}=M.currentTarget,O=a.current;u.current?ae(M.currentTarget,R,R<O):de(M.currentTarget,R<O,R>O),a.current=R},T=c.useCallback(()=>{G==="fixed"&&(A(!0),K())},[G]),F=c.useCallback(()=>{G==="fixed"?setTimeout(()=>Q(),300):D()},[G,Q]),z=c.useCallback(M=>{h.current=M,G==="fixed"?K():l.current||D()},[G,D]),J=c.useCallback(M=>{E(M),M&&(b(0),s.current&&(s.current.disconnect(),s.current=null))},[]),me=c.useCallback(M=>{G==="auto"&&M&&!l.current&&D()},[G,D]),Pe=!(C<=ft)&&!I,Me=c.useCallback(()=>o.current>ft,[]);return i.createElement(qd,{value:{ref:$,state:{bottomSpace:v,isAwayFromBottom:Pe,isScrollPositionReconciled:w,shouldCountNewMessages:Me},props:{onScroll:we},actions:{scrollToBottom:D,onBeforeMessageSend:T,onAfterMessageSend:F,onStreamingUpdate:z,onConversationClosed:J,onTypingIndicatorUpdate:me}}},n)}const{Provider:Yd,Context:Kd,useContext:ye}=Ee("Conversation"),jd=({children:e})=>{var s;const{channelSource:t}=ye(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=fc(n);return c.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)},Xd=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:s})=>{const{activeChannel:o,refreshActiveChannel:a}=Ne(),l=Wo(),u=e||(o==null?void 0:o.url);Ud(u);const{onBeforeSendMessage:d,onAfterSendMessage:m}=Vd({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),h=c.useCallback(b=>(l.actions.onBeforeMessageSend(),d(b)),[l.actions,d]),f=c.useCallback(b=>{const C=b.some(g=>Ke.isStreaming(g));l.actions.onStreamingUpdate(C)},[l.actions.onStreamingUpdate]),v=c.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(Xl,{key:u,channelUrl:u,onBeforeSendMessage:h,onAfterSendMessage:m,onMessagesUpdated:f,onMessagesReceived:f,onChannelDeleted:v,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},b=>i.createElement(Yd,{value:{...b,scrollSource:l,goToActiveConversation:v,onNavigateToConversationList:n}},i.createElement(jd,null,s)))},Yo=({children:e,...t})=>{var a;const{config:n}=$e(),{agentPreviewConfigs:r}=fe(),s=((a=n==null?void 0:n.conversation)==null?void 0:a.scrollMode)??"auto",o=r==null?void 0:r.messageStackDirection;return i.createElement(Wd,{scrollMode:s,messageStackDirection:o},i.createElement(Xd,{...t},e))},vr=c.createContext({onDrop:he,subscribe:()=>he}),jn=({children:e})=>{const t=c.useRef(new Set);return i.createElement(vr.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)},Zd=({onDropFiles:e})=>{const{subscribe:t}=c.useContext(vr);c.useEffect(()=>t(e),[e])};jn.Consumer=({children:e})=>{const{onDrop:t}=c.useContext(vr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const Qt=(e,t)=>Array.from(e.querySelectorAll(t)).find(yt)??null,Jd=e=>{const t=Qt(e,gr);if(t){t.focus();return}const n=e.querySelector(uu);if(n){const s=Qt(n,ad);if(s){s.focus();return}}const r=Qt(e,_n);if(r){r.focus();return}e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus()},Qd=e=>{const{announcementsActive:t}=st(),{channelSource:n}=ye(),r=c.useRef(!1),s=n.channel,o=n.error,a=s!=null||o!=null;c.useEffect(()=>{if(!t||r.current||!e.current||!(Qt(e.current,gr)!=null)&&!a)return;let u=!1;return Oe(()=>{u||r.current||!e.current||(r.current=!0,Jd(e.current))}),()=>{u=!0}},[t,a,e])},em=e=>at(e)||to(e);function tm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function nm(e,t){return e.filter(n=>Ke.isWelcomeMessage(n,t))}const Ko=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>tm(r)?!1:t.length>0?!Ke.isWelcomeMessage(r,n):!0),rm=[],jo=()=>{var b,C,g,y,E,I;const{agentPreviewConfigs:e={},aiAgentId:t}=fe(),{aiAgentInfo:n,userSession:r}=Ne(),{channelSource:s,messageSource:o,state:{input:a,streamAnimation:l}}=ye(),u=e.welcomeMessages??rm,d=c.useMemo(()=>Ko(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=nt(s.channel),h=(C=(b=lo(s.channel,r.userId))==null?void 0:b.nickname)==null?void 0:C.trim(),f=m?(y=(g=s.channel)==null?void 0:g.name)==null?void 0:y.trim():(E=n==null?void 0:n.nickname)==null?void 0:E.trim(),v=h||f||void 0;return{initialized:o.initialized,channelUrl:(I=s.channel)==null?void 0:I.url,agentName:v,isClosed:De(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:a.disabled,inputDisabledBy:a.disabledBy,isStreamAnimating:l.isAnimating,subscribeMessageEvents:o.subscribeMessageEvents,currentUserId:r.userId}},sm=(e={})=>{const{announceScreenEntry:t,announcementsActive:n}=st(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:a=!1,messages:l=[],hasWelcomeMessages:u=!1}=e,d=c.useRef(null),m=c.useMemo(()=>l.some(f=>Te.isAdmin(f)&&Te.isCSAT(f)),[l]),h=l.length===0&&!u;c.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=jo();sm(e)},im=(e,t,n)=>t!=null&&t.startsWith("image")?n.A11Y_FILE_IMAGE(e):t!=null&&t.startsWith("video")?n.A11Y_FILE_VIDEO(e):n.A11Y_FILE_DOCUMENT(e),am=(e,t)=>{var r,s,o,a,l,u;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const d=((s=e.name)==null?void 0:s.trim())||"";return _t({markdownText:n,comparisonText:d,plainText:im(d,e.type,t)})}if(e.isMultipleFilesMessage()){const d=((l=(a=(o=e.fileInfoList)==null?void 0:o[0])==null?void 0:a.fileName)==null?void 0:l.trim())||"",m=((u=e.fileInfoList)==null?void 0:u.length)??0;return _t({markdownText:n,comparisonText:d,plainText:m>0?t.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(m):""})}return n?_t({markdownText:n}):fr("")},bs=(e,t,n=et.format)=>{const r=am(e,t),s="sender"in e?e.sender:void 0,o=pt({message:r.text,messageFormat:r.format,codeBlockPlaceholder:t.A11Y_CODE_BLOCK_PLACEHOLDER}),a=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,l=typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0;return[t.SCROLL_TO_NEW_MESSAGES_LABEL([e]),a,l,o].filter(u=>!!u).join(", ")},Cs=2e3,vs=400,en=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]},Xo=e=>{if(!Te.isAdmin(e)||!Te.isCSAT(e))return null;const t=nu(e);return t?`csat:${t}`:null},lm=e=>{const t=new Set;for(const n of e){const r=Xo(n);r&&t.add(r)}return t},cm=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&en(r).some(s=>t.includes(s)))return r}},Nn=(e,t)=>e.some(n=>t.includes(n)),ys=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,Dn=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),um=()=>{const{announceStatusText:e,announceStatus:t,announcementsActive:n}=st(),{stringSet:r,format:s}=re(),{channelUrl:o,messages:a,isClosed:l,isHandedOff:u,agentName:d,initialized:m,inputDisabled:h,inputDisabledBy:f,isStreamAnimating:v,subscribeMessageEvents:b,currentUserId:C}=jo(),{outgoingMessageStates:g,outgoingMessageStatusSignature:y}=c.useMemo(()=>{if(!C)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const T=a.flatMap(F=>{const z=tu(F,C);return!z||!("sendingStatus"in F)?[]:[{key:z,sendingStatus:F.sendingStatus}]});return{outgoingMessageStates:T,outgoingMessageStatusSignature:T.map(({key:F,sendingStatus:z})=>`${F}:${z}`).join(",")}},[C,a]),E=c.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:h,inputDisabledBy:f,outgoingMessageStatuses:Dn(g)}),I=c.useRef({messages:a,currentUserId:C,inputDisabledBy:f,isStreamAnimating:v,stringSet:r,format:s}),A=c.useRef([]),w=c.useRef(null),k=c.useRef({eventKeys:[],text:null,replaceableUntil:null}),N=c.useRef(new Set),W=c.useRef(new Set),G=c.useRef(!1),K=c.useRef(o);I.current={messages:a,currentUserId:C,inputDisabledBy:f,isStreamAnimating:v,stringSet:r,format:s};const L=()=>I.current.isStreamAnimating||I.current.inputDisabledBy==="ai_responding",V=()=>{w.current!=null&&(clearTimeout(w.current),w.current=null)},Y=(T,F,z)=>{k.current={eventKeys:T,text:F,replaceableUntil:z!=null&&z.replaceableForMs?Date.now()+z.replaceableForMs:null}},x=()=>A.current.length>0,D=()=>{A.current=[]},$=()=>{const[T,...F]=A.current;if(!T)return!1;A.current=F;const{eventKeys:z,text:J}=T,me=Me=>{Y(z,Me,{replaceableForMs:z.length>0?Cs:void 0}),e(Me)};if(z.length===0)return J&&me(J),!0;const pe=I.current,Pe=cm(pe.messages,z);return Pe?(me(bs(Pe,pe.stringSet,pe.format)),!0):(J&&me(J),!0)},Q=()=>{for(V();$(););},ae=(T=Cs)=>{V(),w.current=setTimeout(()=>{if(w.current=null,L())return;const F=ys(),[z]=A.current;if(!z)return;if(z.focusTarget!==F){A.current=[{...z,focusTarget:F},...A.current.slice(1)],ae(vs);return}$()&&x()&&ae(vs)},T)},de=(T,F)=>{const z={eventKeys:F,text:T,focusTarget:ys()},J=F.length===0?-1:A.current.findIndex(({eventKeys:me})=>Nn(me,F));J>=0?A.current=A.current.map((me,pe)=>pe===J?z:me):A.current=[...A.current,z],ae()},we=(T,F,z)=>{if(T!=="messagesUpdated"||F.length===0)return!1;const J=k.current;return!Nn(J.eventKeys,F)||J.text==null||J.replaceableUntil==null||Date.now()>J.replaceableUntil?!1:z!==J.text};c.useEffect(()=>{const T=K.current!==o;(!n||!m||T)&&(G.current=!1,W.current.clear(),D(),k.current={eventKeys:[],text:null,replaceableUntil:null},N.current.clear(),V(),T&&(K.current=o),!n||!m)||G.current||(G.current=!0,K.current=o,E.current={isClosed:l,isHandedOff:u,inputDisabled:h,inputDisabledBy:f,outgoingMessageStatuses:Dn(g)},N.current=new Set(a.flatMap(F=>{if(!Ke.isStreaming(F))return[];const z="sender"in F?F.sender:void 0;return(z==null?void 0:z.userId)===I.current.currentUserId?[]:en(F)})),W.current=lm(a))},[t,n,o,m,h,l,u,y]),c.useEffect(()=>b(T=>{if(!G.current||T.kind==="initialized"||!ru(T.source))return;const F=I.current,z=ls(T.messages,T.messages,F.currentUserId)??ls(F.messages,T.messages,F.currentUserId);if(!z)return;const J=en(z),me=Xo(z);if(me!=null){if(W.current.has(me))return;W.current.add(me),t({event:"csatDisplayed"});return}if(Ke.isStreaming(z)){en(z).forEach(O=>{N.current.add(O)});return}const pe=J.filter(O=>N.current.has(O)),Pe=T.kind==="messagesUpdated"&&pe.length>0;Pe&&pe.forEach(O=>{N.current.delete(O)});const Me=T.kind==="messagesUpdated"&&A.current.some(({eventKeys:O})=>Nn(O,J)),M=bs(z,F.stringSet,F.format),R=we(T.kind,J,M);if(!(!Pe&&T.kind!=="messagesAdded"&&!Me&&!R)){if(Pe||L()||Me){de(M,[...new Set([...pe,...J])]);return}x()&&Q(),Y(J,M),e(M)}}),[t,e,b]),c.useEffect(()=>{G.current&&(L()||x()&&ae())},[f,v]),c.useEffect(()=>()=>{V()},[]),c.useEffect(()=>{if(!G.current)return;const T=E.current,F=T.outgoingMessageStatuses;T.outgoingMessageStatuses=Dn(g),g.some(({key:J,sendingStatus:me})=>{const pe=F.get(J);return pe!==void 0&&pe!=="failed"&&me==="failed"})&&t({event:"sendFailed"})},[t,y]),c.useEffect(()=>{if(!G.current)return;const T=E.current;l&&!T.isClosed&&t({event:"conversationClosed"}),T.isClosed=l},[t,l]),c.useEffect(()=>{if(!G.current)return;const T=E.current;u&&!T.isHandedOff&&t({event:"agentConnected",agentName:d}),T.isHandedOff=u},[d,t,u]),c.useEffect(()=>{if(!G.current)return;const T=E.current;h&&f!=="ai_responding"&&(!T.inputDisabled||T.inputDisabledBy==="ai_responding")&&t({event:"inputDisabled"}),T.inputDisabled=h,T.inputDisabledBy=f},[t,h,f])},dm=()=>{const{channelSource:e}=ye(),t=vo(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},mm=e=>{const{announceStatus:t,announcementsActive:n}=st();Ec(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},hm=()=>{const e=dm();mm(e)},Z=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=zu(),o=s[e];return i.createElement(fm,{className:n},i.createElement(o,{size:t,color:r??p.color.primary.main,flipInRtl:Pu.has(e)}))},fm=_.default.span.attrs({"aria-hidden":"true"})`
81
81
  display: inline-flex;
82
82
  &:focus {
83
83
  outline: none;
84
84
  }
85
- `,fd=.75,Ls=6,pd=Ls*2;let jn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(jn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const _d=e=>jn?Array.from(jn.segment(e),t=>t.segment):[...e],Ed=e=>{const t=Math.floor(e.length*fd),n=Math.max(0,e.length-Ls);return Math.max(t,n)},uo=(e,t="")=>{if(e.length<pd)return{start:e+t,end:""};const n=_d(e),r=Ed(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},bd=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return uo(t);const o=t.slice(0,n),s=t.slice(n);return uo(o,s)},Ms=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>bd(e),[e]);return r?i.createElement(Cd,null,i.createElement(vd,{...t},n),i.createElement(yd,{...t},r)):i.createElement($,{...t},n)},Cd=_.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,vd=_.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,yd=_.default($)`flex-shrink:0;white-space:nowrap;`,Sd=({id:e,children:t})=>i.createElement(Ad,{id:e},t),Ad=_.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;`,Gt=(e,t)=>e!=null&&e.startsWith("image")?t.A11Y_HINT_OPEN_IMAGE:t.A11Y_HINT_OPEN_FILE,zt=({name:e,mimeType:t,selected:n},r)=>{var s;const o=t!=null&&t.startsWith("image")?r.A11Y_FILE_IMAGE(e):t!=null&&t.startsWith("video")?r.A11Y_FILE_VIDEO(e):r.A11Y_FILE_DOCUMENT(e);return n?((s=r.A11Y_FILE_SELECTED)==null?void 0:s.call(r,o))??`${o}, selected`:o},me=(e,t)=>t?{describedByProps:{"aria-describedby":e},descriptionNode:u.createElement(Sd,{id:e,children:t})}:{describedByProps:{},descriptionNode:null},xd=(e,t,n,r)=>{var s;const o=n.trim()||n;return((s=r.A11Y_CSAT_RATING_LABEL)==null?void 0:s.call(r,e,o))??`${e} / ${t} — ${o}`},Wt=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},ee=()=>{const{stringSet:e}=Q(),t=u.useId(),n=u.useId(),r=u.useId(),o=u.useId(),s=u.useId(),a=u.useId(),l=u.useId(),c=u.useId(),d=u.useId(),m=u.useId(),h=u.useId(),g=u.useId(),C=u.useId(),b=u.useId(),v=u.useId(),f=u.useId(),y=w=>w===e.A11Y_HINT_OPEN_CONVERSATION?me(t,w):w===e.A11Y_HINT_OPEN_CONVERSATIONS?me(n,w):(w===e.A11Y_HINT_CLOSE_CONVERSATION,me(r,w)),E=me(o,e.A11Y_HINT_OPEN_MENU),x=me(s,e.A11Y_HINT_CLOSE_CONVERSATION),S=me(a,e.A11Y_HINT_CONNECT_TO_AGENT),I=me(l,e.A11Y_HINT_ATTACH_FILE),k=me(c,e.A11Y_HINT_SEND_MESSAGE),M=me(d,e.A11Y_HINT_VIEW_NEW_MESSAGES),U=me(m,e.A11Y_HINT_VIEW_NEW_MESSAGES),F=me(h,e.A11Y_HINT_SEND_REPLY),z=me(g,e.A11Y_HINT_SELECT_RATING),L=me(C,e.A11Y_HINT_SELECT_RATING),P=me(b,e.A11Y_HINT_OPEN_CONVERSATION),N=w=>{const D=Gt(w,e);return w!=null&&w.startsWith("image")?me(f,D):me(v,D)};return{launcher:{button:({isOpened:w,opensConversationList:D})=>{const R=xc({intent:yc({isOpened:w,opensConversationList:D}),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}}),Y=y(R.hint);return{props:{"aria-label":R.label,...Y.describedByProps},hint:R.hint,descriptionNode:Y.descriptionNode}}},messenger:{closeButton:{"aria-label":e.A11Y_CLOSE_MESSENGER},expandButton:w=>({"aria-label":w?e.A11Y_COLLAPSE_MESSENGER:e.A11Y_EXPAND_MESSENGER})},conversation:{menuButton:{props:{"aria-label":e.A11Y_MENU,...E.describedByProps},hint:e.A11Y_HINT_OPEN_MENU,descriptionNode:E.descriptionNode},closeConversationButton:{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...x.describedByProps},hint:e.A11Y_HINT_CLOSE_CONVERSATION,descriptionNode:x.descriptionNode},handoffButton:{props:{"aria-label":e.A11Y_CONNECT_AGENT,...S.describedByProps},hint:e.A11Y_HINT_CONNECT_TO_AGENT,descriptionNode:S.descriptionNode},headerTitle:w=>({role:"heading","aria-level":2,"aria-label":w,tabIndex:-1}),messageInput:{attachFileButton:{props:{"aria-label":e.A11Y_ATTACH_FILE,...I.describedByProps},hint:e.A11Y_HINT_ATTACH_FILE,descriptionNode:I.descriptionNode},sendButton:{props:{"aria-label":e.A11Y_SEND_MESSAGE,...k.describedByProps},hint:e.A11Y_HINT_SEND_MESSAGE,descriptionNode:k.descriptionNode},textInput:w=>({role:"textbox","aria-label":w})},suggestedReplies:{hint:e.A11Y_HINT_SEND_REPLY,descriptionNode:F.descriptionNode,item:w=>({props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${w}`,...F.describedByProps}})},feedback:{hint:e.A11Y_HINT_SELECT_RATING,descriptionNode:z.descriptionNode,button:(w,D)=>({props:{"aria-label":w==="good"?e.FEEDBACK_GOOD:e.FEEDBACK_BAD,...z.describedByProps,"aria-pressed":D}}),optionsBottomSheet:{"aria-label":e.A11Y_FEEDBACK_OPTIONS}},newMessagesButton:{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...M.describedByProps},hint:e.A11Y_HINT_VIEW_NEW_MESSAGES,descriptionNode:M.descriptionNode},scrollToBottomButton:{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...U.describedByProps},hint:e.A11Y_HINT_VIEW_NEW_MESSAGES,descriptionNode:U.descriptionNode},startNewConversationButton:({onActivate:w})=>({role:"button",tabIndex:0,"aria-label":e.TALK_TO_AGENT,onClick:w,onKeyDown:Wt(w)}),poweredByLink:{"aria-label":`${e.POWERED_BY} Sendbird`},retryButton:(w=e.RETRY)=>({"aria-label":w}),file:{label:(w,D)=>w?zt({name:w,mimeType:D},e):"",preview:w=>({props:{"aria-label":zt(w,e)}}),interactivePreview:w=>{const D=N(w.mimeType);return{props:{"aria-label":zt(w,e),...D.describedByProps},hint:Gt(w.mimeType,e),descriptionNode:D.descriptionNode}},openDescription:w=>{const D=N(w);return{props:D.describedByProps,hint:Gt(w,e),descriptionNode:D.descriptionNode}},buttonLikeInteractivePreview:({onActivate:w,...D})=>{const R=N(D.mimeType);return{props:{role:"button",tabIndex:0,"aria-label":zt(D,e),...R.describedByProps,onClick:w,onKeyDown:Wt(w)},hint:Gt(D.mimeType,e),descriptionNode:R.descriptionNode}},removeButton:w=>({"aria-label":e.A11Y_FILE_REMOVE_BUTTON(w)})},csat:{scoresContainer:w=>({props:{role:"radiogroup","aria-label":w},descriptionNode:L.descriptionNode}),scoreItem:({score:w,label:D,selected:R,disabled:Y,currentIndex:te,totalCount:re,hasSelection:q,onChange:T})=>({props:{disabled:Y,onClick:()=>T(w),onKeyDown:V=>{var le;if(Y)return;let H=null;switch(V.key){case"ArrowRight":case"ArrowDown":H=(te+1)%re;break;case"ArrowLeft":case"ArrowUp":H=(te-1+re)%re;break;default:return}V.preventDefault(),T(H+1);const j=V.currentTarget.parentElement,se=j==null?void 0:j.querySelectorAll('[role="radio"]');(le=se==null?void 0:se[H])==null||le.focus()},tabIndex:R||!q&&te===0?0:-1,role:"radio","aria-checked":R,"aria-disabled":Y,...L.describedByProps,"aria-label":xd(w,re,D,e)}}),submitButton:w=>({"aria-label":w})},form:{button:w=>({"aria-label":w}),textInput:(w,D,R)=>({"aria-label":w,"aria-required":D,"aria-disabled":R}),numberInput:(w,D,R)=>({"aria-label":w,"aria-required":D,"aria-disabled":R}),singleSelectGroup:w=>({role:"radiogroup",...w?{"aria-label":w}:{}}),singleSelectOption:(w,D,R)=>({role:"radio","aria-label":w,"aria-checked":D,"aria-disabled":R}),multiSelectOption:(w,D,R)=>({"aria-label":w,"aria-pressed":D,"aria-disabled":R})}},conversationList:{footer:{button:({onActivate:w})=>({role:"button",tabIndex:0,"aria-label":e.TALK_TO_AGENT,onClick:w,onKeyDown:Wt(w)})},item:({agent:w,status:D,time:R,unreadCount:Y,onActivate:te})=>{const re=typeof te<"u",q=re?P:{describedByProps:{},descriptionNode:null};return{props:{...re?{role:"button",tabIndex:0,onClick:te,onKeyDown:Wt(te)}:{},...q.describedByProps,"aria-label":e.A11Y_CONVERSATION_ITEM(w,D,R,Y)},hint:re?e.A11Y_HINT_OPEN_CONVERSATION:void 0,descriptionNode:re?q.descriptionNode:void 0}}}}},br=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:o,onClick:s,ariaLabel:a})=>{const{colors:l}=O.useTheme(),{conversation:c}=ee(),d=s?c.file.interactivePreview({name:e,mimeType:t}):c.file.preview({name:e,mimeType:t}),m={...d,props:{...d.props,...a?{"aria-label":a}:{}}};return i.createElement(Td,{as:s?"button":"div",type:s?"button":void 0,onClick:s,...m.props,$clickable:!!s},i.createElement(wd,{$bgColor:o??l.base.primary},i.createElement(W,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(kd,null,i.createElement(Ms,{variant:"button",color:p.themedColor.textHighEmphasis},e),i.createElement($,{color:p.themedColor.textMidEmphasis,variant:"caption3"},n)),m.descriptionNode)},Td=_.default.div`border:none;border-radius:12px;gap:8px;width:${K.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${p.themedColor.textDisabled};background-color:${p.themedColor.bg_50_600};${({$clickable:e})=>e&&Id}`,Id=O.css`cursor:pointer;&:hover{background-color:${p.themedColor.bg_100_500};}`,wd=_.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,kd=_.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Ld({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(Md,null,i.createElement(br,{name:e.name,mimeType:e.type,type:er(e.name,e.type),onClick:r}),t)}const Md=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${K.GAP_GROUPED}px;`,Fe=`${we}-incoming-msg`,Rd=`${we}-marked-text`;function Od({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:o}=ee(),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.buttonLikeInteractivePreview({name:e.name,mimeType:e.type,onActivate:a}):o.file.preview({name:e.name,mimeType:e.type}),c=()=>s?i.createElement(Dd,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(Pd,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(c){const d={id:`${Fe}-media-body`,...l.props};return i.createElement(Nd,null,i.createElement($d,{...d},c(),l.descriptionNode),r)}return null}const Nd=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${K.GAP_GROUPED}px;`,$d=_.default.div`width:${K.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${G.light`
85
+ `,gm=.75,Zo=6,pm=Zo*2;let Xn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Xn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const _m=e=>Xn?Array.from(Xn.segment(e),t=>t.segment):[...e],Em=e=>{const t=Math.floor(e.length*gm),n=Math.max(0,e.length-Zo);return Math.max(t,n)},Ss=(e,t="")=>{if(e.length<pm)return{start:e+t,end:""};const n=_m(e),r=Em(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},bm=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Ss(t);const s=t.slice(0,n),o=t.slice(n);return Ss(s,o)},Jo=({children:e,...t})=>{const{start:n,end:r}=c.useMemo(()=>bm(e),[e]);return r?i.createElement(Cm,null,i.createElement(vm,{...t},n),i.createElement(ym,{...t},r)):i.createElement(B,{...t},n)},Cm=_.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,vm=_.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,ym=_.default(B)`flex-shrink:0;white-space:nowrap;`,yr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:a})=>{const{colors:l}=P.useTheme(),{conversation:u}=se(),d=o?u.file.interactivePreview({name:e,mimeType:t,selected:a}):u.file.preview({name:e,mimeType:t,selected:a});return i.createElement(Sm,{as:o?"button":"div",type:o?"button":void 0,onClick:o,...d.props,$clickable:!!o},i.createElement(xm,{$bgColor:s??l.base.primary},i.createElement(Z,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(Tm,null,i.createElement(Jo,{variant:"button",color:p.themedColor.textHighEmphasis},e),i.createElement(B,{color:p.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},Sm=_.default.div`border:none;border-radius:12px;gap:8px;width:${ee.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${p.themedColor.textDisabled};background-color:${p.themedColor.bg_50_600};${({$clickable:e})=>e&&Am}`,Am=P.css`cursor:pointer;&:hover{background-color:${p.themedColor.bg_100_500};}`,xm=_.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Tm=_.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Im({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(wm,null,i.createElement(yr,{name:e.name,mimeType:e.type,type:nr(e.name,e.type),onClick:r}),t)}const wm=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Ze=`${He}-incoming-msg`,Mm=`${He}-marked-text`;function km({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.buttonLikeInteractivePreview({name:e.name,mimeType:e.type,onActivate:a}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?i.createElement(Om,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(Nm,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${Ze}-media-body`,...l.props};return i.createElement(Lm,null,i.createElement(Rm,{...d},u(),l.descriptionNode),r)}return null}const Lm=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Rm=_.default.div`width:${ee.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${X.light`
86
86
  background-color: ${p.color.background100};
87
87
  `}
88
- ${G.dark`
88
+ ${X.dark`
89
89
  background-color: ${p.color.background400};
90
90
  `}
91
- `,Dd=_.default.img`width:100%;height:100%;object-fit:cover;`,Pd=_.default.video`width:100%;height:100%;object-fit:cover;`,st=({className:e,children:t,size:n=26})=>i.createElement(Fd,{className:e,$size:n},t??i.createElement(W,{type:"spinner",size:n})),Fd=_.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>$e(e)};height:${({$size:e})=>$e(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,un=3,pn=6,Bd=pn/un,Hd=un,Ud=pn,Vd=e=>{const t=e%un;return{gridColumns:t>0?pn:un,wideBottomCount:t}},Rs=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=ee(),o=e.length;if(o===0)return null;const{gridColumns:s,wideBottomCount:a=0}=Vd(o),l=!!n&&!t,c=e.map(C=>C.type??"image/*"),d=c.find(C=>C.startsWith("image")),m=c.find(C=>!C.startsWith("image")),h=l&&d?r.file.openDescription(d):void 0,g=l&&m?r.file.openDescription(m):void 0;return i.createElement(zd,{$width:K.BODY_MAX_WIDTH,$columns:s},e.map((C,b)=>{const v=a>0&&b>=o-a,f=()=>!t&&(n==null?void 0:n(b)),y=C.type??"image/*",E=l?r.file.buttonLikeInteractivePreview({name:C.name||"",mimeType:y,onActivate:f}):r.file.preview({name:C.name||"",mimeType:y});let x=1;return s===pn&&(v?x=a===1?Ud:Hd:x=Bd),i.createElement(Wd,{key:C.url,$clickable:l,$itemSpan:x,$isPending:t,...E.props},i.createElement(Gd,{src:C.url,alt:C.name||""}),t&&i.createElement(qd,null))}),h==null?void 0:h.descriptionNode,g==null?void 0:g.descriptionNode)},Gd=({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(Kd,null,i.createElement(st,{size:20},i.createElement(W,{type:"spinner",color:"textLowEmphasis",size:20}))),o?i.createElement(Yd,null,i.createElement(W,{type:"photo",color:"textLowEmphasis",size:24})):i.createElement(jd,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>s(!0)}))},zd=_.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Wd=_.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${G.light`
91
+ `,Om=_.default.img`width:100%;height:100%;object-fit:cover;`,Nm=_.default.video`width:100%;height:100%;object-fit:cover;`,dt=({className:e,children:t,size:n=26})=>i.createElement(Dm,{className:e,$size:n},t??i.createElement(Z,{type:"spinner",size:n})),Dm=_.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ye(e)};height:${({$size:e})=>Ye(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Qo=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=se(),s=e.length;if(s===0)return null;const o=el(s),a=!!n&&!t,l=e.map(f=>f.type??"image/*"),u=l.find(f=>f.startsWith("image")),d=l.find(f=>!f.startsWith("image")),m=a&&u?r.file.openDescription(u):void 0,h=a&&d?r.file.openDescription(d):void 0;return i.createElement(Pm,{$width:ee.BODY_MAX_WIDTH,$columns:o},e.map((f,v)=>{const{columnSpan:b}=tl({index:v,itemCount:s}),C=()=>!t&&(n==null?void 0:n(v)),g=f.type??"image/*",y=a?r.file.buttonLikeInteractivePreview({name:f.name||"",mimeType:g,onActivate:C}):r.file.preview({name:f.name||"",mimeType:g});return i.createElement(Fm,{key:f.url,$clickable:a,$itemSpan:b,$isPending:t,...y.props},i.createElement($m,{src:f.url,alt:f.name||""}),t&&i.createElement(Bm,null))}),m==null?void 0:m.descriptionNode,h==null?void 0:h.descriptionNode)},$m=({src:e,alt:t})=>{const[n,r]=c.useState(!1),[s,o]=c.useState(!1);return i.createElement(i.Fragment,null,!n&&!s&&i.createElement(Um,null,i.createElement(dt,{size:20},i.createElement(Z,{type:"spinner",color:"textLowEmphasis",size:20}))),s?i.createElement(Hm,null,i.createElement(Z,{type:"photo",color:"textLowEmphasis",size:24})):i.createElement(Gm,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},Pm=_.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,Fm=_.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${X.light`
92
92
  background-color: ${p.color.background100};
93
93
  `}
94
- ${G.dark`
94
+ ${X.dark`
95
95
  background-color: ${p.color.background400};
96
96
  `}
97
97
  ${e=>e.$itemSpan&&e.$itemSpan>1&&`
@@ -111,19 +111,19 @@
111
111
  }
112
112
  `}
113
113
  }
114
- `,qd=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${p.color.overlay.dark};pointer-events:none;`,Os=_.default.div`display:flex;align-items:center;justify-content:center;`,Kd=_.default(Os)`position:absolute;inset:0;`,Yd=_.default(Os)`position:absolute;inset:0;${G.light`
114
+ `,Bm=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${p.color.overlay.dark};pointer-events:none;`,ei=_.default.div`display:flex;align-items:center;justify-content:center;`,Um=_.default(ei)`position:absolute;inset:0;`,Hm=_.default(ei)`position:absolute;inset:0;${X.light`
115
115
  background-color: ${p.color.background200};
116
116
  `}
117
- ${G.dark`
117
+ ${X.dark`
118
118
  background-color: ${p.color.background500};
119
119
  `}
120
- `,jd=_.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Xd=({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(Zd,null,i.createElement(Rs,{images:e,onClickImage:o}),t)},Zd=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${K.GAP_GROUPED}px;`,Jd="✱",Ns=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Jd}+)`,"g");return e.replace(t,(n,r,o,s)=>r?n:s?`<span id=${Rd} aria-label="masked-text">${s}</span>`:n)},Qd=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),mo=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)}}},em=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs"))).MarkdownText})),tm=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock}));function nm(e){var o,s;const t=e.maxBodyWidth??K.BODY_MAX_WIDTH,n=u.useMemo(()=>Pi(e.message,Ns),[e.message]),r={id:`${Fe}-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(ho,{...r},e.children):null:i.createElement(ho,{...r},n.map((a,l)=>a.type==="text"?i.createElement(go,{key:l,variant:"body3"},i.createElement(ln,{fallback:a.value},i.createElement(em,{onClickImage:c=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:c,type:"image/*"})}},a.value))):a.type==="code"?i.createElement(ln,{key:l,fallback:i.createElement(go,{variant:"body3"},a.value)},i.createElement(tm,{code:a.value,language:a.language})):null),e.children)}const ho=_.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})=>O.css`
120
+ `,Gm=_.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Vm=({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(zm,null,i.createElement(Qo,{images:e,onClickImage:s}),t)},zm=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,qm="✱",ti=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${qm}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${Mm} aria-label="masked-text">${o}</span>`:n)},Wm=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),As=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)}}},Ym=c.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs"))).MarkdownText})),xs=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?c.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function Km(e){var s,o;const t=e.maxBodyWidth??ee.BODY_MAX_WIDTH,n=c.useMemo(()=>Ji(e.message,ti),[e.message]),r={id:`${Ze}-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(Ts,{...r},e.children):null:i.createElement(Ts,{...r},n.map((a,l)=>a.type==="text"?i.createElement(Is,{key:l,variant:"body3"},i.createElement(mn,{fallback:a.value},i.createElement(Ym,{onClickImage:u=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:u,type:"image/*"})}},a.value))):a.type==="code"?xs?i.createElement(mn,{key:l,fallback:i.createElement(Is,{variant:"body3"},a.value)},i.createElement(xs,{code:a.value,language:a.language})):i.createElement(jm,{key:l},i.createElement("code",null,a.value)):null),e.children)}const Ts=_.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})=>P.css`
121
121
  color: ${t||e.colors.messageIncoming.text};
122
- ${r==="bubble"?O.css`background-color:${n||e.colors.messageIncoming.background};border-radius:12px;overflow:hidden;padding:12px 0;`:O.css`background-color:transparent;border-radius:0;overflow:visible;padding:0;`}
122
+ ${r==="bubble"?P.css`background-color:${n||e.colors.messageIncoming.background};border-radius:12px;overflow:hidden;padding:12px 0;`:P.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
- `,go=_.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`;function $s({id:e,src:t,size:n=56,onClick:r,style:o,...s}){return i.createElement(rm,{id:e,tabIndex:r?0:void 0,onClick:r,$size:$e(n),style:o,...s},t?i.createElement(om,{src:t,alt:""}):i.createElement(W,{type:"user",size:n}))}const rm=_.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:${p.themedColor.bg_100_500};&:focus{outline:none;}${_e}`,om=_.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,sm=({sender:e,isBotMessage:t})=>{const n=`${Fe}-sender-avatar`;return t&&!e.profileUrl?i.createElement(im,{id:n},i.createElement(W,{type:"delight",size:"100%"})):i.createElement($s,{id:n,size:K.AVATAR_SIZE,src:e.profileUrl})},im=_.default.div`flex-shrink:0;width:${K.AVATAR_SIZE}px;height:${K.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;}}`,am=({sender:e})=>i.createElement(lm,{id:`${Fe}-sender-name`,variant:"caption1",color:p.themedColor.textMidEmphasis},e.nickname),lm=_.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;`,cm=({createdAt:e})=>{const{stringSet:t,format:n}=Q();return e?i.createElement($,{id:`${Fe}-sent-time`,variant:"caption4",color:p.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Ds="(prefers-reduced-motion: reduce)",um=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Ds).matches,Ps=()=>{const[e,t]=u.useState(um);return u.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(Ds);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},dm=({thinkingMessage:e,customStyle:t})=>{const n=Ps();return e?i.createElement(gm,{$prefersReducedMotion:n},i.createElement(fm,null,e),!n&&i.createElement(pm,null)):i.createElement(mm,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>i.createElement(hm,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},mm=_.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};`,hm=_.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;}`,gm=_.default.div.attrs({id:`${Fe}-typing-indicator`})`
126
+ `,Is=_.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,jm=_.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 ni({id:e,src:t,size:n=56,onClick:r,style:s,...o}){return i.createElement(Xm,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ye(n),style:s,...o},t?i.createElement(Zm,{src:t,alt:""}):i.createElement(Z,{type:"user",size:n}))}const Xm=_.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:${p.themedColor.bg_100_500};&:focus{outline:none;}${Ie}`,Zm=_.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,Jm=({sender:e,isBotMessage:t})=>{const n=`${Ze}-sender-avatar`;return t&&!e.profileUrl?i.createElement(Qm,{id:n},i.createElement(Z,{type:"delight",size:"100%"})):i.createElement(ni,{id:n,size:ee.AVATAR_SIZE,src:e.profileUrl})},Qm=_.default.div`flex-shrink:0;width:${ee.AVATAR_SIZE}px;height:${ee.AVATAR_SIZE}px;box-sizing:border-box;padding:4px;border-radius:50%;display:flex;justify-content:center;align-items:center;background-color:${({theme:e})=>e.colors.base.primary}!important;ellipse,path{fill:${({theme:e})=>e.colors.base.primaryContrastContent}!important;}}`,eh=({sender:e})=>i.createElement(th,{id:`${Ze}-sender-name`,variant:"caption1",color:p.themedColor.textMidEmphasis},e.nickname),th=_.default(B)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,nh=({createdAt:e})=>{const{stringSet:t,format:n}=re();return e?i.createElement(B,{id:`${Ze}-sent-time`,variant:"caption4",color:p.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},ri="(prefers-reduced-motion: reduce)",rh=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(ri).matches,si=()=>{const[e,t]=c.useState(rh);return c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(ri);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},sh=({thinkingMessage:e,customStyle:t})=>{const n=si();return e?i.createElement(ah,{$prefersReducedMotion:n},i.createElement(lh,null,e),!n&&i.createElement(ch,null)):i.createElement(oh,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>i.createElement(ih,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},oh=_.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};`,ih=_.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;}`,ah=_.default.div.attrs({id:`${Ze}-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
- `,fm=_.default($).attrs({variant:"body3"})`
138
+ `,lh=_.default(B).attrs({variant:"body3"})`
139
139
  white-space: pre-wrap;
140
140
  word-break: break-word;
141
141
  color: ${p.themedColor.textHighEmphasis};
142
- `,pm=_.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=Fr(e.colors.base.background,.5),n=Fr(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
143
- `,_m=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>pr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return i.createElement(Em,{id:`${Fe}-ext-cta-button`,onClick:r},i.createElement(bm,{variant:"button"},n.label))},Em=_.default.button.attrs({type:"button"})`
142
+ `,ch=_.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=Hr(e.colors.base.background,.5),n=Hr(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
143
+ `,uh=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>br(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return i.createElement(dh,{id:`${Ze}-ext-cta-button`,onClick:r},i.createElement(mh,{variant:"button"},n.label))},dh=_.default.button.attrs({type:"button"})`
144
144
  all: unset;
145
145
  display: flex;
146
146
  width: 100%;
@@ -152,12 +152,12 @@
152
152
  padding: 8px;
153
153
  color: ${p.themedColor.textHighEmphasis};
154
154
  background-color: ${p.color.background50};
155
- ${G.dark`
155
+ ${X.dark`
156
156
  background-color: ${p.color.ondark.textDisabled};
157
157
  `}
158
158
 
159
- ${_e}
160
- `,bm=_.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Cm=({extendedMessagePayload:e,onClickCitation:t=n=>pr(n.link)})=>{const{stringSet:n}=Q(),{theme:r}=lr(),o=e==null?void 0:e.citations;return!o||o.length===0?null:i.createElement(vm,{id:`${Fe}-ext-citation`},i.createElement(ym,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),i.createElement(Sm,null,o.map((s,a)=>i.createElement(xm,{key:`${s.embedding_id}-${a}`,onClick:()=>t(s)},i.createElement(W,{type:"source",size:16,color:r.colors.messageIncoming.text}),i.createElement(Am,{variant:"body3",color:r.colors.messageIncoming.text},s.title)))))},vm=_.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,ym=_.default($)`opacity:0.5;`,Sm=_.default.div`display:flex;flex-direction:column;gap:8px;`,Am=_.default($)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,xm=_.default.button.attrs({type:"button"})`
159
+ ${Ie}
160
+ `,mh=_.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,hh=({extendedMessagePayload:e,onClickCitation:t=n=>br(n.link)})=>{const{stringSet:n}=re(),{theme:r}=dr(),s=e==null?void 0:e.citations;return!s||s.length===0?null:i.createElement(fh,{id:`${Ze}-ext-citation`},i.createElement(gh,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),i.createElement(ph,null,s.map((o,a)=>i.createElement(Eh,{key:`${o.embedding_id}-${a}`,onClick:()=>t(o)},i.createElement(Z,{type:"source",size:16,color:r.colors.messageIncoming.text}),i.createElement(_h,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},fh=_.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,gh=_.default(B)`opacity:0.5;`,ph=_.default.div`display:flex;flex-direction:column;gap:8px;`,_h=_.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Eh=_.default.button.attrs({type:"button"})`
161
161
  background: none;
162
162
  border: none;
163
163
  padding: 0;
@@ -172,127 +172,127 @@
172
172
  &:hover {
173
173
  opacity: 0.5;
174
174
  }
175
- `,Tm=e=>i.createElement(i.Fragment,null),Im=({visible:e,onClose:t,children:n,"aria-label":r})=>i.createElement(ft,{rootElementId:ce.WINDOW,visible:e,onClose:t,"aria-label":r},i.createElement(Mm,null,n)),wm=({onClick:e,destructive:t,icon:n,initialFocus:r,children:o})=>i.createElement(km,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&i.createElement(Lm,null,i.createElement(W,{type:n,size:24,color:p.themedColor.primary})),o),Ke=Object.assign(Im,{ActionItem:wm}),km=_.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?p.themedColor.error:p.themedColor.textHighEmphasis};${_e}`,Lm=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Mm=_.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`,Rm=e=>e==="good"?be.AIAgentMessageFeedbackRating.GOOD:be.AIAgentMessageFeedbackRating.BAD,Cr=O.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,qt={good:{onlight:p.color.secondary.dark,ondark:p.color.secondary.light},bad:{onlight:p.color.error.dark,ondark:p.color.error.light}},Om={good:p.themedColor.secondary,bad:p.themedColor.error},Fs=e=>O.css`color:${qt[e].onlight};border-color:${qt[e].onlight};${G.dark`
176
- color: ${qt[e].ondark};
177
- border-color: ${qt[e].ondark};
175
+ `,bh=e=>i.createElement(i.Fragment,null),Ch=({visible:e,onClose:t,children:n,"aria-label":r})=>i.createElement(ut,{portalContainerId:ve.WINDOW,visible:e,onClose:t,"aria-label":r},i.createElement(Ah,null,n)),vh=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>i.createElement(yh,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&i.createElement(Sh,null,i.createElement(Z,{type:n,size:24,color:p.themedColor.primary})),s),tt=Object.assign(Ch,{ActionItem:vh}),yh=_.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?p.themedColor.error:p.themedColor.textHighEmphasis};${Ie}`,Sh=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Ah=_.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};`,Zn=e=>`${e}-filled`,xh=e=>e==="good"?Re.AIAgentMessageFeedbackRating.GOOD:Re.AIAgentMessageFeedbackRating.BAD,Sr=P.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,Kt={good:{onlight:p.color.secondary.dark,ondark:p.color.secondary.light},bad:{onlight:p.color.error.dark,ondark:p.color.error.light}},Th={good:p.themedColor.secondary,bad:p.themedColor.error},oi=e=>P.css`color:${Kt[e].onlight};border-color:${Kt[e].onlight};${X.dark`
176
+ color: ${Kt[e].ondark};
177
+ border-color: ${Kt[e].ondark};
178
178
  `}
179
- `,Nm=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:o="",onSubmit:s,isCommentEnabled:a=!1})=>{const{stringSet:l}=Q(),{rootElement:c}=gr(),d=He(c),[m,h]=u.useState(r),[g,C]=u.useState(o),[b,v]=u.useState(!1),f=u.useRef(!1),y=m??r??"good";u.useLayoutEffect(()=>{e?(h(r),C(o)):(h(void 0),C(""))},[e,r,o]),u.useEffect(()=>{if(!e)return;const S=k=>{const M=k;M.metaKey||M.altKey||M.ctrlKey||(f.current=!0)},I=()=>{f.current=!1,v(!1)};return d.addEventListener("keydown",S),d.addEventListener("pointerdown",I),()=>{d.removeEventListener("keydown",S),d.removeEventListener("pointerdown",I)}},[d,e]);const E=()=>{m&&(s({rating:m,comment:g.trim()||void 0}),t())},x=()=>{t()};return e?i.createElement(ft,{rootElementId:ce.WINDOW,visible:e,onClose:x,"aria-label":l.FEEDBACK_TITLE},i.createElement($m,null,i.createElement(Dm,null,i.createElement($,{variant:"h2",color:p.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),i.createElement(Pm,null,i.createElement(Fm,null,["good","bad"].map(S=>{const I=m===S,k=S==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD;return i.createElement(Bm,{key:S,$selected:I,$rating:S,onClick:()=>h(S),"data-sb-initial-focus":S===y?"true":void 0},i.createElement(W,{type:I?Xn(S):S,size:24,color:"currentColor"}),i.createElement($,{variant:"caption1",color:"currentColor"},k))})),a&&i.createElement(Hm,null,i.createElement($,{variant:"caption3",color:p.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),i.createElement(Um,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:S=>C(S.target.value),onFocus:()=>v(f.current),onBlur:()=>v(!1),maxLength:100,$focusVisible:b,"data-focus-visible":b?"true":"false"}))),i.createElement(Vm,null,i.createElement(Gm,{onClick:x},i.createElement($,{variant:"button",color:p.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),i.createElement(zm,{onClick:E,disabled:!m},i.createElement($,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT))))):null},$m=_.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,Dm=_.default.div`padding:24px;`,Pm=_.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,Fm=_.default.div`display:flex;gap:4px;`,Bm=_.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${p.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:${p.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Fs(t)}${Cr}`,Hm=_.default.div`display:flex;flex-direction:column;gap:6px;`,Um=_.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${p.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${p.themedColor.textHighEmphasis};background-color:${p.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${p.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&O.css`
179
+ `,Ih=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:a=!1})=>{const{stringSet:l}=re(),{rootElement:u}=Fo(),d=ct(u),[m,h]=c.useState(r),[f,v]=c.useState(s),[b,C]=c.useState(!1),g=c.useRef(!1),y=m??r??"good";c.useLayoutEffect(()=>{e?(h(r),v(s)):(h(void 0),v(""))},[e,r,s]),c.useEffect(()=>{if(!e)return;const A=k=>{const N=k;N.metaKey||N.altKey||N.ctrlKey||(g.current=!0)},w=()=>{g.current=!1,C(!1)};return d.addEventListener("keydown",A),d.addEventListener("pointerdown",w),()=>{d.removeEventListener("keydown",A),d.removeEventListener("pointerdown",w)}},[d,e]);const E=()=>{m&&(o({rating:m,comment:f.trim()||void 0}),t())},I=()=>{t()};return e?i.createElement(ut,{portalContainerId:ve.WINDOW,visible:e,onClose:I,"aria-label":l.FEEDBACK_TITLE},i.createElement(wh,null,i.createElement(Mh,null,i.createElement(B,{variant:"h2",color:p.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),i.createElement(kh,null,i.createElement(Lh,null,["good","bad"].map(A=>{const w=m===A,k=A==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD;return i.createElement(Rh,{key:A,$selected:w,$rating:A,onClick:()=>h(A),"data-sb-initial-focus":A===y?"true":void 0},i.createElement(Z,{type:w?Zn(A):A,size:24,color:"currentColor"}),i.createElement(B,{variant:"caption1",color:"currentColor"},k))})),a&&i.createElement(Oh,null,i.createElement(B,{variant:"caption3",color:p.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),i.createElement(Nh,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:f,onChange:A=>v(A.target.value),onFocus:()=>C(g.current),onBlur:()=>C(!1),maxLength:100,$focusVisible:b,"data-focus-visible":b?"true":"false"}))),i.createElement(Dh,null,i.createElement($h,{onClick:I},i.createElement(B,{variant:"button",color:p.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),i.createElement(Ph,{onClick:E,disabled:!m},i.createElement(B,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT))))):null},wh=_.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,Mh=_.default.div`padding:24px;`,kh=_.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,Lh=_.default.div`display:flex;gap:4px;`,Rh=_.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${p.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:${p.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&oi(t)}${Sr}`,Oh=_.default.div`display:flex;flex-direction:column;gap:6px;`,Nh=_.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${p.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${p.themedColor.textHighEmphasis};background-color:${p.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${p.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&P.css`
180
180
  outline: 2px solid ${p.themedColor.primary};
181
181
  outline-offset: 2px;
182
182
  `}
183
- `,Vm=_.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Bs=_.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;`,Gm=_.default(Bs)`background-color:transparent;${Cr}`,zm=_.default(Bs)`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};}`,Wm=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:o,extendedMessagePayload:s,onFeedbackUpdate:a})=>{const{stringSet:l}=Q(),{conversation:c}=ee(),[d,m]=u.useState(!1),[h,g]=u.useState(!1),[C,b]=u.useState(void 0),[v,f]=u.useState(""),y=u.useRef(null),E=u.useRef(null),x=u.useRef(null),S=u.useRef(!1),I=c.feedback,k=s==null?void 0:s.feedback,M=(k==null?void 0:k.rating)??"none";if(M!=="none"?!1:!!(n||!e||!r||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const F=R=>{R&&ve(()=>{const Y=R==="good"?y.current:E.current;Y==null||Y.focus()})},z=({restoreTrigger:R=!0}={})=>{g(!1),R&&F(x.current)},L=R=>{M==="none"?(b(R),f(""),m(!0)):(x.current=R,g(!0))},P=()=>{a==null||a(null),z()},N=()=>{S.current=!0,z({restoreTrigger:!1}),b(k==null?void 0:k.rating),f((k==null?void 0:k.comment)??""),m(!0)},w=R=>{S.current=!1,a==null||a(R),m(!1),F(x.current)},D=()=>{m(!1),S.current&&(S.current=!1,g(!0))};return t&&M!=="none"?i.createElement(fo,{role:"presentation",$horizontal:!0},i.createElement(qm,null,i.createElement(W,{type:Xn(M),size:12,color:Om[M]})),(k==null?void 0:k.comment)&&i.createElement(po,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):i.createElement(i.Fragment,null,i.createElement(fo,{role:"presentation"},i.createElement(Km,{role:"presentation"},["good","bad"].map(R=>{const Y=M===R,te=I.button(R,Y);return i.createElement(Ym,{key:R,$selected:Y,$rating:R,ref:R==="good"?y:E,...te.props,onClick:()=>L(R)},i.createElement(W,{type:Y?Xn(R):R,size:14,color:"currentColor"}))})),I.descriptionNode,M!=="none"&&(k==null?void 0:k.comment)&&i.createElement(po,{variant:"caption2"},k.comment)),i.createElement(Ke,{visible:h,onClose:z,...I.optionsBottomSheet},i.createElement(Ke.ActionItem,{onClick:N,initialFocus:!0},l.FEEDBACK_EDIT),i.createElement(Ke.ActionItem,{onClick:P,destructive:!0},l.FEEDBACK_REMOVE)),i.createElement(Nm,{visible:d,onClose:D,isEdit:M!=="none",initialRating:C,initialComment:v,onSubmit:w,isCommentEnabled:o}))},fo=_.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:${K.BODY_MAX_WIDTH}px;`,qm=_.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,Km=_.default.div`display:flex;gap:2px;`,Ym=_.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:${p.themedColor.textMidEmphasis};border:1px solid ${p.color.background200};background-color:transparent;${G.dark`
183
+ `,Dh=_.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,ii=_.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;`,$h=_.default(ii)`background-color:transparent;${Sr}`,Ph=_.default(ii)`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};}`,Fh=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:a})=>{const{stringSet:l}=re(),{conversation:u}=se(),[d,m]=c.useState(!1),[h,f]=c.useState(!1),[v,b]=c.useState(void 0),[C,g]=c.useState(""),y=c.useRef(null),E=c.useRef(null),I=c.useRef(null),A=c.useRef(!1),w=u.feedback,k=o==null?void 0:o.feedback,N=(k==null?void 0:k.rating)??"none";if(N!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const G=$=>{$&&Oe(()=>{const Q=$==="good"?y.current:E.current;Q==null||Q.focus()})},K=({restoreTrigger:$=!0}={})=>{f(!1),$&&G(I.current)},L=$=>{N==="none"?(b($),g(""),m(!0)):(I.current=$,f(!0))},V=()=>{a==null||a(null),K()},Y=()=>{A.current=!0,K({restoreTrigger:!1}),b(k==null?void 0:k.rating),g((k==null?void 0:k.comment)??""),m(!0)},x=$=>{A.current=!1,a==null||a($),m(!1),G(I.current)},D=()=>{m(!1),A.current&&(A.current=!1,f(!0))};return t&&N!=="none"?i.createElement(ws,{role:"presentation",$horizontal:!0},i.createElement(Bh,null,i.createElement(Z,{type:Zn(N),size:12,color:Th[N]})),(k==null?void 0:k.comment)&&i.createElement(Ms,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):i.createElement(i.Fragment,null,i.createElement(ws,{role:"presentation"},i.createElement(Uh,{role:"presentation"},["good","bad"].map($=>{const Q=N===$,ae=w.button($,Q);return i.createElement(Hh,{key:$,$selected:Q,$rating:$,ref:$==="good"?y:E,...ae.props,onClick:()=>L($)},i.createElement(Z,{type:Q?Zn($):$,size:14,color:"currentColor"}))})),w.descriptionNode,N!=="none"&&(k==null?void 0:k.comment)&&i.createElement(Ms,{variant:"caption2"},k.comment)),i.createElement(tt,{visible:h,onClose:K,...w.optionsBottomSheet},i.createElement(tt.ActionItem,{onClick:Y,initialFocus:!0},l.FEEDBACK_EDIT),i.createElement(tt.ActionItem,{onClick:V,destructive:!0},l.FEEDBACK_REMOVE)),i.createElement(Ih,{visible:d,onClose:D,isEdit:N!=="none",initialRating:v,initialComment:C,onSubmit:x,isCommentEnabled:s}))},ws=_.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${ee.BODY_MAX_WIDTH}px;`,Bh=_.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,Uh=_.default.div`display:flex;gap:2px;`,Hh=_.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:${p.themedColor.textMidEmphasis};border:1px solid ${p.color.background200};background-color:transparent;${X.dark`
184
184
  border: 1px solid ${p.color.background400};
185
185
  `}
186
186
 
187
- ${({$selected:e,$rating:t})=>e&&Fs(t)}
187
+ ${({$selected:e,$rating:t})=>e&&oi(t)}
188
188
 
189
- ${Cr}
190
- `,po=_.default($)`color:${p.themedColor.textMidEmphasis};${G.dark`
189
+ ${Sr}
190
+ `,Ms=_.default(B)`color:${p.themedColor.textMidEmphasis};${X.dark`
191
191
  color: ${p.themedColor.textHighEmphasis};
192
192
  `}
193
- `,vr=O.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;${_e}&:disabled{cursor:not-allowed;}`,_o=_.default.button`${vr};background-color:${p.themedColor.primary};color:${p.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,jm=_.default.button`${vr};color:${p.themedColor.primary};${G.light`
193
+ `,Ar=P.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;${Ie}&:disabled{cursor:not-allowed;}`,ks=_.default.button`${Ar};background-color:${p.themedColor.primary};color:${p.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,Gh=_.default.button`${Ar};color:${p.themedColor.primary};${X.light`
194
194
  background-color: ${p.color.background50};
195
195
  `};
196
- ${G.dark`
196
+ ${X.dark`
197
197
  background-color: ${p.color.background700};
198
198
  `};
199
199
 
200
200
  &:hover:not(:disabled) {
201
201
  opacity: 0.9;
202
202
  }
203
- `,Xm=_.default.button`${vr};background-color:transparent;color:${p.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,Zm=e=>{switch(e){case"primary":return _o;case"secondary":return jm;case"clear":return Xm;default:return _o}},Jm=_.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);}}`,Qm=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:o=!1,className:s,ariaLabel:a})=>{const l=()=>{switch(n){case"primary":return p.themedColor.textHighEmphasisInverse;case"secondary":return p.themedColor.primary;case"clear":return p.themedColor.textHighEmphasis;default:return p.themedColor.textHighEmphasisInverse}},c=Zm(n);return i.createElement(c,{onClick:t,disabled:r||o,className:s,"aria-label":a},o?i.createElement(Jm,null,i.createElement(W,{type:"spinner",size:22,color:l()})):i.createElement($,{variant:"button",color:l()},e))},eh=({children:e,className:t,style:n,id:r,role:o})=>i.createElement($,{variant:"caption4",color:p.themedColor.error,className:t,style:n,id:r,role:o},e),th=({id:e,children:t,className:n,style:r,required:o,ariaHidden:s=!1,"aria-hidden":a})=>{const{stringSet:l}=Q();return i.createElement($,{id:e,variant:"caption3",color:p.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":a??s},t,!o&&i.createElement("span",{style:{color:p.themedColor.textLowEmphasis}},` (${l.OPTIONAL})`))},nh=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:o=!1,className:s,disabled:a=!1,max:l,ariaLabel:c,required:d=!1})=>{const m=g=>{const b=g.target.value.replace(/[^0-9.-]/g,""),v=b.split("."),y=v.length>1?v[0]+"."+v.slice(1).join("").replace(/\./g,""):b;if(g.target.value=y,y===""||y==="-")t==null||t(null);else{const E=Number(y);if(!isNaN(E)){if(l!==void 0&&E>l)return;t==null||t(E)}}},h=e==null?"":String(e);return i.createElement(ah,{type:"text",value:h,onChange:m,placeholder:n,className:s,disabled:a||o,inputMode:"decimal","aria-label":c,"aria-required":d,"aria-disabled":a||o,$error:r,$submitted:o})},rh=O.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;${_e}&::placeholder{color:${p.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,oh=O.css`color:${p.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${G.light`
203
+ `,Vh=_.default.button`${Ar};background-color:transparent;color:${p.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,zh=e=>{switch(e){case"primary":return ks;case"secondary":return Gh;case"clear":return Vh;default:return ks}},qh=_.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);}}`,Wh=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...a})=>{const l=()=>{switch(n){case"primary":return p.themedColor.textHighEmphasisInverse;case"secondary":return p.themedColor.primary;case"clear":return p.themedColor.textHighEmphasis;default:return p.themedColor.textHighEmphasisInverse}},u=zh(n);return i.createElement(u,{onClick:t,disabled:r||s,className:o,...a},s?i.createElement(qh,null,i.createElement(Z,{type:"spinner",size:22,color:l()})):i.createElement(B,{variant:"button",color:l()},e))},Yh=({children:e,className:t,style:n,id:r,role:s})=>i.createElement(B,{variant:"caption4",color:p.themedColor.error,className:t,style:n,id:r,role:s},e),Kh=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:a}=re();return i.createElement(B,{id:e,variant:"caption3",color:p.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&i.createElement("span",{style:{color:p.themedColor.textLowEmphasis}},` (${a.OPTIONAL})`))},jh=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:a=!1,max:l,...u})=>{const d=h=>{const v=h.target.value.replace(/[^0-9.-]/g,""),b=v.split("."),g=b.length>1?b[0]+"."+b.slice(1).join("").replace(/\./g,""):v;if(h.target.value=g,g===""||g==="-")t==null||t(null);else{const y=Number(g);if(!isNaN(y)){if(l!==void 0&&y>l)return;t==null||t(y)}}},m=e==null?"":String(e);return i.createElement(ef,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:a||s,inputMode:"decimal",$error:r,$submitted:s,...u})},Xh=P.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;${Ie}&::placeholder{color:${p.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,Zh=P.css`color:${p.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${X.light`
204
204
  background-color: ${p.color.ondark.textMidEmphasis};
205
205
  `}
206
- ${G.dark`
206
+ ${X.dark`
207
207
  background-color: ${p.color.onlight.textLowEmphasis};
208
208
  `}
209
209
 
210
210
  &::placeholder {
211
211
  color: ${p.themedColor.textLowEmphasis};
212
212
  }
213
- `,sh=O.css`border:1px solid ${p.themedColor.error};color:${p.themedColor.textHighEmphasis};${G.light`
213
+ `,Jh=P.css`border:1px solid ${p.themedColor.error};color:${p.themedColor.textHighEmphasis};${X.light`
214
214
  background-color: ${p.color.background50};
215
215
  `}
216
- ${G.dark`
216
+ ${X.dark`
217
217
  background-color: ${p.color.onlight.textLowEmphasis};
218
218
  `}
219
- `,ih=O.css`border:1px solid ${p.themedColor.textDisabled};color:${p.themedColor.textHighEmphasis};${G.light`
219
+ `,Qh=P.css`border:1px solid ${p.themedColor.textDisabled};color:${p.themedColor.textHighEmphasis};${X.light`
220
220
  background-color: ${p.color.background50};
221
221
  `}
222
- ${G.dark`
222
+ ${X.dark`
223
223
  background-color: ${p.color.onlight.textLowEmphasis};
224
224
  `}
225
225
 
226
226
  &:focus {
227
227
  border-color: ${p.themedColor.primary};
228
228
  }
229
- `,ah=_.default.input`${rh}${({$error:e,$submitted:t})=>t?oh:e?sh:ih}`,lh=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))}}}},Hs=e=>{const{options:t,submitted:n=!1,error:r=!1,className:o,groupLabel:s}=e,{conversation:a}=ee(),l=e.multiple===!0,{selectedValues:c,handleOptionClick:d}=lh(e),m=l?void 0:a.form.singleSelectGroup(s),h=u.useRef([]),g=l?-1:Math.max(t.findIndex(b=>c.includes(b.value)),0),C=(b,v)=>{var E;if(l||n)return;let f=null;switch(b.key){case"ArrowRight":case"ArrowDown":f=(v+1)%t.length;break;case"ArrowLeft":case"ArrowUp":f=(v-1+t.length)%t.length;break;default:return}b.preventDefault();const y=t[f];y&&(d(y.value),(E=h.current[f])==null||E.focus())};return i.createElement(uh,{className:o,...m},t.map((b,v)=>{const f=c.includes(b.value),y=s?`${s}, ${b.label}`:b.label,E=l?a.form.multiSelectOption(y,f,n):a.form.singleSelectOption(y,f,n);return i.createElement(_h,{key:b.value,ref:x=>{h.current[v]=x},type:"button",$active:f,$submitted:n,$error:r,...E,disabled:n,onClick:()=>d(b.value),onKeyDown:x=>C(x,v),tabIndex:l?void 0:v===g?0:-1},i.createElement($,{variant:"caption1",color:ch(f,n)},b.label))}))},ch=(e,t)=>t?e?p.themedColor.textHighEmphasis:p.themedColor.textDisabled:e?p.themedColor.primary:p.themedColor.textMidEmphasis,uh=_.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,dh=O.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,mh=O.css`cursor:default;background-color:${p.color.ondark.textMidEmphasis};color:${p.themedColor.textHighEmphasis};${G.dark`
229
+ `,ef=_.default.input`${Xh}${({$error:e,$submitted:t})=>t?Zh:e?Jh:Qh}`,tf=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 u=t.filter(d=>d!==a);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,a];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},ai=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:a}=se(),l=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=tf(e),m=l?void 0:a.form.singleSelectGroup(o),h=c.useRef([]),f=l?-1:Math.max(t.findIndex(b=>u.includes(b.value)),0),v=(b,C)=>{var E;if(l||n)return;let g=null;switch(b.key){case"ArrowRight":case"ArrowDown":g=(C+1)%t.length;break;case"ArrowLeft":case"ArrowUp":g=(C-1+t.length)%t.length;break;default:return}b.preventDefault();const y=t[g];y&&(d(y.value),(E=h.current[g])==null||E.focus())};return i.createElement(rf,{className:s,...m},t.map((b,C)=>{const g=u.includes(b.value),y=o?`${o}, ${b.label}`:b.label,E=l?a.form.multiSelectOption(y,g,n):a.form.singleSelectOption(y,g,n);return i.createElement(df,{key:b.value,ref:I=>{h.current[C]=I},type:"button",$active:g,$submitted:n,$error:r,...E,disabled:n,onClick:()=>d(b.value),onKeyDown:I=>v(I,C),tabIndex:l?void 0:C===f?0:-1},i.createElement(B,{variant:"caption1",color:nf(g,n)},b.label))}))},nf=(e,t)=>t?e?p.themedColor.textHighEmphasis:p.themedColor.textDisabled:e?p.themedColor.primary:p.themedColor.textMidEmphasis,rf=_.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,sf=P.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,of=P.css`cursor:default;background-color:${p.color.ondark.textMidEmphasis};color:${p.themedColor.textHighEmphasis};${X.dark`
230
230
  background-color: transparent;
231
231
  border: 1px solid white;
232
232
  color: white;
233
233
  `}
234
- `,hh=O.css`cursor:default;${G.light`
234
+ `,af=P.css`cursor:default;${X.light`
235
235
  background-color: ${p.color.ondark.textMidEmphasis};
236
236
  color: ${p.themedColor.textDisabled};
237
237
  `}
238
- ${G.dark`
238
+ ${X.dark`
239
239
  background-color: ${p.color.onlight.textLowEmphasis};
240
240
  border: 1px solid ${p.color.onlight.textLowEmphasis};
241
241
  color: ${p.themedColor.textDisabled};
242
242
  `}
243
- `,gh=O.css`cursor:pointer;border:1px solid ${p.themedColor.primary};${G.light`
243
+ `,lf=P.css`cursor:pointer;border:1px solid ${p.themedColor.primary};${X.light`
244
244
  background-color: ${p.color.background50};
245
245
  color: ${p.themedColor.primary};
246
246
  `}
247
- ${G.dark`
247
+ ${X.dark`
248
248
  background-color: ${p.color.onlight.textLowEmphasis};
249
249
  color: ${p.themedColor.primary};
250
250
  `}
251
- `,fh=O.css`cursor:pointer;border:1px solid ${p.themedColor.textDisabled};${G.light`
251
+ `,cf=P.css`cursor:pointer;border:1px solid ${p.themedColor.textDisabled};${X.light`
252
252
  background-color: ${p.color.background50};
253
253
  color: ${p.themedColor.textMidEmphasis};
254
254
  `}
255
- ${G.dark`
255
+ ${X.dark`
256
256
  background-color: ${p.color.onlight.textLowEmphasis};
257
257
  color: ${p.themedColor.textMidEmphasis};
258
258
  `}
259
- `,ph=O.css`border-color:${p.themedColor.error}!important;`,_h=_.default.button`${dh}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?mh:hh;const r=e?gh:fh;return n?O.css`
260
- ${r} ${ph}
259
+ `,uf=P.css`border-color:${p.themedColor.error}!important;`,df=_.default.button`${sf}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?of:af;const r=e?lf:cf;return n?P.css`
260
+ ${r} ${uf}
261
261
  `:r}}
262
- `,Eh=e=>i.createElement(Hs,{...e,multiple:!1}),bh=e=>i.createElement(Hs,{...e,multiple:!0}),Ch=_.default.div`width:100%;height:1px;background-color:${p.themedColor.textDisabled};`,vh=({className:e})=>i.createElement(Ch,{className:e}),yh=({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,ariaLabel:m,required:h=!1,ariaInvalid:g=!1,ariaErrorMessage:C,"aria-label":b,"aria-required":v,"aria-invalid":f,"aria-errormessage":y,"aria-disabled":E})=>{const S={id:e,value:t,onChange:I=>{const k=I.target.value;d&&k.length>d||n==null||n(k)},placeholder:r,className:l,disabled:c||a,maxLength:d,"aria-label":b??m,"aria-required":v??h,"aria-disabled":E??(c||a),"aria-invalid":f??g,"aria-errormessage":y??C,$error:s,$submitted:a};return o==="multi-line"?i.createElement(Ah,{...S}):i.createElement(Sh,{...S})},Us=O.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;${_e}&::placeholder{color:${p.themedColor.textLowEmphasis};}`,Vs=O.css`color:${p.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${G.light`
262
+ `,mf=e=>i.createElement(ai,{...e,multiple:!1}),hf=e=>i.createElement(ai,{...e,multiple:!0}),ff=_.default.div`width:100%;height:1px;background-color:${p.themedColor.textDisabled};`,gf=({className:e})=>i.createElement(ff,{className:e}),pf=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:a=!1,className:l,disabled:u=!1,maxLength:d,...m})=>{const f={id:e,value:t,onChange:v=>{const b=v.target.value;d&&b.length>d||n==null||n(b)},placeholder:r,className:l,disabled:u||a,maxLength:d,$error:o,$submitted:a,...m};return s==="multi-line"?i.createElement(Ef,{...f}):i.createElement(_f,{...f})},li=P.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;${Ie}&::placeholder{color:${p.themedColor.textLowEmphasis};}`,ci=P.css`color:${p.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${X.light`
263
263
  background-color: ${p.color.ondark.textMidEmphasis};
264
264
  `}
265
- ${G.dark`
265
+ ${X.dark`
266
266
  background-color: ${p.color.onlight.textLowEmphasis};
267
267
  `}
268
268
 
269
269
  &::placeholder {
270
270
  color: ${p.themedColor.textLowEmphasis};
271
271
  }
272
- `,Gs=O.css`border:1px solid ${p.themedColor.error};color:${p.themedColor.textHighEmphasis};${G.light`
272
+ `,ui=P.css`border:1px solid ${p.themedColor.error};color:${p.themedColor.textHighEmphasis};${X.light`
273
273
  background-color: ${p.color.background50};
274
274
  `}
275
- ${G.dark`
275
+ ${X.dark`
276
276
  background-color: ${p.color.onlight.textLowEmphasis};
277
277
  `}
278
- `,zs=O.css`border:1px solid ${p.themedColor.textDisabled};color:${p.themedColor.textHighEmphasis};${G.light`
278
+ `,di=P.css`border:1px solid ${p.themedColor.textDisabled};color:${p.themedColor.textHighEmphasis};${X.light`
279
279
  background-color: ${p.color.background50};
280
280
  `}
281
- ${G.dark`
281
+ ${X.dark`
282
282
  background-color: ${p.color.onlight.textLowEmphasis};
283
283
  `}
284
284
 
285
285
  &:focus {
286
286
  border-color: ${p.themedColor.primary};
287
287
  }
288
- `,Sh=_.default.input`${Us};height:36px;${({$error:e,$submitted:t})=>t?Vs:e?Gs:zs}`,Ah=_.default.textarea`${Us};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Vs:e?Gs:zs}`,xh=({children:e,className:t,style:n})=>i.createElement($,{variant:"button",color:p.themedColor.textHighEmphasis,className:t,style:n},e),fe={Title:xh,Label:th,ErrorLabel:eh,Separator:vh,Button:Qm,TextInput:yh,NumberInput:nh,SingleSelect:Eh,MultiSelect:bh},Th=1,Ih=new Set(["text","number","single-select","multi-select"]),wh=e=>{var y;const t=(y=e.extendedMessagePayload)==null?void 0:y.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=Q(),{conversation:r}=ee(),[o,s]=u.useState({submitting:!1,canceling:!1}),[a,l]=u.useState({visible:!1}),{state:c,fields:d,submit:m,cancel:h,updateFieldValue:g}=Pl(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 x;return(x=e.onSubmitForm)==null?void 0:x.call(e,{key:t.key,data:E})},onCancel:()=>{var E;return(E=e.onCancelForm)==null?void 0:E.call(e,{key:t.key})}}),C=c==="submitted",b=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}))}},v=async()=>{s(E=>({...E,canceling:!0}));try{await h()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{s(E=>({...E,canceling:!1}))}},f=u.useMemo(()=>{const E=()=>t.version>Th,x=()=>t.fields.some(S=>!Ih.has(S.type));return E()||x()?{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:f.visible?i.createElement(u.Fragment,null,i.createElement(Eo,{$maxWidth:e.maxBodyWidth??K.BODY_MAX_WIDTH},i.createElement(fe.Title,null,t.title),i.createElement(kh,null,d.map(E=>i.createElement(Lh,{key:E.key},i.createElement(fe.Label,{style:{marginBottom:"6px"},required:E.required},E.label),E.type==="text"&&i.createElement(fe.TextInput,{value:E.value||"",placeholder:E.placeholder,onChange:x=>g(E.key,x),disabled:C,error:!!E.error,submitted:C,variant:E.layout==="multiline"?"multi-line":"single-line",maxLength:E.maxLength,ariaLabel:E.label,required:E.required}),E.type==="number"&&i.createElement(fe.NumberInput,{value:E.value||null,placeholder:E.placeholder,onChange:x=>g(E.key,x),disabled:C,error:!!E.error,submitted:C,max:E.max,ariaLabel:E.label,required:E.required}),E.type==="single-select"&&i.createElement(fe.SingleSelect,{options:E.options.map(x=>({label:x,value:x})),value:E.value||"",onChange:x=>g(E.key,x),submitted:C,groupLabel:E.label}),E.type==="multi-select"&&i.createElement(fe.MultiSelect,{options:E.options.map(x=>({label:x,value:x})),value:E.value||[],onChange:x=>g(E.key,x),submitted:C,maxSelect:E.maxSelect,groupLabel:E.label}),E.error&&i.createElement(fe.ErrorLabel,{style:{marginTop:"4px"}},E.error)))),i.createElement(fe.Separator,null),i.createElement(Mh,null,i.createElement(fe.Button,{variant:C?"clear":"primary",ariaLabel:r.form.button(C?n.SUBMITTED:n.BUTTON__SUBMIT)["aria-label"],onClick:b,disabled:C||o.canceling,loading:o.submitting},C?n.SUBMITTED:n.BUTTON__SUBMIT),c!=="submitted"&&i.createElement(fe.Button,{variant:"secondary",ariaLabel:r.form.button(n.BUTTON__CANCEL)["aria-label"],onClick:v,disabled:o.submitting,loading:o.canceling},n.BUTTON__CANCEL))),i.createElement(_r,{...a,onClose:()=>l({visible:!1,title:""})})):i.createElement(Eo,{$maxWidth:e.maxBodyWidth??K.BODY_MAX_WIDTH},i.createElement($,{variant:"body3"},f.reason),f.cancelable&&i.createElement(fe.Button,{variant:"primary",ariaLabel:r.form.button(n.BUTTON__CANCEL)["aria-label"],onClick:v,loading:o.canceling},n.BUTTON__CANCEL))},Eo=_.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>O.css`
288
+ `,_f=_.default.input`${li};height:36px;${({$error:e,$submitted:t})=>t?ci:e?ui:di}`,Ef=_.default.textarea`${li};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?ci:e?ui:di}`,bf=({children:e,className:t,style:n})=>i.createElement(B,{variant:"button",color:p.themedColor.textHighEmphasis,className:t,style:n},e),xe={Title:bf,Label:Kh,ErrorLabel:Yh,Separator:gf,Button:Wh,TextInput:pf,NumberInput:jh,SingleSelect:mf,MultiSelect:hf},Cf=1,vf=new Set(["text","number","single-select","multi-select"]),yf=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,Sf=e=>{var y;if(!yf)return null;const t=(y=e.extendedMessagePayload)==null?void 0:y.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=re(),{conversation:r}=se(),[s,o]=c.useState({submitting:!1,canceling:!1}),[a,l]=c.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=hc(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 I;return(I=e.onSubmitForm)==null?void 0:I.call(e,{key:t.key,data:E})},onCancel:()=>{var E;return(E=e.onCancelForm)==null?void 0:E.call(e,{key:t.key})}}),v=u==="submitted",b=async()=>{o(E=>({...E,submitting:!0}));try{await m()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{o(E=>({...E,submitting:!1}))}},C=async()=>{o(E=>({...E,canceling:!0}));try{await h()}catch(E){l({visible:!0,description:E instanceof Error?E.message:n.TRY_AGAIN})}finally{o(E=>({...E,canceling:!1}))}},g=c.useMemo(()=>{const E=()=>t.version>Cf,I=()=>t.fields.some(A=>!vf.has(A.type));return E()||I()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:g.visible?i.createElement(c.Fragment,null,i.createElement(Ls,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},i.createElement(xe.Title,null,t.title),i.createElement(Af,null,d.map(E=>i.createElement(xf,{key:E.key},i.createElement(xe.Label,{style:{marginBottom:"6px"},required:E.required},E.label),E.type==="text"&&i.createElement(xe.TextInput,{value:E.value||"",placeholder:E.placeholder,onChange:I=>f(E.key,I),disabled:v,error:!!E.error,submitted:v,variant:E.layout==="multiline"?"multi-line":"single-line",maxLength:E.maxLength,...r.form.textInput(E.label,E.required??!1,v)}),E.type==="number"&&i.createElement(xe.NumberInput,{value:E.value||null,placeholder:E.placeholder,onChange:I=>f(E.key,I),disabled:v,error:!!E.error,submitted:v,max:E.max,...r.form.numberInput(E.label,E.required??!1,v)}),E.type==="single-select"&&i.createElement(xe.SingleSelect,{options:E.options.map(I=>({label:I,value:I})),value:E.value||"",onChange:I=>f(E.key,I),submitted:v,groupLabel:E.label}),E.type==="multi-select"&&i.createElement(xe.MultiSelect,{options:E.options.map(I=>({label:I,value:I})),value:E.value||[],onChange:I=>f(E.key,I),submitted:v,maxSelect:E.maxSelect,groupLabel:E.label}),E.error&&i.createElement(xe.ErrorLabel,{style:{marginTop:"4px"}},E.error)))),i.createElement(xe.Separator,null),i.createElement(Tf,null,i.createElement(xe.Button,{variant:v?"clear":"primary",...r.form.button(v?n.SUBMITTED:n.BUTTON__SUBMIT),onClick:b,disabled:v||s.canceling,loading:s.submitting},v?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&i.createElement(xe.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL),onClick:C,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),i.createElement(Cr,{...a,onClose:()=>l({visible:!1,title:""})})):i.createElement(Ls,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},i.createElement(B,{variant:"body3"},g.reason),g.cancelable&&i.createElement(xe.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL),onClick:C,loading:s.canceling},n.BUTTON__CANCEL))},Ls=_.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>P.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
- `,kh=_.default.div`display:flex;flex-direction:column;gap:12px;`,Lh=_.default.div`display:flex;flex-direction:column;`,Mh=_.default.div`display:flex;flex-direction:column;gap:8px;`,Rh=e=>i.createElement(i.Fragment,null),Oh=new Set(["default"]),{MessageTemplate:Nh}=wi.createMessageTemplate({parser:Bn.parser,renderer:Bn.renderer,Container:e=>i.createElement("div",{...e})}),$h=e=>i.createElement(ln,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},i.createElement(Dh,{...e})),Dh=({extendedMessagePayload:e,onGetCachedMessageTemplate:t=()=>null,onRequestMessageTemplate:n,onHandleTemplateInternalAction:r=oe})=>{const o=e==null?void 0:e.message_template;if(!Oh.has((o==null?void 0:o.type)??"default"))throw new Error("Unsupported template type");if(!n)throw new Error("onRequestMessageTemplate is required");const a=o==null?void 0:o.key;if(!a)throw new Error("Template key is missing");const{theme:l}=gr(),c=Il({onRequestTemplate:n,onGetCachedTemplate:t,theme:l.selectedTheme,templateKey:a,variables:o==null?void 0:o.variables,viewVariables:o==null?void 0:o.view_variables,aiAgentColorVariables:l.aiAgentColorVariables});return i.createElement(Ph,{id:`${Fe}-ext-message-template`},i.createElement(Bn.MessageProvider,{handleInternalAction:(d,m)=>{d.stopPropagation(),r==null||r(m)}},i.createElement(Nh,{templateItems:c.body.items,templateVersion:c.version})))},Ph=_.default.div`box-sizing:border-box;overflow:hidden;width:100%;`,Fh=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=ee(),[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(Bh,{id:`${Fe}-ext-suggested-replies`,role:"presentation",$type:n},l.map((d,m)=>{const h=a.item(d);return i.createElement(Hh,{key:m,$type:n,...h.props,onClick:()=>c(d)},i.createElement(Uh,{variant:"body3"},d))}),a.descriptionNode)},Bh=_.default.div`margin:16px 0;padding:0 ${K.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?Vh:Gh};`,Hh=_.default.button.attrs({type:"button"})`
295
+ `,Af=_.default.div`display:flex;flex-direction:column;gap:12px;`,xf=_.default.div`display:flex;flex-direction:column;`,Tf=_.default.div`display:flex;flex-direction:column;gap:8px;`,If=e=>i.createElement(i.Fragment,null),Rs=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?c.lazy(()=>Promise.resolve().then(()=>require("./cjs/BjKg30ip.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,wf=e=>Rs?i.createElement(mn,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},i.createElement(Rs,{...e})):null,Mf=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=se(),[s,o]=c.useState(!1),{suggestedReplies:a}=r,l=(e==null?void 0:e.suggested_replies)??[];if(l.length===0||s)return null;const u=d=>{t&&(t({reply:d}),o(!0))};return i.createElement(kf,{id:`${Ze}-ext-suggested-replies`,role:"presentation",$type:n},l.map((d,m)=>{const h=a.item(d);return i.createElement(Lf,{key:m,$type:n,...h.props,onClick:()=>u(d)},i.createElement(Rf,{variant:"body3"},d))}),a.descriptionNode)},kf=_.default.div`margin:16px 0;padding:0 ${ee.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?Of:Nf};`,Lf=_.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: ${p.themedColor.bg_100_500};
311
311
  }
312
312
 
313
- ${_e}
313
+ ${Ie}
314
314
 
315
- ${({$type:e,theme:t})=>O.css`${e==="vertical"?zh:Wh};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
316
- `,Uh=_.default($)`color:inherit;`,Vh=O.css`flex-direction:column;align-items:flex-end;`,Gh=O.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,zh=O.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,Wh=O.css`white-space:nowrap;`,qh=e=>{const{components:t}=Je.useContext(),{stringSet:n}=Q(),r=Vo(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})},Kh=e=>i.createElement(Ws,{...e,testerMode:!1}),Je=Pe({template:Kh,components:{SenderName:am,SenderAvatar:sm,SentTime:cm,MessageBody:qh,TextMessageBody:nm,MediaMessageBody:Od,FileMessageBody:Ld,MultipleFilesMessageBody:Xd,TypingIndicator:dm,SuggestedReplies:Fh,MessageTemplate:$h,CustomMessageTemplate:Tm,CTAButton:_m,Citation:Cm,Form:wh,Feedback:Wm,MessageLogs:Rh}}),Yh=/(?:!\[[^\]]*]\([^)]+\)|\[[^\]]+]\([^)]+\)|https?:\/\/\S+|www\.\S+)/i,jh=e=>e?Yh.test(e):!1,Ws=e=>{var x,S,I,k,M,U,F;const{components:t}=Je.useContext(),{streamText:n,isAnimating:r}=Kl({text:e.message,enabled:e.isStreaming,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)&&!((S=o.extendedMessagePayload)!=null&&S.form.canceled_at),d=!!((I=o.extendedMessagePayload)!=null&&I.message_template),m=!!((k=o.extendedMessagePayload)!=null&&k.cta_button),h=!!((M=o.extendedMessagePayload)!=null&&M.citations)&&o.extendedMessagePayload.citations.length>0,g=!!o.createdAt,C=m||h,b=o.messageType==="user"&&!jh(o.message),v=o.groupType==="top"||o.groupType==="single",f=o.groupType==="bottom"||o.groupType==="single",y=a||!l?0:K.AVATAR_SIZE,E=z=>b?i.createElement(eg,null,z):z;return i.createElement(Xh,{$marginBottom:s?0:hn(o.groupType)},v&&i.createElement(Qh,{"aria-hidden":"true"},!a&&l&&i.createElement(t.SenderAvatar,{...o}),i.createElement(t.SenderName,{...o})),i.createElement(ng,null,i.createElement(Nn,{$extraStartPadding:y},s?i.createElement(t.TypingIndicator,{...o}):C?i.createElement(Zh,{$maxWidth:o.maxBodyWidth??K.BODY_MAX_WIDTH},E(i.createElement(t.MessageBody,{...o,surface:"plain"})),m&&i.createElement(Jh,{$marginTop:12,$paddingInline:12},i.createElement(t.CTAButton,{...o})),h&&i.createElement(t.Citation,{...o})):E(i.createElement(t.MessageBody,{...o}))),d&&i.createElement(bo,{$startPadding:0,$endPadding:0},i.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??i.createElement(Nn,{$extraStartPadding:y},i.createElement(t.MessageBody,{...o,messageType:"user",message:((F=(U=o.extendedMessagePayload)==null?void 0:U.message_template)==null?void 0:F.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??i.createElement(Nn,{$extraStartPadding:y},i.createElement(t.TypingIndicator,{...o}))})),i.createElement(t.CustomMessageTemplate,{...o}),c&&i.createElement(bo,{$extraStartPadding:y},i.createElement(t.Form,{...o}))),f&&g&&i.createElement(tg,{$extraStartPadding:y+8,"aria-hidden":"true"},i.createElement(t.SentTime,{...o})),i.createElement(u.Fragment,null,!s&&i.createElement(Ot,{$extraStartPadding:y+8},i.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&i.createElement(t.SuggestedReplies,{...o}),i.createElement(t.MessageLogs,{...o})))},Xh=_.default.div.attrs({role:"presentation"})`
315
+ ${({$type:e,theme:t})=>P.css`${e==="vertical"?Df:$f};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
316
+ `,Rf=_.default(B)`color:inherit;`,Of=P.css`flex-direction:column;align-items:flex-end;`,Nf=P.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,Df=P.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,$f=P.css`white-space:nowrap;`,Pf=e=>{const{components:t}=rt.useContext(),{stringSet:n}=re(),r=no(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})},Ff=e=>i.createElement(mi,{...e,testerMode:!1}),rt=qe({template:Ff,components:{SenderName:eh,SenderAvatar:Jm,SentTime:nh,MessageBody:Pf,TextMessageBody:Km,MediaMessageBody:km,FileMessageBody:Im,MultipleFilesMessageBody:Vm,TypingIndicator:sh,SuggestedReplies:Mf,MessageTemplate:wf,CustomMessageTemplate:bh,CTAButton:uh,Citation:hh,Form:Sf,Feedback:Fh,MessageLogs:If}}),Bf=/(?:!\[[^\]]*]\([^)]+\)|\[[^\]]+]\([^)]+\)|https?:\/\/\S+|www\.\S+)/i,Uf=e=>e?Bf.test(e):!1,mi=e=>{var I,A,w,k,N,W,G;const{components:t}=rt.useContext(),{streamText:n,isAnimating:r}=Ac({text:e.message,enabled:e.isStreaming,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,u=!!((I=s.extendedMessagePayload)!=null&&I.form)&&!((A=s.extendedMessagePayload)!=null&&A.form.canceled_at),d=!!((w=s.extendedMessagePayload)!=null&&w.message_template),m=!!((k=s.extendedMessagePayload)!=null&&k.cta_button),h=!!((N=s.extendedMessagePayload)!=null&&N.citations)&&s.extendedMessagePayload.citations.length>0,f=!!s.createdAt,v=m||h,b=s.messageType==="user"&&!Uf(s.message),C=s.groupType==="top"||s.groupType==="single",g=s.groupType==="bottom"||s.groupType==="single",y=a||!l?0:ee.AVATAR_SIZE,E=K=>b?i.createElement(qf,null,K):K;return i.createElement(Hf,{$marginBottom:o?0:gn(s.groupType)},C&&i.createElement(zf,{"aria-hidden":"true"},!a&&l&&i.createElement(t.SenderAvatar,{...s}),i.createElement(t.SenderName,{...s})),i.createElement(Yf,null,i.createElement($n,{$extraStartPadding:y},o?i.createElement(t.TypingIndicator,{...s}):v?i.createElement(Gf,{$maxWidth:s.maxBodyWidth??ee.BODY_MAX_WIDTH},E(i.createElement(t.MessageBody,{...s,surface:"plain"})),m&&i.createElement(Vf,{$marginTop:12,$paddingInline:12},i.createElement(t.CTAButton,{...s})),h&&i.createElement(t.Citation,{...s})):E(i.createElement(t.MessageBody,{...s}))),d&&i.createElement(Os,{$startPadding:0,$endPadding:0},i.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??i.createElement($n,{$extraStartPadding:y},i.createElement(t.MessageBody,{...s,messageType:"user",message:((G=(W=s.extendedMessagePayload)==null?void 0:W.message_template)==null?void 0:G.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??i.createElement($n,{$extraStartPadding:y},i.createElement(t.TypingIndicator,{...s}))})),i.createElement(t.CustomMessageTemplate,{...s}),u&&i.createElement(Os,{$extraStartPadding:y},i.createElement(t.Form,{...s}))),g&&f&&i.createElement(Wf,{$extraStartPadding:y+8,"aria-hidden":"true"},i.createElement(t.SentTime,{...s})),i.createElement(c.Fragment,null,!o&&i.createElement($t,{$extraStartPadding:y+8},i.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&i.createElement(t.SuggestedReplies,{...s}),i.createElement(t.MessageLogs,{...s})))},Hf=_.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
- `,Ot=_.default.div.attrs({role:"presentation"})`
321
+ `,$t=_.default.div.attrs({role:"presentation"})`
322
322
  display: flex;
323
323
  align-self: stretch;
324
324
  justify-content: flex-start;
325
- ${({$startPadding:e=K.HORIZONTAL_PADDING,$endPadding:t=K.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
325
+ ${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
326
326
  padding-inline: ${e+n}px ${t}px;
327
327
  `}
328
- `,Zh=_.default.div.attrs({role:"presentation"})`
328
+ `,Gf=_.default.div.attrs({role:"presentation"})`
329
329
  display: flex;
330
330
  flex-direction: column;
331
331
  min-width: 0;
@@ -333,57 +333,57 @@
333
333
  border-radius: 12px;
334
334
  overflow: hidden;
335
335
  padding: 12px 0;
336
- ${({theme:e})=>O.css`color:${e.colors.messageIncoming.text};background-color:${e.colors.messageIncoming.background};`}
337
- `,Jh=_.default.div.attrs({role:"presentation"})`
336
+ ${({theme:e})=>P.css`color:${e.colors.messageIncoming.text};background-color:${e.colors.messageIncoming.background};`}
337
+ `,Vf=_.default.div.attrs({role:"presentation"})`
338
338
  display: flex;
339
339
  flex-direction: column;
340
340
  min-width: 0;
341
- ${({$marginTop:e=0,$paddingInline:t=0})=>O.css`margin-top:${e}px;padding-inline:${t}px;`}
342
- `,Qh=_.default(Ot)`display:flex;flex-direction:row;align-items:center;gap:8px;`,Nn=_.default(Ot)`display:flex;`,eg=_.default.div.attrs({"aria-hidden":"true",role:"presentation"})``,tg=_.default(Ot)`margin-top:${K.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,bo=_.default(Ot).attrs({role:"presentation"})`
341
+ ${({$marginTop:e=0,$paddingInline:t=0})=>P.css`margin-top:${e}px;padding-inline:${t}px;`}
342
+ `,zf=_.default($t)`display:flex;flex-direction:row;align-items:center;gap:8px;`,$n=_.default($t)`display:flex;`,qf=_.default.div.attrs({"aria-hidden":"true",role:"presentation"})``,Wf=_.default($t)`margin-top:${ee.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Os=_.default($t).attrs({role:"presentation"})`
343
343
  display: flex;
344
- ${({$startPadding:e=K.HORIZONTAL_PADDING,$endPadding:t=K.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
344
+ ${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
345
345
  padding-inline: ${e+n}px ${t}px;
346
346
  `}
347
- `,ng=_.default.div.attrs({role:"presentation"})`
347
+ `,Yf=_.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: ${K.GAP_GROUPED}px;
353
- `;function rg({file:e,children:t,onClickFile:n,sendingStatus:r}){const o=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return i.createElement(og,null,i.createElement(br,{name:e.name,mimeType:e.type,type:er(e.name,e.type),onClick:o}),t)}const og=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${K.GAP_GROUPED}px;`;function sg({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s}){const{conversation:a}=ee(),{aspectRatio:l,localFile:c}=n,[d]=u.useState(()=>c instanceof Blob?URL.createObjectURL(c):t.url),[m,h]=u.useState(!1),g=(()=>{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})}})(),C=g?a.file.buttonLikeInteractivePreview({name:t.name,mimeType:t.type,onActivate:g}):a.file.preview({name:t.name,mimeType:t.type}),b={...C.props,$ratio:l,$clickable:!!g};return i.createElement(ig,null,i.createElement(ag,{...b},!m&&i.createElement(st,{size:26},i.createElement(W,{type:"spinner",color:"textLowEmphasis",size:26})),i.createElement(lg,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),C.descriptionNode),s)}const ig=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${K.GAP_GROUPED}px;`,ag=_.default.div`width:${K.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;${G.light`
352
+ gap: ${ee.GAP_GROUPED}px;
353
+ `;function Kf({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return i.createElement(jf,null,i.createElement(yr,{name:e.name,mimeType:e.type,type:nr(e.name,e.type),onClick:s}),t)}const jf=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function Xf({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:a}=se(),{aspectRatio:l,localFile:u}=n,[d]=c.useState(()=>u instanceof Blob?URL.createObjectURL(u):t.url),[m,h]=c.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})}})(),v=f?a.file.buttonLikeInteractivePreview({name:t.name,mimeType:t.type,onActivate:f}):a.file.preview({name:t.name,mimeType:t.type}),b={...v.props,$ratio:l,$clickable:!!f};return i.createElement(Zf,null,i.createElement(Jf,{...b},!m&&i.createElement(dt,{size:26},i.createElement(Z,{type:"spinner",color:"textLowEmphasis",size:26})),i.createElement(Qf,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),v.descriptionNode),o)}const Zf=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`,Jf=_.default.div`width:${ee.BODY_MAX_WIDTH}px;border-radius:12px;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};height:auto;aspect-ratio:${e=>e.$ratio};position:relative;display:flex;align-items:center;justify-content:center;${X.light`
354
354
  background-color: ${p.color.background100};
355
355
  `}
356
- ${G.dark`
356
+ ${X.dark`
357
357
  background-color: ${p.color.background400};
358
358
  `}
359
- `,lg=_.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;`,cg=({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 h=a[m];h&&(o?o({files:a,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return i.createElement(ug,null,i.createElement(Rs,{images:a,isPending:l,onClickImage:d}),s)},ug=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${K.GAP_GROUPED}px;`;function dg(e){var n,r;const t=u.useMemo(()=>{const o=Qd(Ns(e.message));return Fo.default.sanitize(o)},[e.message]);return i.createElement(mg,{$maxWidth:e.maxBodyWidth??K.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},i.createElement(hg,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const mg=_.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>O.css`
359
+ `,Qf=_.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;`,eg=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[a]=c.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),l=e==="pending",u=e==="failed",d=m=>{if(u||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(tg,null,i.createElement(Qo,{images:a,isPending:l,onClickImage:d}),o)},tg=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function ng(e){var n,r;const t=c.useMemo(()=>{const s=Wm(ti(e.message));return Js.default.sanitize(s)},[e.message]);return i.createElement(rg,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},i.createElement(sg,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const rg=_.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>P.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
- `,hg=_.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,gg=({sendingStatus:e})=>{const t=O.useTheme();switch(e){case"pending":return i.createElement(fg,{size:16},i.createElement(W,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return i.createElement("div",{style:{marginBottom:2}},i.createElement(W,{type:"error",color:p.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return i.createElement("div",{style:{marginBottom:2}},i.createElement(W,{type:"done",color:p.themedColor.secondary,size:16}))}},fg=_.default(st)`margin-bottom:2px;width:16px;height:16px;`,pg=({createdAt:e})=>{const{stringSet:t,format:n}=Q();return e?i.createElement($,{variant:"caption4",color:p.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},_g=e=>{const{components:t}=Nt.useContext(),{stringSet:n}=Q(),r=()=>{const c=Vo(e)?i.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?c:e.messageType==="file"?e.file.type.startsWith("image")?i.createElement(t.MediaMessageBody,{...e},c):i.createElement(t.FileMessageBody,{...e},c):e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},c):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},o=e.sendingStatus==="failed"&&e.onClickFailedMessage,s=()=>{var c;return(c=e.onClickFailedMessage)==null?void 0:c.call(e)},l=o?{role:"button",tabIndex:0,onClick:s,onKeyDown:c=>{c.repeat||(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),s())}}:{};return i.createElement("div",{...l,style:{display:"contents",cursor:o?"pointer":"default"}},r())},Eg=e=>{const{components:t}=Nt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single",o=e.messageType==="user"&&e.sendingStatus!=="failed";return i.createElement(bg,{$marginBottom:hn(e.groupType)},i.createElement(Cg,{"aria-hidden":o?"true":void 0},i.createElement(t.MessageBody,{...e})),r&&i.createElement(vg,{$extraEndPadding:8,"aria-hidden":n?"true":void 0},n?i.createElement(t.SentTime,{...e}):i.createElement(t.SendingStatus,{...e})))},Nt=Pe({template:Eg,components:{SendingStatus:gg,SentTime:pg,MessageBody:_g,TextMessageBody:dg,MediaMessageBody:sg,FileMessageBody:rg,MultipleFilesMessageBody:cg}}),bg=_.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
367
- `,qs=_.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=K.HORIZONTAL_PADDING,$endPadding:t=K.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
368
- `,Cg=_.default(qs)``,vg=_.default(qs)`margin-top:${K.BODY_TIME_GAP}px;`,yg=e=>e.messageType!=="admin"?null:i.createElement(Sg,null,i.createElement($,{variant:"caption2",color:p.themedColor.textMidEmphasis},Ag(Fo.default.sanitize(e.message)))),Sg=_.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${K.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,Ag=e=>{try{const t=[];let n=e,r=0;for(;n;){const o=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),s=n.match(/\*\*([^*]+)\*\*/),a=[o&&{match:o,type:"link"},s&&{match:s,type:"bold"}].filter(h=>!!h);if(!a.length){t.push(n);break}const l=a.reduce((h,g)=>g.match.index<h.match.index?g: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:hr},c[1])):d==="bold"&&t.push(i.createElement("strong",{key:r++},c[1])),n=n.slice(m+c[0].length)}return t.filter(o=>o!=="")}catch{return[e]}},xg=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Ks=({options:e,value:t,disabled:n,hasError:r=!1,errorId:o,onChange:s})=>{const a=u.useRef([]),l=e.findIndex(h=>h.value===t),c=l>=0?l:0,d=h=>{requestAnimationFrame(()=>{var g;(g=a.current[h])==null||g.focus()})},m=h=>{const g=e[h];!g||n||(s==null||s(g.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&o?{"aria-invalid":!0,"aria-errormessage":o}:{}}),getRadioProps:h=>({ref:g=>{a.current[h]=g},tabIndex:n?-1:h===c?0:-1,describedBy:r&&o?o:void 0,onArrowNavigate:g=>{m(xg({direction:g,currentIndex:h,totalCount:e.length}))}})}},Tg=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},Ig=({event:e,onClick:t,onArrowNavigate:n})=>{if(wg(e))return;const r=Tg(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},wg=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",yr=u.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:o=0,labelVariant:s="caption2",describedBy:a,onArrowNavigate:l},c)=>{const d=t?p.themedColor.primary:r?p.themedColor.textDisabled:p.themedColor.textLowEmphasis,m=t?p.themedColor.textHighEmphasis:r?p.themedColor.textLowEmphasis:p.themedColor.textHighEmphasis;return i.createElement(Mg,{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:h=>Ig({event:h,onClick:e,onArrowNavigate:l})},i.createElement(kg,{"aria-hidden":"true"},i.createElement(W,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(Lg,{"aria-hidden":"true",variant:s,color:m},n))});yr.displayName="Radio";const kg=_.default.div`width:20px;height:20px;`,Lg=_.default($)`line-height:20px;word-break:break-word;`,Mg=_.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${_e}&[aria-disabled='false']{cursor:pointer;}`,Rg=({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=Ks({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(Og,null,i.createElement(fe.Label,{required:l.required,ariaHidden:!0},l.question),i.createElement(Ng,{...a.radioGroupProps(l.question)},s.map((m,h)=>i.createElement(yr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(h),onClick:()=>o==null?void 0:o(m.value)}))))},Og=_.default.div`display:flex;flex-direction:column;gap:8px;`,Ng=_.default.div`display:flex;flex-direction:column;gap:8px;`,$g=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:s}=Q(),a=u.useId(),l=e.response_type!=="free_text",c={ariaInvalid:o,ariaErrorMessage:o?a:void 0},d=e.response_type==="single_choice"?e.options.map(h=>({label:h,value:h})):[],m=Ks({options:d,value:n,disabled:t,hasError:o,errorId:a,onChange:r});return i.createElement(Dg,null,i.createElement(fe.Label,{required:e.required,ariaHidden:l},e.question),e.response_type==="free_text"&&i.createElement(fe.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:h=>r(h),error:o,ariaLabel:s.A11Y_CSAT_TEXT_INPUT_LABEL,required:e.required,ariaInvalid:c.ariaInvalid,ariaErrorMessage:c.ariaErrorMessage}),e.response_type==="single_choice"&&i.createElement(Pg,{...m.radioGroupProps(e.question)},d.map((h,g)=>i.createElement(yr,{key:h.value,checked:n===h.value,label:h.label,disabled:t,...m.getRadioProps(g),onClick:()=>r==null?void 0:r(h.value),labelVariant:"body3"}))),o&&i.createElement(Fg,{role:"alert",id:a},s.FORM_VALIDATION_REQUIRED))},Dg=_.default.div`display:flex;flex-direction:column;gap:8px;`,Pg=_.default.div`display:flex;flex-direction:column;gap:8px;`,Fg=_.default(fe.ErrorLabel)``,Bg=({value:e,selected:t})=>i.createElement(Hg,{$selected:t,"aria-hidden":"true"},Ug[e-1]),Hg=_.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Ug=[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)"}))))],Vg=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",{conversation:s}=ee(),a=s.csat.scoresContainer(e.csat_question);return i.createElement(zg,null,i.createElement($,{variant:"caption3",color:p.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(Wg,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:c},d)=>{const m=d+1,h=n===m,g=e.csat_scores.length,C=s.csat.scoreItem({score:m,label:l,selected:h,disabled:t,currentIndex:d,totalCount:g,hasSelection:!o,onChange:r});return i.createElement(qg,{key:d,type:"button",...C.props},i.createElement(Gg,{value:m,selected:o||h,src:c}),!!l&&i.createElement($,{"aria-hidden":"true",color:h?p.themedColor.textHighEmphasis:p.themedColor.textLowEmphasis,variant:"caption3"},l))})))},Gg=({value:e,src:t,selected:n})=>{const[r,o]=u.useState(!1),s=r?i.createElement(Bg,{value:e,selected:n}):i.createElement(Yg,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>o(!0)});return i.createElement(Kg,null,s)},zg=_.default.div`display:flex;flex-direction:column;gap:8px;`,Wg=_.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,qg=_.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;${_e}&:not(:disabled):hover span{color:${p.themedColor.textHighEmphasis};}`,Kg=_.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${p.color.background200};${G.dark`
366
+ `,sg=_.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,og=({sendingStatus:e})=>{const t=P.useTheme();switch(e){case"pending":return i.createElement(ig,{size:16},i.createElement(Z,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return i.createElement("div",{style:{marginBottom:2}},i.createElement(Z,{type:"error",color:p.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return i.createElement("div",{style:{marginBottom:2}},i.createElement(Z,{type:"done",color:p.themedColor.secondary,size:16}))}},ig=_.default(dt)`margin-bottom:2px;width:16px;height:16px;`,ag=({createdAt:e})=>{const{stringSet:t,format:n}=re();return e?i.createElement(B,{variant:"caption4",color:p.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},lg=e=>{const{components:t}=Pt.useContext(),{stringSet:n}=re(),r=()=>{const a=no(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?wt({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())},cg=e=>{const{components:t}=Pt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single",s=e.messageType==="user"&&e.sendingStatus!=="failed";return i.createElement(ug,{$marginBottom:gn(e.groupType)},i.createElement(dg,{"aria-hidden":s?"true":void 0},i.createElement(t.MessageBody,{...e})),r&&i.createElement(mg,{$extraEndPadding:8,"aria-hidden":n?"true":void 0},n?i.createElement(t.SentTime,{...e}):i.createElement(t.SendingStatus,{...e})))},Pt=qe({template:cg,components:{SendingStatus:og,SentTime:ag,MessageBody:lg,TextMessageBody:ng,MediaMessageBody:Xf,FileMessageBody:Kf,MultipleFilesMessageBody:eg}}),ug=_.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
367
+ `,hi=_.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
368
+ `,dg=_.default(hi)``,mg=_.default(hi)`margin-top:${ee.BODY_TIME_GAP}px;`,hg=e=>e.messageType!=="admin"?null:i.createElement(fg,null,i.createElement(B,{variant:"caption2",color:p.themedColor.textMidEmphasis},gg(Js.default.sanitize(e.message)))),fg=_.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ee.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,gg=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:u,type:d}=l,m=u.index;m>0&&t.push(n.slice(0,m)),d==="link"?t.push(i.createElement("a",{key:r++,href:u[2],target:"_blank",rel:pr},u[1])):d==="bold"&&t.push(i.createElement("strong",{key:r++},u[1])),n=n.slice(m+u[0].length)}return t.filter(s=>s!=="")}catch{return[e]}},pg=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,fi=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const a=c.useRef([]),l=e.findIndex(h=>h.value===t),u=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===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(pg({direction:f,currentIndex:h,totalCount:e.length}))}})}},_g=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},Eg=({event:e,onClick:t,onArrowNavigate:n})=>{if(bg(e))return;const r=_g(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},bg=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",xr=c.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:a,onArrowNavigate:l},u)=>{const d=t?p.themedColor.primary:r?p.themedColor.textDisabled:p.themedColor.textLowEmphasis,m=t?p.themedColor.textHighEmphasis:r?p.themedColor.textLowEmphasis:p.themedColor.textHighEmphasis;return i.createElement(yg,{ref:u,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=>Eg({event:h,onClick:e,onArrowNavigate:l})},i.createElement(Cg,{"aria-hidden":"true"},i.createElement(Z,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(vg,{"aria-hidden":"true",variant:o,color:m},n))});xr.displayName="Radio";const Cg=_.default.div`width:20px;height:20px;`,vg=_.default(B)`line-height:20px;word-break:break-word;`,yg=_.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Ie}&[aria-disabled='false']{cursor:pointer;}`,Sg=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],a=fi({options:o,value:r,disabled:t,onChange:s});if(c.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const l=e.cre;return i.createElement(Ag,null,i.createElement(xe.Label,{required:l.required,"aria-hidden":!0},l.question),i.createElement(xg,{...a.radioGroupProps(l.question)},o.map((m,h)=>i.createElement(xr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},Ag=_.default.div`display:flex;flex-direction:column;gap:8px;`,xg=_.default.div`display:flex;flex-direction:column;gap:8px;`,Tg=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=re(),{conversation:a}=se(),l=c.useId(),u=e.response_type!=="free_text",d=e.response_type==="single_choice"?e.options.map(h=>({label:h,value:h})):[],m=fi({options:d,value:n,disabled:t,hasError:s,errorId:l,onChange:r});return i.createElement(Ig,null,i.createElement(xe.Label,{required:e.required,"aria-hidden":u},e.question),e.response_type==="free_text"&&i.createElement(xe.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),"aria-invalid":s,"aria-errormessage":s?l:void 0}),e.response_type==="single_choice"&&i.createElement(wg,{...m.radioGroupProps(e.question)},d.map((h,f)=>i.createElement(xr,{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(Mg,{role:"alert",id:l},o.FORM_VALIDATION_REQUIRED))},Ig=_.default.div`display:flex;flex-direction:column;gap:8px;`,wg=_.default.div`display:flex;flex-direction:column;gap:8px;`,Mg=_.default(xe.ErrorLabel)``,kg=({value:e,selected:t})=>i.createElement(Lg,{$selected:t,"aria-hidden":"true"},Rg[e-1]),Lg=_.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Rg=[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)"}))))],Og=({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(Dg,null,i.createElement(B,{variant:"caption3",color:p.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement($g,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,v=o.csat.scoreItem({score:m,label:l,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return i.createElement(Pg,{key:d,type:"button",...v.props},i.createElement(Ng,{value:m,selected:s||h,src:u}),!!l&&i.createElement(B,{"aria-hidden":"true",color:h?p.themedColor.textHighEmphasis:p.themedColor.textLowEmphasis,variant:"caption3"},l))})))},Ng=({value:e,src:t,selected:n})=>{const[r,s]=c.useState(!1),o=r?i.createElement(kg,{value:e,selected:n}):i.createElement(Bg,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return i.createElement(Fg,null,o)},Dg=_.default.div`display:flex;flex-direction:column;gap:8px;`,$g=_.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Pg=_.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;${Ie}&:not(:disabled):hover span{color:${p.themedColor.textHighEmphasis};}`,Fg=_.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${p.color.background200};${X.dark`
369
369
  background-color: ${p.color.background500};
370
370
  `}
371
371
  }
372
- `,Yg=_.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,jg=({csatPayload:e})=>i.createElement($,{variant:"button",color:p.themedColor.textHighEmphasis},e.title),$n=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:s})=>{const{params:a,setParams:l,error:c,setError:d,followUpItem:m,state:h,validateParams:g,itemProps:C}=Gl({csatPayload:e,type:t,initialCsat:r,initialCsatReason:o,initialIsResolved:s});return i.createElement(i.Fragment,null,i.createElement(Xg,null,i.createElement(jg,{...C}),t===Ne.AI_AGENT_CSAT_5_WITH_CRE&&i.createElement(Rg,{...C,defaultValue:s,value:a.isResolved,onChange:b=>l({isResolved:b})}),i.createElement(Vg,{...C,value:a.csat,onChange:b=>l({csat:b})}),m&&i.createElement($g,{...C,followUpItem:m,value:a.csatReason,onChange:b=>{l({csatReason:b}),d({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&i.createElement(i.Fragment,null,i.createElement(fe.Separator,null),n({state:h,params:a,validateParams:g})))},Xg=_.default.div`display:flex;flex-direction:column;gap:12px;`,Zg=e=>{const{stringSet:t}=Q();return ua(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})},Jg=()=>{const{stringSet:e}=Q();return i.createElement($,{variant:"body2",color:p.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},Qg=({onMount:e,children:t})=>(u.useEffect(()=>{e&&ve(e)},[]),t),ef=e=>{const{conversation:t}=ee(),{announceStatusText:n,announceError:r}=ot();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,h=Ye.useForceUpdate(),g=Zg(o==null?void 0:o.csat),C=u.useRef(null),b=u.useRef(!1),v=u.useRef(null),f=u.useRef(typeof l=="number"),y=(g==null?void 0:g.csat_submitted_label)??"",E=!!g&&g.visibility&&!!Ne[g.type];if(u.useEffect(()=>{E&&y&&(typeof l!="number"||f.current||(f.current=!0,n(y),ve(()=>{var I;(I=v.current)==null||I.focus()})))},[n,l,E,y]),!E||!g)return null;const x=()=>{var k;const I=(k=C.current)==null?void 0:k.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},S=g.type===Ne.AI_AGENT_CSAT_5||g.type===Ne.AI_AGENT_CSAT_5_WITH_CRE||g.type===Ne.HELPDESK_CSAT_5?$n:()=>null;return i.createElement(tf,{ref:C},!l&&$r(d)?i.createElement(Jg,null):i.createElement(S,{csatPayload:g,type:g.type,initialCsat:l,initialCsatReason:c,initialIsResolved:m,renderSubmitButton:({state:I,params:k,validateParams:M})=>I==="submitted"?i.createElement(rf,{ref:v,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":y,tabIndex:-1},i.createElement($,{variant:"button","aria-hidden":"true"},g.csat_submitted_label)):i.createElement(Qg,{onMount:a},i.createElement(nf,{type:"button",...t.csat.submitButton(g.csat_submit_label),onClick:async()=>{if(b.current)return;const U=$r(d);!U&&M()?(b.current=!0,await s(k).finally(()=>{b.current=!1})):(h(),U||ve(()=>{r({type:"csatFormError"},x())}))}},i.createElement($,{variant:"button"},g.csat_submit_label)))}))},tf=_.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,nf=_.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;${_e}&:hover{background-color:${p.color.primary.dark};}`,rf=_.default.div`width:100%;box-sizing:border-box;color:${p.themedColor.textHighEmphasis};background-color:${p.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${G.dark`
372
+ `,Bg=_.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Ug=({csatPayload:e})=>i.createElement(B,{variant:"button",color:p.themedColor.textHighEmphasis},e.title),Pn=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:a,setParams:l,error:u,setError:d,followUpItem:m,state:h,validateParams:f,itemProps:v}=Cc({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return i.createElement(i.Fragment,null,i.createElement(Hg,null,i.createElement(Ug,{...v}),t===We.AI_AGENT_CSAT_5_WITH_CRE&&i.createElement(Sg,{...v,defaultValue:o,value:a.isResolved,onChange:b=>l({isResolved:b})}),i.createElement(Og,{...v,value:a.csat,onChange:b=>l({csat:b})}),m&&i.createElement(Tg,{...v,followUpItem:m,value:a.csatReason,onChange:b=>{l({csatReason:b}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&i.createElement(i.Fragment,null,i.createElement(xe.Separator,null),n({state:h,params:a,validateParams:f})))},Hg=_.default.div`display:flex;flex-direction:column;gap:12px;`,Gg=e=>{const{stringSet:t}=re();return xa(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})},Vg=()=>{const{stringSet:e}=re();return i.createElement(B,{variant:"body2",color:p.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},zg=({onMount:e,children:t})=>(c.useEffect(()=>{e&&Oe(e)},[]),t),qg=e=>{const{conversation:t}=se(),{announceStatusText:n,announceError:r}=st();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:s,onSubmitCSAT:o,onScrollToBottom:a}=e,{csat:l,csatReason:u,csatExpireAt:d,isResolvedWhenDeterminedByUser:m}=e,h=ur(),f=Gg(s==null?void 0:s.csat),v=c.useRef(null),b=c.useRef(!1),C=c.useRef(null),g=c.useRef(typeof l=="number"),y=(f==null?void 0:f.csat_submitted_label)??"",E=!!f&&f.visibility&&!!We[f.type];if(c.useEffect(()=>{E&&y&&(typeof l!="number"||g.current||(g.current=!0,n(y),Oe(()=>{var w;(w=C.current)==null||w.focus()})))},[n,l,E,y]),!E||!f)return null;const I=()=>{var k;const w=(k=v.current)==null?void 0:k.querySelector('[aria-invalid="true"]');return w?w.getAttribute("role")==="radiogroup"?w.querySelector('[role="radio"]'):w:null},A=f.type===We.AI_AGENT_CSAT_5||f.type===We.AI_AGENT_CSAT_5_WITH_CRE||f.type===We.HELPDESK_CSAT_5?Pn:()=>null;return i.createElement(Wg,{ref:v},!l&&Fr(d)?i.createElement(Vg,null):i.createElement(A,{csatPayload:f,type:f.type,initialCsat:l,initialCsatReason:u,initialIsResolved:m,renderSubmitButton:({state:w,params:k,validateParams:N})=>w==="submitted"?i.createElement(Kg,{ref:C,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":y,tabIndex:-1},i.createElement(B,{variant:"button","aria-hidden":"true"},f.csat_submitted_label)):i.createElement(zg,{onMount:a},i.createElement(Yg,{type:"button",...t.csat.submitButton(f.csat_submit_label),onClick:async()=>{if(b.current)return;const W=Fr(d);!W&&N()?(b.current=!0,await o(k).finally(()=>{b.current=!1})):(h(),W||Oe(()=>{r({type:"csatFormError"},I())}))}},i.createElement(B,{variant:"button"},f.csat_submit_label)))}))},Wg=_.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,Yg=_.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;${Ie}&:hover{background-color:${p.color.primary.dark};}`,Kg=_.default.div`width:100%;box-sizing:border-box;color:${p.themedColor.textHighEmphasis};background-color:${p.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${X.dark`
373
373
  background-color: ${p.color.onlight.textDisabled};
374
374
  `}
375
- `,of=e=>{const{components:t}=_n.useContext(),n=e.messageType==="admin"?i.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?i.createElement(t.CSATMessage,{...e}):null;return i.createElement(sf,{$marginBottom:hn(e.groupType)},n)},_n=Pe({template:of,components:{AdminMessage:yg,CSATMessage:ef}}),sf=_.default.div`padding-inline:${K.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Co={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Ys=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,onClickActionbook:o,onClickFunctionCall:s,onClickFunctionCallDetail:a,onClickGroundedness:l,onClickAgentMessageTemplate:c,bottomContent:d,renderCustomGroundednessIcon:m=g=>g.default,style:h={}})=>{const{iconColor:g="#000000",textColor:C="#000000",highlightColor:b=xt.DEFAULT_PRIMARY}=h;return i.createElement(vo,null,e&&i.createElement(vo,null,i.createElement(dn,null,i.createElement(Yt,null,i.createElement(W,{size:16,type:"actionbook",color:g})),i.createElement(Kt,{$clickable:!!o,$highlightColor:b,variant:"body2",color:C,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(v=>i.createElement(Dn,{key:v.key},i.createElement(Yt,null,i.createElement(W,{size:16,type:"function",color:g})),i.createElement(dn,null,i.createElement(Kt,{$clickable:!!s,$highlightColor:b,variant:"body2",color:C,onClick:()=>s==null?void 0:s(v),maxTextLines:1},v.name),a&&i.createElement(lf,{role:"button",onClick:()=>a==null?void 0:a(v)},i.createElement($,{variant:"body2",color:b},"View details"),i.createElement(W,{type:"chevron-right",size:16,color:b}))))),n==null?void 0:n.map(v=>i.createElement(Dn,{key:v.id},i.createElement(Yt,null,m({default:i.createElement(W,{size:16,type:Co[v.source_type]??Co.snippet,color:g}),sourceType:v.source_type})),i.createElement(Kt,{$clickable:!!l,$highlightColor:b,variant:"body2",color:C,onClick:()=>l==null?void 0:l(v),maxTextLines:1},v.preview_title))),r==null?void 0:r.map(v=>i.createElement(Dn,{key:v.key},i.createElement(Yt,null,i.createElement(W,{size:16,type:"template",color:g})),i.createElement(Kt,{$clickable:!!c,$highlightColor:b,variant:"body2",color:C,onClick:()=>c==null?void 0:c(v),maxTextLines:1},v.name))),d)},af=_.default($)`font-weight:400;`,Kt=_.default(af)`${({$clickable:e,$highlightColor:t})=>e&&O.css`
375
+ `,jg=e=>{const{components:t}=bn.useContext(),n=e.messageType==="admin"?i.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?i.createElement(t.CSATMessage,{...e}):null;return i.createElement(Xg,{$marginBottom:gn(e.groupType)},n)},bn=qe({template:jg,components:{AdminMessage:hg,CSATMessage:qg}}),Xg=_.default.div`padding-inline:${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Ns={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},gi=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,onClickActionbook:s,onClickFunctionCall:o,onClickFunctionCallDetail:a,onClickGroundedness:l,onClickAgentMessageTemplate:u,bottomContent:d,renderCustomGroundednessIcon:m=f=>f.default,style:h={}})=>{const{iconColor:f="#000000",textColor:v="#000000",highlightColor:b=Rt.DEFAULT_PRIMARY}=h;return i.createElement(Ds,null,e&&i.createElement(Ds,null,i.createElement(fn,null,i.createElement(Xt,null,i.createElement(Z,{size:16,type:"actionbook",color:f})),i.createElement(jt,{$clickable:!!s,$highlightColor:b,variant:"body2",color:v,onClick:()=>s==null?void 0:s(e),maxTextLines:1},e.name))),t==null?void 0:t.map(C=>i.createElement(Fn,{key:C.key},i.createElement(Xt,null,i.createElement(Z,{size:16,type:"function",color:f})),i.createElement(fn,null,i.createElement(jt,{$clickable:!!o,$highlightColor:b,variant:"body2",color:v,onClick:()=>o==null?void 0:o(C),maxTextLines:1},C.name),a&&i.createElement(Jg,{role:"button",onClick:()=>a==null?void 0:a(C)},i.createElement(B,{variant:"body2",color:b},"View details"),i.createElement(Z,{type:"chevron-right",size:16,color:b}))))),n==null?void 0:n.map(C=>i.createElement(Fn,{key:C.id},i.createElement(Xt,null,m({default:i.createElement(Z,{size:16,type:Ns[C.source_type]??Ns.snippet,color:f}),sourceType:C.source_type})),i.createElement(jt,{$clickable:!!l,$highlightColor:b,variant:"body2",color:v,onClick:()=>l==null?void 0:l(C),maxTextLines:1},C.preview_title))),r==null?void 0:r.map(C=>i.createElement(Fn,{key:C.key},i.createElement(Xt,null,i.createElement(Z,{size:16,type:"template",color:f})),i.createElement(jt,{$clickable:!!u,$highlightColor:b,variant:"body2",color:v,onClick:()=>u==null?void 0:u(C),maxTextLines:1},C.name))),d)},Zg=_.default(B)`font-weight:400;`,jt=_.default(Zg)`${({$clickable:e,$highlightColor:t})=>e&&P.css`
376
376
  cursor: pointer;
377
377
  text-decoration: underline;
378
378
  &:hover {
379
379
  color: ${t};
380
380
  }
381
381
  `}
382
- `,Yt=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,dn=_.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,lf=_.default(dn)`cursor:pointer;gap:4px;`,Dn=_.default(dn)`flex-direction:row;align-items:center;`,vo=_.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,js=u.createContext(null);function cf({testerType:e,origin:t,children:n}){return i.createElement(js.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(uf,null),n)}const pt=()=>{const e=u.useContext(js);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},uf=()=>{const{isActionbookTester:e}=pt();return i.createElement(Je.Template,{template:e?df:void 0},i.createElement(Je.MessageLogs,{component:mf}))},df=e=>i.createElement(Ws,{...e,testerMode:!0,maxBodyWidth:K.WIDE_BODY_MAX_WIDTH}),mf=({extendedMessagePayload:e={}})=>{const{handlers:t}=ne(),{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(hf,null,i.createElement(gf,{width:4}),i.createElement(Ys,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:p.themedColor.textHighEmphasis,textColor:p.themedColor.textHighEmphasis,barColor:p.themedColor.textDisabled},bottomContent:i.createElement(ff,{variant:"caption2",color:p.themedColor.textLowEmphasis},"Only visible in the tester")}))},hf=_.default.div`display:flex;gap:16px;margin:16px ${K.HORIZONTAL_PADDING}px 0;align-self:stretch;`,gf=_.default.div`width:${({width:e})=>e}px;background-color:${p.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,ff=_.default($)`margin-top:5px;`,yo=40,So=.9,pf="[data-message-listitem]",_f='input, textarea, select, [role="textbox"], [contenteditable="true"]',Ef=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*So;case"PageUp":return t.clientHeight*-So;case"ArrowDown":return n?yo:void 0;case"ArrowUp":return n?yo*-1:void 0;default:return}},bf=({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(_f))return;const s=o===r||o.matches(pf),a=Ef({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]),Cf="[data-message-listitem]",vf=e=>Math.min(Math.max(0,e),1),yf=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Cf),o=n===e||n===r;return!n||!e.contains(n)?null:o?e:n},Sf=({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})},Af=({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),h=u.useRef(null),g=u.useRef(null),C=u.useRef(null);u.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),u.useLayoutEffect(()=>{const y=t.current;y&&(c.current==="top"&&(y.scrollTop=y.scrollHeight-m.current,Sf({list:y,focusRestoreTarget:h.current}),h.current=null),c.current==="bottom"&&(y.scrollTop=d.current),c.current=void 0)},[t,r]);const b=u.useCallback(async y=>{const E=t.current;if(!E||(a==null||a(y),m.current=E.scrollHeight-E.scrollTop,d.current=E.scrollTop,l.current))return;const x=E.clientHeight*vf(n);if(E.scrollTop<=x){l.current=!0,c.current="top",h.current=yf(E),await s(),l.current=!1;return}if(E.scrollHeight-E.scrollTop-E.clientHeight<=x){l.current=!0,c.current="bottom",await o(),l.current=!1;return}c.current=void 0},[t,n,o,s,a]),v=u.useCallback(y=>{const E=t.current;if(!E)return;const x=C.current;if(x!=null){if(x===E.scrollTop){C.current=null;return}C.current=null}const S=g.current;if(S!=null&&S===E.scrollTop){g.current=null,C.current=E.scrollTop,b(y);return}g.current=null,b(y)},[b,t]),f=u.useCallback(y=>{const E=t.current;E&&(g.current=y,C.current=null,E.scrollTop=y,E.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return u.useLayoutEffect(()=>()=>{g.current=null,C.current=null},[]),{handleScroll:v,syncScrollPosition:f}},xf=u.forwardRef(function(t,n){const{messages:r,renderMessage:o,loading:s,LoadingComponent:a,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:g,overlayArea:C,onLoadPrev:b,onLoadNext:v,loadThreshold:f=.05,onScroll:y=oe,depsForResetScrollPositionToBottom:E,stackDirection:x="top",bottomSpacerHeight:S=0,ariaLabel:I}=t,k=u.useRef(null),M=u.useCallback(L=>{k.current=L,n&&(typeof n=="function"?n(L):n.current=L)},[n]),{handleScroll:U,syncScrollPosition:F}=Af({depsForResetScrollPositionToBottom:E,listRef:k,loadThreshold:f,messagesLength:r.length,onLoadNext:v,onLoadPrev:b,onScroll:y}),z=bf({listRef:k,syncScrollPosition:F});return l?i.createElement(i.Fragment,null,c):s?i.createElement(i.Fragment,null,a):i.createElement(Tf,{id:"infinite-list-container"},i.createElement(If,{id:"infinite-list-inner",ref:M,onScroll:U,onKeyDown:z,role:"list","aria-label":I,tabIndex:0},x==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((L,P)=>o({message:L,index:P})),g,S>0&&i.createElement("div",{style:{minHeight:S}})),i.createElement(wf,{id:"infinite-list-overlay-container"},i.createElement(kf,{id:"infinite-list-overlay"},C)))}),Tf=_.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,If=_.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${p.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,wf=_.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,kf=_.default.div`pointer-events:auto;`,Ue=({as:e,type:t,size:n=16,color:r,disabled:o,children:s,...a})=>{const l=o?p.themedColor.textDisabled:p.themedColor.textHighEmphasis;return i.createElement(Lf,{as:e,disabled:o,...a},i.createElement(W,{type:t,size:n,color:r??l}),s)},Lf=_.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${_e}&:disabled{cursor:not-allowed;}`,Mf=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{var I,k;const[o,s]=u.useState(t),[a,l]=u.useState(!1),{stringSet:c,format:d}=Q(),{config:m}=ne(),h=e.length,g=e[o],C=((k=(I=m==null?void 0:m.conversation)==null?void 0:I.fileViewer)==null?void 0:k.downloadEnabled)!==!1,b=h>1,v=(g==null?void 0:g.type)||"",f=ze(v),y=Uo(v),E=!ed(v);u.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const x=u.useCallback(()=>{o>0&&(s(M=>M-1),l(!1))},[o]),S=u.useCallback(()=>{o<h-1&&(s(M=>M+1),l(!1))},[o,h]);return u.useEffect(()=>{if(!r)return;const M=U=>{U.key==="ArrowLeft"?x():U.key==="ArrowRight"&&S()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[r,x,S]),!r||!g?null:i.createElement(ft,{onClose:n,visible:r,rootElementId:ce.MODAL_ROOT,"aria-label":(g==null?void 0:g.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(Rf,null,i.createElement(Of,null,i.createElement(Nf,null,i.createElement($f,null,i.createElement($,{variant:"button",maxTextLines:1,color:p.themedColor.textHighEmphasis},g.name||c.IMAGE_VIEWER__DEFAULT_TITLE),g.timestamp&&i.createElement($,{variant:"caption2",color:p.themedColor.textMidEmphasis},d(new Date(g.timestamp),"h:mm a")))),i.createElement(Df,{type:"close",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(Pf,{onClick:M=>M.currentTarget===M.target&&n()},b&&i.createElement(Ao,{$position:"left",type:"chevron-right",size:32,onClick:x,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(Ff,null,f&&i.createElement(i.Fragment,null,!a&&i.createElement(Bf,null,i.createElement(st,{size:32},i.createElement(W,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(Hf,{src:g.url,alt:g.name||"Image",$loaded:a,onLoad:()=>l(!0)})),y&&i.createElement(Uf,{controls:!0},i.createElement("source",{src:g.url,type:v})),E&&i.createElement(Vf,null,i.createElement($,{variant:"h1",color:p.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),b&&i.createElement(Ao,{$position:"right",type:"chevron-right",size:32,onClick:S,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===h-1})),i.createElement(Gf,null,i.createElement(zf,null),b&&i.createElement($,{variant:"body3",color:p.themedColor.textHighEmphasis},o+1,"/",h),i.createElement(Wf,null,C&&!E&&i.createElement(Ue,{as:"a",href:g.url,download:g.name||"file",type:"download",size:24,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD})))))},Rf=_.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${p.themedColor.bg_50_600};`,Of=_.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 16px;min-height:56px;border-bottom:1px solid ${p.themedColor.textDisabled};`,Nf=_.default.div`flex:1;min-width:0;padding-right:16px;`,$f=_.default.div`display:flex;flex-direction:column;gap:2px;`,Df=_.default(Ue)`flex-shrink:0;width:32px;height:32px;border-radius:50%;&:hover{background-color:${p.themedColor.bg_100_500};}`,En=_.default.div`display:flex;align-items:center;justify-content:center;`,Pf=_.default(En)`flex:1;min-height:0;position:relative;padding:0 16px;`,Ff=_.default(En)`position:relative;max-width:100%;max-height:100%;`,Bf=_.default(En)`position:absolute;inset:0;`,Hf=_.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;`,Uf=_.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Vf=_.default(En)`flex-direction:column;gap:16px;`,Ao=_.default(Ue)`position:absolute;${e=>e.$position==="left"?"left: 16px;":"right: 16px;"}top:50%;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;&:hover:not(:disabled){background-color:${p.themedColor.bg_200_400};}&:disabled{opacity:0.3;}@media (max-width:480px){width:38px;height:38px;${e=>e.$position==="left"?"left: 8px;":"right: 8px;"}}`,Gf=_.default.footer`display:flex;align-items:center;justify-content:space-between;padding:16px;min-height:56px;border-top:1px solid ${p.themedColor.textDisabled};`,zf=_.default.div`width:40px;`,Wf=_.default.div`display:flex;align-items:center;justify-content:flex-end;width:40px;`,Xs=({title:e,description:t,negativeText:n,positiveText:r,onCancel:o,onConfirm:s})=>i.createElement(qf,null,i.createElement(Kf,null,i.createElement($,{as:"div",variant:"h2",color:p.themedColor.textHighEmphasis},e)),i.createElement(Yf,null,i.createElement($,{as:"div",variant:"body3",color:p.themedColor.textMidEmphasis},t)),i.createElement(jf,null,i.createElement(Xf,{type:"button",onClick:o},i.createElement($,{variant:"button",color:p.themedColor.textHighEmphasis},n)),i.createElement(Zf,{type:"button",onClick:s},i.createElement($,{variant:"button",color:p.themedColor.textHighEmphasisInverse},r)))),qf=_.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${p.color.background50};${G.dark`
382
+ `,Xt=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,fn=_.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Jg=_.default(fn)`cursor:pointer;gap:4px;`,Fn=_.default(fn)`flex-direction:row;align-items:center;`,Ds=_.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,pi=c.createContext(null);function Qg({testerType:e,origin:t,children:n}){return i.createElement(pi.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(ep,null),n)}const St=()=>{const e=c.useContext(pi);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},ep=()=>{const{isActionbookTester:e}=St();return i.createElement(rt.Template,{template:e?tp:void 0},i.createElement(rt.MessageLogs,{component:np}))},tp=e=>i.createElement(mi,{...e,testerMode:!0,maxBodyWidth:ee.WIDE_BODY_MAX_WIDTH}),np=({extendedMessagePayload:e={}})=>{const{handlers:t}=fe(),{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(rp,null,i.createElement(sp,{$width:4}),i.createElement(gi,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:p.themedColor.textHighEmphasis,textColor:p.themedColor.textHighEmphasis,barColor:p.themedColor.textDisabled},bottomContent:i.createElement(op,{variant:"caption2",color:p.themedColor.textLowEmphasis},"Only visible in the tester")}))},rp=_.default.div`display:flex;gap:16px;margin:16px ${ee.HORIZONTAL_PADDING}px 0;align-self:stretch;`,sp=_.default.div`width:${({$width:e})=>e}px;background-color:${p.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,op=_.default(B)`margin-top:5px;`,$s=40,Ps=.9,ip="[data-message-listitem]",ap='input, textarea, select, [role="textbox"], [contenteditable="true"]',lp=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Ps;case"PageUp":return t.clientHeight*-Ps;case"ArrowDown":return n?$s:void 0;case"ArrowUp":return n?$s*-1:void 0;default:return}},cp=({listRef:e,syncScrollPosition:t})=>c.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(ap))return;const o=s===r||s.matches(ip),a=lp({event:n,list:r,isMessageAnchor:o});if(a==null||a===0)return;const l=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(l,Math.max(0,r.scrollTop+a));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),up="[data-message-listitem]",dp=e=>Math.min(Math.max(0,e),1),mp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(up),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},hp=({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})},fp=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:a})=>{const l=c.useRef(!1),u=c.useRef(void 0),d=c.useRef(0),m=c.useRef(0),h=c.useRef(null),f=c.useRef(null),v=c.useRef(null);c.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),c.useLayoutEffect(()=>{const y=t.current;y&&(u.current==="top"&&(y.scrollTop=y.scrollHeight-m.current,hp({list:y,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(y.scrollTop=d.current),u.current=void 0)},[t,r]);const b=c.useCallback(async y=>{const E=t.current;if(!E||(a==null||a(y),m.current=E.scrollHeight-E.scrollTop,d.current=E.scrollTop,l.current))return;const I=E.clientHeight*dp(n);if(E.scrollTop<=I){l.current=!0,u.current="top",h.current=mp(E),await o(),l.current=!1;return}if(E.scrollHeight-E.scrollTop-E.clientHeight<=I){l.current=!0,u.current="bottom",await s(),l.current=!1;return}u.current=void 0},[t,n,s,o,a]),C=c.useCallback(y=>{const E=t.current;if(!E)return;const I=v.current;if(I!=null){if(I===E.scrollTop){v.current=null;return}v.current=null}const A=f.current;if(A!=null&&A===E.scrollTop){f.current=null,v.current=E.scrollTop,b(y);return}f.current=null,b(y)},[b,t]),g=c.useCallback(y=>{const E=t.current;E&&(f.current=y,v.current=null,E.scrollTop=y,E.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return c.useLayoutEffect(()=>()=>{f.current=null,v.current=null},[]),{handleScroll:C,syncScrollPosition:g}},gp=c.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:a,error:l,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:v,onLoadPrev:b,onLoadNext:C,loadThreshold:g=.05,onScroll:y=he,depsForResetScrollPositionToBottom:E,stackDirection:I="top",bottomSpacerHeight:A=0,"aria-label":w}=t,k=c.useRef(null),N=c.useCallback(L=>{k.current=L,n&&(typeof n=="function"?n(L):n.current=L)},[n]),{handleScroll:W,syncScrollPosition:G}=fp({depsForResetScrollPositionToBottom:E,listRef:k,loadThreshold:g,messagesLength:r.length,onLoadNext:C,onLoadPrev:b,onScroll:y}),K=cp({listRef:k,syncScrollPosition:G});return l?i.createElement(i.Fragment,null,u):o?i.createElement(i.Fragment,null,a):i.createElement(pp,{id:"infinite-list-container"},i.createElement(_p,{id:"infinite-list-inner",ref:N,onScroll:W,onKeyDown:K,role:"list","aria-label":w,tabIndex:0},I==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((L,V)=>s({message:L,index:V})),f,A>0&&i.createElement("div",{style:{minHeight:A}})),i.createElement(Ep,{id:"infinite-list-overlay-container"},i.createElement(bp,{id:"infinite-list-overlay"},v)))}),pp=_.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,_p=_.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${p.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,Ep=_.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,bp=_.default.div`pointer-events:auto;`,Je=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...a})=>{const l=s?p.themedColor.textDisabled:p.themedColor.textHighEmphasis;return i.createElement(Cp,{as:e,disabled:s,...a},i.createElement(Z,{type:t,size:n,color:r??l}),o)},Cp=_.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Ie}&:disabled{cursor:not-allowed;}`,vp=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{var w,k;const[s,o]=c.useState(t),[a,l]=c.useState(!1),{stringSet:u,format:d}=re(),{config:m}=fe(),h=e.length,f=e[s],v=((k=(w=m==null?void 0:m.conversation)==null?void 0:w.fileViewer)==null?void 0:k.downloadEnabled)!==!1,b=h>1,C=(f==null?void 0:f.type)||"",g=at(C),y=to(C),E=!em(C);c.useEffect(()=>{r&&(o(t),l(!1))},[r,t]);const I=c.useCallback(()=>{s>0&&(o(N=>N-1),l(!1))},[s]),A=c.useCallback(()=>{s<h-1&&(o(N=>N+1),l(!1))},[s,h]);return c.useEffect(()=>{if(!r)return;const N=W=>{W.key==="ArrowLeft"?I():W.key==="ArrowRight"&&A()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[r,I,A]),!r||!f?null:i.createElement(ut,{onClose:n,visible:r,portalContainerId:ve.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(yp,null,i.createElement(Sp,null,i.createElement(Ap,null,i.createElement(xp,null,i.createElement(B,{variant:"button",maxTextLines:1,color:p.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&i.createElement(B,{variant:"caption2",color:p.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),i.createElement(Tp,{type:"close",size:18,color:p.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(Ip,{onClick:N=>N.currentTarget===N.target&&n()},b&&i.createElement(Fs,{$position:"left",type:"chevron-right",size:22,color:p.color.ondark.textHighEmphasis,onClick:I,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),i.createElement(wp,null,g&&i.createElement(i.Fragment,null,!a&&i.createElement(Mp,null,i.createElement(dt,{size:32},i.createElement(Z,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(kp,{src:f.url,alt:f.name||"Image",$loaded:a,onLoad:()=>l(!0)})),y&&i.createElement(Lp,{controls:!0},i.createElement("source",{src:f.url,type:C})),E&&i.createElement(Rp,null,i.createElement(B,{variant:"h1",color:p.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),b&&i.createElement(Fs,{$position:"right",type:"chevron-right",size:22,color:p.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),i.createElement(Op,null,b&&i.createElement(B,{variant:"body2",color:p.color.ondark.textHighEmphasis},s+1,"/",h),v&&!E&&i.createElement(Np,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:p.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},yp=_.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${p.themedColor.bg_50_600};`,Sp=_.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 12px 12px 16px;min-height:56px;background-color:${p.color.overlay.dark};`,Ap=_.default.div`flex:1;min-width:0;padding-right:8px;`,xp=_.default.div`display:flex;flex-direction:column;gap:2px;`,Tp=_.default(Je)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Cn=_.default.div`display:flex;align-items:center;justify-content:center;`,Ip=_.default(Cn)`flex:1;min-height:0;position:relative;`,wp=_.default(Cn)`position:relative;max-width:100%;max-height:100%;`,Mp=_.default(Cn)`position:absolute;inset:0;`,kp=_.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,Lp=_.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Rp=_.default(Cn)`flex-direction:column;gap:16px;`,Fs=_.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:${p.color.overlay.dark};&:disabled{opacity:0.3;}`,Op=_.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding:16px;min-height:56px;background-color:${p.color.overlay.dark};`,Np=_.default(Je)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,_i=({title:e,description:t,negativeText:n,positiveText:r,onCancel:s,onConfirm:o})=>i.createElement(Dp,null,i.createElement($p,null,i.createElement(B,{as:"div",variant:"h2",color:p.themedColor.textHighEmphasis},e)),i.createElement(Pp,null,i.createElement(B,{as:"div",variant:"body3",color:p.themedColor.textMidEmphasis},t)),i.createElement(Fp,null,i.createElement(Bp,{type:"button",onClick:s},i.createElement(B,{variant:"button",color:p.themedColor.textHighEmphasis},n)),i.createElement(Up,{type:"button",onClick:o},i.createElement(B,{variant:"button",color:p.themedColor.textHighEmphasisInverse},r)))),Dp=_.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${p.color.background50};${X.dark`
383
383
  background-color: ${p.color.background500};
384
384
  `}
385
- `,Kf=_.default.div`padding:24px 24px 16px;`,Yf=_.default.div`padding-inline:24px;`,jf=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,Xf=_.default.button`display:flex;align-items:center;justify-content:center;padding:12px 20px;border-radius:0;cursor:pointer;border:none;background:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,Zf=_.default.button`display:flex;align-items:center;justify-content:center;padding:12px 20px;border-radius:20px;cursor:pointer;border:none;background-color:${p.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,jt=16,Jf=({status:e})=>e===en.COMPLETED?i.createElement(W,{type:"done-circle",size:jt,color:p.themedColor.textHighEmphasis}):e===en.CANCELED?i.createElement(W,{type:"stop-circle",size:jt,color:p.themedColor.textLowEmphasis}):i.createElement(st,{size:jt},i.createElement(W,{type:"spinner",size:jt,color:p.themedColor.textHighEmphasis})),Zs=24,Qf=8,ep=40,tp=({task:e,isFirst:t,isLast:n})=>i.createElement(np,{role:"listitem"},i.createElement(rp,null,i.createElement(xo,{$hidden:t}),i.createElement(op,null,i.createElement(Jf,{status:e.status})),i.createElement(xo,{$hidden:n})),i.createElement(sp,null,i.createElement($,{as:"div",variant:"body3",color:e.status===en.CANCELED?p.themedColor.textLowEmphasis:p.themedColor.textHighEmphasis},e.user_facing_title))),np=_.default.div`display:flex;gap:4px;`,rp=_.default.div`display:flex;flex-direction:column;align-items:center;width:${Zs}px;flex-shrink:0;`,xo=_.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${p.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,op=_.default.div`display:flex;height:${Zs}px;align-items:center;justify-content:center;`,sp=_.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${ep}px;padding-block:${Qf}px;`,ip=({steward:e,onCancelSteward:t})=>{const{logger:n}=ne(),[r,o]=u.useState(!1),[s,a]=u.useState(!1),l=!!e.cancellation_option,c=Ni(e.status);return i.createElement(ap,{$marginBottom:hn("single")},i.createElement(lp,null,i.createElement(cp,null,i.createElement(up,null,i.createElement($,{as:"div",variant:"caption1",color:p.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement($,{as:"div",variant:"caption4",color:p.themedColor.textLowEmphasis},e.description)),l&&i.createElement(gp,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(W,{type:"stop",size:16,color:s?p.themedColor.textDisabled:p.themedColor.textHighEmphasis}))),i.createElement(dp,null),e.tasks.length===0?c!==St.IN_PROGRESS?null:i.createElement(hp,null,i.createElement(st,{size:16},i.createElement(W,{type:"spinner",size:16,color:p.themedColor.textHighEmphasis}))):i.createElement(mp,{role:"list"},e.tasks.map((d,m)=>i.createElement(tp,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(ft,{rootElementId:ce.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(Xs,{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)}}})))},ap=_.default.div`display:flex;flex-direction:column;margin:0 ${K.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
386
- `,lp=_.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${p.themedColor.bg_300_500};background-color:${p.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,cp=_.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,up=_.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,dp=_.default.div`height:1px;margin-block:12px;background-color:${p.themedColor.bg_200_400};`,mp=_.default.div`display:flex;flex-direction:column;`,hp=_.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,gp=_.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:${p.themedColor.textHighEmphasis};background-color:${p.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,fp=({className:e,label:t,onClick:n})=>{const{colors:r}=O.useTheme(),{conversation:o}=ee(),s=o.newMessagesButton;return i.createElement(pp,{className:e,onClick:n,...s.props},i.createElement($,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(W,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),s.descriptionNode)},pp=_.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;}${_e}`,Sr=({iconSize:e=64,icon:t,className:n,label:r,children:o})=>i.createElement(Ep,{className:n},t&&i.createElement(W,{type:t,size:e,color:p.themedColor.textLowEmphasis}),r&&i.createElement($,{variant:"body1",color:p.themedColor.textMidEmphasis},r),o),_p=_.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,Ep=_.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,bp=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(Sr,{icon:t,label:e,...r},n&&i.createElement(Cp,{onClick:n.onClick,label:n.label??"Retry"})),Cp=({label:e,onClick:t})=>{const{conversation:n}=ee();return i.createElement(vp,{tabIndex:0,"aria-label":n.retryButton(e)["aria-label"],onClick:t},i.createElement(W,{type:"refresh",size:20}),i.createElement($,{variant:"button",color:p.color.primary.main},e))},vp=_.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${_e}`,yp=({iconSize:e=48,className:t})=>i.createElement(st,{size:e,className:t}),Sp=({label:e="No channels",icon:t="chat",...n})=>i.createElement(Sr,{icon:t,label:e,...n}),Ap=({label:e="No messages",icon:t="message",...n})=>i.createElement(Sr,{icon:t,label:e,...n}),xp=e=>{const{components:t}=bn.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(_p,null,n)},bn=Pe({template:xp,components:{Loading:yp,Error:bp,NoChannels:Sp,NoMessages:Ap}}),At=e=>{const{Template:t}=bn.useContext();return i.createElement(t,{...e})},Tp=[0,150,450];function Ip({enabled:e}){const{state:t,actions:n}=xs(),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=Tp.map(l=>setTimeout(()=>{ve(()=>{r.current===s&&(o.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const wp=({className:e,date:t=Date.now(),style:n})=>{const{format:r,stringSet:o}=Q();return i.createElement(kp,{id:`${we}-date-separator`,style:n,className:e},i.createElement($,{variant:"caption4",color:p.themedColor.textMidEmphasis},r(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},kp=_.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Lp=({className:e,style:t,onClick:n})=>{const{conversation:r}=ee(),o=r.scrollToBottomButton;return i.createElement(Mp,{className:e,style:t,onClick:n,tabIndex:0,...o.props},i.createElement(W,{size:24,type:"chevron-down",color:p.color.primary.main}),o.descriptionNode??null)},Mp=_.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);${G.light`
385
+ `,$p=_.default.div`padding:24px 24px 16px;`,Pp=_.default.div`padding-inline:24px;`,Fp=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,Bp=_.default.button`display:flex;align-items:center;justify-content:center;padding:12px 20px;border-radius:0;cursor:pointer;border:none;background:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,Up=_.default.button`display:flex;align-items:center;justify-content:center;padding:12px 20px;border-radius:20px;cursor:pointer;border:none;background-color:${p.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,Zt=16,Hp=({status:e})=>e===rn.COMPLETED?i.createElement(Z,{type:"done-circle",size:Zt,color:p.themedColor.textHighEmphasis}):e===rn.CANCELED?i.createElement(Z,{type:"stop-circle",size:Zt,color:p.themedColor.textLowEmphasis}):i.createElement(dt,{size:Zt},i.createElement(Z,{type:"spinner",size:Zt,color:p.themedColor.textHighEmphasis})),Ei=24,Gp=8,Vp=40,zp=({task:e,isFirst:t,isLast:n})=>i.createElement(qp,{role:"listitem"},i.createElement(Wp,null,i.createElement(Bs,{$hidden:t}),i.createElement(Yp,null,i.createElement(Hp,{status:e.status})),i.createElement(Bs,{$hidden:n})),i.createElement(Kp,null,i.createElement(B,{as:"div",variant:"body3",color:e.status===rn.CANCELED?p.themedColor.textLowEmphasis:p.themedColor.textHighEmphasis},e.user_facing_title))),qp=_.default.div`display:flex;gap:4px;`,Wp=_.default.div`display:flex;flex-direction:column;align-items:center;width:${Ei}px;flex-shrink:0;`,Bs=_.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${p.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,Yp=_.default.div`display:flex;height:${Ei}px;align-items:center;justify-content:center;`,Kp=_.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${Vp}px;padding-block:${Gp}px;`,jp=({steward:e,onCancelSteward:t})=>{const{logger:n}=fe(),[r,s]=c.useState(!1),[o,a]=c.useState(!1),l=!!e.cancellation_option,u=ji(e.status);return i.createElement(Xp,{$marginBottom:gn("single")},i.createElement(Zp,null,i.createElement(Jp,null,i.createElement(Qp,null,i.createElement(B,{as:"div",variant:"caption1",color:p.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement(B,{as:"div",variant:"caption4",color:p.themedColor.textLowEmphasis},e.description)),l&&i.createElement(r_,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},i.createElement(Z,{type:"stop",size:16,color:o?p.themedColor.textDisabled:p.themedColor.textHighEmphasis}))),i.createElement(e_,null),e.tasks.length===0?u!==kt.IN_PROGRESS?null:i.createElement(n_,null,i.createElement(dt,{size:16},i.createElement(Z,{type:"spinner",size:16,color:p.themedColor.textHighEmphasis}))):i.createElement(t_,{role:"list"},e.tasks.map((d,m)=>i.createElement(zp,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(ut,{portalContainerId:ve.WINDOW,visible:r,onClose:()=>s(!1)},i.createElement(_i,{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)}}})))},Xp=_.default.div`display:flex;flex-direction:column;margin:0 ${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
386
+ `,Zp=_.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${p.themedColor.bg_300_500};background-color:${p.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,Jp=_.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,Qp=_.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,e_=_.default.div`height:1px;margin-block:12px;background-color:${p.themedColor.bg_200_400};`,t_=_.default.div`display:flex;flex-direction:column;`,n_=_.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,r_=_.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:${p.themedColor.textHighEmphasis};background-color:${p.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,s_=({className:e,label:t,onClick:n})=>{const{colors:r}=P.useTheme(),{conversation:s}=se(),o=s.newMessagesButton;return i.createElement(o_,{className:e,onClick:n,...o.props},i.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(Z,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.descriptionNode)},o_=_.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;}${Ie}`,Tr=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>i.createElement(a_,{className:n},t&&i.createElement(Z,{type:t,size:e,color:p.themedColor.textLowEmphasis}),r&&i.createElement(B,{variant:"body1",color:p.themedColor.textMidEmphasis},r),s),i_=_.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,a_=_.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,l_=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(Tr,{icon:t,label:e,...r},n&&i.createElement(c_,{onClick:n.onClick,label:n.label??"Retry"})),c_=({label:e,onClick:t})=>{const{conversation:n}=se();return i.createElement(u_,{tabIndex:0,"aria-label":n.retryButton(e)["aria-label"],onClick:t},i.createElement(Z,{type:"refresh",size:20}),i.createElement(B,{variant:"button",color:p.color.primary.main},e))},u_=_.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Ie}`,d_=({iconSize:e=48,className:t})=>i.createElement(dt,{size:e,className:t}),m_=({label:e="No channels",icon:t="chat",...n})=>i.createElement(Tr,{icon:t,label:e,...n}),h_=({label:e="No messages",icon:t="message",...n})=>i.createElement(Tr,{icon:t,label:e,...n}),f_=e=>{const{components:t}=vn.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(i_,null,n)},vn=qe({template:f_,components:{Loading:d_,Error:l_,NoChannels:m_,NoMessages:h_}}),Lt=e=>{const{Template:t}=vn.useContext();return i.createElement(t,{...e})},g_=[0,150,450];function p_({enabled:e}){const{state:t,actions:n}=Wo(),r=c.useRef(0),s=c.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,c.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const a=g_.map(l=>setTimeout(()=>{Oe(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const __=({className:e,date:t=Date.now(),style:n})=>{const{format:r,stringSet:s}=re();return i.createElement(E_,{id:`${He}-date-separator`,style:n,className:e},i.createElement(B,{variant:"caption4",color:p.themedColor.textMidEmphasis},r(t,s.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},E_=_.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,b_=({className:e,style:t,onClick:n})=>{const{conversation:r}=se(),s=r.scrollToBottomButton;return i.createElement(C_,{className:e,style:t,onClick:n,tabIndex:0,...s.props},i.createElement(Z,{size:24,type:"chevron-down",color:p.color.primary.main}),s.descriptionNode??null)},C_=_.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:24px;box-shadow:0 2px 8px 0 rgba(0,0,0,0.08),0 4px 6px 0 rgba(0,0,0,0.12);${X.light`
387
387
  background-color: ${p.color.background50};
388
388
  &:hover {
389
389
  background-color: ${p.color.background100};
@@ -392,7 +392,7 @@
392
392
  background-color: ${p.color.background200};
393
393
  }
394
394
  `}
395
- ${G.dark`
395
+ ${X.dark`
396
396
  background-color: ${p.color.background400};
397
397
  &:hover {
398
398
  background-color: ${p.color.background500};
@@ -406,19 +406,15 @@
406
406
  outline: none;
407
407
  }
408
408
 
409
- ${_e}
410
- `,Rp=()=>null,Cn=Pe({template:Rp,components:{DateSeparator:wp,ScrollToBottomButton:Lp}}),Op=()=>{const{stringSet:e,format:t}=Q(),{agentPreviewConfigs:n={},aiAgentId:r}=ne(),{aiAgentInfo:o}=Ee(),{messageSource:s}=he(),{Template:a}=Je.useContext(),{components:l}=Cn.useContext(),c=n.welcomeMessages??[],d=s.messages,m=nd(d,r),h=d[m.length+1],g=m[0]??h;return{filteredMessages:Is(d,{previewWelcomeMessages:c,aiAgentUserId:r}),shouldShowOriginalDate:C=>C>0||c.length===0?!0:h&&!We.isSameDay(h.createdAt,(g==null?void 0:g.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>c.length===0?null:i.createElement(i.Fragment,null,i.createElement(l.DateSeparator,{style:{margin:"16px 0"},date:g==null?void 0:g.createdAt}),c.map((C,b)=>{const v=b===c.length-1,f=m.length!==d.length,y=c.length===1?"single":b===0?"top":v||f?"bottom":"middle",E=(g==null?void 0:g.createdAt)??Date.now();return i.createElement("div",{key:b,role:"listitem",tabIndex:-1,"aria-label":dt({sender:(o==null?void 0:o.nickname)||"",message:C.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:C.message,sender:o,groupType:y,createdAt:E,extendedMessagePayload:{suggested_replies:C.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!f,isBotMessage:!0,onClickSuggestedReply:async({reply:x})=>{s.sendUserMessage({message:x})}}))}))}},Np=()=>{const{messageSource:e,scrollSource:t}=he();u.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},$p=e=>_.default(e).withConfig({shouldForwardProp:Oi.default}),Dp=({style:e})=>{const{stringSet:t}=Q(),{conversation:n}=ee(),{isActionbookTester:r}=pt();return!ur("powered-by")||r?null:i.createElement(Pp,{variant:"caption2",style:e},t.POWERED_BY+" ",i.createElement(Fp,{variant:"caption2",as:"a",href:"https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",...n.poweredByLink,rel:hr,target:"_blank"},"Sendbird"))},Pp=_.default($)`color:${p.themedColor.textLowEmphasis};text-align:center;`,Fp=$p($)`
411
- color: ${p.themedColor.textLowEmphasis};
412
- cursor: pointer;
413
- text-decoration: none;
414
- `,Bp=()=>{var c;const{stringSet:e}=Q(),{conversation:t}=ee(),{channelSource:n,goToActiveConversation:r,scrollSource:o}=he(),s=Ce(n.channel),a=u.useRef(s);if(u.useEffect(()=>{if(!a.current&&s){const h=setTimeout(()=>{o.actions.scrollToBottom()},100);return()=>clearTimeout(h)}a.current=s},[s,o.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!s)return null;const l=t.startNewConversationButton({onActivate:r});return i.createElement(Hp,null,i.createElement(Up,{variant:"button",color:p.themedColor.textHighEmphasis,...l},e.TALK_TO_AGENT))},Hp=_.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Up=_.default($)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${p.color.background50};border:1px solid ${p.color.onlight.textDisabled};${G.dark`
409
+ ${Ie}
410
+ `,v_=()=>null,yn=qe({template:v_,components:{DateSeparator:__,ScrollToBottomButton:b_}}),y_=()=>{const{stringSet:e,format:t}=re(),{agentPreviewConfigs:n={},aiAgentId:r}=fe(),{aiAgentInfo:s}=Ne(),{messageSource:o}=ye(),{Template:a}=rt.useContext(),{components:l}=yn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=nm(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:Ko(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:v=>v>0||u.length===0?!0:h&&!et.isSameDay(h.createdAt,(f==null?void 0:f.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:i.createElement(i.Fragment,null,i.createElement(l.DateSeparator,{style:{margin:"16px 0"},date:f==null?void 0:f.createdAt}),u.map((v,b)=>{const C=b===u.length-1,g=m.length!==d.length,y=u.length===1?"single":b===0?"top":C||g?"bottom":"middle",E=(f==null?void 0:f.createdAt)??Date.now();return i.createElement("div",{key:b,role:"listitem",tabIndex:-1,"aria-label":pt({sender:(s==null?void 0:s.nickname)||"",message:v.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:v.message,sender:s,groupType:y,createdAt:E,extendedMessagePayload:{suggested_replies:v.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:C&&!g,isBotMessage:!0,onClickSuggestedReply:async({reply:I})=>{o.sendUserMessage({message:I})}}))}))}},S_=()=>{const{messageSource:e,scrollSource:t}=ye();c.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},A_=({style:e})=>{const{stringSet:t}=re(),{conversation:n}=se(),{isActionbookTester:r}=St();return!mr("powered-by")||r?null:i.createElement(x_,{variant:"caption2",style:e},t.POWERED_BY+" ",i.createElement(T_,{variant:"caption2",forwardedAs:"a",href:"https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",...n.poweredByLink,rel:pr,target:"_blank"},"Sendbird"))},x_=_.default(B)`color:${p.themedColor.textLowEmphasis};text-align:center;`,T_=_.default(B)`color:${p.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,I_=()=>{var u;const{stringSet:e}=re(),{conversation:t}=se(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=ye(),o=De(n.channel),a=c.useRef(o);if(c.useEffect(()=>{if(!a.current&&o){const h=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(h)}a.current=o},[o,s.actions.scrollToBottom]),!((u=n.channel)!=null&&u.isAIAgent)||!o)return null;const l=t.startNewConversationButton({onActivate:r});return i.createElement(w_,null,i.createElement(M_,{variant:"button",color:p.themedColor.textHighEmphasis,...l},e.TALK_TO_AGENT))},w_=_.default.div`display:flex;justify-content:center;margin-bottom:16px;`,M_=_.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${p.color.background50};border:1px solid ${p.color.onlight.textDisabled};${X.dark`
415
411
  background-color: ${p.color.background700};
416
412
  border-color: ${p.color.ondark.textLowEmphasis};
417
413
  `}
418
- `,Vp=()=>{var Y,te,re,q;const{Template:e}=Nt.useContext(),{Template:t}=Je.useContext(),{Template:n}=_n.useContext(),{components:r}=Cn.useContext(),{stringSet:o,format:s}=Q(),{conversation:a}=ee(),{config:l,cache:c,agentPreviewConfigs:d,chatSDK:m,state:h}=ne(),{userSession:g,aiAgentInfo:C,connectionError:b}=Ee(),{conversation:v,channelSource:f,messageSource:y,scrollSource:E,state:{input:x,streamAnimation:S}}=he(),{isActionbookTester:I}=pt(),{filteredMessages:k,shouldShowOriginalDate:M,renderAgentPreviewWelcomeMessages:U}=Op(),F=os(f.channel),[z,L]=u.useState(null),[P,N]=u.useState(null);u.useEffect(()=>{E.actions.onTypingIndicatorUpdate(!!F)},[!!F,E.actions.onTypingIndicatorUpdate]),Np(),Ip({enabled:y.initialized&&y.messages.length>0});const w=(T,V=!1)=>{var H;return V?C:((H=f.channel)==null?void 0:H.members.find(j=>j.userId===T.sender.userId))??T.sender},D=T=>{if(T.sendingStatus==="failed"&&!x.disabled)return()=>N(T)},R=({message:T,index:V})=>{const H=$i(T),j=k[V-1],se=k[V+1],le=k[k.length-1],Oe=T===le,Ae=Tt(T,C.userId),B=!(C.isUserFeedbackEnabled&&Ae&&!De.isWelcomeMessage(T)),Z=Di(T,j,se,B),X=!Ii.isSameDay((j==null?void 0:j.createdAt)??0,T.createdAt)&&M(V)&&!I,ge=xe=>{L({files:xe.files.map(et=>({...et,timestamp:T.createdAt})),index:xe.index})},ye=xe=>{ge({files:[xe],index:0})},Be=()=>{T.isFileMessage()&&pr(T.url)},at=X?i.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:T.createdAt}):null,Le={data:T.data,maxBodyWidth:h.expanded?K.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:T.extendedMessagePayload,createdAt:T.createdAt,groupType:Z,onClickMedia:ye,onClickMediaFiles:ge,onClickFile:Be},Ve=()=>{if(pe.isOutgoing(T,g.userId))return"outgoingmessage";if(pe.isIncoming(T,g.userId))return"incomingmessage"},lt=T.createdAt!=null&&T.createdAt!==0?s(T.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,Qe=(()=>{var et,Et,Te,J,de,Ie;const xe=(et=T.message)==null?void 0:et.trim();if(T.isFileMessage()){const Dt=((Et=T.name)==null?void 0:Et.trim())||"";return mt({markdownText:xe,comparisonText:Dt,plainText:a.file.label(Dt,T.type)})}if(T.isMultipleFilesMessage()){const Dt=((de=(J=(Te=T.fileInfoList)==null?void 0:Te[0])==null?void 0:J.fileName)==null?void 0:de.trim())||"",Lr=((Ie=T.fileInfoList)==null?void 0:Ie.length)??0;return mt({markdownText:xe,comparisonText:Dt,plainText:Lr>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Lr):""})}return xe?mt({markdownText:xe}):mr("")})(),vi=(()=>{if(pe.isAdmin(T))return dt({message:Qe.text,messageFormat:Qe.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(pe.isOutgoing(T,g.userId))return dt({sender:o.A11Y_MESSAGE_SENDER_YOU,message:Qe.text,messageFormat:"plain",time:lt,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(pe.isIncoming(T,g.userId))return dt({sender:w(T,Ae).nickname,message:Qe.text,messageFormat:Qe.format,time:lt,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),yi=(()=>{var xe,et,Et;if(pe.isAdmin(T))return pe.isCSAT(T)?v?i.createElement(n,{...Le,...v,isResolvedWhenDeterminedByUser:la(v),messageType:"admin.csat",onSubmitCSAT:async Te=>{var J;await((J=f.channel)==null?void 0:J.submitCSAT(Te))},onScrollToBottom:()=>E.actions.scrollToBottom()}):null:i.createElement(n,{...Le,messageType:"admin",message:T.message});if(pe.isSteward(T))return i.createElement(ip,{steward:T.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:T.channelUrl,messageId:T.messageId})}});if(pe.isOutgoing(T,g.userId)){const Te={...Le,message:T.message,sender:w(T),sendingStatus:T.sendingStatus,onClickFailedMessage:D(T)};if(T.isUserMessage())return i.createElement(e,{messageType:"user",...Te});if(T.isFileMessage()){const[J,de]=((xe=T.metaArrays.find(Ie=>Ie.key===Bo))==null?void 0:xe.value)??[];return i.createElement(e,{messageType:"file",file:T,metadata:{aspectRatio:J&&de?`${J}/${de}`:"1/1",localFile:(et=T.messageParams)==null?void 0:et.file},...Te})}if(T.isMultipleFilesMessage()){const{files:J,metadata:de}=mo(T);return i.createElement(e,{messageType:"multipleFiles",files:J,metadata:de,...Te})}}if(pe.isIncoming(T,g.userId)){const Te={...Le,sender:w(T,Ae),message:T.message,suggestedRepliesVisible:Oe,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:Ae,isStreaming:De.isStreaming(T),isHandedOff:je(f.channel),isConversationClosed:Ce(f.channel),isFeedbackEnabled:C.isUserFeedbackEnabled,isFeedbackCommentEnabled:C.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(Et=l==null?void 0:l.conversation)==null?void 0:Et.senderAvatarEnabled,onClickSuggestedReply:async({reply:J})=>{y.sendUserMessage({message:J})},onRequestMessageTemplate:async J=>{const{template:de}=await m.aiAgent.getMessageTemplate(J);return c.template.set(J,de),de},onGetCachedMessageTemplate:J=>c.template.get(J),onHandleTemplateInternalAction:J=>{if(J.type==="internal"&&J.internalData){const{method:de,payload:Ie}=J.internalData;de==="message.send"&&(Ie!=null&&Ie.message)&&y.sendUserMessage({message:Ie.message})}},onFeedbackUpdate:J=>{const de={messageId:T.messageId,channelUrl:T.channelUrl};if(!J)return m.aiAgent.deleteMessageFeedback(de);const Ie={...de,rating:Rm(J.rating),comment:J.comment};return De.hasFeedback(T)?m.aiAgent.updateMessageFeedback(Ie):m.aiAgent.createMessageFeedback(Ie)},onSubmitForm:({key:J,data:de})=>m.aiAgent.submitForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:J,formData:de}),onCancelForm:({key:J})=>m.aiAgent.cancelForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:J}),onStreamAnimationStart:()=>{S.start(T.messageId)},onStreamAnimationProgress:()=>{E.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{S.stop(T.messageId),E.actions.onStreamingUpdate(!1)}};if(T.isUserMessage())return i.createElement(t,{messageType:"user",...Te});if(T.isFileMessage())return i.createElement(t,{messageType:"file",file:T,...Te});if(T.isMultipleFilesMessage()){const{files:J}=mo(T);return i.createElement(t,{messageType:"multipleFiles",files:J,...Te})}}})();return i.createElement("div",{key:H,id:`${we}-message-item`,role:"listitem",tabIndex:-1,"aria-label":vi,"data-message-listitem":"","data-layout-id":Ve()},at,yi)};return i.createElement(Gp,{id:`${we}-message-list`},i.createElement(xf,{ref:E.ref,onScroll:E.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:k,renderMessage:R,onLoadPrev:y.loadPrevious,onLoadNext:y.loadNext,depsForResetScrollPositionToBottom:[y.initialized,y.messages.length!==0],bottomSpacerHeight:E.state.bottomSpace,ariaLabel:o.A11Y_MESSAGE_LIST,loading:!y.initialized||!f.channel,empty:k.length===0&&!F,error:!!(b||f.error),LoadingComponent:i.createElement(At,{type:"loading"}),EmptyComponent:(()=>{const T=U();return T?i.createElement("div",{style:{width:"100%"}},T):i.createElement(At,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(At,{type:"error",label:(b==null?void 0:b.message)??((Y=f.error)==null?void 0:Y.message),action:f.error?{label:o.RETRY,onClick:()=>f.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(Dp,{style:{marginTop:16}}),U()),messageBottomArea:i.createElement(i.Fragment,null,F&&i.createElement("div",{id:`${we}-message-item`,role:"listitem",tabIndex:-1,"aria-label":dt({sender:F.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:k.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:F.isBot,sender:F.user,thinkingMessage:F.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(te=l==null?void 0:l.conversation)==null?void 0:te.senderAvatarEnabled})),((re=l==null?void 0:l.conversation)==null?void 0:re.isTalkToAgentViewEnabled)&&i.createElement(Bp,null)),overlayArea:i.createElement(i.Fragment,null,((q=l==null?void 0:l.conversation)==null?void 0:q.newMessageIndicatorEnabled)&&E.state.isAwayFromBottom&&y.newMessages.length>0&&i.createElement(zp,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(y.newMessages),onClick:()=>E.actions.scrollToBottom()}),E.state.isAwayFromBottom&&y.newMessages.length===0&&!F&&i.createElement(r.ScrollToBottomButton,{onClick:()=>E.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),z&&i.createElement(Mf,{files:z.files,initialIndex:z.index,onClose:()=>L(null),visible:!0}),P&&i.createElement(Ke,{visible:!0,onClose:()=>N(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(Ke.ActionItem,{onClick:()=>{y.resendMessage(P),N(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(Ke.ActionItem,{destructive:!0,onClick:()=>{y.deleteMessage(P),N(null)}},o.FAILED_MESSAGE_REMOVE)))},Gp=_.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,zp=_.default(fp)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Wp=()=>i.createElement(Vp,null),qp=()=>{var o;const{origin:e}=pt(),{appId:t,aiAgentId:n}=ke(),{channelSource:r}=he();return(o=r.channel)!=null&&o.conversation?i.createElement(Kp,null,i.createElement(Zn,{style:{gap:4}},i.createElement(W,{color:p.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement($,{as:"i",color:p.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($,{variant:"body3",color:p.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:p.themedColor.primary}},"conversation link")),i.createElement(W,{color:p.themedColor.primary,size:14,type:"copy"}))):null},Zn=_.default.div`display:flex;justify-content:center;align-items:center;`,Kp=_.default(Zn)`flex-direction:column;padding-block:16px;background-color:${p.themedColor.bg_100_500};gap:8px;`,Yp=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>ze(o.type)),r=e.some(o=>!ze(o.type));return n&&r?ze(t.type)?e.filter(o=>ze(o.type)):[t]:r?[t]:e},jp=(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}},Js=u.createContext(void 0),Xp=({children:e})=>{var L,P;const{chatSDK:t}=ne(),{createAttachmentRules:n}=Ee(),{stringSet:r}=Q(),{channelSource:o,state:s}=he(),[a,l]=u.useState([]),{announceError:c}=fr(),[d,m]=u.useState(null),h=n({channel:o.channel,uploadSizeLimit:(L=t.appInfo)==null?void 0:L.uploadSizeLimit}),g=((P=s==null?void 0:s.input)==null?void 0:P.disabled)??!1,C=h.isEnabled(),b=h.maxAttachmentCount,v=()=>m(null),f=N=>m(N),y=()=>{f({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",b.toString())})},E=N=>{f({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",N.toString())}),c({type:"fileSizeExceeded",maxSizeMB:N})},x=N=>{f({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",N.toString())})},S=N=>N.map(w=>({file:w,preview:{url:URL.createObjectURL(w),type:w.type,name:w.name}})),I=N=>{l(w=>[...w,...S(N)])},k=N=>{l(w=>(w.forEach(D=>URL.revokeObjectURL(D.preview.url)),S(N)))},M=N=>{const{passed:w,failedBySize:D,failedByType:R}=jp(N,h),Y=D.length+R.length,te=N.length===1?D[0]:void 0;return te?E(h.getUploadSizeLimitInMB(te.type)):Y>0&&x(Y),w},U=N=>{if(!C||g||N.length===0)return;if(a.length>=b||a.length+N.length>b){y();return}const w=Yp(N),D=a.every(re=>ze(re.file.type)),R=w.every(re=>ze(re.type));if(a.length>0&&D!==R){f({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>{const re=M(w);re.length>0&&k(re)}});return}const Y=M(w);if(Y.length===0)return;a.length>0&&D&&R?I(Y):k(Y)},F=N=>{l(w=>{var R;const D=(R=w[N])==null?void 0:R.preview;return D&&URL.revokeObjectURL(D.url),w.filter((Y,te)=>te!==N)})},z=()=>{l(N=>(N.forEach(w=>URL.revokeObjectURL(w.preview.url)),[]))};return i.createElement(Js.Provider,{value:{files:a,addFiles:U,removeFile:F,clearFiles:z,isFileUploadEnabled:C,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:f}},e,i.createElement(_r,{visible:!!d,...d??{},onClose:v}))},Ar=()=>{const e=u.useContext(Js);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Zp({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 Jp=()=>{const{announceError:e}=ot();return u.useCallback(t=>{e({type:"sendFailed"},t)},[e])},Qp=1e3,e_=(e,t,n)=>{const{announcementsActive:r,setIsSuppressed:o}=ot(),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]),Bl(t,c,{enabled:s,idleMs:Qp})},t_=({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=h=>{const g=h;g.metaKey||g.altKey||g.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}}},n_=_.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,r_=_.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;}`,o_=_.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;${G.light`
414
+ `,k_=()=>{var Q,ae,de,we;const{Template:e}=Pt.useContext(),{Template:t}=rt.useContext(),{Template:n}=bn.useContext(),{components:r}=yn.useContext(),{stringSet:s,format:o}=re(),{conversation:a}=se(),{config:l,cache:u,agentPreviewConfigs:d,chatSDK:m,state:h}=fe(),{userSession:f,aiAgentInfo:v,connectionError:b}=Ne(),{conversation:C,channelSource:g,messageSource:y,scrollSource:E,state:{input:I,streamAnimation:A}}=ye(),{isActionbookTester:w}=St(),{filteredMessages:k,shouldShowOriginalDate:N,renderAgentPreviewWelcomeMessages:W}=y_(),G=vo(g.channel),[K,L]=c.useState(null),[V,Y]=c.useState(null);c.useEffect(()=>{E.actions.onTypingIndicatorUpdate(!!G)},[!!G,E.actions.onTypingIndicatorUpdate]),S_(),p_({enabled:y.initialized&&y.messages.length>0});const x=(T,F=!1)=>{var z;return F?v:((z=g.channel)==null?void 0:z.members.find(J=>J.userId===T.sender.userId))??T.sender},D=T=>{if(T.sendingStatus==="failed"&&!I.disabled)return()=>Y(T)},$=({message:T,index:F})=>{const z=Xi(T),J=k[F-1],me=k[F+1],pe=k[k.length-1],Pe=T===pe,Me=Et(T,v.userId),M=!(v.isUserFeedbackEnabled&&Me&&!Ke.isWelcomeMessage(T)),R=Zi(T,J,me,M),O=!qi.isSameDay((J==null?void 0:J.createdAt)??0,T.createdAt)&&N(F)&&!w,j=ge=>{L({files:ge.files.map(be=>({...be,timestamp:T.createdAt})),index:ge.index})},q=ge=>{j({files:[ge],index:0})},U=()=>{T.isFileMessage()&&br(T.url)},H=O?i.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:T.createdAt}):null,oe={data:T.data,maxBodyWidth:h.expanded?ee.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:T.extendedMessagePayload,createdAt:T.createdAt,groupType:R,onClickMedia:q,onClickMediaFiles:j,onClickFile:U},Ge=()=>{if(Te.isOutgoing(T,f.userId))return"outgoingmessage";if(Te.isIncoming(T,f.userId))return"incomingmessage"},ne=T.createdAt!=null&&T.createdAt!==0?o(T.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ie=(()=>{var be,ke,Le,te,Se,Be;const ge=(be=T.message)==null?void 0:be.trim();if(T.isFileMessage()){const Bt=((ke=T.name)==null?void 0:ke.trim())||"";return _t({markdownText:ge,comparisonText:Bt,plainText:a.file.label(Bt,T.type)})}if(T.isMultipleFilesMessage()){const Bt=((Se=(te=(Le=T.fileInfoList)==null?void 0:Le[0])==null?void 0:te.fileName)==null?void 0:Se.trim())||"",Or=((Be=T.fileInfoList)==null?void 0:Be.length)??0;return _t({markdownText:ge,comparisonText:Bt,plainText:Or>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Or):""})}return ge?_t({markdownText:ge}):fr("")})(),ce=(()=>{if(Te.isAdmin(T))return pt({message:ie.text,messageFormat:ie.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Te.isOutgoing(T,f.userId))return pt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:ie.text,messageFormat:"plain",time:ne,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Te.isIncoming(T,f.userId))return pt({sender:x(T,Me).nickname,message:ie.text,messageFormat:ie.format,time:ne,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),ue=(()=>{var ge,be,ke;if(Te.isAdmin(T))return Te.isCSAT(T)?C?i.createElement(n,{...oe,...C,isResolvedWhenDeterminedByUser:Sa(C),messageType:"admin.csat",onSubmitCSAT:async Le=>{var te;await((te=g.channel)==null?void 0:te.submitCSAT(Le))},onScrollToBottom:()=>E.actions.scrollToBottom()}):null:i.createElement(n,{...oe,messageType:"admin",message:T.message});if(Te.isSteward(T))return i.createElement(jp,{steward:T.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:T.channelUrl,messageId:T.messageId})}});if(Te.isOutgoing(T,f.userId)){const Le={...oe,message:T.message,sender:x(T),sendingStatus:T.sendingStatus,onClickFailedMessage:D(T)};if(T.isUserMessage())return i.createElement(e,{messageType:"user",...Le});if(T.isFileMessage()){const[te,Se]=((ge=T.metaArrays.find(Be=>Be.key===Qs))==null?void 0:ge.value)??[];return i.createElement(e,{messageType:"file",file:T,metadata:{aspectRatio:te&&Se?`${te}/${Se}`:"1/1",localFile:(be=T.messageParams)==null?void 0:be.file},...Le})}if(T.isMultipleFilesMessage()){const{files:te,metadata:Se}=As(T);return i.createElement(e,{messageType:"multipleFiles",files:te,metadata:Se,...Le})}}if(Te.isIncoming(T,f.userId)){const Le={...oe,sender:x(T,Me),message:T.message,suggestedRepliesVisible:Pe,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:Me,isStreaming:Ke.isStreaming(T),isHandedOff:nt(g.channel),isConversationClosed:De(g.channel),isFeedbackEnabled:v.isUserFeedbackEnabled,isFeedbackCommentEnabled:v.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(ke=l==null?void 0:l.conversation)==null?void 0:ke.senderAvatarEnabled,onClickSuggestedReply:async({reply:te})=>{y.sendUserMessage({message:te})},onRequestMessageTemplate:async te=>{const{template:Se}=await m.aiAgent.getMessageTemplate(te);return u.template.set(te,Se),Se},onGetCachedMessageTemplate:te=>u.template.get(te),onHandleTemplateInternalAction:te=>{if(te.type==="internal"&&te.internalData){const{method:Se,payload:Be}=te.internalData;Se==="message.send"&&(Be!=null&&Be.message)&&y.sendUserMessage({message:Be.message})}},onFeedbackUpdate:te=>{const Se={messageId:T.messageId,channelUrl:T.channelUrl};if(!te)return m.aiAgent.deleteMessageFeedback(Se);const Be={...Se,rating:xh(te.rating),comment:te.comment};return Ke.hasFeedback(T)?m.aiAgent.updateMessageFeedback(Be):m.aiAgent.createMessageFeedback(Be)},onSubmitForm:({key:te,data:Se})=>m.aiAgent.submitForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:te,formData:Se}),onCancelForm:({key:te})=>m.aiAgent.cancelForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:te}),onStreamAnimationStart:()=>{A.start(T.messageId)},onStreamAnimationProgress:()=>{E.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{A.stop(T.messageId),E.actions.onStreamingUpdate(!1)}};if(T.isUserMessage())return i.createElement(t,{messageType:"user",...Le});if(T.isFileMessage())return i.createElement(t,{messageType:"file",file:T,...Le});if(T.isMultipleFilesMessage()){const{files:te}=As(T);return i.createElement(t,{messageType:"multipleFiles",files:te,...Le})}}})();return i.createElement("div",{key:z,id:`${He}-message-item`,role:"listitem",tabIndex:-1,"aria-label":ce,"data-message-listitem":"","data-layout-id":Ge()},H,ue)};return i.createElement(L_,{id:`${He}-message-list`},i.createElement(gp,{ref:E.ref,onScroll:E.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:k,renderMessage:$,onLoadPrev:y.loadPrevious,onLoadNext:y.loadNext,depsForResetScrollPositionToBottom:[y.initialized,y.messages.length!==0],bottomSpacerHeight:E.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!y.initialized||!g.channel,empty:k.length===0&&!G,error:!!(b||g.error),LoadingComponent:i.createElement(Lt,{type:"loading"}),EmptyComponent:(()=>{const T=W();return T?i.createElement("div",{style:{width:"100%"}},T):i.createElement(Lt,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(Lt,{type:"error",label:(b==null?void 0:b.message)??((Q=g.error)==null?void 0:Q.message),action:g.error?{label:s.RETRY,onClick:()=>g.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(A_,{style:{marginTop:16}}),W()),messageBottomArea:i.createElement(i.Fragment,null,G&&i.createElement("div",{id:`${He}-message-item`,role:"listitem",tabIndex:-1,"aria-label":pt({sender:G.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:G.isBot,sender:G.user,thinkingMessage:G.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(ae=l==null?void 0:l.conversation)==null?void 0:ae.senderAvatarEnabled})),((de=l==null?void 0:l.conversation)==null?void 0:de.isTalkToAgentViewEnabled)&&i.createElement(I_,null)),overlayArea:i.createElement(i.Fragment,null,((we=l==null?void 0:l.conversation)==null?void 0:we.newMessageIndicatorEnabled)&&E.state.isAwayFromBottom&&y.newMessages.length>0&&i.createElement(R_,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(y.newMessages),onClick:()=>E.actions.scrollToBottom()}),E.state.isAwayFromBottom&&y.newMessages.length===0&&!G&&i.createElement(r.ScrollToBottomButton,{onClick:()=>E.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),K&&i.createElement(vp,{files:K.files,initialIndex:K.index,onClose:()=>L(null),visible:!0}),V&&i.createElement(tt,{visible:!0,onClose:()=>Y(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(tt.ActionItem,{onClick:()=>{y.resendMessage(V),Y(null)}},s.FAILED_MESSAGE_RESEND),i.createElement(tt.ActionItem,{destructive:!0,onClick:()=>{y.deleteMessage(V),Y(null)}},s.FAILED_MESSAGE_REMOVE)))},L_=_.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,R_=_.default(s_)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,O_=()=>i.createElement(k_,null),N_=()=>{var s;const{origin:e}=St(),{appId:t,aiAgentId:n}=$e(),{channelSource:r}=ye();return(s=r.channel)!=null&&s.conversation?i.createElement(D_,null,i.createElement(Jn,{style:{gap:4}},i.createElement(Z,{color:p.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement(B,{as:"i",color:p.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(Jn,{role:"button",style:{gap:4},onClick:()=>{var u,d;const o=e??window.location.origin,a=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,l=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},i.createElement(B,{variant:"body3",color:p.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:p.themedColor.primary}},"conversation link")),i.createElement(Z,{color:p.themedColor.primary,size:14,type:"copy"}))):null},Jn=_.default.div`display:flex;justify-content:center;align-items:center;`,D_=_.default(Jn)`flex-direction:column;padding-block:16px;background-color:${p.themedColor.bg_100_500};gap:8px;`,$_=(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}},bi=c.createContext(void 0),P_=({children:e})=>{var V,Y;const{chatSDK:t}=fe(),{createAttachmentRules:n}=Ne(),{stringSet:r}=re(),{channelSource:s,state:o}=ye(),[a,l]=c.useState([]),{announceError:u}=Er(),[d,m]=c.useState(null),h=n({channel:s.channel,uploadSizeLimit:(V=t.appInfo)==null?void 0:V.uploadSizeLimit}),f=((Y=o==null?void 0:o.input)==null?void 0:Y.disabled)??!1,v=h.isEnabled(),b=h.maxAttachmentCount,C=()=>m(null),g=x=>m(x),y=()=>{g({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",b.toString())})},E=x=>{g({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",x.toString())}),u({type:"fileSizeExceeded",maxSizeMB:x})},I=x=>{g({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",x.toString())})},A=x=>x.map(D=>({file:D,preview:{url:URL.createObjectURL(D),type:D.type,name:D.name}})),w=x=>{l(D=>[...D,...A(x)])},k=x=>{l(D=>(D.forEach($=>URL.revokeObjectURL($.preview.url)),A(x)))},N=x=>{const{passed:D,failedBySize:$,failedByType:Q}=$_(x,h),ae=$.length+Q.length,de=x.length===1?$[0]:void 0;return de?E(h.getUploadSizeLimitInMB(de.type)):ae>0&&I(ae),D},W=x=>{const D=N(x.files);D.length!==0&&(x.type==="append"?w(D):k(D))},G=x=>{if(!v||f||!Za(x))return;const D=Qa({currentFiles:a.map(({file:$})=>$),incomingFiles:x,maxAttachmentCount:b});switch(D.type){case"reject":y();return;case"confirm_replace":g({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>W(D.action)});return;case"apply":W(D.action);return}},K=x=>{l(D=>{var Q;const $=(Q=D[x])==null?void 0:Q.preview;return $&&URL.revokeObjectURL($.url),D.filter((ae,de)=>de!==x)})},L=()=>{l(x=>(x.forEach(D=>URL.revokeObjectURL(D.preview.url)),[]))};return i.createElement(bi.Provider,{value:{files:a,addFiles:G,removeFile:K,clearFiles:L,isFileUploadEnabled:v,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:g}},e,i.createElement(Cr,{visible:!!d,...d??{},onClose:C}))},Ir=()=>{const e=c.useContext(bi);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function F_({elementRef:e,ready:t,onRestore:n}){const r=c.useRef(!1);c.useEffect(()=>{var a;!t||!r.current||(n==null||n(),(a=e.current)==null||a.focus(),r.current=!1)},[t,n]);const s=c.useCallback(()=>{r.current=!0},[]),o=c.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function B_({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=c.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),c.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const U_=()=>{const{announceError:e}=st();return c.useCallback(t=>{e({type:"sendFailed"},t)},[e])},H_=1e3,G_=(e,t,n)=>{const{announcementsActive:r,setIsSuppressed:s}=st(),o=n??!0,a=c.useRef(!1),l=c.useRef(void 0),u=c.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]);c.useLayoutEffect(()=>{s(a.current)},[r,s]),pc(t,u,{enabled:o,idleMs:H_})},V_=({enabled:e=!0,focusRoot:t})=>{const[n,r]=c.useState(!1),s=c.useRef(!1),o=c.useRef(!1);c.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=c.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),l=c.useCallback(()=>{r(!1)},[]),u=c.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:a,onBlur:l}}},z_=_.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,q_=_.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;}`,W_=_.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;${X.light`
419
415
  background-color: ${p.color.background50};
420
416
  `}
421
- ${G.dark`
417
+ ${X.dark`
422
418
  background-color: ${p.color.background500};
423
419
  `}
424
420
  path {
@@ -440,7 +436,7 @@
440
436
  circle {
441
437
  stroke: ${p.themedColor.bg_50_600};
442
438
  }
443
- `,s_=()=>{const e=Mt(),{conversation:t}=ee(),{files:n,removeFile:r,isFileUploadEnabled:o}=Ar();return o&&n.length>0?i.createElement(n_,null,n.map(({preview:{type:a,name:l,url:c}},d)=>{const m=t.file.removeButton(l),g=t.file.preview({name:l,mimeType:a,selected:!0}).props["aria-label"];return i.createElement(r_,{key:c},i.createElement(o_,{type:"button",title:m["aria-label"],"aria-label":m["aria-label"],$mobile:e,onClick:()=>r(d)},i.createElement(W,{type:"close-filled",color:p.themedColor.textMidEmphasis})),a.startsWith("image/")?i.createElement("img",{alt:g,src:c}):i.createElement(br,{name:l,mimeType:a,type:er(l,a),ariaLabel:g}))})):null},i_={textArea:O.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Qs=_.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${_e}`,To=_.default.div`width:100%;position:relative;background-color:${p.themedColor.bg_100_500};border-radius:20px;`,Io=_.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,wo=_.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:${p.themedColor.textHighEmphasis};resize:none;width:100%;height:${ms}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${Cs&&i_.textArea};${({$focusVisible:e})=>e&&O.css`
439
+ `,Y_=()=>{const e=Dt(),{conversation:t}=se(),{files:n,removeFile:r,isFileUploadEnabled:s}=Ir();return s&&n.length>0?i.createElement(z_,null,n.map(({preview:{type:a,name:l,url:u}},d)=>{const m=t.file.removeButton(l),h=t.file.preview({name:l,mimeType:a,selected:!0});return i.createElement(q_,{key:u},i.createElement(W_,{type:"button",...m,$mobile:e,onClick:()=>r(d)},i.createElement(Z,{type:"close-filled",color:p.themedColor.textMidEmphasis})),a.startsWith("image/")?i.createElement("img",{alt:h.props["aria-label"],src:u}):i.createElement(yr,{name:l,mimeType:a,type:nr(l,a),selected:!0}))})):null},K_={textArea:P.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Ci=_.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Ie}`,Us=_.default.div`width:100%;position:relative;background-color:${p.themedColor.bg_100_500};border-radius:20px;`,Hs=_.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Gs=_.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:${p.themedColor.textHighEmphasis};resize:none;width:100%;height:${Lo}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${Vo&&K_.textArea};${({$focusVisible:e})=>e&&P.css`
444
440
  outline: 2px solid ${p.themedColor.primary};
445
441
  outline-offset: 2px;
446
442
  `}
@@ -456,15 +452,15 @@
456
452
  }
457
453
  }
458
454
 
459
- ${({$blocked:e})=>e&&O.css`cursor:not-allowed;&::placeholder{color:${p.themedColor.textDisabled};}`}
460
- `,a_=_.default.input`display:none;`;_.default.div`display:flex;align-items:center;gap:24px;`;const l_=_.default(Qs)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${p.themedColor.bg_100_500};path{fill:${p.themedColor.textHighEmphasis};}}&:active{background-color:${p.themedColor.bg_200_400};}}`,ko=_.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Lo=e=>e.startsWith("image/"),Mo=({disabled:e})=>{var k,M,U,F,z;const{stringSet:t}=Q(),{conversation:n}=ee(),{config:r}=ne(),o=u.useRef(null),s=u.useRef(null),[a,l]=u.useState(!1),{addFiles:c,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=Ar(),g=m.includes(Hn),C=g?["image/*"]:m.filter(Lo),b=g?[Hn]:m.filter(L=>!Lo(L)),v=!!((U=(M=(k=r==null?void 0:r.conversation)==null?void 0:k.input)==null?void 0:M.gallery)!=null&&U.photoEnabled),f=!!((z=(F=r==null?void 0:r.conversation)==null?void 0:F.input)!=null&&z.fileEnabled),y=()=>g||C.length>0,E=()=>g||b.length>0,x=L=>{const P=L.currentTarget.files;P&&c(Array.from(P)),L.target.value=""},S=()=>{l(!0)},I=u.useMemo(()=>{const L=[];return v&&L.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:C.join(","),inputRef:o,onSelect:()=>{if(!y()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var P;return(P=o.current)==null?void 0:P.click()},100)}}),f&&L.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:s,onSelect:()=>{if(!E()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var P;return(P=s.current)==null?void 0:P.click()},100)}}),L},[C,m,t,v,f]);return d?i.createElement(i.Fragment,null,i.createElement(l_,{...n.messageInput.attachFileButton.props,disabled:e,onClick:S},i.createElement(W,{type:"add",color:e?p.themedColor.textDisabled:p.color.primary.main,size:20}),n.messageInput.attachFileButton.descriptionNode),I.map(L=>i.createElement(a_,{key:L.type,type:"file",ref:L.inputRef,multiple:L.type==="image",onChange:x,accept:L.accept})),i.createElement(Ke,{visible:a,onClose:()=>l(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},I.map(L=>i.createElement(Ke.ActionItem,{key:L.type,onClick:L.onSelect,icon:L.icon},L.label)))):null},c_=()=>{const e=u.useRef(null),[t,n]=u.useState(""),{stringSet:r}=Q(),{conversation:o}=ee(),{rootElement:s}=ne(),a=He(s),{focusHandlers:l,isFocusVisible:c,suppressNextFocusVisible:d}=t_({focusRoot:a}),{channelSource:m,messageSource:h,state:g}=he(),{files:C,addFiles:b,clearFiles:v}=Ar(),f=Jp(),y=u.useRef(!1),{_mode:E,disabled:x,disabledBy:S}=g.input,I=E==="readOnly",k=o.messageInput.textInput(r.A11Y_MESSAGE_INPUT),M=(()=>{if(!x)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(S){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}})();Qu({onDropFiles:q=>{b(q)}}),Zp({blurred:E==="disabled",elementRef:e,document:a,onRecoverFocus:()=>{d()}}),e_(m.channel,t,!x);const U=t.trim().length>0,F=C.length>0,z=!x&&(U||F),L=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},P=()=>{var q;d(),(q=e.current)==null||q.focus()};u.useEffect(()=>{var q;E!=="readOnly"||!y.current||(d(),(q=e.current)==null||q.focus(),y.current=!1)},[E,d]);const N=q=>{y.current=!1,f(q)},w=()=>{y.current=!1},D=async q=>{try{await q(),w()}catch{N(e.current)}},R=async()=>{if(x)return;const q=t.trim();if(!q&&!C.length)return;const T=[...C];if(y.current=!0,L(),P(),T.length===0){await D(()=>h.sendUserMessage({message:q}));return}if(T.length===1)await D(()=>h.sendFileMessage({message:q,file:T[0].file}));else{const V=T.map(({file:H})=>({file:H}));await D(()=>h.sendMultipleFilesMessage({message:q,fileInfoList:V}))}},Y=q=>{const T=Array.from(q.clipboardData.files);T.length>0&&(q.preventDefault(),b(T))},te=q=>{q.key!=="Enter"||q.nativeEvent.isComposing||q.shiftKey||(q.preventDefault(),R())},re=q=>{if(x){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const T=Math.min(kc,e.current.scrollHeight);ms<T&&(e.current.style.height=`${T}px`)}n(q.target.value)};return E==="disabled"?i.createElement(ko,null,i.createElement(Mo,{disabled:!0}),i.createElement(To,null,i.createElement(Io,null,i.createElement(wo,{rows:1,...k,disabled:!0,placeholder:M,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):i.createElement(ko,{"data-message-composer":""},i.createElement(Mo,{disabled:x}),i.createElement(To,null,i.createElement(s_,null),i.createElement(Io,null,i.createElement(wo,{ref:e,rows:1,...k,readOnly:I,"aria-disabled":I?"true":void 0,placeholder:M,maxLength:5e3,$blocked:x,$focusVisible:c,"data-focus-visible":c?"true":"false",onKeyDown:te,onChange:re,onFocus:l.onFocus,onBlur:l.onBlur,onPaste:Y}))),z&&i.createElement(Qs,{...o.messageInput.sendButton.props,onClick:()=>R()},i.createElement(W,{type:"send",color:p.color.primary.main,size:20}),o.messageInput.sendButton.descriptionNode))},u_=_.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:${p.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${G.light`
455
+ ${({$blocked:e})=>e&&P.css`cursor:not-allowed;&::placeholder{color:${p.themedColor.textDisabled};}`}
456
+ `,j_=_.default.input`display:none;`;_.default.div`display:flex;align-items:center;gap:24px;`;const X_=_.default(Ci)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${p.themedColor.bg_100_500};path{fill:${p.themedColor.textHighEmphasis};}}&:active{background-color:${p.themedColor.bg_200_400};}}`,Vs=_.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,zs=e=>e.startsWith("image/"),qs=({disabled:e})=>{var k,N,W,G,K;const{stringSet:t}=re(),{conversation:n}=se(),{config:r}=fe(),s=c.useRef(null),o=c.useRef(null),[a,l]=c.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=Ir(),f=m.includes(Hn),v=f?["image/*"]:m.filter(zs),b=f?[Hn]:m.filter(L=>!zs(L)),C=!!((W=(N=(k=r==null?void 0:r.conversation)==null?void 0:k.input)==null?void 0:N.gallery)!=null&&W.photoEnabled),g=!!((K=(G=r==null?void 0:r.conversation)==null?void 0:G.input)!=null&&K.fileEnabled),y=()=>f||v.length>0,E=()=>f||b.length>0,I=L=>{const V=L.currentTarget.files;V&&u(Array.from(V)),L.target.value=""},A=()=>{l(!0)},w=c.useMemo(()=>{const L=[];return C&&L.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:v.join(","),inputRef:s,onSelect:()=>{if(!y()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var V;return(V=s.current)==null?void 0:V.click()},100)}}),g&&L.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!E()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var V;return(V=o.current)==null?void 0:V.click()},100)}}),L},[v,m,t,C,g]);return d?i.createElement(i.Fragment,null,i.createElement(X_,{...n.messageInput.attachFileButton.props,disabled:e,onClick:A},i.createElement(Z,{type:"add",color:e?p.themedColor.textDisabled:p.color.primary.main,size:20}),n.messageInput.attachFileButton.descriptionNode),w.map(L=>i.createElement(j_,{key:L.type,type:"file",ref:L.inputRef,multiple:L.type==="image",onChange:I,accept:L.accept})),i.createElement(tt,{visible:a,onClose:()=>l(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},w.map(L=>i.createElement(tt.ActionItem,{key:L.type,onClick:L.onSelect,icon:L.icon},L.label)))):null},Z_=()=>{const e=c.useRef(null),[t,n]=c.useState(""),{stringSet:r}=re(),{conversation:s}=se(),{rootElement:o}=fe(),a=ct(o),{focusHandlers:l,isFocusVisible:u,suppressNextFocusVisible:d}=V_({focusRoot:a}),{channelSource:m,messageSource:h,state:f}=ye(),{files:v,addFiles:b,clearFiles:C}=Ir(),g=U_(),{focusPolicy:y,disabled:E,disabledBy:I}=f.input,A=y==="preserve",w=y==="release",k=s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),N=(()=>{if(!E)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(I){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}})();Zd({onDropFiles:F=>{b(F)}}),B_({blurred:w,elementRef:e,document:a,onRecoverFocus:()=>{d()}}),G_(m.channel,t,!E);const W=t.trim().length>0,G=v.length>0,K=!E&&(W||G),L=()=>{e.current&&(e.current.value="",e.current.style.height=""),C(),n("")},V=()=>{var F;d(),(F=e.current)==null||F.focus()},{requestRestore:Y,cancelRestore:x}=F_({elementRef:e,ready:A,onRestore:d}),D=F=>{x(),g(F)},$=()=>{x()},Q=async F=>{try{await F(),$()}catch{D(e.current)}},ae=async()=>{if(E)return;const F=t.trim();if(!F&&!v.length)return;const z=[...v];if(Y(),L(),V(),z.length===0){await Q(()=>h.sendUserMessage({message:F}));return}if(z.length===1)await Q(()=>h.sendFileMessage({message:F,file:z[0].file}));else{const J=z.map(({file:me})=>({file:me}));await Q(()=>h.sendMultipleFilesMessage({message:F,fileInfoList:J}))}},de=F=>{const z=Array.from(F.clipboardData.files);z.length>0&&(F.preventDefault(),b(z))},we=F=>{F.key!=="Enter"||F.nativeEvent.isComposing||F.shiftKey||(F.preventDefault(),ae())},T=F=>{if(E){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const z=Math.min(mu,e.current.scrollHeight);Lo<z&&(e.current.style.height=`${z}px`)}n(F.target.value)};return w?i.createElement(Vs,null,i.createElement(qs,{disabled:!0}),i.createElement(Us,null,i.createElement(Hs,null,i.createElement(Gs,{rows:1,...k,disabled:!0,placeholder:N,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):i.createElement(Vs,{"data-message-composer":""},i.createElement(qs,{disabled:E}),i.createElement(Us,null,i.createElement(Y_,null),i.createElement(Hs,null,i.createElement(Gs,{ref:e,rows:1,...k,readOnly:A,"aria-disabled":A?"true":void 0,placeholder:N,maxLength:5e3,$blocked:E,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:we,onChange:T,onFocus:l.onFocus,onBlur:l.onBlur,onPaste:de}))),K&&i.createElement(Ci,{...s.messageInput.sendButton.props,onClick:()=>ae()},i.createElement(Z,{type:"send",color:p.color.primary.main,size:20}),s.messageInput.sendButton.descriptionNode))},J_=_.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:${p.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${X.light`
461
457
  color: ${p.color.information.light};
462
458
  `};
463
- ${G.dark`
459
+ ${X.dark`
464
460
  color: ${p.color.information.main};
465
461
  `};
466
462
  }
467
- `,d_=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),m_=()=>{const{aiAgentInfo:e,userSession:t}=Ee(),{messageSource:n,channelSource:r}=he(),[o,s]=u.useState(null),a=ur("special-notice",r.channel),l=u.useCallback(()=>r.channel?a?n.messages.some(c=>Tt(c,(t==null?void 0:t.userId)??"")):!0:null,[r.channel,a,n.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{o||s(l())},[l,o]),o||!e.specialNotice?null:i.createElement(u_,null,i.createElement(d_,null,e.specialNotice))},h_=()=>i.createElement(g_,null,i.createElement(m_,null),i.createElement(Xp,null,i.createElement(c_,null))),g_=_.default.div`z-index:0;border:none;width:100%;`,f_=()=>{var o;const{testerType:e}=pt(),{channelSource:t}=he(),n=Ce(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(qp,null):i.createElement(h_,null)},ei=({start:e,title:t,titleAlign:n="start",end:r})=>{const o=u.useRef(null),s=u.useRef(null),[a,l]=u.useState(0),[c,d]=u.useState(0);return u.useLayoutEffect(()=>{o.current&&l(o.current.offsetWidth),s.current&&d(s.current.offsetWidth)},[e,r]),i.createElement(p_,null,i.createElement(__,null,n==="center"&&t&&i.createElement(E_,{$sideWidth:Math.max(a,c)},i.createElement(b_,null,t)),i.createElement(C_,null,i.createElement(v_,{ref:o},e),(n==="start"||n==="end")&&t&&i.createElement(S_,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(y_,{ref:s},r))))},p_=_.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${p.themedColor.textDisabled};`,__=_.default.div`position:relative;height:56px;padding:11px 12px;`,E_=_.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,b_=_.default.div`max-width:100%;overflow:hidden;`,C_=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,v_=_.default.div`flex-shrink:0;display:flex;align-items:center;`,y_=_.default.div`flex-shrink:0;display:flex;align-items:center;`,S_=_.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=()=>Mt()?24:16,A_=()=>{const{state:e}=ne(),{messenger:t}=ee(),n=$t(),r=()=>{e.setOpened(!1)};return i.createElement(Ue,{...t.closeButton,type:"close",size:n,onClick:r})},x_=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ne(),{channelSource:n}=he(),{conversation:r}=ee(),o=n.channel,s=$t(),a=(o==null?void 0:o.isAIAgent)&&e,l=!nr(o);if(!a)return null;const c=async()=>{o&&await t.send(rt.CloseConversation({channelUrl:o.url}))};return i.createElement(i.Fragment,null,i.createElement(Ue,{...r.closeConversationButton.props,type:"mute",size:s,disabled:l,onClick:c}),r.closeConversationButton.descriptionNode)},T_=()=>{const{state:e,enableExpandButton:t}=ne(),{messenger:n}=ee(),r=$t();return t?i.createElement(Ue,{...n.expandButton(e.expanded),type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},I_=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(Jn,null,t,i.createElement(L_,{$position:n},i.createElement(M_,{variant:"caption1"},e),i.createElement(w_,{$position:n}))),w_=({$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:p.themedColor.textHighEmphasis})),k_={top:O.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:O.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Jn=_.default.div`position:relative;`,L_=_.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${gt.TOOLTIP};${({$position:e})=>k_[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Jn}:hover &,${Jn}:focus-within &{opacity:1;}`,M_=_.default($)`padding:6px 8px;background:${p.themedColor.textHighEmphasis};color:${p.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,R_=2e3,Ro=0,O_=1500,Xt=Symbol("header-focus-status-pause"),Oo="data-sb-header-focus-protected",N_="[data-message-composer]",No=new WeakMap,Pn=e=>{const t=No.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return No.set(e,n),n},Fn=(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)},$_=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),Jt(e)},D_=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)})},P_=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(N_),!1),ti=()=>{const{setStatusPauseState:e}=ot(),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()+O_,s();const c=Pn(e);Fn(c,t.current),c.focusedTargetIds.add(t.current),c.focusedTargetIds.size===1&&e(Xt,!0),Jt(c),c.maxPauseTimeout=setTimeout(()=>{$_(c),e(Xt,!1)},R_)},[s,e]),l=u.useCallback(c=>{if(!n.current)return;n.current=!1;const d=c.currentTarget,m=Pn(e),h=d instanceof HTMLElement&&Date.now()<=r.current;Fn(m,t.current),h&&(s(),o.current=setTimeout(()=>{if(o.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const C=d.ownerDocument.activeElement,b=C instanceof HTMLElement&&C.hasAttribute(Oo);if(C===d||b||!P_(C))return;const v=D_(d);d.focus({preventScroll:!0}),v()},Ro)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(Jt(m),e(Xt,!1))},Ro))},[s,e]);return u.useEffect(()=>()=>{const c=Pn(e);n.current=!1,s(),Fn(c,t.current),c.focusedTargetIds.delete(t.current)&&c.focusedTargetIds.size===0&&(Jt(c),e(Xt,!1))},[s,e]),{[Oo]:"true",onFocus:a,onBlur:l}},F_=()=>{const{logger:e}=ne(),{stringSet:t}=Q(),{channelSource:n}=he(),{conversation:r}=ee(),o=n.channel,s=$t(),a=ur("handoff-button",o),l=!nr(o)||je(o),[c,d]=u.useState(!1),m=ti(),h=async()=>{d(!1);try{const g=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};return a?i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(I_,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(Ue,{...r.handoffButton.props,type:"agent",size:s,disabled:l,...m,onClick:()=>d(!0)})),r.handoffButton.descriptionNode),i.createElement(ft,{rootElementId:ce.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(Xs,{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}))):null},B_=()=>{const{conversation:e}=ee(),{onNavigateToConversationList:t}=he();return t?i.createElement(i.Fragment,null,i.createElement(Ue,{...e.menuButton.props,...wc,type:"menu",size:24,onClick:()=>t()}),e.menuButton.descriptionNode):null},ni=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Ee(),{fallbackIcon:o,url:s}=dr({channel:e,aiAgentInfo:r,userSession:n}),a=O.useTheme();return s?i.createElement($s,{src:s,size:t,"aria-hidden":"true"}):i.createElement(H_,{"aria-hidden":"true",$size:t,$bgColor:a.colors.base.primary},i.createElement(W,{type:o,size:t*.55,color:a.colors.base.primaryContrastContent}))},H_=_.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;`,U_=()=>{var m,h;const{channelSource:e}=he(),{aiAgentInfo:t,userSession:n}=Ee(),{conversation:r}=ee(),{config:o}=ke(),s=e.channel,a=dr({channel:s,userSession:n,aiAgentInfo:t}),l=(h=(m=o==null?void 0:o.conversation)==null?void 0:m.header)==null?void 0:h.avatarEnabled,c=ti(),d=r.headerTitle(a.title);return i.createElement(V_,null,l&&i.createElement(ni,{channel:s,size:34}),i.createElement(G_,{...d,...c},a.title))},V_=_.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;overflow:hidden;`,G_=_.default($).attrs({variant:"h2",color:p.themedColor.textHighEmphasis})`
463
+ `,Q_=c.lazy(()=>Promise.resolve().then(()=>require("./cjs/D2Opuq0j.cjs")).then(e=>({default:e.MarkdownText}))),eE=()=>{const{aiAgentInfo:e,userSession:t}=Ne(),{messageSource:n,channelSource:r}=ye(),[s,o]=c.useState(null),a=mr("special-notice",r.channel),l=c.useCallback(()=>r.channel?a?n.messages.some(u=>Et(u,(t==null?void 0:t.userId)??"")):!0:null,[r.channel,a,n.messages,t==null?void 0:t.userId]);return c.useEffect(()=>{s||o(l())},[l,s]),s||!e.specialNotice?null:i.createElement(J_,null,i.createElement(Q_,null,e.specialNotice))},tE=()=>i.createElement(nE,null,i.createElement(eE,null),i.createElement(P_,null,i.createElement(Z_,null))),nE=_.default.div`z-index:0;border:none;width:100%;`,rE=()=>{var s;const{testerType:e}=St(),{channelSource:t}=ye(),n=De(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?i.createElement(N_,null):i.createElement(tE,null)},vi=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=c.useRef(null),a=c.useRef(null),[l,u]=c.useState(0),[d,m]=c.useState(0);return c.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),a.current&&m(a.current.offsetWidth)},[e,r]),i.createElement(sE,{...s},i.createElement(oE,null,n==="center"&&t&&i.createElement(iE,{$sideWidth:Math.max(l,d)},i.createElement(aE,null,t)),i.createElement(lE,null,i.createElement(cE,{ref:o},e),(n==="start"||n==="end")&&t&&i.createElement(dE,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(uE,{ref:a},r))))},sE=_.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${p.themedColor.textDisabled};`,oE=_.default.div`position:relative;height:56px;padding:11px 12px;`,iE=_.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;`,aE=_.default.div`max-width:100%;overflow:hidden;`,lE=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,cE=_.default.div`flex-shrink:0;display:flex;align-items:center;`,uE=_.default.div`flex-shrink:0;display:flex;align-items:center;`,dE=_.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;`,Ft=()=>Dt()?24:16,mE=()=>{const{state:e}=fe(),{messenger:t}=se(),n=Ft(),r=()=>{e.setOpened(!1)};return i.createElement(Je,{...t.closeButton,type:"close",size:n,onClick:r})},hE=()=>{const{enableCloseConversationButton:e,dispatcher:t}=fe(),{channelSource:n}=ye(),{conversation:r}=se(),s=n.channel,o=Ft(),a=(s==null?void 0:s.isAIAgent)&&e,l=!sr(s);if(!a)return null;const u=async()=>{s&&await t.send(lt.CloseConversation({channelUrl:s.url}))};return i.createElement(i.Fragment,null,i.createElement(Je,{...r.header.closeConversationButton.props,type:"mute",size:o,disabled:l,onClick:u}),r.header.closeConversationButton.descriptionNode)},fE=()=>{const{state:e,enableExpandButton:t}=fe(),{messenger:n}=se(),r=Ft();return t?i.createElement(Je,{...n.expandButton(e.expanded),type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},gE=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(Qn,null,t,i.createElement(EE,{$position:n},i.createElement(bE,{variant:"caption1"},e),i.createElement(pE,{$position:n}))),pE=({$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:p.themedColor.textHighEmphasis})),_E={top:P.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:P.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Qn=_.default.div`position:relative;`,EE=_.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${vt.TOOLTIP};${({$position:e})=>_E[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Qn}:hover &,${Qn}:focus-within &{opacity:1;}`,bE=_.default(B)`padding:6px 8px;background:${p.themedColor.textHighEmphasis};color:${p.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,CE=2e3,Ws=0,vE=1500,Jt=Symbol("header-focus-status-pause"),Ys="data-sb-header-focus-protected",yE="[data-message-composer]",Ks=new WeakMap,Bn=e=>{const t=Ks.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return Ks.set(e,n),n},Un=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},tn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},SE=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),tn(e)},AE=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)})},xE=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(yE),!1),yi=()=>{const{setStatusPauseState:e}=st(),t=c.useRef(Symbol("header-focus-target")),n=c.useRef(!1),r=c.useRef(0),s=c.useRef(null),o=c.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),a=c.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+vE,o();const u=Bn(e);Un(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(Jt,!0),tn(u),u.maxPauseTimeout=setTimeout(()=>{SE(u),e(Jt,!1)},CE)},[o,e]),l=c.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=Bn(e),h=d instanceof HTMLElement&&Date.now()<=r.current;Un(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const v=d.ownerDocument.activeElement,b=v instanceof HTMLElement&&v.hasAttribute(Ys);if(v===d||b||!xE(v))return;const C=AE(d);d.focus({preventScroll:!0}),C()},Ws)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(tn(m),e(Jt,!1))},Ws))},[o,e]);return c.useEffect(()=>()=>{const u=Bn(e);n.current=!1,o(),Un(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(tn(u),e(Jt,!1))},[o,e]),{[Ys]:"true",onFocus:a,onBlur:l}},TE=()=>{const{logger:e}=fe(),{stringSet:t}=re(),{channelSource:n}=ye(),{conversation:r}=se(),s=n.channel,o=Ft(),a=mr("handoff-button",s),l=!sr(s)||nt(s),[u,d]=c.useState(!1),m=yi(),h=async()=>{d(!1);try{const f=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",f)}catch(f){e.error("conversation.handleAgentHandoff: error",f)}};return a?i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(gE,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(Je,{...r.header.handoffButton.props,type:"agent",size:o,disabled:l,...m,onClick:()=>d(!0)})),r.header.handoffButton.descriptionNode),i.createElement(ut,{portalContainerId:ve.WINDOW,visible:u,onClose:()=>d(!1)},i.createElement(_i,{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}))):null},IE=()=>{const{conversation:e}=se(),{onNavigateToConversationList:t}=ye();return t?i.createElement(i.Fragment,null,i.createElement(Je,{...e.header.menuButton.props,...cu,type:"menu",size:24,onClick:()=>t()}),e.header.menuButton.descriptionNode):null},Si=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Ne(),{fallbackIcon:s,url:o}=hr({channel:e,aiAgentInfo:r,userSession:n}),a=P.useTheme();return o?i.createElement(ni,{src:o,size:t,"aria-hidden":"true"}):i.createElement(wE,{"aria-hidden":"true",$size:t,$bgColor:a.colors.base.primary},i.createElement(Z,{type:s,size:t*.55,color:a.colors.base.primaryContrastContent}))},wE=_.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;`,ME=()=>{var m,h;const{channelSource:e}=ye(),{aiAgentInfo:t,userSession:n}=Ne(),{conversation:r}=se(),{config:s}=$e(),o=e.channel,a=hr({channel:o,userSession:n,aiAgentInfo:t}),l=(h=(m=s==null?void 0:s.conversation)==null?void 0:m.header)==null?void 0:h.avatarEnabled,u=yi(),d=r.header.title(a.title);return i.createElement(kE,null,l&&i.createElement(Si,{channel:o,size:34}),i.createElement(LE,{...d,...u},a.title))},kE=_.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;overflow:hidden;`,LE=_.default(B).attrs({variant:"h2",color:p.themedColor.textHighEmphasis})`
468
464
  margin: 0;
469
465
  flex: 1;
470
466
  min-width: 0;
@@ -476,10 +472,10 @@
476
472
  &:focus {
477
473
  outline: none;
478
474
  }
479
- `,z_=e=>{const{components:t}=it.useContext();return i.createElement(ei,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null)})},W_=()=>{const{components:e}=it.useContext();return i.createElement(e.MenuButton,null)},q_=()=>{const{components:e}=it.useContext();return i.createElement(e.Title,null)},K_=()=>{const{components:e}=it.useContext();return i.createElement(j_,null,i.createElement(e.HandoffButton,null),i.createElement(e.ConversationCloseButton,null),i.createElement(e.ExpandButton,null),i.createElement(e.CloseButton,null))},it=Pe({template:z_,components:{StartArea:W_,TitleArea:q_,EndArea:K_,MenuButton:B_,Title:U_,HandoffButton:F_,ConversationCloseButton:x_,ExpandButton:T_,CloseButton:A_}}),Y_=()=>{const{isActionbookTester:e}=pt(),{Template:t}=it.useContext();return e?null:i.createElement(t,{titleAlign:"start"})},j_=_.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,ri=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:o,announcementsEnabled:s,style:a,closedChannelUrl:l,onClearClosedChannelUrl:c})=>{const{Template:d}=vn.useContext();return i.createElement(Ts,{onNavigateToConversationList:t,channelUrl:n??l,onClearChannelUrl:r??c,shouldMarkAsRead:o},i.createElement(Yn,null,i.createElement(Yn.Consumer,null,m=>i.createElement(gu,{announcementsActive:s},i.createElement(X_,null),i.createElement(J_,{style:a,...m},i.createElement(d,null)),e))))},X_=()=>(hd(),sd(),ud(),null),Z_=e=>{const{components:t}=vn.useContext();return i.createElement(i.Fragment,null,i.createElement(t.Header,null),i.createElement(t.Body,null),i.createElement(t.Footer,null))},vn=Pe({template:Z_,components:{Header:Y_,Body:Wp,Footer:f_}}),J_=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,{Provider:Q_,Context:eE,useContext:yn}=ue("ConversationList");function oi({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=oe,children:r}){return i.createElement(El,{conversationListLimit:e,conversationListFilter:t},o=>i.createElement(Q_,{value:{...o,onOpenConversationView:n}},r))}const tE=({channel:e})=>i.createElement(ni,{channel:e}),Qn=99,nE=e=>{var f,y;const{channel:t,onClick:n}=e,{stringSet:r,format:o}=Q(),{userSession:s,aiAgentInfo:a}=Ee(),{conversationList:l}=ee(),c=dr({channel:t,userSession:s,aiAgentInfo:a}),d=ka(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=La(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}),h=t.unreadMessageCount,g=(f=t.lastMessage)!=null&&f.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:c.title,C=Ce(t)?r.CONVERSATION_LIST__ENDED:Jo(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),b=n?()=>n():void 0,v=l.item({agent:g,status:C,time:m,unreadCount:h,onActivate:b});return i.createElement(rE,{"data-testid":"sb-conversation-list-item",$clickable:!!b,...v.props},i.createElement(oE,null,i.createElement(tE,{...e})),i.createElement(sE,null,i.createElement(iE,null,(y=t.lastMessage)!=null&&y.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?i.createElement(Ms,{variant:"subtitle1",color:p.themedColor.textHighEmphasis},d):i.createElement($,{variant:"subtitle1",color:p.themedColor.textHighEmphasis,maxTextLines:1},d),i.createElement(aE,null,Ce(t)&&i.createElement(i.Fragment,null,i.createElement($,{variant:"caption1",color:p.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),i.createElement(lE,null)),i.createElement($,{variant:"caption2",color:p.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&i.createElement(cE,{$count:h},i.createElement($,{variant:"caption3",color:p.themedColor.textHighEmphasisInverse},h<=Qn?h:`${Qn}+`))),v.descriptionNode)},xr=Pe({template:nE,components:{}}),rE=_.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"};`,oE=_.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,sE=_.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 ${p.themedColor.textDisabled};`,iE=_.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;`,aE=_.default.div`display:flex;align-items:center;gap:6px;`,lE=_.default.div`width:2px;height:2px;border-radius:1px;background-color:${p.themedColor.textLowEmphasis};`,cE=_.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${p.themedColor.error};${({$count:e})=>e<=Qn&&O.css`
475
+ `,RE=e=>{const{components:t}=mt.useContext();return i.createElement(vi,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:du})},OE=()=>{const{components:e}=mt.useContext();return i.createElement(e.MenuButton,null)},NE=()=>{const{components:e}=mt.useContext();return i.createElement(e.Title,null)},DE=()=>{const{components:e}=mt.useContext();return i.createElement(PE,null,i.createElement(e.HandoffButton,null),i.createElement(e.ConversationCloseButton,null),i.createElement(e.ExpandButton,null),i.createElement(e.CloseButton,null))},mt=qe({template:RE,components:{StartArea:OE,TitleArea:NE,EndArea:DE,MenuButton:IE,Title:ME,HandoffButton:TE,ConversationCloseButton:hE,ExpandButton:fE,CloseButton:mE}}),$E=()=>{const{isActionbookTester:e}=St(),{Template:t}=mt.useContext();return e?null:i.createElement(t,{titleAlign:"start"})},PE=_.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Ai=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,announcementsEnabled:o,style:a,closedChannelUrl:l,onClearClosedChannelUrl:u})=>{const{Template:d}=Sn.useContext();return i.createElement(Yo,{onNavigateToConversationList:t,channelUrl:n??l,onClearChannelUrl:r??u,shouldMarkAsRead:s},i.createElement(jn,null,i.createElement(jn.Consumer,null,m=>i.createElement(rd,{announcementsActive:o},i.createElement(FE,null),i.createElement(BE,{style:a,dragHandlers:m},i.createElement(d,null)),e))))},FE=()=>(hm(),om(),um(),null),BE=({style:e,dragHandlers:t,children:n})=>{const r=c.useRef(null);return Qd(r),i.createElement(HE,{ref:r,style:e,...t},n)},UE=e=>{const{components:t}=Sn.useContext();return i.createElement(i.Fragment,null,i.createElement(t.Header,null),i.createElement(t.Body,null),i.createElement(t.Footer,null))},Sn=qe({template:UE,components:{Header:$E,Body:O_,Footer:rE}}),HE=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,{Provider:GE,Context:VE,useContext:An}=Ee("ConversationList");function xi({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=he,children:r}){return i.createElement(Ql,{conversationListLimit:e,conversationListFilter:t},s=>i.createElement(GE,{value:{...s,onOpenConversationView:n}},r))}const zE=({channel:e})=>i.createElement(Si,{channel:e}),er=99,qE=e=>{var g,y;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=re(),{userSession:o,aiAgentInfo:a}=Ne(),{conversationList:l}=se(),u=hr({channel:t,userSession:o,aiAgentInfo:a}),d=Ya(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=Ka(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=(g=t.lastMessage)!=null&&g.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,v=De(t)?r.CONVERSATION_LIST__ENDED:go(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),b=n?()=>n():void 0,C=l.item({agent:f,status:v,time:m,unreadCount:h,onActivate:b});return i.createElement(WE,{"data-testid":"sb-conversation-list-item",$clickable:!!b,...C.props},i.createElement(YE,null,i.createElement(zE,{...e})),i.createElement(KE,null,i.createElement(jE,null,(y=t.lastMessage)!=null&&y.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?i.createElement(Jo,{variant:"subtitle1",color:p.themedColor.textHighEmphasis},d):i.createElement(B,{variant:"subtitle1",color:p.themedColor.textHighEmphasis,maxTextLines:1},d),i.createElement(XE,null,De(t)&&i.createElement(i.Fragment,null,i.createElement(B,{variant:"caption1",color:p.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),i.createElement(ZE,null)),i.createElement(B,{variant:"caption2",color:p.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&i.createElement(JE,{$count:h},i.createElement(B,{variant:"caption3",color:p.themedColor.textHighEmphasisInverse},h<=er?h:`${er}+`))),C.descriptionNode)},wr=qe({template:qE,components:{}}),WE=_.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"};`,YE=_.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,KE=_.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 ${p.themedColor.textDisabled};`,jE=_.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;`,XE=_.default.div`display:flex;align-items:center;gap:6px;`,ZE=_.default.div`width:2px;height:2px;border-radius:1px;background-color:${p.themedColor.textLowEmphasis};`,JE=_.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${p.themedColor.error};${({$count:e})=>e<=er&&P.css`
480
476
  width: 20px;
481
477
  `}
482
- `,uE=({items:e,renderItem:t,onEndReached:n})=>{const r=o=>{const s=o.target;s.scrollHeight-s.scrollTop===s.clientHeight&&(n==null||n())};return i.createElement(dE,{onScroll:o=>r(o)},e.map((o,s)=>t(o,s)))},dE=_.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,mE=()=>{const{stringSet:e}=Q(),{listSource:t,onOpenConversationView:n}=yn(),{Template:r}=xr.useContext();return t.initialized?t.channels.length===0?i.createElement(At,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):i.createElement(uE,{items:t.channels,renderItem:o=>{var s,a,l;return i.createElement(r,{key:o.url,channel:o,onClick:()=>n(o.url,Ce(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(At,{type:"loading"})},hE=()=>{const{stringSet:e}=Q(),{_aiAgentSDK:t}=ke(),{language:n,countryCode:r,context:o}=ne(),{aiAgentInfo:s,refreshActiveChannel:a,createConversation:l}=Ee(),{onOpenConversationView:c}=yn(),{conversationList:d}=ee(),m=async()=>{var h;if(s.isMultipleActiveConversationsEnabled){const g=await l({aiAgentId:s.userId,language:n,country:r,context:o});(h=t.session)==null||h._updateActiveChannel({url:g,status:"open"}),c(g,"open")}else{const g=await a();c(g,"open")}};return i.createElement(gE,{...d.footer.button({onActivate:m})},i.createElement(fE,{variant:"h1"},e.TALK_TO_AGENT))},gE=_.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,fE=_.default($)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,pE=()=>{const{state:e}=ne(),{messenger:t}=ee(),n=$t(),r=()=>{e.setOpened(!1)};return i.createElement(Ue,{...t.closeButton,type:"close",size:n,onClick:r})},_E=()=>{const{stringSet:e}=Q();return i.createElement(EE,{forwardedAs:"h2",variant:"h2",color:p.themedColor.textHighEmphasis},e.CONVERSATION_LIST__HEADER_TITLE)},EE=_.default($)`margin:0;padding:0 4px;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,bE=e=>{const{components:t}=_t.useContext();return i.createElement(ei,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null)})},CE=()=>null,vE=()=>{const{components:e}=_t.useContext();return i.createElement(e.Title,null)},yE=()=>{const{components:e}=_t.useContext();return i.createElement(e.CloseButton,null)},_t=Pe({template:bE,components:{StartArea:CE,TitleArea:vE,EndArea:yE,Title:_E,CloseButton:pE}}),SE=()=>{const{Template:e}=_t.useContext();return i.createElement(e,{titleAlign:"start"})},si=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,style:o})=>{const{Template:s}=Sn.useContext();return i.createElement(oi,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},i.createElement(xE,{style:o},i.createElement(s,null)),n)},AE=()=>{const{components:e}=Sn.useContext();return i.createElement(i.Fragment,null,i.createElement(e.Header,null),i.createElement(e.Body,null),i.createElement(e.Footer,null))},Sn=Pe({template:AE,components:{Header:SE,Body:mE,Footer:hE}}),xE=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,TE=O.css`:where(#${ce.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,IE=[TE,Uc,Vc],wE=(e,...t)=>O.createGlobalStyle(e,...IE,...t),kE=wE``,LE=wa(vn,Je,Nt,_n,Cn,Sn,it,xr,_t,bn);function ii({appearance:e,rootElement:t,logger:n,language:r,languageCode:o,stringSet:s,children:a,messageTemplate:l,icons:c,theme:d}){return au(Nc,t),i.createElement(O.StyleSheetManager,{target:t},i.createElement(ou,{rootElement:t,logger:n,appearance:e,theme:d},i.createElement(vl,{internalVariables:l==null?void 0:l.__internalVariables},i.createElement(Hc,{stringSet:s,logger:n,language:r,languageCode:o},i.createElement(nu,{icons:c},i.createElement(LE,null,a,i.createElement(kE,null)))))))}const Tr=u.forwardRef(function({rootElement:t=document.body,logLevel:n=ie.LogLevel.WARN,language:r=navigator.language,userSessionInfo:o,children:s,chatParams:a,icons:l,...c},d){var g,C,b;yt.level!==n&&(yt.level=n),iu("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const m=gs(r),h=fs.has(m)?m:Lt;return i.createElement("div",{id:ce.ENTRY,lang:h,style:{width:"fit-content",height:"fit-content",...c.entryStyle}},i.createElement(ii,{logger:yt,rootElement:t,appearance:(g=c.agentPreviewConfigs)==null?void 0:g.appearance,stringSet:c.stringSet,language:h,messageTemplate:c.messageTemplate,icons:l,theme:c.theme},i.createElement(pu,{rootElement:t,language:r,logger:yt,dispatcher:ai,chatParams:{...a,...c.customApiHost&&{customApiHost:c.customApiHost},...c.customWebSocketHost&&{customWebSocketHost:c.customWebSocketHost}},chatSDK:c.customChatSDK,_forceCreateChannel:(C=c.agentPreviewConfigs)==null?void 0:C.forceCreateChannel,_agentVersion:(b=c.agentPreviewConfigs)==null?void 0:b.agentVersion,...c},i.createElement(Du,{ref:d,userSessionInfo:o},i.createElement(cf,{...c._UNSAFE_INTERNAL_dashboardTester},i.createElement(mu,null,s,i.createElement("div",{id:ce.MODAL_ROOT,dir:c.dir})))))))}),yt=new qo(ie.LogLevel.WARN),ai=new Wo(yt),{Provider:ME,useContext:Ir}=ue("PageChildren"),li=({children:e})=>{const[t,n]=u.useState(null),[r,o]=u.useState(null);return i.createElement(ME,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:o}},e)},ci=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>{const{dir:r,rootElement:o}=ne(),s=He(o,!0);return u.useEffect(()=>{const a="sb-agent-block-scroll";return t?s.body.classList.add(a):s.body.classList.remove(a),()=>{s.body.classList.remove(a)}},[s,t]),i.createElement(RE,{dir:r,$visible:t,$zIndex:n},e)},RE=_.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,OE=48,NE=2/3;function ui({className:e,children:t,isOpened:n,onClick:r,ariaLabel:o,"aria-label":s,"aria-describedby":a,type:l,imageUrl:c,dir:d,animated:m=!0,backgroundColor:h,size:g=OE}){const C=Ps(),b=m&&!C,v=Wn(h),f=Math.round(g*NE),y=s??o;return i.createElement(PE,{dir:d,id:ce.LAUNCHER,className:e,"aria-label":y??"Sendbird AIAgent Launcher","aria-describedby":a,onClick:r,$animated:b,$backgroundColor:h,$prefersReducedMotion:C,$size:g},i.createElement(FE,{$isOpened:n,$animated:b,$fillColor:v,$iconSize:f,$prefersReducedMotion:C},i.createElement($o.Open,{url:c,isDefaultIcon:l==="default_icon",size:f})),i.createElement(BE,{$isOpened:n,$animated:b,$fillColor:v,$iconSize:f,$prefersReducedMotion:C},i.createElement($o.Close,{size:f})),t)}const $E=O.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,DE=O.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===xt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,di=O.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>O.css`
478
+ `,QE=({items:e,renderItem:t,onEndReached:n})=>{const r=s=>{const o=s.target;o.scrollHeight-o.scrollTop===o.clientHeight&&(n==null||n())};return i.createElement(eb,{onScroll:s=>r(s)},e.map((s,o)=>t(s,o)))},eb=_.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,tb=()=>{const{stringSet:e}=re(),{listSource:t,onOpenConversationView:n}=An(),{Template:r}=wr.useContext();return t.initialized?t.channels.length===0?i.createElement(Lt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):i.createElement(QE,{items:t.channels,renderItem:s=>{var o,a,l;return i.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,De(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(Lt,{type:"loading"})},nb=()=>{const{stringSet:e}=re(),{_aiAgentSDK:t}=$e(),{language:n,countryCode:r,context:s}=fe(),{aiAgentInfo:o,refreshActiveChannel:a,createConversation:l}=Ne(),{onOpenConversationView:u}=An(),{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"}),u(f,"open")}else{const f=await a();u(f,"open")}};return i.createElement(rb,{...d.footer.button({onActivate:m})},i.createElement(sb,{variant:"h1"},e.TALK_TO_AGENT))},rb=_.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,sb=_.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,ob=()=>{const{state:e}=fe(),{messenger:t}=se(),n=Ft(),r=()=>{e.setOpened(!1)};return i.createElement(Je,{...t.closeButton,type:"close",size:n,onClick:r})},ib=()=>{const{stringSet:e}=re();return i.createElement(ab,{forwardedAs:"h2",variant:"h2",color:p.themedColor.textHighEmphasis},e.CONVERSATION_LIST__HEADER_TITLE)},ab=_.default(B)`margin:0;padding:0 4px;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,lb=e=>{const{components:t}=At.useContext();return i.createElement(vi,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null)})},cb=()=>null,ub=()=>{const{components:e}=At.useContext();return i.createElement(e.Title,null)},db=()=>{const{components:e}=At.useContext();return i.createElement(e.CloseButton,null)},At=qe({template:lb,components:{StartArea:cb,TitleArea:ub,EndArea:db,Title:ib,CloseButton:ob}}),mb=()=>{const{Template:e}=At.useContext();return i.createElement(e,{titleAlign:"start"})},Ti=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,style:s})=>{const{Template:o}=xn.useContext();return i.createElement(xi,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},i.createElement(fb,{style:s},i.createElement(o,null)),n)},hb=()=>{const{components:e}=xn.useContext();return i.createElement(i.Fragment,null,i.createElement(e.Header,null),i.createElement(e.Body,null),i.createElement(e.Footer,null))},xn=qe({template:hb,components:{Header:mb,Body:tb,Footer:nb}}),fb=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,gb=P.css`:where(#${ve.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,pb=[gb,ku,Lu],_b=(e,...t)=>P.createGlobalStyle(e,...pb,...t),Eb=_b``,bb=Wa(Sn,rt,Pt,bn,yn,xn,mt,wr,At,vn,En),Cb=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Ii({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:a,messageTemplate:l,icons:u,theme:d,entryElement:m,modalRootElement:h}){Xu(Cb?_u:"",t);const[f,v]=c.useState(null),b=c.useCallback(y=>{v(E=>E===y?E:y)},[]),C=m??f,g=i.createElement(P.StyleSheetManager,{target:t},i.createElement(Yu,{rootElement:t,logger:n,appearance:e,theme:d},i.createElement(vu,{rootElement:t,boundaryElement:C},i.createElement(rc,{internalVariables:l==null?void 0:l.__internalVariables},i.createElement(Mu,{stringSet:o,logger:n,language:r,languageCode:s},i.createElement(qu,{icons:u},i.createElement(bb,null,i.createElement(bu,{entryElement:C,modalRootElement:h,rootElement:t},a),i.createElement(Eb,null))))))));return m?g:i.createElement("div",{ref:b,style:{display:"contents"}},g)}const vb=()=>{const[e,t]=c.useState(null),[n,r]=c.useState(null),s=c.useCallback(a=>{t(l=>l===a?l:a)},[]),o=c.useCallback(a=>{r(l=>l===a?l:a)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},Mr=c.forwardRef(function({rootElement:t=document.body,logLevel:n=le.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:a,icons:l,...u},d){var g,y,E;Mt.level!==n&&(Mt.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:v}=vb();ju("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const b=Oo(r),C=No.has(b)?b:Nt;return i.createElement("div",{ref:f,id:ve.ENTRY,lang:C,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&i.createElement(Ii,{logger:Mt,rootElement:t,appearance:(g=u.agentPreviewConfigs)==null?void 0:g.appearance,stringSet:u.stringSet,language:C,messageTemplate:u.messageTemplate,icons:l,theme:u.theme,entryElement:m,modalRootElement:h},i.createElement(Id,{rootElement:t,language:r,logger:Mt,dispatcher:wi,chatParams:{...a,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(y=u.agentPreviewConfigs)==null?void 0:y.forceCreateChannel,_agentVersion:(E=u.agentPreviewConfigs)==null?void 0:E.agentVersion,...u},i.createElement(Dd,{ref:d,userSessionInfo:s},i.createElement(Qg,{...u._UNSAFE_INTERNAL_dashboardTester},i.createElement(td,null,o))))),i.createElement("div",{ref:v,id:ve.MODAL_ROOT,dir:u.dir}))}),Mt=new io(le.LogLevel.WARN),wi=new oo(Mt),{Provider:yb,useContext:kr}=Ee("PageChildren"),Mi=({children:e})=>{const[t,n]=c.useState(null),[r,s]=c.useState(null);return i.createElement(yb,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:s}},e)},ki=({children:e,isOpened:t,zIndex:n=vt.WINDOW})=>{const{dir:r,rootElement:s}=fe(),o=ct(s,!0);return c.useEffect(()=>{const a="sb-agent-block-scroll";return t?o.body.classList.add(a):o.body.classList.remove(a),()=>{o.body.classList.remove(a)}},[o,t]),i.createElement(Sb,{id:ve.WINDOW,dir:r,$visible:t,$zIndex:n},e)},Sb=_.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,Ab=48,xb=2/3;function Li({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:a,imageUrl:l,dir:u,animated:d=!0,backgroundColor:m,size:h=Ab}){const f=si(),v=d&&!f,b=Wn(m),C=Math.round(h*xb);return i.createElement(wb,{dir:u,id:ve.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:v,$backgroundColor:m,$prefersReducedMotion:f,$size:h},i.createElement(Mb,{$isOpened:n,$animated:v,$fillColor:b,$iconSize:C,$prefersReducedMotion:f},i.createElement(js.Open,{url:l,isDefaultIcon:a==="default_icon",size:C})),i.createElement(kb,{$isOpened:n,$animated:v,$fillColor:b,$iconSize:C,$prefersReducedMotion:f},i.createElement(js.Close,{size:C})),t)}const Tb=P.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,Ib=P.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===Rt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Ri=P.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>P.css`
483
479
  ellipse,
484
480
  path {
485
481
  fill: ${e};
@@ -489,7 +485,7 @@
489
485
  }
490
486
  `}
491
487
  }
492
- `,PE=_.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&&$E}`,mi=_.default.span.attrs({"aria-hidden":"true"})`
488
+ `,wb=_.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&&Tb}`,Oi=_.default.span.attrs({"aria-hidden":"true"})`
493
489
  position: absolute;
494
490
  width: 100%;
495
491
  height: 100%;
@@ -499,15 +495,15 @@
499
495
  display: flex;
500
496
  justify-content: center;
501
497
  align-items: center;
502
- `,FE=_.default(mi)`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)")};${DE}${di}`,BE=_.default(mi)`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)")};${di}`,$o={Open:e=>e.url?i.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):i.createElement(W,{size:e.size,type:"delight"}),Close:({size:e})=>i.createElement(W,{size:e,type:"chevron-down"})},Do=(e,t)=>Array.from(e.querySelectorAll(t)).find(Rt)??null,hi=e=>Do(e,Ic)??Do(e,ys),HE=e=>{const t=hi(e)??e;t===e&&!t.hasAttribute("tabindex")&&t.setAttribute("tabindex","-1"),t.focus()},UE=(e,t)=>{u.useEffect(()=>{if(!e||!t.current)return;let n=!1;return ve(()=>{n||!t.current||HE(t.current)}),()=>{n=!0}},[e,t])};function gi({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:o}=O.useTheme(),{dir:s,rootElement:a,state:l}=ne(),{launcher:c}=ee(),{launcherInfo:d,statsTrackers:m}=Ee(),h=(r??n)==="ConversationList",g=c.button({isOpened:l.opened,opensConversationList:h}),C=He(a);u.useLayoutEffect(()=>{m.initialRender.setPresentMethod("launcher_toggle")},[m]),GE();const b=E=>C.querySelector(`#${E}`),v=()=>{ve(()=>{const E=b(ce.WINDOW),x=E?hi(E):null;x==null||x.focus()})},f=()=>{ve(()=>{var E;(E=b(ce.LAUNCHER))==null||E.focus()})},y=()=>{const E=!l.opened;l.setOpened(E),E?v():f()};return i.createElement(ui,{dir:s,className:e,isOpened:l.opened,onClick:y,type:d.type,imageUrl:d.imageUrl,backgroundColor:o.base.primary,size:t,...g.props},g.descriptionNode)}const VE=1e3*60;function GE(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ne(),o=u.useRef(null);u.useEffect(()=>{if(!r)return;function s(){o.current&&(clearTimeout(o.current),o.current=null)}function a(){e.connectionState===ie.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")},VE)}t.opened?a():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const fi=u.createContext(null);function wr(){const e=u.useContext(fi);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function pi({children:e}){const t=wr();return typeof e=="function"?e(t):i.createElement(i.Fragment,null,e)}const zE=O.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,WE=O.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,qE=O.css`animation-name:${zE};animation-duration:0.3s;animation-fill-mode:forwards;`,KE=O.css``,YE=O.css`animation-name:${WE};animation-duration:0.3s;animation-fill-mode:forwards;`,jE=O.css`visibility:hidden;`,XE=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return qE;case"entered":return KE;case"exiting":return YE;case"exited":return jE;default:return""}}}${({$active:e})=>e?O.css`
498
+ `,Mb=_.default(Oi)`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)")};${Ib}${Ri}`,kb=_.default(Oi)`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)")};${Ri}`,js={Open:e=>e.url?i.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):i.createElement(Z,{size:e.size,type:"delight"}),Close:({size:e})=>i.createElement(Z,{size:e,type:"chevron-down"})},Xs=(e,t)=>Array.from(e.querySelectorAll(t)).find(yt)??null,Ni=e=>Xs(e,gr)??Xs(e,_n),Lb=e=>{const t=Ni(e)??e;t===e&&!t.hasAttribute("tabindex")&&t.setAttribute("tabindex","-1"),t.focus()},Rb=(e,t)=>{c.useEffect(()=>{if(!e||!t.current)return;let n=!1;return Oe(()=>{n||!t.current||Lb(t.current)}),()=>{n=!0}},[e,t])};function Di({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=P.useTheme(),{dir:o,state:a}=fe(),{resolveElement:l}=_r(),{launcher:u}=se(),{launcherInfo:d,statsTrackers:m}=Ne(),h=(r??n)==="ConversationList",f=u.button({isOpened:a.opened,opensConversationList:h});c.useLayoutEffect(()=>{m.initialRender.setPresentMethod("launcher_toggle")},[m]),Nb();const v=()=>{Oe(()=>{const g=l(ve.WINDOW),y=g?Ni(g):null;y==null||y.focus()})},b=()=>{Oe(()=>{var g;(g=l(ve.LAUNCHER))==null||g.focus()})},C=()=>{const g=!a.opened;a.setOpened(g),g?v():b()};return i.createElement(Li,{dir:o,className:e,isOpened:a.opened,onClick:C,type:d.type,imageUrl:d.imageUrl,backgroundColor:s.base.primary,size:t,...f.props},f.descriptionNode)}const Ob=1e3*60;function Nb(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=fe(),s=c.useRef(null);c.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function a(){e.connectionState===le.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")},Ob)}t.opened?a():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const $i=c.createContext(null);function Lr(){const e=c.useContext($i);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Pi({children:e}){const t=Lr();return typeof e=="function"?e(t):i.createElement(i.Fragment,null,e)}const Db=P.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,$b=P.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,Pb=P.css`animation-name:${Db};animation-duration:0.3s;animation-fill-mode:forwards;`,Fb=P.css``,Bb=P.css`animation-name:${$b};animation-duration:0.3s;animation-fill-mode:forwards;`,Ub=P.css`visibility:hidden;`,Hb=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return Pb;case"entered":return Fb;case"exiting":return Bb;case"exited":return Ub;default:return""}}}${({$active:e})=>e?P.css`
503
499
  z-index: 999;
504
- `:O.css`z-index:1;pointer-events:none;`}
505
- `;function Qt({initialId:e,children:t}){const[n,r]=u.useState([e]),o=n[n.length-1],s=u.useCallback((f,y)=>{r(E=>[...E,f]),h(E=>({...E,[f]:!0})),y!=null&&y.reset&&v(E=>({...E,[f]:(E[f]||0)+1})),C(E=>({...E,[f]:"entering"})),setTimeout(()=>{C(E=>({...E,[f]:"entered"}))},300)},[]),a=u.useCallback(()=>{r(f=>{if(f.length<=1)return f;const y=f[f.length-1];return C(E=>({...E,[y]:"exiting"})),setTimeout(()=>{C(E=>({...E,[y]:"exited"})),r(E=>E.slice(0,-1))},300),f})},[]),l=u.useMemo(()=>({navigation:{navigate:s,pop:a},activeScreenId:o}),[s,a,o]),c=u.useMemo(()=>u.Children.toArray(t).filter(f=>f.type===pi),[t]),d=u.useMemo(()=>{const f={};return c.forEach(y=>{const{id:E,lazy:x,children:S}=y.props;f[E]={lazy:x,element:typeof S=="function"?S(l):S}}),f},[c,l]),[m,h]=u.useState(()=>{const f={};return Object.entries(d).forEach(([y,{lazy:E}])=>{E===!1&&(f[y]=!0)}),f[e]=!0,f}),[g,C]=u.useState(()=>{const f={};return Object.keys(d).forEach(y=>{y===e?f[y]="entered":f[y]="exited"}),f}),[b,v]=u.useState({});return i.createElement(fi.Provider,{value:l},i.createElement(ZE,null,Object.keys(d).map(f=>{var S;if(!m[f])return null;const y=g[f]||"exited",E=f===o,x=`${f}-${b[f]||0}`;return i.createElement(XE,{key:x,$transitionState:y,$active:E},(S=d[f])==null?void 0:S.element)})))}const ZE=_.default.div`position:relative;width:100%;height:100%;`;Qt.Screen=pi;const Se={conv:"conv",convList:"conv-list"},Po=({isOpened:e,activeScreenId:t})=>e&&t===Se.conv,JE=({screenId:e,conversationKey:t,navigationKey:n})=>e===Se.conv?`${e}:${t??""}`:n?`${e}:${n}`:e,QE=({initialRoute:e,isOpened:t,selectedChannelUrl:n,setSelectedChannelUrl:r})=>{const{announceScreenEntry:o}=fr(),s=u.useRef(null),a=u.useRef(null),l=u.useRef(0),[c,d]=u.useState(0),m=u.useCallback(b=>{const v=JE(b);s.current!==v&&(s.current=v,a.current=b,b.screenId===Se.convList&&o({screen:"conversationList"}))},[o]),h=u.useCallback((b,v)=>{const f={screenId:Se.conv,conversationKey:v};r(v),b.navigate(Se.conv),a.current=f,t&&m(f)},[m,t,r]),g=u.useCallback(b=>{l.current+=1;const v=l.current,f={screenId:Se.convList,navigationKey:`visit:${v}`};a.current=f,d(v),b.navigate(Se.convList)},[]),C=u.useCallback(()=>{var v;const b=((v=a.current)==null?void 0:v.screenId)===Se.convList?a.current:{screenId:Se.convList};m(b)},[m]);return u.useEffect(()=>{if(t){const b=a.current?a.current.screenId===Se.conv?{screenId:Se.conv,conversationKey:n??a.current.conversationKey}:a.current:{screenId:e,conversationKey:e===Se.conv?n:void 0};b.screenId!==Se.convList&&m(b)}else s.current=null,a.current=null},[m,e,t,n]),{announceConversationListScreen:C,conversationListAnnouncementToken:c,navigateToConversationList:g,openConversation:h}},nt={conv:"conv",convList:"conv-list"},eb=e=>e===nt.convList?"ConversationList":"Conversation",_i=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:o})=>{const{conversationChildren:s,conversationListChildren:a}=Ir(),l=(()=>{switch(t){case"Conversation":return nt.conv;case"ConversationList":return nt.convList;default:return nt.conv}})(),{announceConversationListScreen:c,conversationListAnnouncementToken:d,navigateToConversationList:m,openConversation:h}=QE({initialRoute:l,isOpened:e,selectedChannelUrl:n,setSelectedChannelUrl:r}),g=i.createElement(i.Fragment,null,i.createElement(tb,{onOpenConversationView:(C,b)=>h(C,b)}),i.createElement(rb,{onActiveRouteChange:o}));return i.createElement(Qt,{initialId:l},i.createElement(Qt.Screen,{id:nt.conv},({navigation:C,activeScreenId:b})=>i.createElement(ri,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>m(C),announcementsEnabled:Po({isOpened:e,activeScreenId:b}),shouldMarkAsRead:Po({isOpened:e,activeScreenId:b})},g,s)),i.createElement(Qt.Screen,{id:nt.convList,lazy:!0},({navigation:C,activeScreenId:b})=>{const v=e&&b===nt.convList;return i.createElement(si,{onOpenConversationView:f=>{h(C,f)}},i.createElement(nb,{announcementToken:d,enabled:v,onAnnounce:c}),g,a)}))},tb=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Ee(),{navigation:n}=wr();return t(({channel:r})=>{e(n,r.url)}),null},nb=({announcementToken:e,enabled:t,onAnnounce:n})=>{const{listSource:r}=yn();return u.useEffect(()=>{if(!t||!r.initialized)return;const o=setTimeout(()=>{n()},0);return()=>{clearTimeout(o)}},[e,t,r.initialized,n]),null},rb=({onActiveRouteChange:e})=>{const{activeScreenId:t}=wr();return u.useEffect(()=>{e==null||e(eb(t))},[t,e]),null},ob=`#${ce.WINDOW} [role="dialog"][aria-modal="true"], #${ce.MODAL_ROOT} [role="dialog"][aria-modal="true"]`,sb=e=>!!e.querySelector(ob),Ei=(e,t)=>u.useCallback(n=>{var r;if(n.key==="Escape"&&e){const s=n.currentTarget.getRootNode();if(sb(s))return;n.stopPropagation(),t(!1),(r=s.querySelector(`#${ce.LAUNCHER}`))==null||r.focus()}},[e,t]),ib=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:o,state:s}=ne(),a=Ei(t,s.setOpened),l=u.useRef(null);return UE(t,l),i.createElement(ab,null,i.createElement(lb,{ref:l,dir:o,id:ce.WINDOW,$isExpanded:e,$isOpened:t,onKeyDown:a},n),r)},ab=_.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,lb=_.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&&ub};${({$isExpanded:e})=>e&&cb};`,cb=O.css`width:743px;height:723px;`,ub=O.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;`,db=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const o=Mt(),[s,a]=u.useState(t),[l,c]=u.useState(n.entryPoint??"Conversation"),d=o?ci:ib;return i.createElement(Tr,{enableExpandButton:!o,ref:r,...n},i.createElement(bs,null,({state:m})=>i.createElement(li,null,i.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...o&&{zIndex:"auto"},launcher:i.createElement(gi,{entryPoint:n.entryPoint,activeRoute:l})},i.createElement(_i,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:a,onActiveRouteChange:c})),e)))}),{Provider:mb,useContext:kr}=ue("FixedMessengerStyle");function bi(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: ${$e(a)}`;break;case"end":d=`inset-inline-end: ${$e(l)}`;break}switch(t){case"top":c=`top: calc(${$e(o)} + ${r}px)`;break;case"bottom":c=`bottom: calc(${$e(s)} + ${r}px)`;break}return O.css`${c};${d};`}function hb(e){const{horizontal:t,vertical:n,margin:r,launcherSize:o}=kr();return i.createElement(gb,{...e,size:o,$horizontal:t,$vertical:n,$margin:r})}const gb=_.default(gi)`position:fixed;z-index:${gt.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>bi(e,t,n)};`,fb=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r,state:o}=ne(),{horizontal:s,vertical:a,margin:l,launcherSize:c}=kr(),d=Ei(t,o.setOpened);return i.createElement(pb,{dir:r,id:ce.WINDOW,"aria-hidden":t?void 0:"true",inert:t?void 0:!0,$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:a,$margin:l,$launcherSize:c,onKeyDown:d},n)},pb=_.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})=>bi(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;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
500
+ `:P.css`z-index:1;pointer-events:none;`}
501
+ `;function nn({initialId:e,children:t}){const[n,r]=c.useState([e]),s=n[n.length-1],o=c.useCallback((g,y)=>{r(E=>[...E,g]),h(E=>({...E,[g]:!0})),y!=null&&y.reset&&C(E=>({...E,[g]:(E[g]||0)+1})),v(E=>({...E,[g]:"entering"})),setTimeout(()=>{v(E=>({...E,[g]:"entered"}))},300)},[]),a=c.useCallback(()=>{r(g=>{if(g.length<=1)return g;const y=g[g.length-1];return v(E=>({...E,[y]:"exiting"})),setTimeout(()=>{v(E=>({...E,[y]:"exited"})),r(E=>E.slice(0,-1))},300),g})},[]),l=c.useMemo(()=>({navigation:{navigate:o,pop:a},activeScreenId:s}),[o,a,s]),u=c.useMemo(()=>c.Children.toArray(t).filter(g=>g.type===Pi),[t]),d=c.useMemo(()=>{const g={};return u.forEach(y=>{const{id:E,lazy:I,children:A}=y.props;g[E]={lazy:I,element:typeof A=="function"?A(l):A}}),g},[u,l]),[m,h]=c.useState(()=>{const g={};return Object.entries(d).forEach(([y,{lazy:E}])=>{E===!1&&(g[y]=!0)}),g[e]=!0,g}),[f,v]=c.useState(()=>{const g={};return Object.keys(d).forEach(y=>{y===e?g[y]="entered":g[y]="exited"}),g}),[b,C]=c.useState({});return i.createElement($i.Provider,{value:l},i.createElement(Gb,null,Object.keys(d).map(g=>{var A;if(!m[g])return null;const y=f[g]||"exited",E=g===s,I=`${g}-${b[g]||0}`;return i.createElement(Hb,{key:I,$transitionState:y,$active:E,"aria-hidden":E?void 0:!0,inert:E?void 0:!0},(A=d[g])==null?void 0:A.element)})))}const Gb=_.default.div`position:relative;width:100%;height:100%;`;nn.Screen=Pi;const Fe={conv:"conv",convList:"conv-list"},Zs=({isOpened:e,activeScreenId:t})=>e&&t===Fe.conv,Vb=({screenId:e,conversationKey:t,navigationKey:n})=>e===Fe.conv?`${e}:${t??""}`:n?`${e}:${n}`:e,zb=({initialRoute:e,isOpened:t,selectedChannelUrl:n,setSelectedChannelUrl:r})=>{const{announceScreenEntry:s}=Er(),o=c.useRef(null),a=c.useRef(null),l=c.useRef(0),[u,d]=c.useState(0),m=c.useCallback(b=>{const C=Vb(b);o.current!==C&&(o.current=C,a.current=b,b.screenId===Fe.convList&&s({screen:"conversationList"}))},[s]),h=c.useCallback((b,C)=>{const g={screenId:Fe.conv,conversationKey:C};r(C),b.navigate(Fe.conv),a.current=g,t&&m(g)},[m,t,r]),f=c.useCallback(b=>{l.current+=1;const C=l.current,g={screenId:Fe.convList,navigationKey:`visit:${C}`};a.current=g,d(C),b.navigate(Fe.convList)},[]),v=c.useCallback(()=>{var C;const b=((C=a.current)==null?void 0:C.screenId)===Fe.convList?a.current:{screenId:Fe.convList};m(b)},[m]);return c.useEffect(()=>{if(t){const b=a.current?a.current.screenId===Fe.conv?{screenId:Fe.conv,conversationKey:n??a.current.conversationKey}:a.current:{screenId:e,conversationKey:e===Fe.conv?n:void 0};b.screenId!==Fe.convList&&m(b)}else o.current=null,a.current=null},[m,e,t,n]),{announceConversationListScreen:v,conversationListAnnouncementToken:u,navigateToConversationList:f,openConversation:h}},it={conv:"conv",convList:"conv-list"},qb=e=>e===it.convList?"ConversationList":"Conversation",Fi=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:s})=>{const{conversationChildren:o,conversationListChildren:a}=kr(),l=(()=>{switch(t){case"Conversation":return it.conv;case"ConversationList":return it.convList;default:return it.conv}})(),{announceConversationListScreen:u,conversationListAnnouncementToken:d,navigateToConversationList:m,openConversation:h}=zb({initialRoute:l,isOpened:e,selectedChannelUrl:n,setSelectedChannelUrl:r}),f=i.createElement(i.Fragment,null,i.createElement(Wb,{onOpenConversationView:(v,b)=>h(v,b)}),i.createElement(Kb,{onActiveRouteChange:s}));return i.createElement(nn,{initialId:l},i.createElement(nn.Screen,{id:it.conv},({navigation:v,activeScreenId:b})=>i.createElement(Ai,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>m(v),announcementsEnabled:Zs({isOpened:e,activeScreenId:b}),shouldMarkAsRead:Zs({isOpened:e,activeScreenId:b})},f,o)),i.createElement(nn.Screen,{id:it.convList,lazy:!0},({navigation:v,activeScreenId:b})=>{const C=e&&b===it.convList;return i.createElement(Ti,{onOpenConversationView:g=>{h(v,g)}},i.createElement(Yb,{announcementToken:d,enabled:C,onAnnounce:u}),f,a)}))},Wb=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Ne(),{navigation:n}=Lr();return t(({channel:r})=>{e(n,r.url)}),null},Yb=({announcementToken:e,enabled:t,onAnnounce:n})=>{const{listSource:r}=An();return c.useEffect(()=>{if(!t||!r.initialized)return;const s=setTimeout(()=>{n()},0);return()=>{clearTimeout(s)}},[e,t,r.initialized,n]),null},Kb=({onActiveRouteChange:e})=>{const{activeScreenId:t}=Lr();return c.useEffect(()=>{e==null||e(qb(t))},[t,e]),null},jb=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=fe(),o=c.useRef(null);return Rb(t,o),i.createElement(Xb,null,i.createElement(Zb,{ref:o,dir:s,id:ve.WINDOW,$isExpanded:e,$isOpened:t},n),r)},Xb=_.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,Zb=_.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&&Qb};${({$isExpanded:e})=>e&&Jb};`,Jb=P.css`width:743px;height:723px;`,Qb=P.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;`,eC=c.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=Dt(),[o,a]=c.useState(t),[l,u]=c.useState(n.entryPoint??"Conversation"),d=s?ki:jb;return i.createElement(Mr,{enableExpandButton:!s,ref:r,...n},i.createElement(Go,null,({state:m})=>i.createElement(Mi,null,i.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...s&&{zIndex:"auto"},launcher:i.createElement(Di,{entryPoint:n.entryPoint,activeRoute:l})},i.createElement(Fi,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:a,onActiveRouteChange:u})),e)))}),{Provider:tC,useContext:Rr}=Ee("FixedMessengerStyle");function Bi(e,t,n,r=0){const{top:s,bottom:o,start:a,end:l}=n;let u="",d="";switch(e){case"start":d=`inset-inline-start: ${Ye(a)}`;break;case"end":d=`inset-inline-end: ${Ye(l)}`;break}switch(t){case"top":u=`top: calc(${Ye(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Ye(o)} + ${r}px)`;break}return P.css`${u};${d};`}function nC(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Rr();return i.createElement(rC,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const rC=_.default(Di)`position:fixed;z-index:${vt.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>Bi(e,t,n)};`,sC=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=fe(),{horizontal:s,vertical:o,margin:a,launcherSize:l}=Rr();return i.createElement(oC,{dir:r,id:ve.WINDOW,"aria-hidden":t?void 0:"true",inert:t?void 0:!0,$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:a,$launcherSize:l},n)},oC=_.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})=>Bi(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}`};
506
502
  [dir='rtl'] &:not([dir='ltr']),
507
503
  &[dir='rtl'] {
508
504
  transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
509
505
  }
510
506
 
511
- ${({$isOpened:e})=>e&&Eb};
512
- ${({$isExpanded:e})=>e&&_b};
513
- `,_b=O.css`width:743px;height:723px;`,Eb=O.css`z-index:${gt.WINDOW};pointer-events:all;visibility:visible;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;`,Ci={top:24,bottom:24,start:24,end:24},bb=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,h]=u.useState(Ci),[g,C]=u.useState(48),b=Mt(),v=b?ci:fb,{horizontal:f,vertical:y}=u.useMemo(()=>{const[E,x]=c.split("-");return{horizontal:E==="start"?"start":"end",vertical:x==="top"?"top":"bottom"}},[c]);return i.createElement(Tr,{enableExpandButton:!b,ref:r,...n},i.createElement(bs,null,({state:E})=>i.createElement(mb,{value:{horizontal:f,vertical:y,margin:m,launcherSize:g,setPosition:d,setMargin:h,setLauncherSize:C}},i.createElement(li,null,i.createElement(v,{isExpanded:E.expanded,isOpened:E.opened},i.createElement(_i,{isOpened:E.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:s,onActiveRouteChange:l})),i.createElement(hb,{entryPoint:n.entryPoint,activeRoute:a}),e))))}),Cb=e=>{var o,s,a,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=kr();return u.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...Ci,...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},vb=({children:e})=>{const{setConversationChildren:t}=Ir();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},yb=({children:e})=>{const{setConversationListChildren:t}=Ir();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Sb=Object.assign(bb,{Style:Cb,ConversationChildren:vb,ConversationListChildren:yb}),Ab=e=>{const{refreshActiveChannel:t}=Ee(),[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])};Xo.set(ie.SendbirdPlatform.JS,{deviceOSPlatform:Gi()?ie.DeviceOsPlatform.MOBILE_WEB:ie.DeviceOsPlatform.WEB,messengerVersion:Lc,keyValueStorage:Rc(),networkStateAdapter:Mc()});exports.ANCHOR_REL=hr;exports.AgentProviderContainer=Tr;exports.AgentUIProviderContainer=ii;exports.AnonymousSessionInfo=Gn;exports.CSATType=Ne;exports.Commands=rt;exports.Conversation=ri;exports.ConversationContext=Xu;exports.ConversationContextProvider=Ts;exports.ConversationHeaderLayout=it;exports.ConversationLayout=vn;exports.ConversationList=si;exports.ConversationListContext=eE;exports.ConversationListContextProvider=oi;exports.ConversationListHeaderLayout=_t;exports.ConversationListItemLayout=xr;exports.ConversationListLayout=Sn;exports.DefaultMessenger=db;exports.DeskTicketPriority=ir;exports.DeskTicketStatus=sr;exports.FixedMessenger=Sb;exports.IncomingMessageLayout=Je;exports.LauncherBase=ui;exports.LogLevel=tr;exports.ManualSessionInfo=Ko;exports.MessageListUILayout=Cn;exports.MessageLogs=Ys;exports.OutgoingMessageLayout=Nt;exports.PlaceholderLayout=bn;exports.SystemMessageLayout=_n;exports.cssVars=p;exports.escapeMarkdownSyntax=Ui;exports.mapCommonStringsToReactFormat=hs;exports.messengerDispatcher=ai;exports.useAIAgentContext=ke;exports.useConversationContext=he;exports.useConversationListContext=yn;exports.useLocalizationContext=Q;exports.useMessengerContext=ne;exports.useMessengerSessionContext=Ee;exports.useRefreshActiveChannel=Ab;
507
+ ${({$isOpened:e})=>e&&aC};
508
+ ${({$isExpanded:e})=>e&&iC};
509
+ `,iC=P.css`width:743px;height:723px;`,aC=P.css`z-index:${vt.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;`,Ui={top:24,bottom:24,start:24,end:24},lC=c.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=c.useState(t),[a,l]=c.useState(n.entryPoint??"Conversation"),[u,d]=c.useState("end-bottom"),[m,h]=c.useState(Ui),[f,v]=c.useState(48),b=Dt(),C=b?ki:sC,{horizontal:g,vertical:y}=c.useMemo(()=>{const[E,I]=u.split("-");return{horizontal:E==="start"?"start":"end",vertical:I==="top"?"top":"bottom"}},[u]);return i.createElement(Mr,{enableExpandButton:!b,ref:r,...n},i.createElement(Go,null,({state:E})=>i.createElement(tC,{value:{horizontal:g,vertical:y,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:v}},i.createElement(Mi,null,i.createElement(C,{isExpanded:E.expanded,isOpened:E.opened},i.createElement(Fi,{isOpened:E.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,onActiveRouteChange:l})),i.createElement(nC,{entryPoint:n.entryPoint,activeRoute:a}),e))))}),cC=e=>{var s,o,a,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=Rr();return c.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...Ui,...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},uC=({children:e})=>{const{setConversationChildren:t}=kr();return c.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},dC=({children:e})=>{const{setConversationListChildren:t}=kr();return c.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},mC=Object.assign(lC,{Style:cC,ConversationChildren:uC,ConversationListChildren:dC}),hC=e=>{const{refreshActiveChannel:t}=Ne(),[n,r]=c.useState(!1),s=c.useRef(null),o=c.useRef(null);return c.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]),c.useCallback(()=>new Promise((a,l)=>{s.current=a,o.current=l,e().then(()=>r(!0)).catch(l)}),[e])};ho.set(le.SendbirdPlatform.JS,{deviceOSPlatform:sa()?le.DeviceOsPlatform.MOBILE_WEB:le.DeviceOsPlatform.WEB,messengerVersion:hu,keyValueStorage:gu(),networkStateAdapter:fu()});exports.ANCHOR_REL=pr;exports.AgentProviderContainer=Mr;exports.AgentUIProviderContainer=Ii;exports.AnonymousSessionInfo=zn;exports.CSATType=We;exports.Commands=lt;exports.ConnectionDelayLayout=En;exports.Conversation=Ai;exports.ConversationContext=Kd;exports.ConversationContextProvider=Yo;exports.ConversationHeaderLayout=mt;exports.ConversationLayout=Sn;exports.ConversationList=Ti;exports.ConversationListContext=VE;exports.ConversationListContextProvider=xi;exports.ConversationListHeaderLayout=At;exports.ConversationListItemLayout=wr;exports.ConversationListLayout=xn;exports.DefaultMessenger=eC;exports.DeskTicketPriority=ar;exports.DeskTicketStatus=ir;exports.FixedMessenger=mC;exports.ID_INCOMING=Ze;exports.IncomingMessageLayout=rt;exports.LauncherBase=Li;exports.LogLevel=rr;exports.ManualSessionInfo=ao;exports.MessageListUILayout=yn;exports.MessageLogs=gi;exports.OutgoingMessageLayout=Pt;exports.PlaceholderLayout=vn;exports.SystemMessageLayout=bn;exports.cssVars=p;exports.escapeMarkdownSyntax=na;exports.flattenObject=ka;exports.mapCommonStringsToReactFormat=Ro;exports.messengerDispatcher=wi;exports.noop=he;exports.parseToMessageTemplate=uo;exports.parseToUITemplate=wa;exports.pickColorByTheme=Ma;exports.replaceVariablesAsync=Ra;exports.replaceVariablesSync=La;exports.useAIAgentContext=$e;exports.useConversationContext=ye;exports.useConversationListContext=An;exports.useLocalizationContext=re;exports.useMessageTemplateFetchingContext=nc;exports.useMessengerContext=fe;exports.useMessengerSessionContext=Ne;exports.useMessengerThemeContext=Fo;exports.useRefreshActiveChannel=hC;