@sendbird/ai-agent-messenger-react-native 1.10.0 → 1.10.1
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 +1 -1
- package/dist/index.d.ts +28 -2
- package/dist/index.js +1750 -1708
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ps=Object.defineProperty;var Os=(e,t,n)=>t in e?Ps(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var f=(e,t,n)=>Os(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react-native"),q=require("@sendbird/chat"),d=require("react"),pe=require("react-native-safe-area-context"),W=require("@sendbird/chat/aiAgent"),ve=require("date-fns"),Se=require("@sendbird/chat/message"),Le=require("@sendbird/chat/groupChannel"),Ze=require("@sendbird/uikit-tools"),Ns=require("date-fns/isSameDay"),Hs=require("date-fns/locale/de"),Bs=require("date-fns/locale/en-US"),Us=require("date-fns/locale/es"),Fs=require("date-fns/locale/fr"),zs=require("date-fns/locale/hi"),$s=require("date-fns/locale/it"),Vs=require("date-fns/locale/ja"),qs=require("date-fns/locale/ko"),js=require("date-fns/locale/pt"),Gs=require("date-fns/locale/tr"),Ws=require("@react-native-clipboard/clipboard"),Ks=require("react-native-code-highlighter"),Ys=require("react-native-markdown-display"),tt=e=>e&&e.__esModule?e:{default:e};function Xs(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 s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Zs=tt(q),a=Xs(d),Js=tt(Ws),Qs=tt(Ks),er=tt(Ys),Ee="sb-agent",Wn="KEY_IMG_ASPECT_RATIO",Kn="*/*",D={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},ne=e=>!!e&&"sender"in e,tr=e=>ne(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),nr=(e,t,n,s=!0)=>{if(!s||!ne(e))return"single";const r=()=>{if(!t||!ne(t))return!1;const c=t.sender.userId===e.sender.userId,u=ve.isSameMinute(t.createdAt,e.createdAt);return c&&u},o=()=>{if(!n||!ne(n))return!1;const c=n.sender.userId===e.sender.userId,u=ve.isSameMinute(n.createdAt,e.createdAt);return c&&u},i=r(),l=o();return i&&l?"middle":i?"bottom":l?"top":"single"},Ne=(e,t)=>(()=>{var s;return ne(e)?e.sender.userId:((s=e==null?void 0:e.sender)==null?void 0:s.userId)??void 0})()===t,Ue={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>ne(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>ne(e)&&(e.sender.userId===t||e.sendingStatus===Se.SendingStatus.PENDING)},sr=e=>e.startsWith("image/"),Xt=(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"},Yn=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},Zt=e=>{switch(e){case"top":case"middle":return D.GAP_GROUPED;default:return D.GAP_UNGROUPED}},rr=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,s=[];let r=0;return e.replace(n,(o,...i)=>{const[l,c,u]=i;return r<u&&s.push({type:"text",value:e.slice(r,u).trim()}),s.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),r=u+o.length,o}),r<e.length&&s.push({type:"text",value:e.slice(r).trim()}),s},or=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),ar=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),ir=e=>e.replace(/~~/g,"\\~\\~"),lr=e=>{let t=e;return t=or(t),t=ar(t),t=ir(t),t},cr=typeof navigator<"u"&&navigator.product==="ReactNative",yn=(e,t)=>{const n=s=>!t||t.length===0?!0:ne(s)&&t.includes(s.sendingStatus);return cr?e.find(n):e.findLast(n)};function Lt(){}function ur(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const bn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ye={isStreaming(e){const t=bn(e.data);return typeof t=="object"&&!!t.stream},isWelcomeMessage(e,t){var n;if(((n=e.extendedMessagePayload)==null?void 0:n.bot_message_type)==="welcome")return!0;if(Ne(e,t)){const s=bn(e.data);return!(s!=null&&s.respond_mesg_id)&&!(s!=null&&s.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)}},ht=`@${Ee}`,dr=({appId:e,aiAgentId:t,storage:n})=>{const s={templateBase:`${ht}-template`,template:r=>`${s.templateBase}/templates/${r}`,templateToken:()=>`${s.templateBase}/tokens`,messengerSession:r=>{const o=ur(`${e}/${t}/${r}`);return`${ht}-udata/${o}`},anonUserSession:()=>`${ht}-session/${e}/${t}`};return{template:{set:(r,o)=>n.set(s.template(r),o),get:r=>n.get(s.template(r)),setCachedToken:r=>n.set(s.templateToken(),r),getCachedToken:()=>n.get(s.templateToken()),clear:()=>{n.getKeys(s.templateBase).forEach(n.delete)}},messenger:{getSettings:r=>{try{const o=n.get(s.messengerSession(r));return o?JSON.parse(o):null}catch{return null}},setSettings:(r,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(s.messengerSession(r),i)}catch{return}},getAnonUser:()=>{try{const r=n.get(s.anonUserSession());return r?JSON.parse(r):null}catch{return null}},setAnonUser:r=>{try{const o=JSON.stringify(r);n.set(s.anonUserSession(),o)}catch{return}},clear:r=>{try{r&&n.delete(s.messengerSession(r)),n.delete(s.anonUserSession())}catch{return}}}}},Xn=(e,t,n={})=>{let s=null,r=null,o=null;const{leading:i=!0,trailing:l=!0}=n,c=(...u)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...u),o=m):(r=u,o=m);else if(r=u,l&&!s){const h=t-(m-o);s=setTimeout(()=>{r&&l&&(e(...r),o=Date.now()),s=null,r=null},h)}};return c.cancel=()=>{s&&(clearTimeout(s),s=null),r=null,o=null},c};class Zn{constructor(t,{filter:n,limit:s=20}){f(this,"filter");f(this,"_sdk");f(this,"_pinnedChannels");f(this,"_channels");f(this,"_isDisposed",!1);f(this,"_handlerId",`handler-id-${Date.now()}`);f(this,"_order",Le.GroupChannelListOrder.LATEST_LAST_MESSAGE);f(this,"_limit");f(this,"_query");f(this,"_token");f(this,"_timestamp");f(this,"_isSyncing");f(this,"_channelHandler");f(this,"_connectionHandler");f(this,"_collectionEventHandler");f(this,"_throttledOnChannelChanged");var r,o,i,l,c,u,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=s,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(r=this.filter)==null?void 0:r.aiAgentChannelFilter,aiAgentConversationStatusFilter:(o=this.filter)==null?void 0:o.aiAgentConversationStatusFilter,aiAgentIds:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.pinnedChannelUrls,copilotConversationOnly:(u=this.filter)==null?void 0:u.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=Xn(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new Le.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new q.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,i;const n=new Set(((o=this.filter)==null?void 0:o.pinnedChannelUrls)??[]),s=t.find(l=>!n.has(l.url));let r;s?r=((i=s.lastMessage)==null?void 0:i.createdAt)??s.createdAt:r=this._query.lastResponseAt,this._timestamp>r&&(this._timestamp=r)}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)??[],s=new Map(n.map((c,u)=>[c,u])),r=[],o=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const u=s.get(c.url);if(u===void 0)continue;const m=Pt(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),o.push(c)):r.push(c);const g=this._pinnedChannels.findIndex(b=>(s.get(b.url)??1/0)>u),y=g===-1?this._pinnedChannels.length:g;this._pinnedChannels.splice(y,0,c)}return{addedChannels:r,updatedChannels:o,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const s=[],r=[],o=[];for(const i of t){if(!this._query.belongsTo(i)){s.push(i.url);continue}const l=Pt(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=mr(this._channels,i,this._order).place,h=m===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(i),r.push(i)):(this._channels.splice(m,0,i),r.push(i)):(this._channels.splice(m,0,i),o.push(i))}return{addedChannels:r,updatedChannels:o,unmatchedChannelUrls:s}}_addChannelsToView(t,n=!1){var h,g,y,b,E;const s=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),r=[],o=[];for(const _ of t)s.has(_.url)?r.push(_):o.push(_);const i=this._upsertPinnedChannelsToArray(r),l=this._upsertRegularChannelsToArray(o,n),c=i.addedChannels.concat(l.addedChannels),u=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((y=(g=this._collectionEventHandler)==null?void 0:g.onChannelsAdded)==null||y.call(g,{},c)),u.length>0&&((E=(b=this._collectionEventHandler)==null?void 0:b.onChannelsUpdated)==null||E.call(b,{},u)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var r,o,i;const n=new Set(((r=this.filter)==null?void 0:r.pinnedChannelUrls)??[]),s=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(u=>u.url===l);c>=0&&(s.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(u=>u.url===l);c>=0&&(s.push(l),this._channels.splice(c,1))}s.length>0&&((i=(o=this._collectionEventHandler)==null?void 0:o.onChannelsDeleted)==null||i.call(o,{},s))}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 Pt=(e,t)=>e.findIndex(n=>n.isIdentical(t)),mr=(e,t,n)=>{if(e.length>0){const s=Pt(e,t);let r=0,o=e.length-1,i=Math.floor((r+o)/2);for(;r<o;){const c=Cn(e[i],t,n);if(c>0)o=i,i=Math.floor((r+o)/2);else if(c<0)r=i+1,i=Math.floor((r+o)/2);else return{place:i,oldPosition:s}}return{place:Cn(e[i],t,n)>=0?i:i+1,oldPosition:s}}return{place:e.length,oldPosition:-1}},Cn=(e,t,n)=>{switch(n){case Le.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const s=t.lastMessage.createdAt-e.lastMessage.createdAt;return s===0?t.createdAt-e.createdAt:s}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};class gr{constructor(t){f(this,"subscribers",{});this.logger=t}async send(t){const n=hr(),s=this.subscribers[t.type];if(s){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const r=s.map(o=>o(t.payload));await Promise.all(r).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 s=this.subscribers[t];s&&(this.subscribers[t]=s.filter(r=>r!==n))}}const hr=()=>{let e=Lt,t=Lt;return{promise:new Promise((s,r)=>{e=s,t=r}),resolve:e,reject:t}};var ee=(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))(ee||{});class He{constructor(t={}){f(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Pe={CloseConversation:e=>new _r(e),MessengerSettingsUpdated:e=>new fr(e),ActiveChannelUpdated:e=>new pr(e),AnonymousSessionTokenExpired:()=>new yr,AuthTokenRefreshed:()=>new br};class _r extends He{constructor(){super(...arguments);f(this,"type","conv.close")}}class fr extends He{constructor(){super(...arguments);f(this,"type","messenger.settings.updated")}}class pr extends He{constructor(){super(...arguments);f(this,"type","active.channel.updated")}}class yr extends He{constructor(){super(...arguments);f(this,"type","anon.token.expired")}}class br extends He{constructor(){super(...arguments);f(this,"type","auth.token.refreshed")}}var Jn=(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))(Jn||{});class Qn{constructor(t){f(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ee}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ee}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ee}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ee}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ee}/error]`,...t)}}class Jt{constructor({userId:t,authToken:n,sessionHandler:s}){f(this,"userId");f(this,"authToken");f(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=s}}class Je{constructor(){f(this,"userId");f(this,"authToken");f(this,"sessionHandler")}}const Cr=e=>({onSessionTokenRequired:t=>{t(null),e.send(Pe.AnonymousSessionTokenExpired())}}),Er="ai_agent:stats",vr="conversation_initial_render",Sr=800220;var V=(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))(V||{});class Ar{constructor(){f(this,"timers",new Map);f(this,"committed",!1);f(this,"commitCallback",null);f(this,"conversationId",null);f(this,"channelUrl",null);f(this,"errorCode",null);f(this,"errorDescription",null);f(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??Sr,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(Er,t)):!1}}class Ir extends Ar{constructor(){super(...arguments);f(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return vr}buildPayload(){const n=this.getDuration(V.AUTH),s=this.getDuration(V.GET_CHANNEL),r=this.getDuration(V.GET_MESSAGES),o=this.getDuration(V.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(V.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...s!==null&&{get_channel_duration:s},...r!==null&&{get_messages_duration:r},...o!==null&&{total_duration_from_cache:o}},c={key:this.getMetricKey(),value:i!==null?String(i):"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 Tr{constructor(t){f(this,"commitCallback");f(this,"presentMethod","direct_present");f(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Ir().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(V.TOTAL_DURATION).startTimer(V.TOTAL_DURATION_FROM_CACHE).startTimer(V.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(V.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(V.AUTH).setError(t instanceof q.SendbirdError?t.code:void 0,t.message).stopTimer(V.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(V.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(V.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(V.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(V.GET_CHANNEL).setError(t instanceof q.SendbirdError?t.code:void 0,t.message).stopTimer(V.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof q.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(V.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof q.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(V.TOTAL_DURATION).stopTimer(V.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 wr(){let e=null,t=0;const n=(s,r)=>{if((e==null?void 0:e.key)===s)return e.promise;const o=++t,l=(e?e.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:s,id:o,promise:l},l};return n.isPending=()=>e!==null,n}const ce={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}}},En=e=>{var t,n,s,r,o,i,l,c,u,m,h,g,y,b;return e?{...ce,...e,conversation:{...ce.conversation,...e==null?void 0:e.conversation,header:{...(t=ce.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(s=ce.conversation)==null?void 0:s.input,...(r=e==null?void 0:e.conversation)==null?void 0:r.input,camera:{...(i=(o=ce.conversation)==null?void 0:o.input)==null?void 0:i.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(m=(u=ce.conversation)==null?void 0:u.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:{...(y=ce.conversation)==null?void 0:y.fileViewer,...(b=e==null?void 0:e.conversation)==null?void 0:b.fileViewer}}}:ce},se=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===W.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},es=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===W.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function ye(e){var n,s,r;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((r=(s=e==null?void 0:e.conversation)==null?void 0:s.handoff)==null?void 0:r.timestamp))=="number"}function xr(e){var s;const t=(s=e==null?void 0:e.conversation)==null?void 0:s.handoff;return t?typeof t.requestedAt=="number"&&!ye(e):!1}function kr(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function vn(e){return!!e&&e<Date.now()}function Rr(e){return!e.title}function Mr(e,t){var n;if(e)return Rr(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 Dr{constructor(){f(this,"_channelHandlerId",null);f(this,"_connectionHandlerId",null);f(this,"_handleActiveChannelChangedThrottled",null);f(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Xn(r=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:r.url,status:se(r)?"closed":"open",conversationStatus:(o=r.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",r.url)},250,{leading:!0,trailing:!1});const n=new Le.GroupChannelHandler({onChannelChanged:r=>{var o,i;r.isGroupChannel()&&r.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,r))}}),s=new q.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,s),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});f(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")});f(this,"_syncActiveChannelOnReconnect",async()=>{var n,s,r;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((r=this._session)==null||r._updateActiveChannel({url:i.url,status:se(i)?"closed":"open",conversationStatus:(s=i.conversation)==null?void 0:s.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});f(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)}});f(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(ee.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(ee.MessengerSettingsUpdated,t)}));f(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(ee.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(ee.ActiveChannelUpdated,t)}));f(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(ee.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(ee.AuthTokenRefreshed,t)}))}}class Lr{constructor(t){f(this,"_sdkUser");f(this,"_userSession");f(this,"_dispatcher");f(this,"_activeChannel");f(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Pe.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});f(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Pe.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 Pr=e=>JSON.parse(e);var Ot=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Ot||{});const ts=e=>typeof e=="object"&&e!==null,Sn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Or=e=>!ts(e)||!Sn(e,"channel_url")||!Sn(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Nr={1:Or};function Hr(e){if(!ts(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Nr[t];if(!n)return null;const s=n(e.data);return s?{category:t,data:s}:null}function Br(e,t,n,s){const r=Zs.default.init({appId:e,modules:[new Le.GroupChannelModule,new W.AIAgentModule],localCacheEnabled:!0,options:new q.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...s});return r.addSendbirdExtensions([{version:n,product:q.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),r}function Ur(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 Fr=[400300,400301,400302,400310];class Qt{constructor(t,n,s){f(this,"chatSDK");f(this,"_logger");f(this,"_cache");f(this,"connect",async(t,n,s,r)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const o=new q.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,s,r)});this.chatSDK.setSessionHandler(o),this.chatSDK.aiAgent.addEventHandler(Ot.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),i=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",i);const l=Hr(i);(l==null?void 0:l.category)===Ot.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(c=n==null?void 0:n.onExternalAuthTokenExpired)==null||c.call(n,l.data))})}try{return await this.chatSDK.connect(t.userId,t.authToken),await this._syncTemplatesIfNeeded(),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(o){const i=o;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(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",i.message,i.code),i}});f(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")});f(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));f(this,"patchContext",async(t,n,s)=>this.chatSDK.aiAgent.patchContext(t,n,s));f(this,"updateContext",async(t,n,s)=>this.chatSDK.aiAgent.updateContext(t,n,s));f(this,"requestMessengerSettings",async t=>{var r;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 s=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(r=s.active_channel)==null?void 0:r.channel_url),s});f(this,"_interceptTokenRefresh",(t,n,s)=>{if(t)return async(r,o)=>{new Promise((i,l)=>t==null?void 0:t(i,l)).then(i=>{i?n==null||n(i):s==null||s(),r(i)}).catch(i=>{s==null||s(),o(i)})}});f(this,"_isCacheRestrictedError",t=>Fr.some(n=>t.code===n));f(this,"_syncTemplatesIfNeeded",async()=>{var s,r;const t=(r=(s=this.chatSDK.appInfo)==null?void 0:s.aiAgentInfo)==null?void 0:r.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of o){const{key:c}=Pr(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._logger=n,this._cache=s}static init(t){let n;return t.chatSDK?(Ur(t.chatSDK),n=t.chatSDK):n=Br(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Qt(n,t.logger,t.cache)}}const Fe=new Map,ns={set:(e,t)=>{Fe.set(e,t)},get:e=>{if(Fe.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=Fe.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Fe.entries().next().value;return{platform:t[0],...t[1]}}},zr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class An extends Error{constructor(n,s){const r=(s==null?void 0:s.detail)??"";super(r||`Desk API error (${n})`);f(this,"status");f(this,"code");f(this,"detail");this.name="DeskApiError",this.status=n,this.code=(s==null?void 0:s.code)??"",this.detail=r}}var en=(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))(en||{}),tn=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(tn||{}),ss=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(ss||{});const $r=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Vr{constructor(t){f(this,"_appId");f(this,"_apiHost");f(this,"_logger");f(this,"_credential",null);f(this,"_authRefreshPromise",null);f(this,"_onDeskTokenRefreshRequired",async()=>!1);f(this,"request",async(t,n)=>{const s=n.authRequired??!0,r=`${this._apiHost}${t}`;s&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(r,n);return s&&o.status===401?this._handleUnauthorized(o,r,n):this._toResult(o)});f(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});f(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});f(this,"_handleUnauthorized",async(t,n,s)=>{const r=await this._parseErrorCode(t);if(!$r(r))return this._toResult(t);if(!await this._refresh(r)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,s);return this._toResult(i)});f(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}});f(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))}:{}}));f(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));f(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));f(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));f(this,"_toResult",async t=>{if(!t.ok){const s=await t.json().catch(()=>({}));throw new An(t.status,s)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new An(t.status,{})}});f(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 Qe{constructor(t,n){f(this,"id");f(this,"title");f(this,"status");f(this,"agent");f(this,"priority");f(this,"group");f(this,"firstResponseTime");f(this,"issuedAt");f(this,"customFields");f(this,"_client");f(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 s;return new Qe({id:t.id,title:t.channelName??null,status:t.status2??en.INITIALIZED,agent:(()=>{var o;const r=(o=t.recentAssignment)==null?void 0:o.agent;return r?{userId:r.sendbirdId??"",name:r.displayName??"",profileUrl:r.photoThumbnailUrl??""}:null})(),priority:t.priority??tn.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((s=t.customFields)==null?void 0:s.map(r=>[r.key,r.value]))??[])},n)}}class nn{constructor(t){f(this,"_logger");f(this,"_apiClient");f(this,"_onDeskTokenRefreshRequired");f(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);f(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}});f(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});f(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")});f(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return Qe._fromResponse(n,this)});f(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:zr({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 Qe._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Vr(t)}static init(t){return new nn(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function qr(){const e={};return{get:t=>e[t]??null,set:(t,n)=>{e[t]=n},delete:t=>{delete e[t]},getKeys:t=>Object.keys(e).filter(n=>n.startsWith(t))}}function rs(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 jr=1440*60*1e3;function _e(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Gr(e,t){return Object.entries(t).every(([n,s])=>e[n]===s)}class et extends Dr{constructor(n){super();f(this,"appId");f(this,"aiAgentId");f(this,"_chatClient");f(this,"_deskClient");f(this,"_cache");f(this,"_logger");f(this,"_dispatcher");f(this,"_session",null);f(this,"language");f(this,"countryCode");f(this,"context");f(this,"queryParams");f(this,"_config");f(this,"_networkStateAdapter");f(this,"_forceCreateChannel");f(this,"_agentVersion");f(this,"_statsTrackers");f(this,"_operationQueue",wr());f(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"))});f(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));f(this,"authenticate",n=>{const s=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(s,async()=>{var i,l,c,u,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const r=this._getSessionCandidate(n),o=(i=r.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(r.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(Pe.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=r.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=o==null?void 0:o.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let g;if(h.auto_created_user)if(r.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),g={userId:r.userSessionCandidate.userId,authToken:r.userSessionCandidate.authToken};else{const{user_id:E,session_token:_,expire_at:v}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:E,authToken:_,expireAt:v}),g={userId:E,authToken:_},this._logger.debug("AIAgent.authenticate: anonymous user created",E)}else g={userId:((u=r.userSessionCandidate)==null?void 0:u.userId)??"",authToken:((m=r.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,h),this._dispatcher.send(Pe.MessengerSettingsUpdated({settings:h,source:"server"}));const y=(()=>{var E;return r.type==="anonymous"?Cr(this._dispatcher):(E=r.userSessionCandidate)==null?void 0:E.sessionHandler})(),b=await this._chatClient.connect(g,y,E=>{var _;this._logger.debug("AIAgent: session token refreshed"),(_=this._session)==null||_._updateAuthToken(E),this._deskClient.refreshDeskAuthToken(E)},()=>{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:E})=>{var _;if(E===ss.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const v=(_=this._session)==null?void 0:_.userSession.authToken;return v?await this._deskClient.refreshDeskAuthToken(v):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Lr({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}})});f(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")}));f(this,"createConversation",async n=>{_e(this._session),this._logger.debug("AIAgent.createConversation: start",n);const s=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),r=s.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,s),this._logger.debug("AIAgent.createConversation: end",r),r});f(this,"searchConversation",async n=>{if(_e(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 s=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:W.ConversationStatus.OPEN,limit:100}),r=[];for(;s.hasNext;){const o=await s.next();for(const i of o)Gr(i.context??{},n.context)&&r.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:r.length}),r});f(this,"closeConversation",async n=>{var r;_e(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const s=await this._chatClient.getChannel(n);((r=s.conversation)==null?void 0:r.status)===W.ConversationStatus.OPEN?(await s.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:W.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});f(this,"createConversationListCollection",n=>new Zn(this.chatSDK,n??{}));f(this,"patchContext",async(n,s)=>{_e(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:s});const r=await this._chatClient.patchContext(this.aiAgentId,n,s);return this._logger.debug("AIAgent.patchContext: end",r),{...r,context:r.context??{}}});f(this,"updateContext",async(n,s)=>{_e(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:s});const r=await this._chatClient.updateContext(this.aiAgentId,n,s);return this._logger.debug("AIAgent.updateContext: end",r),{...r,context:r.context??{}}});f(this,"getContextObject",async n=>{_e(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const r=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",r),{...r,context:r.context??{}}});f(this,"refreshActiveChannel",async n=>{var i,l;_e(this._session);const s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const r=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:this._session.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(l=(i=this._cache.messenger.getSettings(this._session.userSession.userId))==null?void 0:i.active_channel)==null?void 0:l.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion}),o=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._session._updateActiveChannel({url:o,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",o),o});f(this,"_getSessionCandidate",n=>n instanceof Jt?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Je?{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});f(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-jr<=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});f(this,"_getManualSessionInfo",n=>{if(!n||n instanceof Je)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 s=["userId","authToken","sessionHandler"].filter(r=>!(r in n));return s.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${s.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=En(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 Tr((s,r)=>this._chatClient.chatSDK.aiAgent.appendStat(s,r))}}static init(n){var m;const s=ns.get(n.platform),r=n.logger??new Qn(n.logLevel??Jn.WARN),o=n.dispatcher??new gr(r),i=n.useMMKVStorage?rs(n.useMMKVStorage):s.keyValueStorage,l=dr({appId:n.appId,aiAgentId:n.aiAgentId,storage:i}),c=Qt.init({appId:n.appId,messengerVersion:s.messengerVersion,extensions:{platform:s.platform,deviceOSPlatform:s.deviceOSPlatform,deviceOSVersion:s.deviceOSVersion},chatParams:n.chatParams,chatSDK:n.chatSDK,logger:r,cache:l}),u=nn.init({appId:n.appId,logger:r,customApiHost:(m=n.deskParams)==null?void 0:m.customApiHost});return r.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new et({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:s.networkStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:c,deskClient:u,cache:l,logger:r,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=En(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 j=(e,t)=>{const n=d.createContext(null),s=({children:i,value:l})=>a.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),r=({children:i})=>a.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),o=()=>{const i=d.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,s.displayName=`${e}Provider`,r.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:s,Consumer:r,useContext:o}};function te(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,l]=d.useState(()=>e.template),[c,u]=d.useState(e.components),m={Template:i,updateTemplate:h=>l(()=>h),components:c,updateComponent:(h,g)=>u(y=>({...y,[h]:g}))};return a.createElement(t.Provider,{value:m},o)}function s({template:o,children:i}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{o&&l(o)},[o]),a.createElement(a.Fragment,null,i)}function r({children:o}){return a.createElement(n,null,o)}return r.defaults=e,r.useContext=()=>d.useContext(t),r.Context=t,r.Template=s,Object.keys(e.components).forEach(o=>{r[o]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(o,l)},[l]),null}}),r}function Wr(...e){return function({children:n}){return e.reduce((s,r)=>a.createElement(r,null,s),n)}}function Kr(e,t){var s;const n=e.lastMessage;if(n!=null&&n.isUserMessage()||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 r=n.fileInfoList.length;return((s=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:s.call(t,r))??`${r} photos`}return e.name}function Yr(e,t,n){var i;const s=new Date,r=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ve.differenceInMinutes(s,r);return o<1?n.justNow:o<60?n.minutesAgo(o):ve.isToday(r)?n.hoursAgo(ve.differenceInHours(s,r)):t(r,n.dateShortFormat)}const Xr=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},ze=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),_t=(e,t)=>{const n=ze(Math.round(t*255));if(e.startsWith("#")){const r=e.slice(1);return r.length===3||r.length===4?`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}${n}`:`#${r.slice(0,6)}${n}`}const s=Xr(e);return s?`#${ze(s[0])}${ze(s[1])}${ze(s[2])}${n}`:e},{Provider:Zr,useContext:K}=j("AIAgent");function Jr(e){const t=Qr(e);return a.createElement(Zr,{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 Qr(e){const t=d.useRef(null),n=d.useRef(null);if(!t.current||!n.current)t.current=et.init(e);else{const r=eo(n.current,e);(r.appId||r.aiAgentId||r.chatSDK)&&(t.current.dispose(),t.current=et.init({...e,chatParams:r.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,d.useEffect(()=>()=>{var r;(r=t.current)==null||r.dispose()},[]);const s=t.current;return s.language=e.language??"en",s.countryCode=e.countryCode,s.context=e.context,s.queryParams=e.queryParams,s.config=e.config,s.agentVersion=e._agentVersion,s}function eo(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 to=(e,t,n)=>Ze.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),Nt={DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function os(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function no(e){const t=os(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function so(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function ro(e,t,n){e/=255,t/=255,n/=255;const s=Math.max(e,t,n),r=Math.min(e,t,n),o=s-r;let i=0,l=0;const c=(s+r)/2;return s!==r&&(l=c>.5?o/(2-s-r):o/(s+r)),s===e?i=(t-n)/o+(t<n?6:0):s===t?i=(n-e)/o+2:s===n&&(i=(e-t)/o+4),i/=6,[i,l,c]}function oo(e,t,n){let s,r,o;if(t===0)s=r=o=n;else{const i=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;s=i(c,l,e+1/3),r=i(c,l,e),o=i(c,l,e-1/3)}return[Math.round(s*255),Math.round(r*255),Math.round(o*255)]}function $e(e,t,n){const[s,r,o]=no(e),[i,l,c]=ro(s,r,o),u=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,g,y]=oo(i,m,u);return so([Math.round(h),Math.round(g),Math.round(y)])}function ao(e,t="light"){return{extraDark:$e(e,.6,1.2),dark:$e(e,.85,1.1),main:e,light:$e(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:$e(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function In(e){const t=os(e),n=149,s=+`0x${t[1]}${t[2]}`,r=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return s*.299+r*.587+o*.114>n?Nt.BLACK:Nt.WHITE}function io(e,t,n,s,r){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:r,background:s},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const lo=(e,t,n,s,r)=>({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:r,background:s},messageOutgoing:{text:n,background:t},csat:{background:e.background400}}),Ve={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, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},ft={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 Tn(e){const t=co(e),{colors:n,aiAgentColorVariables:s}=uo(e,t),r=go(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:s,typography:r}}function co({selectedTheme:e,palette:t,primary:n}){const s=t!=null&&t.primary?t.primary:n?n===Ve.primary.main?Ve.primary:ao(n,e):Ve.primary;return{...Ve,primary:s,...t}}function uo({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:s},r){const o=r.primary.main,i=t??In(o),l=n??Nt.DEFAULT_BOT_MSG_BG,c=s??In(l);return{colors:(e==="light"?io:lo)(r,o,i,l,c),aiAgentColorVariables:{primary_color:o,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function mo(e,t,n){const s={...e};return n.forEach(r=>{const o=t[r];o!=null&&(s[r]=o)}),s}function go({typography:e}){if(!e)return ft;const t={...ft};return Object.keys(e).forEach(n=>{const s=e[n];if(s&&typeof s=="object"){const r=ft[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=mo(r,s,o)}}),t}const{Provider:ho,useContext:_o}=j("AIAgentTheme");function fo({logger:e,palette:t,typography:n,appearance:s,children:r}){const o=d.useRef(null),[i,l]=d.useState(()=>Tn({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),c=d.useCallback((u,m)=>{m&&(o.current=m);const h=(s==null?void 0:s.theme)??u,g=o.current?o.current.themes[h]:null,y={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!y.primary&&(g!=null&&g.primary_color)&&(y.primary=g.primary_color,y.primaryContrast=g.primary_contrast_color),!y.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(y.botMessageBackground=g.bot_message_bg_color,y.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const b=Tn({selectedTheme:h,palette:t,typography:n,...y});l(b),e==null||e.info("theme.update:",h)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,e]);return d.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&c(i.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),a.createElement(ho,{value:{theme:i,updateTheme:c}},r)}const pt=25*1024*1024,wn=1,xn=new Set(["image/png","image/jpeg","image/jpg"]),kn=new Set(["application/pdf"]),po={off:"off",always:"always",handed_off_only:"handed_off_only"},yo=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:wn,attachmentMode:"handed_off_only",defaultUploadSizeLimit:pt,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:xn,supportedFileMimeTypes:kn})),n=d.useCallback(({active_channel:r,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??wn,attachmentMode:po[r.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??pt,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)??xn),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??kn)})},[]),s=d.useCallback(r=>{const{channel:o,uploadSizeLimit:i=pt}=r,l=(u=!0)=>o!=null&&o.isAIAgent?u?ye(o):!1:!0,c=u=>{if(l())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(u)??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 ye(o);default:return!0}},get supportedMimeTypes(){return l()?[Kn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:u=>l()?!0:e.supportedImageMimeTypes.has(u)||e.supportedFileMimeTypes.has(u),getUploadSizeLimit:c,getUploadSizeLimitInMB:u=>c(u)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:s}},Rn=(...e)=>{const[t,n,s]=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 s=="object"&&s!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:s};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},ke=e=>({...e,context:e.context??{}}),{Provider:bo,useContext:Be}=j("AIAgentMessengerSession"),Co=d.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:s,chatSDK:r,aiAgentId:o,logger:i}=K(),{updateTheme:l}=_o(),[c,u]=d.useState(void 0),[m,h]=d.useState(void 0),[g,y]=d.useState(null),[b,E]=d.useState(null),[_,v]=d.useState(null),[A,S]=d.useState(null),{updateBaseAttachmentRules:T,createAttachmentRules:x}=yo();d.useEffect(()=>{const w=s.onMessengerSettingsUpdated(({settings:M})=>{const{appearance:U,bot:H,launcher:ue}=M;l(U.selected_theme,U),v({userId:H.bot_userid,profileUrl:H.bot_profile_url,nickname:H.bot_nickname,replyToFile:H.reply_to_file,specialNotice:H.special_notice,specialNoticeEnabled:H.is_special_notice_enabled,showHandoffButton:H.show_handoff_button??!0,isMultipleActiveConversationsEnabled:H.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:H.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:H.is_user_feedback_comment_option_enabled??!1}),S({type:ue.image_type||"default_icon",imageUrl:ue.image_url}),T(M)}),L=s.onActiveChannelUpdated(({channelUrl:M,status:U,conversationStatus:H})=>{h({url:M,status:U,conversationStatus:H})}),I=s.onAuthTokenRefreshed(()=>{var U;const M=(U=s.session)==null?void 0:U.userSession.authToken;M&&E(H=>H?{...H,authToken:M}:null)});return()=>{w(),L(),I()}},[s,l,T]);const R=d.useCallback(async()=>{u(void 0);try{const w=await s.authenticate(e),L=s.session;return y(L.sdkUser),E(L.userSession),h(L.activeChannel),w}catch(w){throw u(w),w}},[s,e]),N=d.useCallback(async()=>{await s.deauthenticate(),y(null),h(void 0),E(null),v(null),S(null)},[s]),Y=d.useCallback(async()=>{if(!s.session)throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready");return h(void 0),await s.refreshActiveChannel()},[s,i]),Q=d.useCallback(async w=>{if(!s.session)throw new Error("Current user is not authenticated. Please authenticate first.");return s.createConversation(w)},[s]),G=d.useCallback(async w=>{if(!s.session)throw new Error("Current user is not authenticated. Please authenticate first.");return s.searchConversation(w)},[s]);return d.useImperativeHandle(n,()=>{const w=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await r.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:r,authenticate:R,deauthenticate:N,updateContext:async(...L)=>{const I=Rn(...L);if(I.type==="active"){const H=await(await w()).updateContext(o,I.context);return ke(H)}const M=await r.aiAgent.updateContext(I.aiAgentId,I.channelUrl,I.context);return ke(M)},patchContext:async(...L)=>{const I=Rn(...L);if(I.type==="active"){const H=await(await w()).patchContext(o,I.context);return ke(H)}const M=await r.aiAgent.patchContext(I.aiAgentId,I.channelUrl,I.context);return ke(M)},getContextObject:async()=>{const I=await(await w()).getContextObject(o);return ke(I)}}},[R,N,m,r,o,i]),a.createElement(bo,{value:{sdkUser:g,userSessionInfo:e,userSession:b,activeChannel:m,setActiveChannel:h,refreshActiveChannel:Y,createConversation:Q,searchConversation:G,connectionError:c,aiAgentInfo:_,launcherInfo:A,authenticate:R,deauthenticate:N,createAttachmentRules:x,statsTrackers:s.statsTrackers}},t)}),sn=(e,t)=>{const n=d.useId(),s=d.useRef(t);d.useLayoutEffect(()=>{s.current=t}),d.useEffect(()=>{const r=new q.ConnectionHandler({onDisconnected:o=>{var i,l;return(l=(i=s.current).onDisconnected)==null?void 0:l.call(i,o)},onConnected:o=>{var i,l;return(l=(i=s.current).onConnected)==null?void 0:l.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=s.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=s.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=s.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=s.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,l;return(l=(i=s.current).onConnectionDelayed)==null?void 0:l.call(i,o)}});return e.addConnectionHandler(n,r),()=>{e.removeConnectionHandler(n)}},[e,n])};function Eo(e){const{chatSDK:t,logger:n,aiAgentId:s,_aiAgentSDK:r}=K(),{sdkUser:o,statsTrackers:i}=Be(),l=Ze.useForceUpdate(),[c,u]=d.useState(void 0),[m,h]=d.useState(void 0),[g,y]=d.useState(!1);function b(_){_.isAIAgent&&!_.conversation&&(y(!0),r.initConversationIfNeeded(_).finally(()=>y(!1)))}async function E(){var _,v,A;if(!o){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),u(void 0),h(void 0),y(!1),e){i.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const S=await t.groupChannel.getChannel(e);b(S),u(S),i.initialRender.onGetChannelComplete((_=S.conversation)==null?void 0:_.id),S.url===((v=r.session)==null?void 0:v.activeChannel.url)&&r.session._updateActiveChannel({url:S.url,status:se(S)?"closed":"open",conversationStatus:(A=S.conversation)==null?void 0:A.status}),n.debug("useChannel.getChannel: fetched channel",S)}catch(S){i.initialRender.onGetChannelError(S),S instanceof q.SendbirdError&&h(S),n.error("useChannel.getChannel: error",S)}}}return d.useEffect(()=>{E()},[t,o,e,s]),sn(t,{async onReconnectSucceeded(){if(!c)return;const _=await c.refresh();b(_),u(_)}}),Ze.useGroupChannelHandler(t,{onChannelChanged:_=>{_.isGroupChannel()&&_.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",_.url),u(_),l())}}),{channel:c,channelFetchError:m,getChannel:E,isInitializingConversation:g}}const vo=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload;return n==null?void 0:n.user_input_disabled_by},So=e=>{var i;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,s=n==null?void 0:n.form,r=!!s&&!s.submitted_at&&!s.canceled_at,o=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return r&&!o},Ao=()=>{const{chatSDK:e,networkStateAdapter:t}=K(),[n,s]=d.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return sn(e,{onConnected:()=>s("connected"),onDisconnected:()=>s("disconnected"),onReconnectStarted:()=>s("reconnecting"),onReconnectSucceeded:()=>s("connected"),onReconnectFailed:()=>s("disconnected"),onConnectionLost:()=>s("reconnecting")}),d.useEffect(()=>{if(t)return t.subscribe(r=>{if(!r){s("reconnecting");return}s(o=>o==="reconnecting"&&e.connectionState===q.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Io=3e4,To=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:s})=>{const[r,o]=d.useState(!1),i=d.useRef(null),l=t&&Ne(t,s)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},u=g=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},g)},m=Date.now()-l,h=Io-m;return n||h<=0?c():u(h),()=>{i.current&&clearTimeout(i.current)}},[n,l]),r&&e},as=e=>{const{chatSDK:t}=K(),[n,s]=d.useState([]);return Ze.useGroupChannelHandler(t,{onTypingStatusUpdated(r){if(r.url===(e==null?void 0:e.url)){const o=r.getTypingUsers();s(o)}}}),n},wo=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:s})=>{const[r,o]=d.useState(!1),i=as(e);return d.useEffect(()=>{if(!t)return;const l=i.some(u=>u.userId===n),c=Ne(t,n)&&(Ye.isStreaming(t)||s);o(c||l)},[i,t,n,s]),r},xo=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:s})=>{const{aiAgentInfo:r,userSession:o}=Be(),i=Ao(),l=wo({channel:e,lastMessage:yn(t,[Se.SendingStatus.SUCCEEDED]),aiAgentUserId:(r==null?void 0:r.userId)??"",isStreamAnimating:n}),c=To({shouldApply:!!(e!=null&&e.isAIAgent)&&!ye(e),isBlockedWhileAIResponding:l,lastMessage:yn(t,[Se.SendingStatus.PENDING,Se.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""});if(!e||i==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(i==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(se(e))return{disabled:!0,disabledBy:"conversation_closed"};if(xr(e))return{disabled:!0,disabledBy:"handoff_pending"};if(So(e))return{disabled:!0,disabledBy:"form_active"};const u=vo(e);return u?{disabled:!0,disabledBy:u}:l||c||s?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},ko=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(r=>{t(o=>{if(o.has(r))return o;const i=new Set(o);return i.add(r),i})},[]),s=d.useCallback(r=>{t(o=>{if(!o.has(r))return o;const i=new Set(o);return i.delete(r),i})},[]);return{isAnimating:e.size>0,start:n,stop:s}},{Provider:Ro}=j("AIAgentConversation");function Mo({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:s,onMessagesUpdated:r,onConversationClosedStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Lt,shouldMarkAsRead:u=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var G;const g=()=>u&&(_==null?void 0:_.markAsRead()),{chatSDK:y,logger:b,dispatcher:E}=K(),{channel:_,channelFetchError:v,getChannel:A,isInitializingConversation:S}=Eo(t),{statsTrackers:T}=Be();d.useEffect(()=>{if(t)return T.initialRender.setChannelUrl(t),()=>{T.initialRender.cleanup()}},[t,T]);const x=to(y,_,{replyType:Se.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:w=>s==null?void 0:s(w),onMessagesUpdated:w=>r==null?void 0:r(w),onCacheResult:w=>T.initialRender.onCacheResult(w),onApiResult:w=>T.initialRender.onApiResult(w),logger:b,markAsRead:g,sortComparator:h}),R=ko(),N=xo({channel:_,messages:x.messages,isStreamAnimating:R.isAnimating,isInitializingConversation:S});d.useEffect(()=>{g()},[u,_]);const Y=se(_);d.useEffect(()=>{o==null||o(Y)},[Y,o]),d.useEffect(()=>{const w=async L=>{const I=typeof(L==null?void 0:L.channelUrl)=="string";_&&I&&L.channelUrl!==_.url||(b.debug("conversation.dispatcher: try to close conversation",_),_!=null&&_.conversation&&_.conversation.status===W.ConversationStatus.OPEN&&(await _.closeConversation(),i==null||i()))};return E.subscribe(ee.ConversationClose,w),()=>{E.unsubscribe(ee.ConversationClose,w)}},[E,_,b,(G=_==null?void 0:_.conversation)==null?void 0:G.status,i]);const Q={conversation:(_==null?void 0:_.conversation)??void 0,channelSource:{channel:_,error:v,refetch:()=>A(),closeConversation:async()=>{se(_)||await(_==null?void 0:_.closeConversation())}},messageSource:{messages:x.messages,newMessages:x.newMessages,initialized:x.initialized,loadPrevious:()=>x.loadPrevious(),loadNext:()=>x.loadNext(),deleteMessage:w=>x.deleteMessage(w),resendMessage:w=>x.resendMessage(w),resetNewMessages:()=>x.resetNewMessages(),sendUserMessage:async w=>{var I;if(((I=_==null?void 0:_.conversation)==null?void 0:I.status)===W.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(w=await l(w));const L=await x.sendUserMessage(w,c);return c==null||c(L),L},sendFileMessage:async w=>{var I;if(((I=_==null?void 0:_.conversation)==null?void 0:I.status)===W.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(w=await l(w));const L=await x.sendFileMessage(w,c);return c==null||c(L),L},sendMultipleFilesMessage:async w=>{var I;if(((I=_==null?void 0:_.conversation)==null?void 0:I.status)===W.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(w=await l(w));const L=await x.sendMultipleFilesMessage(w,c);return c==null||c(L),L}},state:{streamAnimation:R,input:N}};return a.createElement(Ro,{value:Q},e)}function Do(e,t){var y,b,E,_,v,A,S,T,x,R;const[n,s]=d.useState(!1),[r,o]=d.useState(null),[i,l]=d.useState([]),[c,u]=d.useState(null),m=d.useRef(!1),h=d.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,s(!1),o(null),l([]);try{c==null||c.dispose();const N=new Zn(e,t);N.setConversationListCollectionHandler({onChannelsAdded:()=>{l(N.channels)},onChannelsUpdated:()=>{l(N.channels)},onChannelsDeleted:()=>{l(N.channels)}}),await N.loadMore(),u(N),o(null)}catch(N){u(null),o(N)}finally{s(!0),m.current=!1}}},[e,e.currentUser,(y=t.filter)==null?void 0:y.aiAgentChannelFilter,(E=(b=t.filter)==null?void 0:b.aiAgentConversationStatusFilter)==null?void 0:E.join(),(v=(_=t.filter)==null?void 0:_.aiAgentIds)==null?void 0:v.join(),(A=t.filter)==null?void 0:A.deskChannelFilter,(T=(S=t.filter)==null?void 0:S.pinnedChannelUrls)==null?void 0:T.join(),(x=t.filter)==null?void 0:x.copilotConversationOnly,(R=t.filter)==null?void 0:R.copilotSupportChannelUrl,t.limit]),g=d.useCallback(async()=>{if(c)try{await c.loadMore()}catch(N){o(N)}},[c]);return sn(e,{onConnected:()=>h()}),d.useEffect(()=>{h()},[h]),d.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:r,channels:i,loadMore:g}}const{Provider:Lo}=j("AIAgentConversationList");function Po({conversationListLimit:e,conversationListFilter:t,children:n}){var h,g;const{chatSDK:s,aiAgentId:r,queryParams:o}=K(),i={aiAgentIds:[r],aiAgentConversationStatusFilter:[W.ConversationStatus.CLOSED,W.ConversationStatus.OPEN]},l=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c={...i,...(g=o==null?void 0:o.conversationListParams)==null?void 0:g.filter,...t},u=Do(s,{limit:l,filter:c}),m={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return a.createElement(Lo,{value:m},n)}function Oo(e){let t="pending",n=e.then(s=>{t="resolved",n=s}).catch(s=>{t="rejected",n=s});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:No}=j("MessageTemplateFetching");function Ho({children:e,internalVariables:t}){const n=d.useRef({}),s=d.useRef({}),[r,o]=d.useState({}),i=d.useCallback((u,m)=>{o(h=>({...h,[u]:{fetching:!1,error:!1,...h[u],...m}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const y=m(h);if(y)return y;const b=s.current[h];if(b)return b;g||i(h,{fetching:!0});const E=u(h).catch(_=>{throw g||i(h,{error:!0}),_}).finally(()=>{g||i(h,{fetching:!1}),delete s.current[h]});return s.current[h]=E,E},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(u,m)=>{if(n.current[u])return n.current[u];const h=Oo(m());return n.current[u]=h,h},getIsFetching:u=>{var m;return((m=r[u])==null?void 0:m.fetching)??!1},getHasError:u=>{var m;return((m=r[u])==null?void 0:m.error)??!1}};return a.createElement(No,{value:c},e)}const Bo="remove_powered_by",rn=(e,t)=>{var r,o;const{chatSDK:n}=K(),{aiAgentInfo:s}=Be();if(e==="handoff-button"){const i=!!((r=t==null?void 0:t.conversation)!=null&&r.handoff);return!!(t!=null&&t.isAIAgent)&&!!(s!=null&&s.showHandoffButton)&&i&&es(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(s!=null&&s.specialNoticeEnabled)&&!!(s!=null&&s.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return d.useMemo(()=>!(Array.isArray(i)&&i.includes(Bo)),[i])}throw new Error("Unsupported feature")},Uo=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},Fo=e=>{const{aiAgentInfo:t}=Be(),s=as(e)[0];if(!s)return null;const r=s.userId===(t==null?void 0:t.userId),o=r?Uo(s.metaData):void 0;return{user:r?t:s,isBot:r,thinkingMessage:o}},is=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const s=(()=>{const[o]=e.members.filter(i=>i.userId!==t.userId);return o})(),r={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:s==null?void 0:s.profileUrl,title:(s==null?void 0:s.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?ye(e)?r.human("agent"):r.ai("delight"):e.isDesk?r.human("agent"):r.channel("user")},Ht=e=>d.useReducer((t,n)=>({...t,...n}),e);var ie=(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))(ie||{});const zo=new Set(["free_text","single_choice"]),$o=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:s,initialIsResolved:r})=>{const[o,i]=Ht({csatType:t,csat:n,csatReason:s,isResolved:r}),[l,c]=Ht({followUpItem:!1}),u=d.useMemo(()=>{var _;const y=o.csat,b=typeof y=="number",E=(_=e.follow_up)==null?void 0:_.find(v=>b?v.scores.includes(y):v.always_visible??!1);if(zo.has(E==null?void 0:E.response_type))return E},[o.csat,e.follow_up]),m=(()=>{var y;if(typeof n=="number")return"submitted";if((t===ie.AI_AGENT_CSAT_5||t===ie.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===ie.AI_AGENT_CSAT_5_WITH_CRE){const b=typeof o.csat=="number",E=!((y=e.cre)!=null&&y.required)||typeof o.isResolved=="boolean";if(b&&E)return"submittable"}return"unsubmittable"})(),h=d.useCallback(()=>typeof o.csat>"u"?!1:u!=null&&u.required&&!o.csatReason?(c({followUpItem:!0}),!1):!0,[o,u,c]);return d.useEffect(()=>{s||(i({csatReason:""}),c({followUpItem:!1}))},[s,u,i,c]),{params:o,setParams:i,error:l,setError:c,followUpItem:u,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},yt=5,Vo=250,qo=50,Mn=e=>Math.max(0,e-qo),jo=e=>e<1e3?{speed:yt*.5,chunkSize:2}:e<2e3?{speed:yt*.8,chunkSize:2}:{speed:yt*.6,chunkSize:3},Go=e=>{const{text:t,enabled:n=!1,onAnimationStart:s,onAnimationProgress:r,onAnimationComplete:o}=e,[i,l]=d.useState(()=>Mn(t.length)),c=d.useRef(null),u=d.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=d.useRef({onStart:s,onProgress:r,onComplete:o}).current,h=d.useRef({startCalled:!1,completeCalled:!1}).current,g=d.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,y=n,b=i<t.length,E=g.initialEnabled&&(y||b);return d.useLayoutEffect(()=>{m.onStart=s,m.onProgress=r,m.onComplete=o,g.textLength=t.length,g.enabled=n}),d.useLayoutEffect(()=>{var _;g.initialEnabled&&(h.startCalled||(h.startCalled=!0,(_=m.onStart)==null||_.call(m)),l(v=>t.length<v?t.length:v))},[t]),d.useEffect(()=>{if(!g.initialEnabled)return;let _=Mn(t.length);u.lastUpdate=0,u.startTime=0,u.lastProgressCall=0;const v=A=>{var G;u.lastUpdate===0&&(u.lastUpdate=A,u.startTime=A,u.lastProgressCall=A);const S=g.textLength,T=A-u.lastUpdate,x=A-u.startTime,{speed:R,chunkSize:N}=jo(x),Y=R*N;T>=Y&&_<S&&(_=Math.min(_+N,S),l(_),u.lastUpdate=A),A-u.lastProgressCall>=Vo&&(u.lastProgressCall=A,(G=m.onProgress)==null||G.call(m)),(_<S||g.enabled)&&(c.current=requestAnimationFrame(v))};return c.current=requestAnimationFrame(v),()=>{var A;c.current&&cancelAnimationFrame(c.current),h.startCalled&&!h.completeCalled&&(h.completeCalled=!0,(A=m.onComplete)==null||A.call(m))}},[]),d.useEffect(()=>{var S;const _=g.initialEnabled&&h.startCalled,v=!n,A=i>=t.length&&t.length>0;_&&v&&A&&!h.completeCalled&&(h.completeCalled=!0,(S=m.onComplete)==null||S.call(m))},[n,i,t.length]),{streamText:g.initialEnabled?t.slice(0,i):t,isAnimating:E}},Wo="1.10.0",Ko=Wo,Yo={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",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.",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"},conversation_list:{header_title:"Conversations",ended:"Ended",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`},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."},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"},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"}},Bt={language:"en",strings:Yo,dateLocale:Bs.enUS},Xo={conversation:{input_placeholder:"질문하기",input_placeholder_disabled:"이 채널에서는 채팅을 사용할 수 없습니다.",input_placeholder_wait_ai_agent_response:"상담사의 답변을 기다리는 중...",input_placeholder_active_form:"계속 진행하려면 양식을 작성해 주세요.",input_placeholder_reconnecting:"재연결 시도 중. 계속되면 새로고침하세요.",unknown_message_type:"(알 수 없는 메시지 유형)",powered_by:"Powered by",citation_title:"출처",start_new_conversation_label:"대화 시작",scroll_to_new_messages_label:()=>"새 메시지",failed_message_resend:"다시 시도",failed_message_remove:"삭제",file_upload_no_supported_files:"사용 가능한 지원 파일 형식이 없습니다.",a11y_message_list:"채팅 메시지",a11y_scroll_to_bottom:"맨 아래로 스크롤",a11y_scroll_to_new_messages:"새 메시지로 스크롤",a11y_open_conversation_list:"대화 목록 열기"},conversation_list:{header_title:"대화",ended:"종료됨",footer_title:"대화 시작",multiple_files_count:e=>`${e}개의 파일`},date_format:{just_now:"방금",minutes_ago:e=>`${e}분 전`,hours_ago:e=>`${e}시간 전`,date_short:"yyyy/MM/dd",date_separator:"yyyy년 M월 d일",message_timestamp:"p"},csat:{title:"귀하의 피드백은 우리에게 중요합니다.",submitted_label:"성공적으로 제출되었습니다!",cre_question:"문제가 해결되었나요?",cre_positive_label:"네, 감사합니다! 👍",cre_negative_label:"아니요, 도움이 되지 않았어요.",reason_placeholder:"의견을 공유해주세요.",question:"귀하의 경험을 어떻게 평가하시겠습니까?",submit_label:"제출",submission_expired:"죄송합니다. 설문 응답 기간이 종료되었습니다."},form:{optional_label:"선택",validation_required:"이 항목은 필수입니다"},common:{placeholder_something_went_wrong:"문제가 발생했습니다.",placeholder_no_messages:"메시지가 없습니다.",placeholder_no_conversations:"아직 대화가 없습니다",placeholder_something_went_wrong_retry_label:"다시 시도"},feedback:{title:"피드백 제출",good:"좋아요",bad:"별로예요",comment_label:"코멘트 (선택사항)",comment_placeholder:"코멘트를 남겨주세요",cancel:"취소",submit:"제출",save:"저장",edit:"피드백 수정",remove:"피드백 삭제"}},Ut={language:"ko",strings:Xo,dateLocale:qs.ko},Zo={conversation:{input_placeholder:"質問する",input_placeholder_disabled:"このチャンネルではチャットを利用できません",input_placeholder_wait_ai_agent_response:"エージェントの返信を待っています…",input_placeholder_active_form:"続行するには、フォームに記入してください。",input_placeholder_reconnecting:"再接続中。続く場合は更新してください。",unknown_message_type:"(不明なメッセージタイプ)",powered_by:"Powered by",citation_title:"出典",start_new_conversation_label:"会話を始める",scroll_to_new_messages_label:()=>"新しいメッセージ",failed_message_resend:"再試行",failed_message_remove:"削除",file_upload_no_supported_files:"サポートされているファイルタイプがありません。",a11y_message_list:"チャットメッセージ",a11y_scroll_to_bottom:"一番下にスクロール",a11y_scroll_to_new_messages:"新しいメッセージにスクロール",a11y_open_conversation_list:"会話リストを開く"},conversation_list:{header_title:"会話",ended:"終了",footer_title:"会話を始める",multiple_files_count:e=>`${e}個のファイル`},date_format:{just_now:"たった今",minutes_ago:e=>`${e}分前`,hours_ago:e=>`${e}時間前`,date_short:"yyyy/MM/dd",date_separator:"yyyy年 M月 d日",message_timestamp:"p"},csat:{title:"あなたのフィードバックは私たちにとって重要です",submitted_label:"正常に送信されました!",cre_question:"問題は解決されましたか?",cre_positive_label:"はい、ありがとうございます! 👍",cre_negative_label:"いいえ、役に立ちませんでした。",reason_placeholder:"フィードバックを共有する",question:"あなたの経験をどう評価しますか?",submit_label:"送信",submission_expired:"申し訳ありません、アンケートの受付期間は終了しました。"},form:{optional_label:"任意",validation_required:"この質問は必須です"},common:{placeholder_something_went_wrong:"問題が発生しました",placeholder_no_messages:"メッセージがありません",placeholder_no_conversations:"まだ会話がありません",placeholder_something_went_wrong_retry_label:"再試行"},feedback:{title:"フィードバックを送信",good:"良い",bad:"悪い",comment_label:"コメント(オプション)",comment_placeholder:"コメントを残してください",cancel:"キャンセル",submit:"送信",save:"保存",edit:"フィードバックを編集",remove:"フィードバックを削除"}},Ft={language:"ja",strings:Zo,dateLocale:Vs.ja},Jo={conversation:{input_placeholder:"Hacer una pregunta",input_placeholder_disabled:"El chat no está disponible en este canal",input_placeholder_wait_ai_agent_response:"Esperando la respuesta del agente...",input_placeholder_active_form:"Por favor, complete el formulario para continuar.",input_placeholder_reconnecting:"Reconectando. Actualiza si persiste.",unknown_message_type:"(Tipo de mensaje desconocido)",powered_by:"Desarrollado por",citation_title:"Fuente",start_new_conversation_label:"Iniciar una conversación",scroll_to_new_messages_label:()=>"Nuevo mensaje",failed_message_resend:"Reintentar",failed_message_remove:"Eliminar",file_upload_no_supported_files:"No hay tipos de archivo compatibles disponibles.",a11y_message_list:"Mensajes del chat",a11y_scroll_to_bottom:"Desplazarse hacia abajo",a11y_scroll_to_new_messages:"Desplazarse a nuevos mensajes",a11y_open_conversation_list:"Abrir lista de conversaciones"},conversation_list:{header_title:"Conversaciones",ended:"Finalizado",footer_title:"Iniciar una conversación",multiple_files_count:e=>`${e} ${e===1?"archivo":"archivos"}`},date_format:{just_now:"Ahora mismo",minutes_ago:e=>`Hace ${e} minutos`,hours_ago:e=>`Hace ${e} horas`,date_short:"dd/MM/yyyy",date_separator:"d 'de' MMMM 'de' yyyy",message_timestamp:"p"},csat:{title:"Tus comentarios nos importan",submitted_label:"Enviado con éxito!",cre_question:"¿Se resolvió su problema?",cre_positive_label:"¡Sí, gracias! 👍",cre_negative_label:"No, eso no ayudó.",reason_placeholder:"Comparte tu opinión",question:"¿Cómo calificarías tu experiencia?",submit_label:"Enviar",submission_expired:"Lo sentimos, el período de la encuesta ha terminado."},form:{optional_label:"opcional",validation_required:"Esta pregunta es obligatoria"},common:{placeholder_something_went_wrong:"Algo salió mal",placeholder_no_messages:"No hay mensajes",placeholder_no_conversations:"Aún no hay conversaciones",placeholder_something_went_wrong_retry_label:"Reintentar"},feedback:{title:"Enviar comentarios",good:"Bueno",bad:"Malo",comment_label:"Comentario (opcional)",comment_placeholder:"Deja un comentario",cancel:"Cancelar",submit:"Enviar",save:"Guardar",edit:"Editar comentarios",remove:"Eliminar comentarios"}},zt={language:"es",strings:Jo,dateLocale:Us.es},Qo={conversation:{input_placeholder:"Fazer uma pergunta",input_placeholder_disabled:"O chat não está disponível neste canal",input_placeholder_wait_ai_agent_response:"Aguardando a resposta do agente...",input_placeholder_active_form:"Por favor, preencha o formulário para prosseguir.",input_placeholder_reconnecting:"Reconectando. Atualize se persistir.",unknown_message_type:"(Tipo de mensagem desconhecido)",powered_by:"Desenvolvido por",citation_title:"Fonte",start_new_conversation_label:"Iniciar uma conversa",scroll_to_new_messages_label:()=>"Nova mensagem",failed_message_resend:"Tentar novamente",failed_message_remove:"Remover",file_upload_no_supported_files:"Nenhum tipo de arquivo suportado disponível.",a11y_message_list:"Mensagens do chat",a11y_scroll_to_bottom:"Rolar para baixo",a11y_scroll_to_new_messages:"Rolar para novas mensagens",a11y_open_conversation_list:"Abrir lista de conversas"},conversation_list:{header_title:"Conversas",ended:"Encerrada",footer_title:"Iniciar uma conversa",multiple_files_count:e=>`${e} ${e===1?"arquivo":"arquivos"}`},date_format:{just_now:"Agora mesmo",minutes_ago:e=>`Há ${e} minutos`,hours_ago:e=>`Há ${e} horas`,date_short:"dd/MM/yyyy",date_separator:"d 'de' MMMM 'de' yyyy",message_timestamp:"p"},csat:{title:"Seu feedback é importante para nós",submitted_label:"Enviado com sucesso!",cre_question:"Seu problema foi resolvido?",cre_positive_label:"Sim, obrigado! 👍",cre_negative_label:"Não, isso não ajudou.",reason_placeholder:"Compartilhe seu feedback",question:"Como você avaliaria sua experiência?",submit_label:"Enviar",submission_expired:"Desculpe, o período da pesquisa foi encerrado."},form:{optional_label:"opcional",validation_required:"Esta pergunta é obrigatória"},common:{placeholder_something_went_wrong:"Algo deu errado",placeholder_no_messages:"Nenhuma mensagem",placeholder_no_conversations:"Nenhuma conversa ainda",placeholder_something_went_wrong_retry_label:"Tentar novamente"},feedback:{title:"Enviar feedback",good:"Bom",bad:"Ruim",comment_label:"Comentário (opcional)",comment_placeholder:"Deixe um comentário",cancel:"Cancelar",submit:"Enviar",save:"Salvar",edit:"Editar feedback",remove:"Remover feedback"}},$t={language:"pt",strings:Qo,dateLocale:js.pt},ea={conversation:{input_placeholder:"Poser une question",input_placeholder_disabled:"Le chat n'est pas disponible dans ce canal",input_placeholder_wait_ai_agent_response:"En attente de la réponse de l'agent...",input_placeholder_active_form:"Veuillez remplir le formulaire pour continuer.",input_placeholder_reconnecting:"Reconnexion. Actualisez si persiste.",unknown_message_type:"(Type de message inconnu)",powered_by:"Propulsé par",citation_title:"Source",start_new_conversation_label:"Démarrer une conversation",scroll_to_new_messages_label:()=>"Nouveau message",failed_message_resend:"Réessayer",failed_message_remove:"Supprimer",file_upload_no_supported_files:"Aucun type de fichier pris en charge disponible.",a11y_message_list:"Messages du chat",a11y_scroll_to_bottom:"Faire défiler vers le bas",a11y_scroll_to_new_messages:"Aller aux nouveaux messages",a11y_open_conversation_list:"Ouvrir la liste des conversations"},conversation_list:{header_title:"Conversations",ended:"Terminée",footer_title:"Démarrer une conversation",multiple_files_count:e=>`${e} fichier${e===1?"":"s"}`},date_format:{just_now:"À l'instant",minutes_ago:e=>`Il y a ${e} minutes`,hours_ago:e=>`Il y a ${e} heures`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Vos commentaires comptent pour nous",submitted_label:"Soumis avec succès!",cre_question:"Votre problème a-t-il été résolu ?",cre_positive_label:"Oui, merci ! 👍",cre_negative_label:"Non, cela n'a pas aidé.",reason_placeholder:"Partagez votre avis",question:"Comment évalueriez-vous votre expérience ?",submit_label:"Envoyer",submission_expired:"Désolé, la période de l'enquête est terminée."},form:{optional_label:"optionnel",validation_required:"Cette question est obligatoire"},common:{placeholder_something_went_wrong:"Une erreur est survenue",placeholder_no_messages:"Aucun message",placeholder_no_conversations:"Aucune conversation pour le moment",placeholder_something_went_wrong_retry_label:"Réessayer"},feedback:{title:"Envoyer des commentaires",good:"Bien",bad:"Mauvais",comment_label:"Commentaire (optionnel)",comment_placeholder:"Laissez un commentaire",cancel:"Annuler",submit:"Envoyer",save:"Enregistrer",edit:"Modifier les commentaires",remove:"Supprimer les commentaires"}},Vt={language:"fr",strings:ea,dateLocale:Fs.fr},ta={conversation:{input_placeholder:"एक प्रश्न पूछें",input_placeholder_disabled:"इस चैनल में चैट उपलब्ध नहीं है",input_placeholder_wait_ai_agent_response:"एजेंट के उत्तर की प्रतीक्षा कर रहे हैं...",input_placeholder_active_form:"आगे बढ़ने के लिए कृपया फॉर्म भरें।",input_placeholder_reconnecting:"पुनः कनेक्ट हो रहा है। जारी रहे तो रिफ्रेश करें।",unknown_message_type:"(अज्ञात संदेश प्रकार)",powered_by:"द्वारा संचालित",citation_title:"स्रोत",start_new_conversation_label:"एक बातचीत शुरू करें",scroll_to_new_messages_label:()=>"नया संदेश",failed_message_resend:"पुनः प्रयास करें",failed_message_remove:"हटाएं",file_upload_no_supported_files:"कोई समर्थित फ़ाइल प्रकार उपलब्ध नहीं हैं।",a11y_message_list:"चैट संदेश",a11y_scroll_to_bottom:"नीचे स्क्रॉल करें",a11y_scroll_to_new_messages:"नए संदेशों पर स्क्रॉल करें",a11y_open_conversation_list:"बातचीत सूची खोलें"},conversation_list:{header_title:"बातचीत",ended:"समाप्त",footer_title:"एक बातचीत शुरू करें",multiple_files_count:e=>`${e} फ़ाइलें`},date_format:{just_now:"अभी",minutes_ago:e=>`${e} मिनट पहले`,hours_ago:e=>`${e} घंटे पहले`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"आपकी प्रतिक्रिया हमारे लिए मायने रखती है",submitted_label:"सफलतापूर्वक सबमिट किया गया!",cre_question:"क्या आपकी समस्या का समाधान हुआ?",cre_positive_label:"हाँ, धन्यवाद! 👍",cre_negative_label:"नहीं, इससे मदद नहीं मिली।",reason_placeholder:"अपनी प्रतिक्रिया साझा करें",question:"आप अपने अनुभव का मूल्यांकन कैसे करेंगे?",submit_label:"सबमिट करें",submission_expired:"क्षमा करें, सर्वेक्षण अवधि समाप्त हो गई है।"},form:{optional_label:"वैकल्पिक",validation_required:"यह प्रश्न आवश्यक है"},common:{placeholder_something_went_wrong:"कुछ गलत हो गया",placeholder_no_messages:"कोई संदेश नहीं",placeholder_no_conversations:"अभी तक कोई बातचीत नहीं",placeholder_something_went_wrong_retry_label:"पुनः प्रयास करें"},feedback:{title:"प्रतिक्रिया भेजें",good:"अच्छा",bad:"बुरा",comment_label:"टिप्पणी (वैकल्पिक)",comment_placeholder:"एक टिप्पणी छोड़ें",cancel:"रद्द करें",submit:"भेजें",save:"सहेजें",edit:"प्रतिक्रिया संपादित करें",remove:"प्रतिक्रिया हटाएं"}},qt={language:"hi",strings:ta,dateLocale:zs.hi},na={conversation:{input_placeholder:"Fai una domanda",input_placeholder_disabled:"La chat non è disponibile in questo canale",input_placeholder_wait_ai_agent_response:"In attesa della risposta dell'agente...",input_placeholder_active_form:"Compila il modulo per procedere.",input_placeholder_reconnecting:"Riconnessione. Aggiorna se persiste.",unknown_message_type:"(Tipo di messaggio sconosciuto)",powered_by:"Powered by",citation_title:"Fonte",start_new_conversation_label:"Inizia una conversazione",scroll_to_new_messages_label:()=>"Nuovo messaggio",failed_message_resend:"Riprova",failed_message_remove:"Rimuovi",file_upload_no_supported_files:"Nessun tipo di file supportato disponibile.",a11y_message_list:"Messaggi della chat",a11y_scroll_to_bottom:"Scorri in basso",a11y_scroll_to_new_messages:"Scorri ai nuovi messaggi",a11y_open_conversation_list:"Apri elenco conversazioni"},conversation_list:{header_title:"Conversazioni",ended:"Terminata",footer_title:"Inizia una conversazione",multiple_files_count:e=>`${e} file`},date_format:{just_now:"Proprio ora",minutes_ago:e=>`${e} minuti fa`,hours_ago:e=>`${e} ore fa`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Il tuo feedback è importante per noi",submitted_label:"Inviato con successo!",cre_question:"Il tuo problema è stato risolto?",cre_positive_label:"Sì, grazie! 👍",cre_negative_label:"No, non è servito.",reason_placeholder:"Condividi il tuo feedback",question:"Come valuteresti la tua esperienza?",submit_label:"Invia",submission_expired:"Ci dispiace, il periodo per partecipare al sondaggio è terminato."},form:{optional_label:"opzionale",validation_required:"Questa domanda è obbligatoria"},common:{placeholder_something_went_wrong:"Qualcosa è andato storto",placeholder_no_messages:"Nessun messaggio",placeholder_no_conversations:"Nessuna conversazione ancora",placeholder_something_went_wrong_retry_label:"Riprova"},feedback:{title:"Invia feedback",good:"Buono",bad:"Cattivo",comment_label:"Commento (opzionale)",comment_placeholder:"Lascia un commento",cancel:"Annulla",submit:"Invia",save:"Salva",edit:"Modifica feedback",remove:"Rimuovi feedback"}},jt={language:"it",strings:na,dateLocale:$s.it},sa={conversation:{input_placeholder:"Eine Frage stellen",input_placeholder_disabled:"Chat ist in diesem Kanal nicht verfügbar",input_placeholder_wait_ai_agent_response:"Warten auf die Antwort des Agenten...",input_placeholder_active_form:"Bitte fülle das Formular aus, um fortzufahren.",input_placeholder_reconnecting:"Neu verbinden. Aktualisieren falls anhaltend.",unknown_message_type:"(Unbekannter Nachrichtentyp)",powered_by:"Unterstützt von",citation_title:"Quelle",start_new_conversation_label:"Ein Gespräch starten",scroll_to_new_messages_label:()=>"Neue Nachricht",failed_message_resend:"Erneut versuchen",failed_message_remove:"Entfernen",file_upload_no_supported_files:"Keine unterstützten Dateitypen verfügbar.",a11y_message_list:"Chat-Nachrichten",a11y_scroll_to_bottom:"Nach unten scrollen",a11y_scroll_to_new_messages:"Zu neuen Nachrichten scrollen",a11y_open_conversation_list:"Konversationsliste öffnen"},conversation_list:{header_title:"Gespräche",ended:"Beendet",footer_title:"Ein Gespräch starten",multiple_files_count:e=>`${e} ${e===1?"Datei":"Dateien"}`},date_format:{just_now:"Gerade eben",minutes_ago:e=>`Vor ${e} Minuten`,hours_ago:e=>`Vor ${e} Stunden`,date_short:"dd.MM.yyyy",date_separator:"d. MMMM yyyy",message_timestamp:"p"},csat:{title:"Ihr Feedback ist uns wichtig",submitted_label:"Erfolgreich gesendet!",cre_question:"Wurde Ihr Problem gelöst?",cre_positive_label:"Ja, danke! 👍",cre_negative_label:"Nein, das hat nicht geholfen.",reason_placeholder:"Dein Feedback teilen",question:"Wie würden Sie Ihre Erfahrung bewerten?",submit_label:"Absenden",submission_expired:"Die Umfrage ist leider nicht mehr verfügbar."},form:{optional_label:"optional",validation_required:"Diese Frage ist erforderlich"},common:{placeholder_something_went_wrong:"Etwas ist schiefgelaufen",placeholder_no_messages:"Keine Nachrichten",placeholder_no_conversations:"Noch keine Unterhaltungen",placeholder_something_went_wrong_retry_label:"Erneut versuchen"},feedback:{title:"Feedback senden",good:"Gut",bad:"Schlecht",comment_label:"Kommentar (optional)",comment_placeholder:"Hinterlasse einen Kommentar",cancel:"Abbrechen",submit:"Senden",save:"Speichern",edit:"Feedback bearbeiten",remove:"Feedback entfernen"}},Gt={language:"de",strings:sa,dateLocale:Hs.de},ra={conversation:{input_placeholder:"Bir soru sor",input_placeholder_disabled:"Bu kanalda sohbet mevcut değil",input_placeholder_wait_ai_agent_response:"Temsilcinin yanıtını bekliyor...",input_placeholder_active_form:"İlerlemek için lütfen formu doldurun.",input_placeholder_reconnecting:"Yeniden bağlanıyor. Devam ederse yenile.",unknown_message_type:"(Bilinmeyen mesaj türü)",powered_by:"Tarafından desteklenmektedir",citation_title:"Kaynak",start_new_conversation_label:"Bir sohbet başlat",scroll_to_new_messages_label:()=>"Yeni mesaj",failed_message_resend:"Tekrar dene",failed_message_remove:"Kaldır",file_upload_no_supported_files:"Desteklenen dosya türü mevcut değil.",a11y_message_list:"Sohbet mesajları",a11y_scroll_to_bottom:"Aşağı kaydır",a11y_scroll_to_new_messages:"Yeni mesajlara kaydır",a11y_open_conversation_list:"Görüşme listesini aç"},conversation_list:{header_title:"Görüşmeler",ended:"Sona erdi",footer_title:"Bir sohbet başlat",multiple_files_count:e=>`${e} dosya`},date_format:{just_now:"Az önce",minutes_ago:e=>`${e} dakika önce`,hours_ago:e=>`${e} saat önce`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Görüşleriniz bizim için önemli",submitted_label:"Başarıyla gönderildi!",cre_question:"Sorununuz çözüldü mü?",cre_positive_label:"Evet, teşekkürler! 👍",cre_negative_label:"Hayır, bu yardımcı olmadı.",reason_placeholder:"Geri bildiriminizi paylaşın",question:"Deneyiminizi nasıl değerlendirirsiniz?",submit_label:"Gönder",submission_expired:"Üzgünüz, anket süresi sona erdi."},form:{optional_label:"İsteğe bağlı",validation_required:"Bu soru gereklidir"},common:{placeholder_something_went_wrong:"Bir şeyler ters gitti",placeholder_no_messages:"Mesaj yok",placeholder_no_conversations:"Henüz görüşme yok",placeholder_something_went_wrong_retry_label:"Tekrar dene"},feedback:{title:"Geri bildirim gönder",good:"İyi",bad:"Kötü",comment_label:"Yorum (isteğe bağlı)",comment_placeholder:"Bir yorum bırakın",cancel:"İptal",submit:"Gönder",save:"Kaydet",edit:"Geri bildirimi düzenle",remove:"Geri bildirimi kaldır"}},Wt={language:"tr",strings:ra,dateLocale:Gs.tr},re=e=>({conversation:e.conversation,conversation_list:e.conversation_list,date_format:e.date_format,csat:e.csat,form:e.form,common:e.common,feedback:e.feedback}),Dn=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??nt},nt="en",on={borderColor:"red",borderWidth:p.StyleSheet.hairlineWidth},C=({debug:e=!1,style:t,children:n,...s})=>a.createElement(p.View,{style:[t,s,e&&on],...s},n);C.Animated=({debug:e=!1,style:t,children:n,...s})=>a.createElement(p.Animated.View,{style:[t,s,e&&on],...s},n);const{Provider:oa,useContext:J}=j("MessengerSession"),aa=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof Je||t.userSessionInfo instanceof Jt))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return a.createElement(Co,{ref:n,...t},s=>a.createElement(ia,{...s},e))}),ia=({children:e,...t})=>{const{dispatcher:n}=K(),{userSession:s,aiAgentInfo:r,launcherInfo:o,deauthenticate:i}=t;return d.useEffect(()=>{const l=()=>{p.Alert.alert("Session timed out","Start a new conversation.",[{text:"OK",onPress:()=>i()}])};return n.subscribe(ee.AnonymousSessionTokenExpired,l),()=>n.unsubscribe(ee.AnonymousSessionTokenExpired,l)},[n,i]),a.createElement(oa,{value:{...t,userSession:s,aiAgentInfo:r,launcherInfo:o}},e)},qe=50,{Provider:la,useContext:ca}=j("ConversationScroll"),ua=({children:e})=>{var I;const{config:t}=K(),n=((I=t==null?void 0:t.conversation)==null?void 0:I.scrollMode)??"auto",s=d.useRef(null),r=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),o=d.useRef(0),[i,l]=d.useState(0),[c,u]=d.useState(0),[m,h]=d.useState(!1),[g,y]=d.useState(!1),b=d.useMemo(()=>g?"auto":n,[g,n]),E=d.useCallback(()=>{const{shouldUpdate:M,shouldRecalc:U,contentHeight:H,contentSnapshotHeight:ue,viewport:mt}=r.current;M&&ue<H&&l(Ce=>{r.current.shouldUpdate=!1;const gt=H-Ce-ue,de=Math.max(0,mt-gt);return Ce===0||de<Ce||U?(r.current.shouldRecalc=!1,de):Ce})},[]),_=d.useCallback(M=>{r.current.viewport=M.nativeEvent.layout.height},[]),v=d.useCallback((M,U)=>{r.current.contentHeight=U;const H=r.current.viewport;h(U>H),E()},[E]),A=d.useCallback(M=>{const U=M.nativeEvent.contentOffset.y;o.current=U,u(U)},[]),S=d.useMemo(()=>({minIndexForVisible:0,autoscrollToTopThreshold:qe}),[]),T=d.useCallback((M=!0)=>{var U;(U=s.current)==null||U.scrollToOffset({offset:0,animated:M})},[]),x=d.useCallback((M,U=!0)=>{var H;(H=s.current)==null||H.scrollToIndex({index:M,animated:U,viewPosition:1})},[]),R=d.useCallback(()=>{b==="fixed"&&(r.current.contentSnapshotHeight=r.current.contentHeight-i,r.current.shouldUpdate=!0,r.current.shouldRecalc=!0)},[b,i]),N=d.useCallback(()=>{b==="fixed"?x(0):T()},[b,T,x]),Y=d.useCallback(()=>{b==="fixed"?r.current.shouldUpdate=!0:o.current<=qe&&T()},[b,T]),Q=d.useCallback(M=>{y(M)},[]),G=c<=qe,w=m&&!G,L=d.useCallback(()=>o.current>qe,[]);return a.createElement(la,{value:{ref:s,state:{bottomSpace:i,isAwayFromBottom:w,shouldCountNewMessages:L},props:{maintainVisibleContentPosition:S,onLayout:_,onContentSizeChange:v,onScroll:A},actions:{scrollToBottom:T,scrollToIndex:x,onBeforeMessageSend:R,onAfterMessageSend:N,onStreamingUpdate:Y,onConversationClosed:Q}}},e)};function ls(e){return new Promise((t,n)=>{p.Image.getSize(e,(s,r)=>{t({width:String(s),height:String(r)})},s=>{n(s)})})}async function da(e){var t;if("file"in e&&e.file&&typeof e.file=="object"){const n=e.file;if(n.uri&&((t=n.type)!=null&&t.startsWith("image/")))try{const{width:s,height:r}=await ls(n.uri);return new Se.MessageMetaArray({key:Wn,value:[s,r]})}catch{return}}}function ma(e,t){let n=0,s=0;return ne(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),ne(t)&&t.sendingStatus!=="succeeded"&&(s=Number.MAX_SAFE_INTEGER),t.createdAt+s-(e.createdAt+n)}const{Provider:ga,Context:ha,useContext:oe}=j("Conversation"),cs=e=>a.createElement(ua,null,a.createElement(_a,{...e})),_a=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:s,shouldMarkAsRead:r,children:o})=>{const i=ca(),{activeChannel:l,refreshActiveChannel:c,sdkUser:u,authenticate:m}=J();d.useEffect(()=>{u||m()},[]);const h=d.useCallback(async E=>{i.actions.onBeforeMessageSend();const _=await da(E);return{...E,metaArrays:_?[_]:void 0}},[i.actions.onBeforeMessageSend]),g=d.useCallback(()=>{i.actions.onAfterMessageSend()},[i.actions.onAfterMessageSend]),y=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]),b=e??(l==null?void 0:l.url);return a.createElement(Mo,{key:b,channelUrl:b,onBeforeSendMessage:h,onAfterSendMessage:g,onMessagesUpdated:i.actions.onStreamingUpdate,onMessagesReceived:i.actions.onStreamingUpdate,onChannelDeleted:y,onConversationClosedStatusChanged:i.actions.onConversationClosed,sortComparator:ma,shouldMarkAsRead:r,shouldCountNewMessages:i.state.shouldCountNewMessages},E=>a.createElement(ga,{value:{...E,scrollSource:i,onClose:n,onNavigateToConversationList:s,updateActiveChannel:y}},o))},bt=re(Gt.strings),fa={...bt,conversation:{...bt.conversation,attachment_camera:"Kamera",attachment_photo:"Fotobibliothek",attachment_document:"Dateien",file_upload_notification_count_limit:e=>`Sie können nur ${e} Datei${e>1?"en":""} gleichzeitig hochladen.`,file_upload_notification_size_limit:e=>`Die maximale Dateigröße beträgt ${e} MB.`,file_upload_not_supported_file:"Bitte wählen Sie einen unterstützten Dateityp aus."},conversation_list:{...bt.conversation_list}},pa={language:Gt.language,dateLocale:Gt.dateLocale,strings:fa},Ct=re(Bt.strings),ya={...Ct,conversation:{...Ct.conversation,attachment_camera:"Camera",attachment_photo:"Photo library",attachment_document:"Files",file_upload_notification_count_limit:e=>`You can only upload ${e} file${e>1?"s":""} at a time.`,file_upload_notification_size_limit:e=>`Maximum file size is ${e} MB.`,file_upload_not_supported_file:"Please select a supported file type."},conversation_list:{...Ct.conversation_list}},ba={language:Bt.language,dateLocale:Bt.dateLocale,strings:ya},Et=re(zt.strings),Ca={...Et,conversation:{...Et.conversation,attachment_camera:"Cámara",attachment_photo:"Biblioteca de fotos",attachment_document:"Archivos",file_upload_notification_count_limit:e=>`Solo puede cargar ${e} archivo${e>1?"s":""} a la vez.`,file_upload_notification_size_limit:e=>`El tamaño máximo del archivo es ${e} MB.`,file_upload_not_supported_file:"Por favor, seleccione un tipo de archivo compatible."},conversation_list:{...Et.conversation_list}},Ea={language:zt.language,dateLocale:zt.dateLocale,strings:Ca},vt=re(Vt.strings),va={...vt,conversation:{...vt.conversation,attachment_camera:"Caméra",attachment_photo:"Photothèque",attachment_document:"Fichiers",file_upload_notification_count_limit:e=>`Vous ne pouvez télécharger que ${e} fichier${e>1?"s":""} à la fois.`,file_upload_notification_size_limit:e=>`La taille maximale du fichier est de ${e} MB.`,file_upload_not_supported_file:"Veuillez sélectionner un type de fichier pris en charge."},conversation_list:{...vt.conversation_list}},Sa={language:Vt.language,dateLocale:Vt.dateLocale,strings:va},St=re(qt.strings),Aa={...St,conversation:{...St.conversation,attachment_camera:"कैमरा",attachment_photo:"फोटो लाइब्रेरी",attachment_document:"फाइलें",file_upload_notification_count_limit:e=>`आप एक बार में केवल ${e} फ़ाइल${e>1?"ें":""} अपलोड कर सकते हैं।`,file_upload_notification_size_limit:e=>`अधिकतम फ़ाइल आकार ${e} MB है।`,file_upload_not_supported_file:"कृपया समर्थित फ़ाइल प्रकार चुनें।"},conversation_list:{...St.conversation_list}},Ia={language:qt.language,dateLocale:qt.dateLocale,strings:Aa},At=re(jt.strings),Ta={...At,conversation:{...At.conversation,attachment_camera:"Fotocamera",attachment_photo:"Libreria foto",attachment_document:"File",file_upload_notification_count_limit:e=>`Puoi caricare solo ${e} file alla volta.`,file_upload_notification_size_limit:e=>`La dimensione massima del file è ${e} MB.`,file_upload_not_supported_file:"Seleziona un tipo di file supportato."},conversation_list:{...At.conversation_list}},wa={language:jt.language,dateLocale:jt.dateLocale,strings:Ta},It=re(Ft.strings),xa={...It,conversation:{...It.conversation,attachment_camera:"カメラ",attachment_photo:"フォトライブラリ",attachment_document:"ファイル",file_upload_notification_count_limit:e=>`一度にアップロードできるのは${e}ファイルまでです。`,file_upload_notification_size_limit:e=>`ファイルの最大サイズは${e}MBです。`,file_upload_not_supported_file:"サポートされているファイル形式を選択してください。"},conversation_list:{...It.conversation_list}},ka={language:Ft.language,dateLocale:Ft.dateLocale,strings:xa},Tt=re(Ut.strings),Ra={...Tt,conversation:{...Tt.conversation,attachment_camera:"카메라",attachment_photo:"사진 라이브러리",attachment_document:"파일",file_upload_notification_count_limit:e=>`한 번에 ${e}개의 파일만 업로드할 수 있습니다.`,file_upload_notification_size_limit:e=>`파일당 최대 크기는 ${e} MB입니다.`,file_upload_not_supported_file:"지원되는 파일 형식을 선택해 주세요."},conversation_list:{...Tt.conversation_list}},Ma={language:Ut.language,dateLocale:Ut.dateLocale,strings:Ra},wt=re($t.strings),Da={...wt,conversation:{...wt.conversation,attachment_camera:"Câmera",attachment_photo:"Biblioteca de fotos",attachment_document:"Arquivos",file_upload_notification_count_limit:e=>`Você só pode carregar ${e} arquivo${e>1?"s":""} por vez.`,file_upload_notification_size_limit:e=>`O tamanho máximo do arquivo é ${e} MB.`,file_upload_not_supported_file:"Por favor, selecione um tipo de arquivo suportado."},conversation_list:{...wt.conversation_list}},La={language:$t.language,dateLocale:$t.dateLocale,strings:Da},xt=re(Wt.strings),Pa={...xt,conversation:{...xt.conversation,attachment_camera:"Kamera",attachment_photo:"Fotoğraf kitaplığı",attachment_document:"Dosyalar",file_upload_notification_count_limit:e=>`Bir seferde yalnızca ${e} dosya yükleyebilirsiniz.`,file_upload_notification_size_limit:e=>`Maksimum dosya boyutu ${e} MB'dir.`,file_upload_not_supported_file:"Lütfen desteklenen bir dosya türü seçin."},conversation_list:{...xt.conversation_list}},Oa={language:Wt.language,dateLocale:Wt.dateLocale,strings:Pa},Ln=new Map([["en",ba],["ko",Ma],["ja",ka],["es",Ea],["pt",La],["fr",Sa],["hi",Ia],["it",wa],["de",pa],["tr",Oa]]),Pn=e=>Ln.get(e)??Ln.get(nt),Na=(e,t)=>t?{conversation:{...e.conversation,...t.conversation},conversation_list:{...e.conversation_list,...t.conversation_list},date_format:{...e.date_format,...t.date_format},csat:{...e.csat,...t.csat},form:{...e.form,...t.form},common:{...e.common,...t.common},feedback:{...e.feedback,...t.feedback}}:e,{Provider:Ha,useContext:F}=j("Localization"),Ba=({language:e=nt,logger:t,strings:n,children:s})=>{const[r,o]=d.useState(()=>{const i=Dn(e);return Pn(i)});return d.useEffect(()=>{var l;const i=Dn(e);if(r.language!==i){const c=Pn(i);o(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:r.language,to:c.language})}},[e,t]),a.createElement(Ha,{value:{language:r.language,strings:Na(r.strings,n),dateLocale:r.dateLocale,format:(i,l,c)=>ve.format(i,l,{locale:r.dateLocale,...c})}},s)},{Provider:Ua,useContext:st}=j("Modal");function us({children:e}){const[t,n]=d.useState([]),[s,r]=d.useState(null),o=d.useRef(0);d.useEffect(()=>{if(!s&&t.length>0){const[u,...m]=t;u&&(r(u),n(m))}},[s,t]);const i=d.useCallback(u=>new Promise(m=>{const g={id:`modal-${++o.current}`,render:u,resolve:m};n(y=>[...y,g])}),[]),l=d.useCallback((u,m)=>{r(h=>(h==null?void 0:h.id)===u?(h.resolve(m),null):h)},[]),c={openModal:i,currentModal:s};return a.createElement(Ua,{value:c},e,s&&a.createElement(p.Modal,{visible:!0,supportedOrientations:["landscape","portrait"],transparent:!0,animationType:"fade",onRequestClose:()=>l(s.id,null),style:{height:0}},s.render(u=>l(s.id,u??null))))}const{Provider:Fa,useContext:z}=j("MessengerTheme"),za=({children:e,...t})=>a.createElement(fo,{...t,appearance:{theme:t.mode??"light"}},n=>{const s=$a(n.theme);return a.createElement(Fa,{value:{...n,themedColor:s}},e)});function $a(e){const t=n=>n[e.selectedTheme];return{textHighEmphasis:t({light:e.palette.onlight.textHighEmphasis,dark:e.palette.ondark.textHighEmphasis}),textMidEmphasis:t({light:e.palette.onlight.textMidEmphasis,dark:e.palette.ondark.textMidEmphasis}),textLowEmphasis:t({light:e.palette.onlight.textLowEmphasis,dark:e.palette.ondark.textLowEmphasis}),textDisabled:t({light:e.palette.onlight.textDisabled,dark:e.palette.ondark.textDisabled}),textHighEmphasisInverse:t({light:e.palette.ondark.textHighEmphasis,dark:e.palette.onlight.textHighEmphasis}),textMidEmphasisInverse:t({light:e.palette.ondark.textMidEmphasis,dark:e.palette.onlight.textMidEmphasis}),textLowEmphasisInverse:t({light:e.palette.ondark.textLowEmphasis,dark:e.palette.onlight.textLowEmphasis}),textDisabledInverse:t({light:e.palette.ondark.textDisabled,dark:e.palette.onlight.textDisabled}),bg_50_600:t({light:e.palette.background50,dark:e.palette.background600}),bg_100_500:t({light:e.palette.background100,dark:e.palette.background500}),bg_200_400:t({light:e.palette.background200,dark:e.palette.background400}),primary:t({light:e.palette.primary.main,dark:e.palette.primary.light}),secondary:t({light:e.palette.secondary.main,dark:e.palette.secondary.light}),error:t({light:e.palette.error.main,dark:e.palette.error.light}),information:t({light:e.palette.information.light,dark:e.palette.information.light}),overlay:t({light:e.palette.overlay.light,dark:e.palette.overlay.dark})}}const P={create:e=>{const t=new WeakMap,n=s=>{const r=t.get(s.theme);if(r)return r;const o=e(s),i={},l={};for(const m in o)typeof o[m]=="function"?l[m]=o[m]:i[m]=o[m];const u={...p.StyleSheet.create(i),...l};return t.set(s.theme,u),u};return{use:()=>{const s=z(),r=pe.useSafeAreaInsets();return n({...s,edgeInsets:r,select:o=>o[s.theme.selectedTheme]})}}}},Va={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},Te=(e,t=p.I18nManager.isRTL?"rtl":"ltr")=>{const n=pe.useSafeAreaInsets();return e.reduce((s,r)=>{const o=Va[t][r];return s[o]=n[r],s},{})},qa={send:require("./icons/icon-send.png"),close:require("./icons/icon-close.png"),menu:require("./icons/icon-menu.png"),chat:require("./icons/icon-chat.png"),message:require("./icons/icon-message.png"),spinner:require("./icons/icon-spinner.png"),error:require("./icons/icon-error.png"),refresh:require("./icons/icon-refresh.png"),"chevron-down":require("./icons/icon-chevron-down.png"),done:require("./icons/icon-done.png"),"done-all":require("./icons/icon-done-all.png"),user:require("./icons/icon-user.png"),"file-document":require("./icons/icon-file-document.png"),remove:require("./icons/icon-remove.png"),add:require("./icons/icon-add.png"),agent:require("./icons/icon-agent.png"),camera:require("./icons/icon-camera.png"),photo:require("./icons/icon-photo.png"),document:require("./icons/icon-document.png"),"bot-filled":require("./icons/icon-bot-filled.png"),copy:require("./icons/icon-copy.png"),source:require("./icons/icon-source.png"),"radio-on":require("./icons/icon-radio-on.png"),"radio-off":require("./icons/icon-radio-off.png"),good:require("./icons/icon-good.png"),bad:require("./icons/icon-bad.png"),"good-filled":require("./icons/icon-good-filled.png"),"bad-filled":require("./icons/icon-bad-filled.png"),delight:require("./icons/icon-delight.png"),"thumbnail-none":require("./icons/icon-thumbnail-none.png")},ja={send:!0,chat:!0,message:!0,good:!0,bad:!0,"good-filled":!0,"bad-filled":!0},B=({customSource:e,type:t,color:n,size:s=24,style:r})=>{const o=Ga.use(),i=p.I18nManager.isRTL&&!!ja[t];return a.createElement(C,{alignItems:"center",justifyContent:"center"},a.createElement(p.Image,{resizeMode:"contain",source:e??qa[t],style:[o.icon({color:n,size:s,mirror:i}),r]}))},Ga=P.create(({theme:e,themedColor:t})=>({icon:n=>({tintColor:typeof n.color=="function"?n.color({theme:e,themedColor:t}):n.color??e.colors.base.primary,width:n.size,height:n.size,transform:n.mirror?[{scaleX:-1}]:void 0})})),an=(e,t)=>{if(!t||t.length===0)return!1;const n=t.trimStart();if(n.length===0)return!1;const s=e==="start"?Array.from(n)[0]:Array.from(n).pop(),r=s==null?void 0:s.codePointAt(0);return r===void 0?!1:Ya(r)},ds=e=>an("start",e),Wa=e=>an("end",e),Ka=e=>{const{text:t,style:n,isTextInput:s}=e;return n!=null&&n.textAlign&&n.textAlign!=="left"&&n.textAlign!=="right"?n.textAlign:p.I18nManager.isRTL&&typeof t=="string"&&ds(t)?s?"right":p.I18nManager.doLeftAndRightSwapInRTL?"left":"right":n==null?void 0:n.textAlign},Ya=e=>{for(const[t,n]of Xa)if(e>=t&&e<=n)return!0;return!1},Xa=[[1424,1535],[1536,1791],[1872,1919],[2208,2303],[64285,64335],[65136,65279],[126464,126719]],ln={isStartsWithRTL:ds,isEndsWithRTL:Wa,isRTLString:an,useTextAlign:Ka},k=({variant:e="body1",color:t,style:n,...s})=>{const{theme:r,themedColor:o}=z(),i=d.useMemo(()=>{if(typeof t=="function")return t({theme:r,themedColor:o});if(typeof t=="string")return t;const u=p.StyleSheet.flatten(n);return u&&u.color?u.color:t??o.textHighEmphasis},[n,t,o.textHighEmphasis]),l=d.useMemo(()=>{const u=r.typography[e]??r.typography.body1;return p.StyleSheet.flatten([{includeFontPadding:!1,...u,color:i},n])},[e,i,r.typography,o.textHighEmphasis]),c=ln.useTextAlign({text:s.children,style:l});return a.createElement(p.Text,{style:[l,{textAlign:c}],...s})},ms=350,Za=({children:e,...t})=>a.createElement(p.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:ms,...t},n=>typeof e=="function"?e(n):e),Ja=({children:e,style:t,...n})=>{const[s,r]=d.useState(!1),o={pressed:s};return a.createElement(p.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:ms,style:typeof t=="function"?t(o):t,onPressIn:()=>r(!0),onPressOut:()=>r(!1),...n},typeof e=="function"?e(o):e)},O=e=>e.activeOpacity&&e.activeOpacity<1?a.createElement(Ja,{...e}):a.createElement(Za,{...e}),{Provider:Qa,useContext:gs}=j("BottomSheetAnimation");function ei({onClose:e,children:t}){const n=d.useRef(new p.Animated.Value(500)).current;d.useEffect(()=>{p.Animated.timing(n,{toValue:0,duration:300,useNativeDriver:!0}).start()},[n]);const s=d.useCallback(o=>async()=>{p.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(async()=>{try{await(o==null?void 0:o())}catch{e==null||e()}})},[n]),r=d.useRef(p.PanResponder.create({onMoveShouldSetPanResponder:(o,i)=>i.dy>5,onPanResponderMove:(o,i)=>{i.dy>0&&n.setValue(i.dy)},onPanResponderRelease:(o,i)=>{i.dy>100||i.vy>.5?p.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(()=>{e==null||e()}):p.Animated.timing(n,{toValue:0,duration:200,useNativeDriver:!0}).start()}})).current;return a.createElement(Qa,{value:{wrapWithAnimation:s,translateY:n,panHandlers:r.panHandlers}},t)}const ti=({icon:e,label:t="",destructive:n=!1,onPress:s})=>{const r=hs.use(),{themedColor:o}=z();return a.createElement(O,{onPress:s,style:r.actionItem,activeOpacity:.75},e&&a.createElement(B,{type:e,size:24,color:o.primary}),a.createElement(k,{variant:"body3",color:n?o.error:o.textHighEmphasis,numberOfLines:1},t))},ni=({onClose:e,children:t})=>{const n=hs.use(),{translateY:s,panHandlers:r,wrapWithAnimation:o}=gs(),i=Te(["left","right"]);return a.createElement(O,{onPress:o(e),style:n.overlay},a.createElement(C.Animated,{style:[n.container,i,{transform:[{translateY:s}]}],...r},t))},rt=te({template:ni,components:{ActionItem:ti}}),Z=e=>{const{Template:t}=rt.useContext();return a.createElement(ei,{onClose:e.onClose},a.createElement(t,{...e}))};Z.ActionItem=e=>{const{components:t}=rt.useContext(),{wrapWithAnimation:n}=gs();return a.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const hs=P.create(({theme:e,edgeInsets:t})=>({overlay:{flex:1,backgroundColor:e.palette.overlay.dark,justifyContent:"flex-end"},container:{backgroundColor:e.colors.base.modalContentBackground,borderTopStartRadius:8,borderTopEndRadius:8,paddingBottom:t.bottom,maxHeight:"80%"},actionItem:{height:48,flexDirection:"row",alignItems:"center",justifyContent:"flex-start",gap:24,paddingHorizontal:16}})),si=({style:e,label:t,accessibilityLabel:n,onPress:s})=>{const r=ri.use(),{theme:o}=z();return a.createElement(O,{style:[r.button,e],onPress:s,accessibilityLabel:n,accessibilityRole:"button"},a.createElement(C,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(k,{variant:"button",color:o.colors.base.primaryContrastContent},t),a.createElement(B,{size:16,type:"chevron-down",color:o.colors.base.primaryContrastContent})))},ri=P.create(({theme:e})=>({button:{flexDirection:"row",alignItems:"center",paddingVertical:10,paddingStart:16,paddingEnd:12,borderRadius:24,backgroundColor:e.colors.base.primary,boxShadow:[{color:"rgba(13, 13, 13, 0.12)",offsetX:0,offsetY:8,blurRadius:10,spreadDistance:1},{color:"rgba(13, 13, 13, 0.08)",offsetX:0,offsetY:3,blurRadius:14,spreadDistance:2},{color:"rgba(13, 13, 13, 0.04)",offsetX:0,offsetY:3,blurRadius:5,spreadDistance:-3}]}})),cn=({iconSize:e=64,icon:t,style:n,label:s,children:r})=>{const{themedColor:o}=z();return a.createElement(C,{style:[_s.body,n]},t&&a.createElement(B,{type:t,size:e,color:o.textLowEmphasis}),s&&a.createElement(k,{variant:"body1",color:o.textMidEmphasis},s),r)},oi=({children:e})=>{const{theme:t}=z();return a.createElement(C,{backgroundColor:t.colors.base.background,style:_s.container},e)},_s=p.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),ai=({label:e,icon:t="error",action:n,...s})=>{const{strings:r}=F();return a.createElement(cn,{icon:t,label:e??r.common.placeholder_something_went_wrong,...s},n&&a.createElement(ii,{onPress:n.onPress,label:n.label??r.common.placeholder_something_went_wrong_retry_label}))},ii=({label:e,onPress:t})=>{const{themedColor:n}=z();return a.createElement(O,{onPress:t},a.createElement(C,{style:li.button},a.createElement(B,{type:"refresh",size:20}),a.createElement(k,{variant:"button",color:n.primary},e)))},li=p.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),ci=({iconSize:e=48,style:t})=>{const n=d.useRef(new p.Animated.Value(0)).current;d.useEffect(()=>{const r=p.Animated.loop(p.Animated.timing(n,{toValue:1,duration:1e3,easing:p.Easing.linear,useNativeDriver:!0}));return r.start(),()=>{r.stop()}},[n]);const s=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(C.Animated,{style:[{transform:[{rotate:s}]},t]},a.createElement(B,{type:"spinner",size:e}))},ui=({label:e,icon:t="chat",...n})=>{const{strings:s}=F();return a.createElement(cn,{icon:t,label:e??s.common.placeholder_no_conversations,...n})},di=({label:e,icon:t="message",...n})=>{const{strings:s}=F();return a.createElement(cn,{icon:t,label:e??s.common.placeholder_no_messages,...n})},mi=e=>{const{components:t}=ot.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(oi,null,n)},ot=te({template:mi,components:{Loading:ci,Error:ai,NoChannels:ui,NoMessages:di}}),Ae=e=>{const{Template:t}=ot.useContext();return a.createElement(t,{...e})},gi=({loading:e,error:t,empty:n,stackDirection:s,data:r=[],LoadingComponent:o,ErrorComponent:i,EmptyComponent:l,...c},u)=>{if(t)return i;if(e)return o;const{contentContainerStyle:m,...h}=c,g=s==="top"&&!n;return a.createElement(p.FlatList,{ref:u,data:r,ListEmptyComponent:n?l:null,contentContainerStyle:[m,g&&On.stackTop,n&&On.emptyContainer],...h})},On=p.StyleSheet.create({stackTop:{flexGrow:1,justifyContent:"flex-end"},emptyContainer:{flex:1}}),fs=d.memo(d.forwardRef(gi)),un=({name:e,type:t="FILE",onPress:n})=>{const s=hi.use();return a.createElement(O,{onPress:n,style:s.container,activeOpacity:.75},a.createElement(C,{style:s.iconWrapper},a.createElement(B,{type:"file-document",size:24,color:s.icon.tintColor})),a.createElement(C,{flex:1,flexDirection:"column",gap:4,style:s.info},a.createElement(k,{variant:"button",color:({themedColor:r})=>r.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),a.createElement(k,{variant:"caption3",color:({themedColor:r})=>r.textMidEmphasis},t)))},hi=P.create(({theme:e,themedColor:t})=>({container:{width:220,borderRadius:12,gap:8,height:64,flexDirection:"row",alignItems:"center",padding:12,borderWidth:1,borderColor:t.textDisabled,backgroundColor:t.bg_50_600},iconWrapper:{borderRadius:8,width:40,height:40,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary},icon:{tintColor:e.colors.base.primaryContrastContent},info:{alignItems:"flex-start",minWidth:0}})),_i=({file:e,children:t,onClickFile:n=({url:s})=>p.Linking.openURL(s)})=>a.createElement(C,{gap:D.GAP_GROUPED,width:D.BODY_MAX_WIDTH,maxWidth:D.BODY_MAX_WIDTH},a.createElement(un,{name:e.name,type:Xt(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),Ie=({style:e,...t})=>a.createElement(p.Image,{style:[e,t],...t}),fi=({file:e,onClickMedia:t=({url:s})=>p.Linking.openURL(s),children:n})=>{const s=pi.use();return a.createElement(C,{gap:D.GAP_GROUPED},a.createElement(O,{style:s.mediaContainer,onPress:()=>t==null?void 0:t(e)},a.createElement(Ie,{source:{uri:e.url},style:s.media,resizeMode:"cover"})),n)},pi=P.create(({select:e,theme:t})=>({mediaContainer:{width:D.BODY_MAX_WIDTH,height:160,borderRadius:12,overflow:"hidden",backgroundColor:e({light:t.palette.background100,dark:t.palette.background400})},media:{width:"100%",height:"100%"}})),ps=({code:e,language:t})=>{const[n,s]=d.useState(!1),r=async()=>{Js.default.setString(e),s(!0),setTimeout(()=>s(!1),2e3)};return a.createElement(C,{style:je.container,flexDirection:"row"},a.createElement(p.Pressable,{style:je.copyButton,onPress:r},a.createElement(B,{type:n?"done":"copy",size:16,color:"#fff"})),a.createElement(C,null,a.createElement(Qs.default,{hljsStyle:yi,scrollViewProps:{contentContainerStyle:je.codeContainer,bounces:!1},textStyle:je.codeText,language:t},e)))},je=p.StyleSheet.create({container:{marginVertical:4},copyButton:{opacity:.6,position:"absolute",top:8,right:8,zIndex:1,backgroundColor:"#000",borderRadius:4,width:28,height:28,justifyContent:"center",alignItems:"center"},copyButtonText:{fontSize:12},codeContainer:{minWidth:"100%",padding:12},codeText:{fontSize:13,lineHeight:19}}),yi={hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:"#abb2bf",background:"#282c34"},"hljs-keyword":{color:"#F92672"},"hljs-operator":{color:"#F92672"},"hljs-pattern-match":{color:"#F92672"},"hljs-pattern-match .hljs-constructor":{color:"#61aeee"},"hljs-function":{color:"#61aeee"},"hljs-function .hljs-params":{color:"#A6E22E"},"hljs-function .hljs-params .hljs-typing":{color:"#FD971F"},"hljs-module-access .hljs-module":{color:"#7e57c2"},"hljs-constructor":{color:"#e2b93d"},"hljs-constructor .hljs-string":{color:"#9CCC65"},"hljs-comment":{color:"#b18eb1",fontStyle:"italic"},"hljs-quote":{color:"#b18eb1",fontStyle:"italic"},"hljs-doctag":{color:"#c678dd"},"hljs-formula":{color:"#c678dd"},"hljs-section":{color:"#e06c75"},"hljs-name":{color:"#e06c75"},"hljs-selector-tag":{color:"#e06c75"},"hljs-deletion":{color:"#e06c75"},"hljs-subst":{color:"#e06c75"},"hljs-literal":{color:"#56b6c2"},"hljs-string":{color:"#98c379"},"hljs-regexp":{color:"#98c379"},"hljs-addition":{color:"#98c379"},"hljs-attribute":{color:"#98c379"},"hljs-meta-string":{color:"#98c379"},"hljs-built_in":{color:"#e6c07b"},"hljs-class .hljs-title":{color:"#e6c07b"},"hljs-attr":{color:"#d19a66"},"hljs-variable":{color:"#d19a66"},"hljs-template-variable":{color:"#d19a66"},"hljs-type":{color:"#d19a66"},"hljs-selector-class":{color:"#d19a66"},"hljs-selector-attr":{color:"#d19a66"},"hljs-selector-pseudo":{color:"#d19a66"},"hljs-number":{color:"#d19a66"},"hljs-symbol":{color:"#61aeee"},"hljs-bullet":{color:"#61aeee"},"hljs-link":{color:"#61aeee",textDecoration:"underline"},"hljs-meta":{color:"#61aeee"},"hljs-selector-id":{color:"#61aeee"},"hljs-title":{color:"#61aeee"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},ys=d.memo(({src:e,onPress:t})=>{const[n,s]=d.useState("1/1"),[r,o]=d.useState(!1),i=bi.use();return d.useLayoutEffect(()=>{e&&ls(e).then(({width:l,height:c})=>s(`${l}/${c}`))},[e]),a.createElement(p.Pressable,{style:{marginTop:8},onPress:t},a.createElement(C,{style:[i.container,{aspectRatio:n}]},r?a.createElement(B,{size:28,type:"thumbnail-none",color:({themedColor:l})=>l.textHighEmphasisInverse}):a.createElement(p.Image,{source:{uri:e},style:p.StyleSheet.absoluteFillObject,onError:()=>o(!0)})))}),bi=P.create(({themedColor:e})=>({container:{width:"100%",backgroundColor:e.textDisabled,borderRadius:4,overflow:"hidden",justifyContent:"center",alignItems:"center"}}));ys.displayName="MarkdownImage";const Re=e=>d.isValidElement(e)&&"children"in e.props,Kt=(e=.75)=>`rgba(0, 0, 0, ${e})`,Ci=({children:e})=>{var i;const t=p.useWindowDimensions(),n=Kt(.3),s=d.useMemo(()=>{try{if(!Array.isArray(e)||e.length<2)return null;const l=e[0],c=e[1],u=Re(c)?c.props.children:void 0;if(!u||!Array.isArray(u)||u.length===0)return null;const m=u,h=m[0],g=Re(h)?h.props.children:void 0;if(!g||!Array.isArray(g)||g.length===0)return null;const y=m.length,b=g.length,E=Array(b).fill(null).map(()=>[]);for(let S=0;S<y;S++){const T=m[S],x=Re(T)?T.props.children:void 0;if(!(!x||!Array.isArray(x)))for(let R=0;R<b;R++){const N=E[R];N&&R<x.length&&(N[S]=x[R])}}const _=Re(l)?l.props.children:void 0,v=Array.isArray(_)?_[0]:void 0,A=Re(v)?v.props.children:void 0;if(A&&Array.isArray(A))for(let S=0;S<b;S++){const T=E[S];T&&S<A.length&&T.unshift(A[S])}return E}catch{return null}},[e]),[r,o]=d.useState(Array(((i=s==null?void 0:s[0])==null?void 0:i.length)??0).fill(0));return s?a.createElement(p.View,{style:{flexDirection:"row"}},s.map((l,c)=>{const u=c===0,m=c===s.length-1;return a.createElement(p.View,{key:c,style:{flexDirection:"column",borderStartWidth:1,borderEndWidth:m?1:0,borderTopWidth:1,borderBottomWidth:1,borderColor:n,borderTopStartRadius:u?6:0,borderBottomStartRadius:u?6:0,borderTopEndRadius:m?6:0,borderBottomEndRadius:m?6:0}},l.map((h,g)=>{const y=g===0,b=g===l.length-1;return a.createElement(p.View,{key:g,onLayout:({nativeEvent:{layout:E}})=>{const _=E.height;(r[g]??0)<_&&(r[g]=_,o([...r]))},style:{borderBottomWidth:b?0:1,borderColor:n,backgroundColor:y?Kt(.15):"transparent",maxWidth:t.width*2/3,minHeight:(r[g]??0)>0?r[g]:void 0,padding:8}},h)}))})):a.createElement(p.View,null,e)},dn=d.memo(({children:e,textStyle:t,linkStyle:n,onPressImage:s})=>{const{themedColor:r}=z(),o=p.StyleSheet.compose({fontSize:14,color:r.textHighEmphasis,textAlign:"left"},t),i=p.StyleSheet.flatten(o),l=i.fontSize||14,c=i.lineHeight||l*1.286,u=Kt(.3),m={color:i.color,textAlign:ln.useTextAlign({text:e,style:i}),fontSize:l,lineHeight:c,fontWeight:i.fontWeight,fontFamily:i.fontFamily,fontStyle:i.fontStyle,letterSpacing:i.letterSpacing,textDecorationLine:i.textDecorationLine,textDecorationStyle:i.textDecorationStyle,textDecorationColor:i.textDecorationColor},h=d.useMemo(()=>({image:g=>{var b,E;const y=((b=g.attributes)==null?void 0:b.src)||((E=g.attributes)==null?void 0:E.href);return y?a.createElement(ys,{key:g.key,src:y,onPress:()=>s==null?void 0:s(y)}):null},code_block:g=>a.createElement(ps,{code:g.content,language:"text"}),table:(g,y)=>a.createElement(p.View,{key:g.key,style:{marginTop:8}},a.createElement(p.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},a.createElement(Ci,null,y)))}),[s]);return a.createElement(C,{flexDirection:"row",marginTop:-8},a.createElement(er.default,{style:{body:{...m,width:e.length>50?"100%":void 0,marginBottom:0},paragraph:{...m,marginTop:8,marginBottom:0},heading1:{...m,marginTop:8,marginBottom:0,fontSize:l*1.429,lineHeight:l*1.429*1.4,fontWeight:"700"},heading2:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.286,lineHeight:l*1.286*1.333},heading3:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading4:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading5:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading6:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},link:p.StyleSheet.flatten(p.StyleSheet.compose({...m,fontWeight:"700",textDecorationLine:"underline"},n)),code_inline:{...m,fontSize:l*.929,lineHeight:l*.929*1.538,fontWeight:"600",backgroundColor:u},code_block:{...m,borderWidth:0,backgroundColor:u,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538},fence:{...m,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538,backgroundColor:r.textDisabled},bullet_list:{marginTop:4,marginBottom:0},bullet_list_icon:{marginLeft:0,marginRight:4,fontWeight:"900"},ordered_list:{marginTop:4,marginBottom:0},ordered_list_icon:{marginLeft:0,marginRight:4},list_item:{...m,marginTop:4,marginBottom:0},blockquote:{...m,paddingStart:8,marginTop:8,marginBottom:0,paddingVertical:4,borderStartWidth:4,borderStartColor:u,backgroundColor:"transparent",fontWeight:"500",fontSize:l,lineHeight:c},hr:{backgroundColor:u,height:1,marginTop:8,marginBottom:0},th:{...m,padding:4,fontSize:l,lineHeight:l*1.143,fontWeight:"700"},td:{...m,padding:2,fontSize:l,lineHeight:l*1.429},image:{maxHeight:300,maxWidth:"100%"}},rules:h},lr(e)))});dn.displayName="MarkdownText";const Nn=({maxBodyWidth:e,customStyle:t,message:n,children:s})=>{const r=Ei.use(),o=e??D.BODY_MAX_WIDTH,i=d.useMemo(()=>rr(n),[n]),l=d.useCallback(c=>p.Linking.openURL(c),[]);return i.length===0&&!s?null:a.createElement(C,{alignSelf:"flex-start",maxWidth:o,borderRadius:12,paddingVertical:12,style:[r.container,(t==null?void 0:t.bubbleBackgroundColor)&&{backgroundColor:t==null?void 0:t.bubbleBackgroundColor}]},i.map((c,u)=>c.type==="text"?a.createElement(C,{key:u,paddingHorizontal:12},a.createElement(dn,{onPressImage:l,textStyle:r.text},c.value)):c.type==="code"?a.createElement(ps,{key:u,code:c.value,language:c.language}):null),s)},Ei=P.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),vi=e=>{const{strings:t}=F(),n=()=>{const s=Yn(e)?a.createElement(Nn,{...e}):null;return e.messageType==="user"?s:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(fi,{...e},s):a.createElement(_i,{...e},s):a.createElement(Nn,{...e,message:t.conversation.unknown_message_type})};return a.createElement(C,{style:e.containerStyle},n())};function bs({id:e,src:t,size:n=56,onClick:s,style:r}){const o=Si.use(),i=a.createElement(p.View,{style:[o.container(n),r],testID:e},t?a.createElement(p.Image,{source:{uri:t},style:o.image}):a.createElement(B,{type:"user",size:n}));return s?a.createElement(O,{onPress:s,activeOpacity:.75},i):i}const Si=P.create(({themedColor:e})=>({container:t=>({borderRadius:t/2,overflow:"hidden",position:"relative",height:t,width:t,backgroundColor:e.bg_100_500,alignItems:"center",justifyContent:"center"}),image:{width:"100%",height:"100%",position:"absolute"}})),Ai=({sender:e,isBotMessage:t})=>{const n=Ii.use();return t&&!e.profileUrl?a.createElement(C,{style:n.botContainer},a.createElement(B,{type:"delight",color:({theme:s})=>s.colors.base.primaryContrastContent,size:D.AVATAR_SIZE-8})):a.createElement(bs,{src:e.profileUrl,size:D.AVATAR_SIZE})},Ii=P.create(({theme:e})=>({botContainer:{width:D.AVATAR_SIZE,height:D.AVATAR_SIZE,borderRadius:D.AVATAR_SIZE/2,padding:4,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary}})),Ti=({sender:e})=>a.createElement(C,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7,alignItems:"flex-start"},a.createElement(k,{variant:"caption1",color:({themedColor:t})=>t.textMidEmphasis,numberOfLines:1},e.nickname)),wi=({createdAt:e,containerStyle:t})=>{const{strings:n,format:s}=F();return e?a.createElement(C,{alignItems:"flex-start",style:t},a.createElement(k,{variant:"caption4",color:({themedColor:r})=>r.textLowEmphasis},s(e,n.date_format.message_timestamp))):null},xi=()=>{var e;return p.Platform.OS==="web"?{major:0,minor:0,patch:0}:((e=p.Platform.constants)==null?void 0:e.reactNativeVersion)??{major:0,minor:0,patch:0}},ki=.33,Hn=e=>{var t;(t=e.current)==null||t.stop(),e.current=null},Ri=e=>{const[t,n]=d.useState(0),s=d.useRef(new p.Animated.Value(0)).current,r=d.useRef(new p.Animated.Value(0)).current,o=d.useRef(null),i=d.useCallback(u=>{const{width:m}=u.nativeEvent.layout;n(h=>h===m?h:m)},[]),l=t*ki,c=d.useMemo(()=>r.interpolate({inputRange:[0,1],outputRange:p.I18nManager.isRTL?[t+l,-l]:[-l,t+l]}),[l,t,r]);return d.useEffect(()=>{if(!e){Hn(o),s.setValue(0),r.setValue(0);return}s.setValue(0),r.setValue(0),p.Animated.timing(s,{toValue:1,duration:400,easing:p.Easing.inOut(p.Easing.ease),useNativeDriver:!0}).start();const u=p.Animated.loop(p.Animated.timing(r,{toValue:1,duration:1600,easing:p.Easing.linear,useNativeDriver:!0}));return o.current=u,u.start(),()=>{Hn(o)}},[e,r,s]),{bandWidth:l,onLayout:i,shimmerTranslateX:c,textFadeAnim:s}},{major:Mi,minor:Di}=xi(),Li=Mi>0||Di>=76,Pi=e=>{if(Li){const t=_t(e,.5),n=_t(e,0),s=`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`;return{experimental_backgroundImage:s,backgroundImage:s}}return{backgroundColor:_t(e,.3)}},Oi=e=>{var t,n;(t=e.current)==null||t.stop(),(n=e.current)==null||n.reset(),e.current=null},Ni=({thinkingMessage:e,customStyle:t,containerStyle:n})=>{const{theme:s,themedColor:r}=z(),o=d.useRef(new p.Animated.Value(0)).current,i=d.useRef(null),l=d.useMemo(()=>Hi.map(([g,y,b])=>[o.interpolate({inputRange:g,outputRange:y,extrapolate:"clamp"}),o.interpolate({inputRange:g,outputRange:b,extrapolate:"clamp"})]),[o]),{bandWidth:c,onLayout:u,shimmerTranslateX:m,textFadeAnim:h}=Ri(!!e);return d.useEffect(()=>{if(e)return;const g=p.Animated.loop(p.Animated.timing(o,{toValue:1.4,duration:1400,easing:p.Easing.linear,useNativeDriver:!0}));return i.current=g,g.start(),()=>{Oi(i),o.setValue(0)}},[o,e]),e?a.createElement(C,{style:n},a.createElement(C.Animated,{style:{opacity:h}},a.createElement(C,{style:kt.thinkingMessageContainer,onLayout:u},a.createElement(k,{variant:"body3",color:r.textHighEmphasis},e),a.createElement(C.Animated,{style:[kt.shimmerOverlay,{width:c||p.StyleSheet.hairlineWidth,...Pi(s.colors.base.background),transform:[{translateX:m}]}],pointerEvents:"none"})))):a.createElement(C,{style:n},a.createElement(C,{width:60,flexDirection:"row",alignItems:"center",justifyContent:"center",borderRadius:16,paddingHorizontal:12,height:26,backgroundColor:(t==null?void 0:t.bubbleBackgroundColor)??s.colors.messageIncoming.background},l.map(([g,y],b)=>a.createElement(C.Animated,{key:b,style:[kt.dot,{marginEnd:b===l.length-1?0:6,opacity:y,transform:[{scale:g}],backgroundColor:(t==null?void 0:t.bubbleContentColor)??s.colors.messageIncoming.text}]}))))},Hi=[[[.4,.7,1],[1,1.2,1],[.12,.38,.12]],[[.6,.9,1.2],[1,1.2,1],[.12,.38,.12]],[[.8,1.1,1.4],[1,1.2,1],[.12,.38,.12]]],kt=p.StyleSheet.create({dot:{width:8,height:8,borderRadius:4},thinkingMessageContainer:{position:"relative",overflow:"hidden",alignSelf:"flex-start"},shimmerOverlay:{position:"absolute",top:0,left:0,height:"100%"}}),Bi=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>p.Linking.openURL(n)})=>{const n=Ui.use(),s=e==null?void 0:e.cta_button;return s?a.createElement(O,{onPress:()=>t(s),activeOpacity:.75,style:n.button},a.createElement(k,{variant:"button",color:({themedColor:r})=>r.textHighEmphasis,numberOfLines:1},s.label)):null},Ui=P.create(({select:e,themedColor:t})=>({button:{alignItems:"center",justifyContent:"center",borderRadius:6,paddingVertical:8,paddingHorizontal:8,backgroundColor:e({light:t.bg_50_600,dark:t.textDisabled})}})),Fi=({extendedMessagePayload:e,onClickCitation:t=n=>p.Linking.openURL(n.link)})=>{const{strings:n}=F(),{theme:s}=z(),r=e==null?void 0:e.citations;return!r||r.length===0?null:a.createElement(C,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},a.createElement(k,{variant:"caption1",color:s.colors.messageIncoming.text,style:Bn.sourceLabel},n.conversation.citation_title),a.createElement(C,{gap:8},r.map(o=>a.createElement(O,{key:o.embedding_id,onPress:()=>t(o),activeOpacity:.5},a.createElement(C,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(B,{type:"source",size:16,color:s.colors.messageIncoming.text}),a.createElement(C,{flex:1},a.createElement(k,{variant:"body3",color:s.colors.messageIncoming.text,numberOfLines:1,style:Bn.citationText},o.title)))))))},Bn=p.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),zi=e=>a.createElement(a.Fragment,null),Yt=e=>`${e}-filled`,$i=e=>e==="good"?W.AIAgentMessageFeedbackRating.GOOD:W.AIAgentMessageFeedbackRating.BAD,Un=({onClose:e,isEdit:t,initialRating:n,initialComment:s="",isCommentEnabled:r=!1})=>{const{strings:o}=F(),{themedColor:i,theme:l}=z(),c=Vi.use(),[u,m]=d.useState(s),[h,g]=d.useState(n),y=()=>{h&&e({rating:h,comment:u.trim()||void 0})},b=()=>{e()},E={good:i.secondary,bad:i.error};return a.createElement(p.KeyboardAvoidingView,{style:{flex:1},behavior:"padding"},a.createElement(O,{onPress:b,style:c.overlay},a.createElement(C,{width:280,backgroundColor:l.colors.base.modalContentBackground,borderRadius:12,overflow:"hidden",onStartShouldSetResponder:()=>!0},a.createElement(C,{padding:24},a.createElement(k,{variant:"h2",color:i.textHighEmphasis},o.feedback.title)),a.createElement(C,{paddingHorizontal:24,gap:24},a.createElement(C,{flexDirection:"row",gap:4},["good","bad"].map(_=>{const v=h===_,A=_==="good"?o.feedback.good:o.feedback.bad;return a.createElement(O,{key:_,onPress:()=>g(_),activeOpacity:.6,style:c.ratingButton(v)},a.createElement(B,{type:v?Yt(_):_,size:24,color:v?E[_]:i.textLowEmphasis}),a.createElement(k,{variant:"caption1",color:v?E[_]:i.textLowEmphasis},A))})),r&&a.createElement(C,{gap:6},a.createElement(k,{variant:"caption3",color:i.textHighEmphasis},o.feedback.comment_label),a.createElement(p.TextInput,{value:u,onChangeText:_=>m(_),placeholder:o.feedback.comment_placeholder,placeholderTextColor:i.textLowEmphasis,multiline:!0,maxLength:100,style:c.commentInput}))),a.createElement(C,{paddingHorizontal:24,paddingVertical:16,flexDirection:"row",justifyContent:"flex-end",gap:4},a.createElement(O,{onPress:b,activeOpacity:.6,style:c.cancelButton},a.createElement(k,{variant:"button",color:i.textHighEmphasis},o.feedback.cancel)),a.createElement(O,{onPress:y,disabled:!h,activeOpacity:.6,style:c.submitButton(!h)},a.createElement(k,{variant:"button",color:l.colors.base.primaryContrastContent},t?o.feedback.save:o.feedback.submit))))))},Vi=P.create(({select:e,theme:t,themedColor:n})=>({overlay:{flex:1,backgroundColor:t.palette.overlay.dark,alignItems:"center",justifyContent:"center"},ratingButton:s=>({width:114,height:64,borderRadius:12,borderWidth:1,borderColor:n.textDisabled,alignItems:"center",justifyContent:"center",gap:0,backgroundColor:s?e({light:t.palette.background100,dark:t.palette.background600}):"transparent"}),commentInput:{width:"100%",maxHeight:118,borderRadius:4,borderWidth:1,borderColor:n.textDisabled,backgroundColor:n.textLowEmphasisInverse,color:n.textHighEmphasis,paddingHorizontal:12,paddingVertical:6,fontSize:12,lineHeight:16,textAlignVertical:"top"},cancelButton:{width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},submitButton:s=>({width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center",backgroundColor:t.colors.base.primary,opacity:s?.4:1})})),qi=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:s,isFeedbackCommentEnabled:r,extendedMessagePayload:o,onFeedbackUpdate:i,containerStyle:l})=>{const{strings:c}=F(),{themedColor:u}=z(),{openModal:m}=st(),h=ji.use(),g=o==null?void 0:o.feedback,y=(g==null?void 0:g.rating)??"none";if(y!=="none"?!1:!!(n||!e||!s||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const E={good:u.secondary,bad:u.error},_=async S=>{const T=await m(x=>a.createElement(Un,{onClose:x,isEdit:!1,initialRating:S,initialComment:"",isCommentEnabled:r}));T&&(i==null||i(T))},v=async()=>{const S=await m(T=>a.createElement(Z,{onClose:()=>T()},a.createElement(Z.ActionItem,{onPress:()=>T("edit"),label:c.feedback.edit}),a.createElement(Z.ActionItem,{onPress:()=>T("remove"),label:c.feedback.remove,destructive:!0})));if(S==="edit"){const T=await m(x=>a.createElement(Un,{onClose:x,isEdit:!0,initialRating:g==null?void 0:g.rating,initialComment:g==null?void 0:g.comment,isCommentEnabled:r}));T&&(i==null||i(T))}else S==="remove"&&(i==null||i(null))},A=()=>t&&y!=="none"?a.createElement(C,{flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:D.BODY_MAX_WIDTH},a.createElement(C,{padding:2,flexShrink:0,alignItems:"center"},a.createElement(B,{type:Yt(y),size:12,color:E[y]})),(g==null?void 0:g.comment)&&a.createElement(k,{variant:"caption2",style:h.commentText},g.comment)):a.createElement(C,{gap:4,maxWidth:D.BODY_MAX_WIDTH},a.createElement(C,{flexDirection:"row",gap:2},["good","bad"].map(S=>{const T=y===S;return a.createElement(O,{key:S,onPress:()=>{y==="none"?_(S):v()},activeOpacity:.6,style:h.feedbackButton(T)},a.createElement(B,{type:T?Yt(S):S,size:14,color:T?E[S]:u.textMidEmphasis}))})),y!=="none"&&(g==null?void 0:g.comment)&&a.createElement(k,{variant:"caption2",style:h.commentText},g.comment));return a.createElement(C,{style:l},A())},ji=P.create(({select:e,theme:t,themedColor:n})=>({feedbackButton:s=>({width:38,height:20,borderRadius:18,alignItems:"center",justifyContent:"center",borderWidth:1,borderColor:e({light:t.palette.background200,dark:t.palette.background400}),backgroundColor:s?e({light:t.palette.background100,dark:t.palette.background500}):"transparent"}),commentText:{lineHeight:16,color:e({light:n.textMidEmphasis,dark:n.textHighEmphasis})}})),Gi=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},Wi=e=>null,Cs=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:s,...r})=>a.createElement(p.ScrollView,{style:[t,r,e&&on],showsHorizontalScrollIndicator:n,...r},s),Ki=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const s=Yi.use(),[r,o]=d.useState(!1),i=(e==null?void 0:e.suggested_replies)??[];if(i.length===0||r)return null;const l=n==="vertical",c=m=>{t==null||t({reply:m}),o(!0)},u=()=>i.map((m,h)=>a.createElement(O,{key:h,style:s.itemContainer,onPress:()=>c(m)},a.createElement(k,{variant:"body3",color:({themedColor:g})=>g.primary},m)));return l?a.createElement(C,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:D.HORIZONTAL_PADDING},u()):a.createElement(Cs,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:s.horizontalContainer},u())},Yi=P.create(({themedColor:e})=>({itemContainer:{maxWidth:336,paddingHorizontal:12,paddingVertical:8,borderRadius:16,borderWidth:1,borderColor:e.primary,backgroundColor:e.bg_50_600},horizontalContainer:{gap:8,paddingHorizontal:D.HORIZONTAL_PADDING,paddingVertical:16}})),Xi=e=>{var _,v,A,S,T,x,R;const{components:t}=at.useContext(),{streamText:n,isAnimating:s}=Go({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),r={...e,message:n,extendedMessagePayload:s?{}:e.extendedMessagePayload},o=!!r.isTyping,i=!!r.isSenderAvatarVisible,l=!!((_=r.extendedMessagePayload)!=null&&_.form)&&!((v=r.extendedMessagePayload)!=null&&v.form.canceled_at),c=!!((A=r.extendedMessagePayload)!=null&&A.message_template),u=!!((S=r.extendedMessagePayload)!=null&&S.cta_button),m=!!((T=r.extendedMessagePayload)!=null&&T.citations)&&r.extendedMessagePayload.citations.length>0,h=!!r.createdAt,g=r.groupType==="top"||r.groupType==="single",y=r.groupType==="bottom"||r.groupType==="single",b=i?D.AVATAR_SIZE:0,E=Zi.use();return a.createElement(C,{marginBottom:o?0:Zt(r.groupType)},g&&a.createElement(C,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:D.HORIZONTAL_PADDING},i&&a.createElement(t.SenderAvatar,{...r}),a.createElement(t.SenderName,{...r})),a.createElement(C,{gap:D.GAP_GROUPED},o?a.createElement(t.TypingIndicator,{...r,containerStyle:E.middleArea(b)}):a.createElement(t.MessageBody,{...r,containerStyle:E.middleArea(b)},u&&a.createElement(C,{marginTop:12,marginHorizontal:12},a.createElement(t.CTAButton,{...r})),m&&a.createElement(t.Citation,{...r})),c&&a.createElement(t.MessageTemplate,{...r,messageTemplateErrorFallback:r.messageTemplateErrorFallback??a.createElement(t.MessageBody,{...r,messageType:"user",message:((R=(x=r.extendedMessagePayload)==null?void 0:x.message_template)==null?void 0:R.fallback_message)??"Cannot read this template.",containerStyle:E.middleArea(b)}),messageTemplateLoadingFallback:r.messageTemplateLoadingFallback??a.createElement(t.TypingIndicator,{...r,containerStyle:E.middleArea(b)})}),a.createElement(t.CustomMessageTemplate,{...r}),l&&a.createElement(t.Form,{...r,containerStyle:E.middleArea(b)})),y&&h&&a.createElement(t.SentTime,{...r,containerStyle:E.bottomArea(b)}),a.createElement(d.Fragment,null,!o&&a.createElement(t.Feedback,{...r,containerStyle:E.feedbackArea(b)}),r.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...r})))},at=te({template:Xi,components:{SenderName:Ti,SenderAvatar:Ai,SentTime:wi,MessageBody:vi,TypingIndicator:Ni,SuggestedReplies:Ki,MessageTemplate:Wi,CustomMessageTemplate:zi,CTAButton:Bi,Citation:Fi,Form:Gi,Feedback:qi}}),Zi=P.create(()=>({middleArea:e=>({paddingStart:D.HORIZONTAL_PADDING+e,paddingEnd:D.HORIZONTAL_PADDING}),bottomArea:e=>({marginTop:D.BODY_TIME_GAP,paddingStart:D.HORIZONTAL_PADDING+e+8,paddingEnd:D.HORIZONTAL_PADDING}),feedbackArea:e=>({marginTop:8,paddingStart:D.HORIZONTAL_PADDING+e+8,paddingEnd:D.HORIZONTAL_PADDING})})),Ji=({file:e,children:t,sendingStatus:n,onClickFile:s=({url:r})=>p.Linking.openURL(r)})=>{const r=(()=>{if(!(!s||n!=="succeeded"))return()=>s(e)})();return a.createElement(C,{flexDirection:"column",alignItems:"flex-end",gap:D.GAP_GROUPED,width:D.BODY_MAX_WIDTH,maxWidth:D.BODY_MAX_WIDTH},a.createElement(un,{name:e.name,type:Xt(e.name,e.type),onPress:r}),t)},Es=({size:e=26,children:t})=>{const n=d.useRef(new p.Animated.Value(0)).current;d.useEffect(()=>{const r=p.Animated.loop(p.Animated.timing(n,{toValue:1,duration:1e3,easing:p.Easing.linear,useNativeDriver:!0}));return r.start(),()=>{r.stop()}},[n]);const s=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(C.Animated,{style:{transform:[{rotate:s}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??a.createElement(B,{type:"spinner",size:e}))};function Qi(e){return typeof e=="object"&&e!==null&&"uri"in e}const el=({file:e,metadata:t,sendingStatus:n,onClickMedia:s=({url:o})=>p.Linking.openURL(o),children:r})=>{const o=tl.use(),{aspectRatio:i,localFile:l}=t,[c]=d.useState(()=>Qi(l)?l.uri:e.url),[u,m]=d.useState(!1),h=(()=>{if(!(!s||n!=="succeeded"))return()=>s(e)})();return a.createElement(C,{flexDirection:"column",alignItems:"flex-end",gap:D.GAP_GROUPED},a.createElement(O,{onPress:h,style:[o.imageContainer,{aspectRatio:i}],activeOpacity:.75},!u&&a.createElement(C,{alignItems:"center",justifyContent:"center"},a.createElement(Es,{size:26},a.createElement(B,{type:"spinner",color:({themedColor:g})=>g.textLowEmphasis,size:26}))),a.createElement(Ie,{source:{uri:c},style:[o.image,{opacity:u?1:0}],resizeMode:"cover",onLoad:()=>m(!0)})),r)},tl=P.create(({themedColor:e})=>({imageContainer:{width:D.BODY_MAX_WIDTH,borderRadius:12,overflow:"hidden",position:"relative",alignItems:"center",justifyContent:"center",backgroundColor:e.bg_100_500},image:{position:"absolute",width:"100%",height:"100%",top:0,left:0}})),Fn=e=>{var n,s;const t=nl.use();return a.createElement(C,{style:[t.container({maxWidth:e.maxBodyWidth??D.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},a.createElement(k,{variant:"body3",style:[t.text,((s=e.customStyle)==null?void 0:s.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},nl=P.create(({theme:e})=>({container:t=>({flexDirection:"column",borderRadius:12,overflow:"hidden",maxWidth:t.maxWidth,backgroundColor:e.colors.messageOutgoing.background,paddingVertical:12}),text:{textAlign:"left",lineHeight:20,paddingHorizontal:12,color:e.colors.messageOutgoing.text}})),sl=e=>{const{strings:t}=F(),n=()=>{const s=Yn(e)?a.createElement(Fn,{...e}):null;return e.messageType==="user"?s:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(el,{...e},s):a.createElement(Ji,{...e},s):a.createElement(Fn,{...e,message:t.unknown_message_type})};return a.createElement(O,{onPress:e.sendingStatus==="failed"?e.onClickFailedMessage:void 0,activeOpacity:.75},a.createElement(C,{style:e.containerStyle},n()))},rl=({sendingStatus:e,containerStyle:t})=>{const{themedColor:n}=z(),s=()=>{switch(e){case"pending":return a.createElement(C,{marginBottom:2},a.createElement(Es,{size:16},a.createElement(B,{type:"spinner",color:n.primary,size:16})));case"failed":return a.createElement(C,{marginBottom:2},a.createElement(B,{type:"error",color:n.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement(C,{marginBottom:2},a.createElement(B,{type:"done",color:n.secondary,size:16}))}};return a.createElement(C,{style:t},s())},ol=({createdAt:e,containerStyle:t})=>{const{format:n,strings:s}=F();return e?a.createElement(C,{style:t},a.createElement(k,{variant:"caption4",color:({themedColor:r})=>r.textLowEmphasis},n(e,s.date_format.message_timestamp))):null},al=e=>{const{components:t}=it.useContext(),n=e.sendingStatus==="succeeded",s=e.groupType==="bottom"||e.groupType==="single";return a.createElement(C,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:Zt(e.groupType)},a.createElement(t.MessageBody,{...e,containerStyle:Rt.middleArea}),s&&(n?a.createElement(t.SentTime,{...e,containerStyle:Rt.bottomArea}):a.createElement(t.SendingStatus,{...e,containerStyle:Rt.bottomArea})))},it=te({template:al,components:{SendingStatus:rl,SentTime:ol,MessageBody:sl}}),Rt=p.StyleSheet.create({middleArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:D.HORIZONTAL_PADDING},bottomArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingStart:D.HORIZONTAL_PADDING,paddingEnd:D.HORIZONTAL_PADDING+8,marginTop:D.BODY_TIME_GAP}}),il=e=>e.messageType!=="admin"?null:a.createElement(k,{variant:"caption2",color:({themedColor:t})=>t.textMidEmphasis,style:{textAlign:"center"}},ll(e.message)),ll=e=>{try{const t=[];let n=e,s=0;for(;n;){const r=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),o=n.match(/\*\*([^*]+)\*\*/),i=[r&&{match:r,type:"link"},o&&{match:o,type:"bold"}].filter(h=>!!h);if(!i.length){t.push(n);break}const l=i.reduce((h,g)=>g.match.index<h.match.index?g:h),{match:c,type:u}=l,m=c.index;m>0&&t.push(n.slice(0,m)),u==="link"?t.push(a.createElement(p.Text,{key:s++,onPress:()=>p.Linking.openURL((c==null?void 0:c[2])??""),style:{textDecorationLine:"underline"}},c[1])):u==="bold"&&t.push(a.createElement(p.Text,{key:s++,style:{fontWeight:"bold"}},c[1])),n=n.slice(m+c[0].length)}return t.filter(r=>r!=="")}catch{return[e]}},cl=({children:e,style:t})=>a.createElement(k,{variant:"caption4",color:({themedColor:n})=>n.error,style:t},e),ul=({children:e,style:t,required:n})=>{const{strings:s}=F();return a.createElement(k,{variant:"caption3",color:({themedColor:r})=>r.textMidEmphasis,style:t},e,!n&&a.createElement(k,{variant:"caption3",color:({themedColor:r})=>r.textLowEmphasis},` (${s.form.optional_label})`))},dl=({style:e})=>{const t=ml.use();return a.createElement(C,{style:[t.separator,e]})},ml=P.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),gl=({value:e="",onChange:t,placeholder:n,variant:s="single-line",error:r=!1,submitted:o=!1,style:i,disabled:l=!1,maxLength:c})=>{const[u,m]=d.useState(!1),h=hl.use(),{themedColor:g}=z(),y=b=>{c&&b.length>c||t==null||t(b)};return a.createElement(p.TextInput,{value:e,onChangeText:y,placeholder:n,editable:!l&&!o,maxLength:c,multiline:s==="multi-line",style:[h.input(s,r,o,u),i],placeholderTextColor:g.textLowEmphasis,onFocus:()=>m(!0),onBlur:()=>m(!1)})},hl=P.create(({select:e,theme:t,themedColor:n})=>({input:(s,r,o,i)=>{let l,c;o?(l="transparent",c=e({light:t.palette.ondark.textMidEmphasis,dark:t.palette.onlight.textLowEmphasis})):r?(l=n.error,c=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis})):(l=i?n.primary:n.textDisabled,c=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis}));const u={width:"100%",padding:8,paddingHorizontal:12,borderRadius:6,fontSize:14,fontWeight:"400",lineHeight:20,borderWidth:1,borderColor:l,backgroundColor:c,color:o?n.textLowEmphasis:n.textHighEmphasis};return s==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),De={Label:ul,ErrorLabel:cl,TextInput:gl,Separator:dl},vs=({onClick:e,checked:t,label:n,disabled:s,labelVariant:r="caption2"})=>{const{themedColor:o}=z(),i=_l.use(),l=t?o.primary:s?o.textDisabled:o.textLowEmphasis;return a.createElement(O,{disabled:s||!e,onPress:e},a.createElement(C,{style:i.container},a.createElement(C,{style:i.iconContainer},a.createElement(B,{size:20,type:t?"radio-on":"radio-off",color:l})),a.createElement(k,{variant:r,style:i.label(t,s)},n)))},_l=P.create(({themedColor:e})=>({container:{flexDirection:"row",alignItems:"flex-start",justifyContent:"flex-start",width:"100%",gap:2},iconContainer:{width:20,height:20},label:(t,n)=>{let s;return t?s=e.textHighEmphasis:n?s=e.textLowEmphasis:s=e.textHighEmphasis,{flex:1,color:s,lineHeight:20}}})),fl=({csatPayload:e,submitted:t,defaultValue:n,value:s,onChange:r})=>(d.useEffect(()=>{typeof s>"u"&&typeof n=="boolean"&&(r==null||r(n))},[s,n,r]),e.cre?a.createElement(C,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(De.Label,{required:e.cre.required},e.cre.question),a.createElement(C,{flexDirection:"column",gap:8,width:"100%"},[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(o=>a.createElement(vs,{key:o.label,checked:s===o.value,label:o.label,disabled:t,onClick:()=>r==null?void 0:r(o.value)})))):null),pl=({followUpItem:e,submitted:t,value:n="",onChange:s,hasError:r})=>{const{strings:o}=F();return a.createElement(C,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(De.Label,{required:e.required},e.question),e.response_type==="free_text"&&a.createElement(De.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>s(i),error:r}),e.response_type==="single_choice"&&a.createElement(C,{flexDirection:"column",gap:8,width:"100%"},e.options.map(i=>a.createElement(vs,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>s==null?void 0:s(i),labelVariant:"body3"}))),r&&a.createElement(De.ErrorLabel,null,o.form.validation_required))},yl=e=>null,bl=({csatPayload:e,submitted:t,value:n,onChange:s})=>{const r=typeof n>"u",o=Ss.use(),[i,l]=d.useState(16);return a.createElement(C,{onLayout:c=>{c.nativeEvent.layout.width<300&&l(0)},flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(k,{variant:"caption3",color:({themedColor:c})=>c.textMidEmphasis},e.csat_question),a.createElement(C,{style:[o.scoresContainer,{gap:i}]},e.csat_scores.map(({label:c,image_url:u},m)=>{const h=m+1,g=n===h;return a.createElement(O,{key:m,disabled:t,onPress:()=>s(h),style:o.scoreButton},a.createElement(Cl,{value:h,selected:r||g,label:c,src:u}),!!c&&a.createElement(k,{style:{textAlign:"center"},variant:"caption3",color:({themedColor:y})=>g?y.textHighEmphasis:y.textLowEmphasis,lineBreakStrategyIOS:"standard",textBreakStrategy:"simple"},c))})))},Cl=({value:e,src:t,label:n,selected:s})=>{const[r,o]=d.useState(!1),i=Ss.use();return r?a.createElement(yl,{value:e,selected:s,label:n}):a.createElement(Ie,{source:{uri:t},style:i.emojiImage(s),onError:()=>o(!0),accessibilityLabel:n})},Ss=P.create(()=>({scoresContainer:{flexDirection:"row",justifyContent:"space-between",alignSelf:"center",width:"100%",maxWidth:400},scoreButton:{backgroundColor:"transparent",gap:4,flexDirection:"column",alignItems:"center",justifyContent:"flex-start",minWidth:48,maxWidth:68,flex:1},emojiImage:e=>({width:40,height:40,opacity:e?1:.38})})),El=({csatPayload:e})=>a.createElement(k,{style:{textAlign:"left"},variant:"button",color:({themedColor:t})=>t.textHighEmphasis},e.title),Mt=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:s,initialCsatReason:r,initialIsResolved:o})=>{const{params:i,setParams:l,error:c,setError:u,followUpItem:m,state:h,validateParams:g,itemProps:y}=$o({csatPayload:e,type:t,initialCsat:s,initialCsatReason:r,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(C,{flexDirection:"column",gap:12},a.createElement(El,{...y}),t===ie.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(fl,{...y,defaultValue:o,value:i.isResolved,onChange:b=>l({isResolved:b})}),a.createElement(bl,{...y,value:i.csat,onChange:b=>l({csat:b})}),m&&a.createElement(pl,{...y,followUpItem:m,value:i.csatReason,onChange:b=>{l({csatReason:b}),u({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(De.Separator,null),n({state:h,params:i,validateParams:g})))},vl=e=>{const{strings:t}=F();return Mr(e,{title:t.csat.title,question:t.csat.question,cre:{question:t.csat.cre_question,positive_label:t.csat.cre_positive_label,negative_label:t.csat.cre_negative_label},followUp:{question:t.csat.reason_placeholder},submit_label:t.csat.submit_label,submitted_label:t.csat.submitted_label})},Sl=()=>{const{strings:e}=F();return a.createElement(k,{variant:"body2",color:({themedColor:t})=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},Al=({onMount:e,children:t})=>(d.useEffect(()=>{e==null||e()},[]),a.createElement(a.Fragment,null,t)),Il=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n,onScrollToBottom:s}=e,{csat:r,csatReason:o,csatExpireAt:i,isResolvedWhenDeterminedByUser:l}=e,[,c]=d.useState(0),u=vl(t==null?void 0:t.csat),m=d.useRef(!1),h=Tl.use();if(!u||!u.visibility||!ie[u.type])return null;const g=u.type===ie.AI_AGENT_CSAT_5||u.type===ie.AI_AGENT_CSAT_5_WITH_CRE||u.type===ie.HELPDESK_CSAT_5?Mt:()=>null;return a.createElement(C,{style:h.container},!r&&vn(i)?a.createElement(Sl,null):a.createElement(g,{csatPayload:u,type:u.type,initialCsat:r,initialCsatReason:o,initialIsResolved:l,renderSubmitButton:({state:y,params:b,validateParams:E})=>a.createElement(Al,{onMount:s},a.createElement(O,{activeOpacity:.75,disabled:y==="submitted",onPress:async()=>{m.current||(!vn(i)&&E()?(m.current=!0,await n(b).finally(()=>{m.current=!1})):c(_=>_+1))},style:h.submitButton(y)},a.createElement(k,{variant:"button",style:h.submitButtonText(y)},y==="submitted"?u.csat_submitted_label:u.csat_submit_label)))}))},Tl=P.create(({theme:e,themedColor:t})=>({container:{flexDirection:"column",backgroundColor:e.colors.csat.background,borderRadius:16,gap:16,padding:16},submitButton:n=>{let s;return n==="submitted"||n==="unsubmittable"?s=t.textDisabled:s=e.colors.base.primary,{backgroundColor:s,borderRadius:6,padding:10,paddingHorizontal:20,alignItems:"center",justifyContent:"center"}},submitButtonText:n=>{let s;return n==="submitted"?s=t.textHighEmphasis:n==="unsubmittable"?s=t.textLowEmphasis:s=e.colors.base.primaryContrastContent,{color:s}}})),wl=e=>{const{components:t}=lt.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(C,{paddingHorizontal:D.HORIZONTAL_PADDING,marginBottom:Zt(e.groupType)},n)},lt=te({template:wl,components:{AdminMessage:il,CSATMessage:Il}}),xl=({style:e,...t})=>{const{strings:n}=F();if(!rn("powered-by"))return null;const r=()=>{p.Linking.openURL("https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby")};return a.createElement(C,{style:[kl.container,e],...t},a.createElement(k,{variant:"caption2",color:({themedColor:o})=>o.textLowEmphasis},n.conversation.powered_by+" "),a.createElement(O,{onPress:r},a.createElement(k,{variant:"caption2",color:({themedColor:o})=>o.textLowEmphasis},"Sendbird")))},kl=p.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),Rl=()=>{var l;const{strings:e}=F(),{channelSource:t,scrollSource:n,updateActiveChannel:s}=oe(),r=Ml.use(),o=se(t.channel),i=d.useRef(o);return d.useEffect(()=>{const c=i.current;i.current=o,!c&&o&&n.actions.scrollToBottom()},[o,n]),!((l=t.channel)!=null&&l.isAIAgent)||!o?null:a.createElement(C,{justifyContent:"center",flexDirection:"row",style:r.wrapper},a.createElement(O,{activeOpacity:.75,onPress:()=>s(),style:r.button},a.createElement(k,{variant:"button",role:"button",color:({themedColor:c})=>c.textHighEmphasis},e.conversation.start_new_conversation_label)))},Ml=P.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),Dl=({date:e=Date.now(),style:t,...n})=>{const{format:s,strings:r}=F();return a.createElement(C,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},a.createElement(k,{variant:"caption4",color:({themedColor:o})=>o.textMidEmphasis},s(e,r.date_format.date_separator)))},Ll=({style:e,onPress:t})=>{const n=Pl.use(),{theme:s}=z();return a.createElement(O,{style:[n.button,e],onPress:t},a.createElement(C,{alignItems:"center",justifyContent:"center"},a.createElement(B,{size:24,type:"chevron-down",color:s.colors.base.primary})))},Pl=P.create(({select:e,theme:t})=>({button:{width:40,height:40,borderRadius:24,alignItems:"center",justifyContent:"center",backgroundColor:e({light:t.palette.background50,dark:t.palette.background400}),boxShadow:[{color:"rgba(0, 0, 0, 0.08)",offsetX:0,offsetY:2,blurRadius:8,spreadDistance:0},{color:"rgba(0, 0, 0, 0.12)",offsetX:0,offsetY:4,blurRadius:6,spreadDistance:0}]}})),Ol=()=>null,mn=te({template:Ol,components:{DateSeparator:Dl,ScrollToBottomButton:Ll}}),Nl=(e,t)=>!Ns.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Hl=({messageStackDirection:e="top"})=>{var w,L;const{Template:t}=at.useContext(),{Template:n}=it.useContext(),{Template:s}=lt.useContext(),{components:r}=mn.useContext(),{openModal:o}=st(),{strings:i}=F(),{config:l,cache:c,chatSDK:u}=K(),{aiAgentInfo:m,userSession:h,connectionError:g}=J(),{conversation:y,messageSource:b,channelSource:E,scrollSource:_,state:{input:v,streamAnimation:A}}=oe(),S=Bl.use(),T=Te(["left","right"]),x=Fo(E.channel);d.useEffect(()=>{_.state.isAwayFromBottom||b.resetNewMessages()},[_.state.isAwayFromBottom]);const R=(I,M=!1)=>{var U;return M?m??{nickname:"",profileUrl:""}:((U=E.channel)==null?void 0:U.members.find(H=>H.userId===I.sender.userId))??I.sender},N=I=>{if(I.sendingStatus==="failed"&&!v.disabled)return()=>{o(M=>a.createElement(Z,{onClose:()=>M()},a.createElement(Z.ActionItem,{label:i.conversation.failed_message_resend,onPress:async()=>{b.resendMessage(I),M()}}),a.createElement(Z.ActionItem,{destructive:!0,label:i.conversation.failed_message_remove,onPress:async()=>{b.deleteMessage(I),M()}})))}},Y=({item:I,index:M})=>{const U=b.messages[M+1],H=b.messages[M-1],ue=(()=>{var _n,fn,pn;const Ce=!(m!=null&&m.isUserFeedbackEnabled&&Ne(I,m==null?void 0:m.userId)&&!Ye.isWelcomeMessage(I)),gt=nr(I,U,H,Ce),de={data:I.data,extendedMessagePayload:I.extendedMessagePayload,message:I.message,createdAt:I.createdAt,groupType:gt};if(Ue.isAdmin(I))return Ue.isCSAT(I)?y?a.createElement(s,{...de,...y,messageType:"admin.csat",isResolvedWhenDeterminedByUser:kr(y),onSubmitCSAT:async me=>{var ge;await((ge=E.channel)==null?void 0:ge.submitCSAT(me))},onScrollToBottom:()=>_.actions.scrollToBottom()}):null:a.createElement(s,{...de,messageType:"admin"});if(Ue.isOutgoing(I,(h==null?void 0:h.userId)??"")){const me={...de,sender:R(I),sendingStatus:I.sendingStatus,onClickFailedMessage:N(I)};if(I.isUserMessage())return a.createElement(n,{...me,messageType:"user"});if(I.isFileMessage()){const[ge,xe]=((_n=I.metaArrays.find($=>$.key===Wn))==null?void 0:_n.value)??[];return a.createElement(n,{...me,messageType:"file",file:I,metadata:{aspectRatio:ge&&xe?`${ge}/${xe}`:"1/1",localFile:(fn=I.messageParams)==null?void 0:fn.file}})}}if(Ue.isIncoming(I,(h==null?void 0:h.userId)??"")){const me=I.sender.userId===(m==null?void 0:m.userId),ge=M===0,xe={...de,sender:R(I,me),suggestedRepliesVisible:ge,isBotMessage:me,isStreaming:Ye.isStreaming(I),isHandedOff:ye(E.channel),isConversationClosed:se(E.channel),isFeedbackEnabled:m==null?void 0:m.isUserFeedbackEnabled,isFeedbackCommentEnabled:m==null?void 0:m.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(pn=l==null?void 0:l.conversation)==null?void 0:pn.senderAvatarEnabled,onClickSuggestedReply:async({reply:$})=>{b.sendUserMessage({message:$})},onRequestMessageTemplate:async $=>{const{template:ae}=await u.aiAgent.getMessageTemplate($);return c.template.set($,ae),ae},onGetCachedMessageTemplate:$=>c.template.get($),onHandleTemplateInternalAction:$=>{if($.type==="internal"&&$.internalData){const{method:ae,payload:he}=$.internalData;ae==="message.send"&&(he!=null&&he.message)&&b.sendUserMessage({message:he.message})}},onFeedbackUpdate:$=>{const ae={messageId:I.messageId,channelUrl:I.channelUrl};if(!$)return u.aiAgent.deleteMessageFeedback(ae);const he={...ae,rating:$i($.rating),comment:$.comment};return Ye.hasFeedback(I)?u.aiAgent.updateMessageFeedback(he):u.aiAgent.createMessageFeedback(he)},onSubmitForm:({key:$,data:ae})=>u.aiAgent.submitForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:$,formData:ae}),onCancelForm:({key:$})=>u.aiAgent.cancelForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:$}),onStreamAnimationStart:()=>{A.start(I.messageId)},onStreamAnimationProgress:()=>{_.actions.onStreamingUpdate()},onStreamAnimationComplete:()=>{A.stop(I.messageId),_.actions.onStreamingUpdate()}};if(I.isUserMessage())return a.createElement(t,{...xe,messageType:"user"});if(I.isFileMessage())return a.createElement(t,{...xe,messageType:"file",file:I})}return null})(),mt=Nl(I,U)&&a.createElement(r.DateSeparator,{date:I.createdAt,style:S.dateSeparator});return a.createElement(C,null,mt,ue)},Q=()=>a.createElement(xl,{style:S.poweredBy}),G=()=>{var I,M;return a.createElement(a.Fragment,null,x&&a.createElement(C,{marginTop:b.messages.length===0?8:0},a.createElement(t,{isTyping:!0,isBotMessage:x.isBot,sender:x.user,thinkingMessage:x.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(I=l==null?void 0:l.conversation)==null?void 0:I.senderAvatarEnabled})),((M=l==null?void 0:l.conversation)==null?void 0:M.isTalkToAgentViewEnabled)&&a.createElement(Rl,null),_.state.bottomSpace?a.createElement(C,{height:_.state.bottomSpace}):null)};return a.createElement(C,{flex:1},a.createElement(fs,{ref:_.ref,style:S.list,contentContainerStyle:[S.listContent,T],stackDirection:e,data:b.messages,onEndReached:b.loadPrevious,keyExtractor:tr,renderItem:Y,loading:!b.initialized||!E.channel,empty:b.messages.length===0&&!x,error:!!(g||E.error),LoadingComponent:a.createElement(Ae,{type:"loading"}),EmptyComponent:a.createElement(Ae,{type:"noMessages",label:i.common.placeholder_no_messages}),ErrorComponent:a.createElement(Ae,{type:"error",label:(g==null?void 0:g.message)??((w=E.error)==null?void 0:w.message),action:E.error?{label:i.common.placeholder_something_went_wrong_retry_label,onPress:()=>E.refetch()}:void 0}),ListFooterComponent:Q(),ListHeaderComponent:G(),inverted:!0,..._.props}),((L=l==null?void 0:l.conversation)==null?void 0:L.newMessageIndicatorEnabled)&&_.state.isAwayFromBottom&&b.newMessages.length>0&&a.createElement(C,{style:S.newMessagesButtonContainer},a.createElement(si,{label:i.conversation.scroll_to_new_messages_label(b.newMessages),accessibilityLabel:i.conversation.a11y_scroll_to_new_messages,onPress:()=>_.actions.scrollToBottom()})),_.state.isAwayFromBottom&&b.newMessages.length===0&&a.createElement(r.ScrollToBottomButton,{style:S.scrollButtonContainer,onPress:()=>_.actions.scrollToBottom()}))},Bl=P.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background},dateSeparator:{marginVertical:16},poweredBy:{marginTop:16},scrollButtonContainer:{position:"absolute",bottom:12,end:16},newMessagesButtonContainer:{position:"absolute",bottom:12,alignSelf:"center"}})),le={CAMERA_PERMISSION_DENIED:"Camera permission is not granted",GALLERY_PERMISSION_DENIED:"Photo library permission is not granted",IMAGE_PICKER_NOT_CONFIGURED:"Image picker is not configured. Please provide imagePicker in NativeAdapterConfig to use camera or gallery features.",DOCUMENT_PICKER_NOT_CONFIGURED:"Document picker is not configured. Please provide documentPicker in NativeAdapterConfig to use file selection features."};function Ul(e){return{captureCamera:async()=>{if(e.requestCameraPermissionsAsync&&!(await e.requestCameraPermissionsAsync()).granted)throw new Error(le.CAMERA_PERMISSION_DENIED);const t=await e.launchCameraAsync({mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});return t.canceled||!t.assets||t.assets.length===0?null:t.assets.map(zn)},selectFromGallery:async t=>{if(e.requestMediaLibraryPermissionsAsync&&!(await e.requestMediaLibraryPermissionsAsync()).granted)throw new Error(le.GALLERY_PERMISSION_DENIED);const n=await e.launchImageLibraryAsync({selectionLimit:(t==null?void 0:t.selectionLimit)??1,allowsMultipleSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});return n.canceled||!n.assets||n.assets.length===0?null:n.assets.map(zn)}}}function Fl(e,t){const n=async()=>{const r=p.Platform.select({ios:t.PERMISSIONS.IOS.CAMERA,android:t.PERMISSIONS.ANDROID.CAMERA});if(!r)return;const o=await t.request(r);if(o!=="granted"&&o!=="limited")throw new Error(le.CAMERA_PERMISSION_DENIED)},s=async()=>{const r=p.Platform.select({ios:[t.PERMISSIONS.IOS.PHOTO_LIBRARY],android:typeof p.Platform.Version=="number"&&p.Platform.Version>32?[]:typeof p.Platform.Version=="number"&&p.Platform.Version>28?[t.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]:[t.PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,t.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]});if(!r||r.length===0)return;const o=await t.requestMultiple(r);if(!Object.values(o).every(l=>l==="granted"||l==="limited"))throw new Error(le.GALLERY_PERMISSION_DENIED)};return{captureCamera:async()=>{await n();const r=await e.launchCamera({mediaType:"photo",assetRepresentationMode:"compatible"});if(r.didCancel)return null;if(r.errorCode)throw r.errorCode==="permission"?new Error(le.CAMERA_PERMISSION_DENIED):new Error(r.errorMessage||`Camera error: ${r.errorCode}`);return!r.assets||r.assets.length===0?null:r.assets.map($n)},selectFromGallery:async r=>{await s();const o=await e.launchImageLibrary({mediaType:"photo",selectionLimit:(r==null?void 0:r.selectionLimit)??1,assetRepresentationMode:"compatible"});if(o.didCancel)return null;if(o.errorCode)throw o.errorCode==="permission"?new Error(le.GALLERY_PERMISSION_DENIED):new Error(o.errorMessage||`Gallery error: ${o.errorCode}`);return!o.assets||o.assets.length===0?null:o.assets.map($n)}}}function zl(e){return{selectFile:async t=>{const n=(t==null?void 0:t.mimeTypes)??["*/*"],s=await e.getDocumentAsync({multiple:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:n});return s.canceled||!s.assets||s.assets.length===0?null:s.assets.map(Vl)}}}function $l(e){return{selectFile:async t=>{try{const n=(t==null?void 0:t.mimeTypes)??["*/*"],s=p.Platform.select({android:n,ios:void 0}),r=await e.pick({mode:"open",allowMultiSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:s});return(Array.isArray(r)?r:[r]).map(ql)}catch(n){if(n&&typeof n=="object"&&"message"in n){const s=String(n.message).toLowerCase();if(s.includes("cancel")||s.includes("user cancelled"))return null;throw new Error(String(n.message))}throw new Error("File selection failed")}}}}function zn(e){return{uri:e.uri,type:e.mimeType||"image/jpeg",size:e.fileSize||0,name:e.fileName||"image.jpg",width:e.width,height:e.height}}function Vl(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function $n(e){return{uri:e.uri,type:e.type||"image/jpeg",size:e.fileSize||0,name:e.fileName||"image.jpg",width:e.width,height:e.height}}function ql(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function jl(){return{captureCamera:async()=>{throw new Error(le.IMAGE_PICKER_NOT_CONFIGURED)},selectFromGallery:async()=>{throw new Error(le.IMAGE_PICKER_NOT_CONFIGURED)}}}function Gl(){return{selectFile:async()=>{throw new Error(le.DOCUMENT_PICKER_NOT_CONFIGURED)}}}const{Provider:Wl,useContext:As}=j("NativeAdapter"),Is=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:s,documentPicker:r,mmkv:o}=e,i=s?(Kl(e),"launchCameraAsync"in s?Ul(s):Fl(s,e.permissions)):jl(),l=r?"getDocumentAsync"in r?zl(r):$l(r):Gl();return{...i,...l,keyValueStorage:rs(o)}},[e.imagePicker,e.documentPicker,e.mmkv,e.permissions]);return a.createElement(Wl,{value:n},t)};function Kl(e){if(!e.imagePicker)return;if(!("launchCameraAsync"in e.imagePicker)&&!e.permissions)throw new Error("react-native-permissions is required when using react-native-image-picker. Please install react-native-permissions and provide it in nativeModules.permissions")}const Yl=({onPressAddAttachment:e,disabled:t})=>a.createElement(O,{disabled:t,style:Xl.container,activeOpacity:.75,onPress:e},a.createElement(B,{type:"add",size:24,color:({themedColor:n})=>t?n.textDisabled:n.primary})),Xl=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Zl=({name:e,type:t,url:n,onRemove:s})=>{const r=Jl.use();return a.createElement(C,{style:r.wrapper},sr(t)?a.createElement(Ie,{source:{uri:n},style:r.image,resizeMode:"cover"}):a.createElement(un,{name:e,type:Xt(e,t)}),s&&a.createElement(O,{onPress:s,style:r.removeButton},a.createElement(B,{type:"remove",size:20,color:r.removeIcon.tintColor})))},Ge=7,Jl=P.create(({themedColor:e})=>({wrapper:{marginTop:Ge,marginRight:Ge,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-Ge,right:-Ge,width:22,height:22,borderRadius:11,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),Ql=e=>{const{theme:t,themedColor:n}=z(),s=ec.use(),r=ln.useTextAlign({text:e.value??e.placeholder,style:s.input,isTextInput:!0});return a.createElement(C,{style:s.container},e.attachments&&a.createElement(Cs,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),a.createElement(C,null,a.createElement(p.TextInput,{multiline:!0,style:[s.input,{textAlign:r}],placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},ec=P.create(({theme:e})=>({container:{backgroundColor:e.colors.messageInput.background,gap:16,flex:1,paddingHorizontal:16,paddingVertical:8,justifyContent:"center",borderRadius:20,minHeight:36},input:{...tc(e.typography.body3),color:e.colors.messageInput.text,includeFontPadding:!1,padding:0,margin:0,textAlignVertical:"center"}}));function tc(e){const t={maxHeight:52};return e.fontFamily&&(t.fontFamily=e.fontFamily),typeof e.fontSize=="number"&&(t.fontSize=e.fontSize,t.maxHeight=e.fontSize*3.5),typeof e.lineHeight=="number"&&(t.lineHeight=e.lineHeight,t.maxHeight=e.lineHeight*3.5),e.fontWeight&&(t.fontWeight=e.fontWeight),t}const nc=({onPressSend:e})=>a.createElement(O,{style:sc.container,activeOpacity:.75,onPress:e},a.createElement(B,{type:"send",size:24})),sc=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),rc=()=>{const e=oc.use(),{aiAgentInfo:t,userSession:n}=J(),{messageSource:s,channelSource:r}=oe(),[o,i]=d.useState(null),l=rn("special-notice",r.channel),c=d.useCallback(()=>r.channel?l?s.messages.some(u=>Ne(u,(n==null?void 0:n.userId)??"")):!0:null,[r.channel,l,s.messages,n==null?void 0:n.userId]);return d.useEffect(()=>{o||i(c())},[c,o]),o||!(t!=null&&t.specialNotice)?null:a.createElement(C,{style:e.container},a.createElement(dn,{textStyle:e.text,linkStyle:e.link},(t==null?void 0:t.specialNotice)??""))},oc=P.create(({theme:e,themedColor:t,select:n})=>({container:{backgroundColor:e.colors.base.background,paddingVertical:8,paddingHorizontal:16,alignItems:"center"},text:{...e.typography.body3,color:t.textLowEmphasis,textAlign:"center"},link:{fontWeight:"700",textDecorationLine:"none",color:n({light:e.palette.information.light,dark:e.palette.information.main})}})),ac=()=>{var E;const{chatSDK:e}=K(),{strings:t}=F(),{createAttachmentRules:n}=J(),{channelSource:s,state:r}=oe(),[o,i]=d.useState(""),[l,c]=d.useState([]),u=n({channel:s.channel,uploadSizeLimit:(E=e.appInfo)==null?void 0:E.uploadSizeLimit}),m=(_,v)=>{const A=v.filter(R=>u.isSupportedMimeType(R.type));if(A.length===0&&v.length>0)return p.Alert.alert("",t.conversation.file_upload_not_supported_file),_;const S=R=>{const N=u.getUploadSizeLimit(R.type);return R.size&&R.size>N},T=A.find(R=>S(R));if(T){const R=u.getUploadSizeLimitInMB(T.type);return p.Alert.alert("",t.conversation.file_upload_notification_size_limit(R)),_}return _.length+A.length>u.maxAttachmentCount?(p.Alert.alert("",t.conversation.file_upload_notification_count_limit(u.maxAttachmentCount)),_):[..._,...A]},h=_=>{c(v=>m(v,_))},g=_=>{c(v=>v.filter((A,S)=>S!==_))},y=()=>{c([])},b=(()=>{if(!r.input.disabled)return t.conversation.input_placeholder;switch(r.input.disabledBy){case"form_active":return t.conversation.input_placeholder_active_form;case"ai_responding":return t.conversation.input_placeholder_wait_ai_agent_response;case"reconnecting":return t.conversation.input_placeholder_reconnecting;case"unavailable":case"conversation_closed":default:return t.conversation.input_placeholder_disabled}})();return d.useEffect(()=>{r.input.disabled&&(i(""),y())},[r.input.disabled]),{files:l,addFiles:h,removeFile:g,clearFiles:y,value:o,onChangeText:i,editable:!r.input.disabled,placeholder:b,sendButtonVisible:!r.input.disabled&&(!!o.trim()||l.length>0),addAttachmentButtonVisible:u.isEnabled(),addAttachmentButtonDisabled:r.input.disabled||l.length>=u.maxAttachmentCount,hasImageMimeTypes:()=>u.supportedMimeTypes.filter(v=>v.startsWith("image/")||v===Kn).length>0,hasFileMimeTypes:()=>u.supportedMimeTypes.length>0,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount}},ic=()=>{const{config:e}=K(),t=As(),{strings:n}=F(),{messageSource:s}=oe(),{openModal:r}=st(),o=Te(["left","right","bottom"]),i=lc.use(),{maxAttachmentCount:l,sendButtonVisible:c,addAttachmentButtonVisible:u,addAttachmentButtonDisabled:m,acceptableMimeTypes:h,hasImageMimeTypes:g,hasFileMimeTypes:y,...b}=ac(),v={...b,onPressAddAttachment:async()=>{const A=await r(S=>{var T,x,R,N,Y,Q,G,w;return a.createElement(Z,{onClose:()=>S()},((R=(x=(T=e==null?void 0:e.conversation)==null?void 0:T.input)==null?void 0:x.camera)==null?void 0:R.photoEnabled)&&a.createElement(Z.ActionItem,{icon:"camera",label:n.conversation.attachment_camera,onPress:async()=>{if(!g())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),S(null);const L=await t.captureCamera();S(L)}}),((Q=(Y=(N=e==null?void 0:e.conversation)==null?void 0:N.input)==null?void 0:Y.gallery)==null?void 0:Q.photoEnabled)&&a.createElement(Z.ActionItem,{icon:"photo",label:n.conversation.attachment_photo,onPress:async()=>{if(!g())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),S(null);const L=await t.selectFromGallery({selectionLimit:l-b.files.length});S(L)}}),((w=(G=e==null?void 0:e.conversation)==null?void 0:G.input)==null?void 0:w.fileEnabled)&&a.createElement(Z.ActionItem,{icon:"document",label:n.conversation.attachment_document,onPress:async()=>{if(!y())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),S(null);const L=await t.selectFile({selectionLimit:l-b.files.length,mimeTypes:h});S(L)}}))});A&&b.addFiles(A)},onPressSend:()=>{b.files.length>0?s.sendFileMessage({message:b.value.trim(),file:b.files[0]}):s.sendUserMessage({message:b.value}),b.clearFiles(),b.onChangeText("")}};return a.createElement(p.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-o.paddingBottom},a.createElement(rc,null),a.createElement(C,{style:i.container(o)},u&&a.createElement(Yl,{...v,disabled:m}),a.createElement(Ql,{...v,value:v.editable?v.value:"",attachments:v.files.length===0?null:v.files.map((A,S)=>a.createElement(Zl,{key:S,name:A.name,type:A.type,url:A.uri,onRemove:()=>v.removeFile(S)}))}),c&&a.createElement(nc,{...v})))},lc=P.create(({theme:e})=>({container:({paddingStart:t,paddingEnd:n,paddingBottom:s})=>({alignItems:"center",flexDirection:"row",gap:8,paddingTop:10,paddingBottom:10+s,paddingStart:12+t,paddingEnd:12+n,backgroundColor:e.colors.base.background})})),Ts=({start:e,title:t,titleAlign:n="start",end:s})=>{const r=Te(["left","right","top"]),[o,i]=d.useState(0),[l,c]=d.useState(0),u=g=>{i(g.nativeEvent.layout.width)},m=g=>{c(g.nativeEvent.layout.width)},h=cc.use();return a.createElement(C,{style:h.container},a.createElement(C,{height:r.paddingTop}),a.createElement(C,{style:h.contentContainer(r)},n==="center"&&t&&a.createElement(C,{style:h.centerTitleContainer(Math.max(o,l))},a.createElement(C,{style:h.centerTitle},t)),a.createElement(C,{style:h.rowContainer},a.createElement(C,{style:h.startSide,onLayout:u},e),(n==="start"||n==="end")&&t&&a.createElement(C,{style:h.titleSide(n,e,s)},t),a.createElement(C,{style:h.endSide,onLayout:m},s))))},cc=P.create(({theme:e,themedColor:t})=>({container:{width:"100%",backgroundColor:e.colors.base.headerBackground,borderBottomWidth:1,borderBottomColor:t.textDisabled},contentContainer:n=>({position:"relative",height:56,paddingStart:n.paddingStart+12,paddingEnd:n.paddingEnd+12}),centerTitleContainer:n=>({position:"absolute",left:n,right:n,top:0,bottom:0,alignItems:"center",justifyContent:"center"}),centerTitle:{maxWidth:"100%",overflow:"hidden"},rowContainer:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",height:"100%",zIndex:1},startSide:{flexShrink:0},endSide:{flexShrink:0},titleSide:(n,s,r)=>({flex:1,overflow:"hidden",alignItems:`flex-${n}`,marginStart:s?8:0,marginEnd:r?8:0})})),uc=()=>{const{themedColor:e}=z(),{onClose:t}=oe();return t?a.createElement(O,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(B,{color:e.textHighEmphasis,type:"close",size:24})):null},dc=()=>{const{themedColor:e}=z(),{channelSource:{channel:t}}=oe(),n=rn("handoff-button",t),s=!es(t)||ye(t);return n?a.createElement(O,{hitSlop:4,disabled:s,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},a.createElement(B,{color:s?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},mc=()=>{const{strings:e}=F(),{themedColor:t}=z(),{onNavigateToConversationList:n}=oe();return n?a.createElement(O,{hitSlop:4,onPress:n,activeOpacity:.75,"aria-label":e.conversation.a11y_open_conversation_list},a.createElement(B,{color:t.textHighEmphasis,type:"menu",size:24})):null},ws=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:s}=J(),{fallbackIcon:r,url:o}=is({channel:e,aiAgentInfo:s,userSession:n}),{theme:i}=z();return o?a.createElement(bs,{src:o,size:t}):a.createElement(C,{width:t,height:t,borderRadius:t/2,alignItems:"center",justifyContent:"center",flexShrink:0,style:{backgroundColor:i.colors.base.primary}},a.createElement(B,{type:r,size:t*.55,color:i.colors.base.primaryContrastContent}))},gc=()=>{var i,l;const{channelSource:{channel:e}}=oe(),{userSession:t,aiAgentInfo:n}=J(),{config:s}=K(),r=is({channel:e,userSession:t,aiAgentInfo:n}),o=(l=(i=s==null?void 0:s.conversation)==null?void 0:i.header)==null?void 0:l.avatarEnabled;return a.createElement(C,{gap:6,flexDirection:"row",alignItems:"center",maxWidth:"100%"},o&&a.createElement(ws,{channel:e,size:34}),a.createElement(C,{flexShrink:1},a.createElement(k,{numberOfLines:1,variant:"h1"},r.title)))},hc=e=>{const{components:t}=be.useContext();return a.createElement(Ts,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},_c=()=>{const{components:e}=be.useContext();return a.createElement(e.MenuButton,null)},fc=()=>{const{components:e}=be.useContext();return a.createElement(e.Title,null)},pc=()=>{const{components:e}=be.useContext();return a.createElement(C,{flexDirection:"row",alignItems:"center",gap:10},a.createElement(e.HandoffButton,null),a.createElement(e.CloseButton,null))},be=te({template:hc,components:{StartArea:_c,TitleArea:fc,EndArea:pc,MenuButton:mc,Title:gc,HandoffButton:dc,CloseButton:uc}}),yc=()=>{const{Template:e}=be.useContext();return a.createElement(e,{titleAlign:"start"})},bc=e=>{const{components:t}=ct.useContext();return a.createElement(C,{flex:1},a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},ct=te({template:bc,components:{Header:yc,Body:Hl,Footer:ic}}),xs=({children:e,...t})=>{const{Template:n}=ct.useContext();return a.createElement(cs,{...t},a.createElement(n,null),e)},{Provider:Cc,Context:Ec,useContext:ut}=j("ConversationList"),ks=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:s,children:r})=>{const{sdkUser:o,authenticate:i}=J();return d.useEffect(()=>{o||i()},[]),a.createElement(Po,{conversationListLimit:e,conversationListFilter:t},l=>a.createElement(Cc,{value:{...l,onClose:s,onNavigateToConversation:n}},r))},Dt=99,vc=d.memo(function(t){const{channel:n,onClick:s}=t,{strings:r,format:o}=F(),{themedColor:i}=z(),l=Ac.use(),c=Kr(n,{formatMultipleFilesCount:r.conversation_list.multiple_files_count}),u=Yr(n,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}),m=n.unreadMessageCount;return a.createElement(O,{onPress:s,activeOpacity:.75},a.createElement(C,{flexDirection:"row",alignItems:"center",width:"100%",height:72,gap:16},a.createElement(C,{marginStart:16,alignItems:"center",justifyContent:"center"},a.createElement(ws,{channel:n})),a.createElement(C,{flexDirection:"row",alignItems:"center",flex:1,paddingEnd:16,height:"100%",gap:8,style:l.rightContainer},a.createElement(C,{flexDirection:"column",justifyContent:"center",flex:1,gap:4},a.createElement(k,{variant:"subtitle1",color:i.textHighEmphasis,numberOfLines:1},c),a.createElement(C,{flexDirection:"row",alignItems:"center",gap:6},se(n)&&a.createElement(a.Fragment,null,a.createElement(k,{variant:"caption1",color:i.textMidEmphasis,numberOfLines:1},r.conversation_list.ended),a.createElement(C,{width:2,height:2,borderRadius:1,backgroundColor:i.textLowEmphasis})),a.createElement(k,{variant:"caption2",color:i.textLowEmphasis,numberOfLines:1},u))),m>0&&a.createElement(C,{alignItems:"center",justifyContent:"center",height:20,width:m<=Dt?20:void 0,padding:4,borderRadius:10,backgroundColor:i.error},a.createElement(k,{variant:"caption3",color:i.textHighEmphasisInverse,style:{lineHeight:12}},m<=Dt?m:`${Dt}+`)))))}),Sc=te({template:vc,components:{}}),Ac=P.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),Ic=()=>{var l;const{Template:e}=Sc.useContext(),{strings:t}=F(),{connectionError:n}=J(),{listSource:s,onNavigateToConversation:r}=ut(),o=Te(["left","right"]),i=Tc.use();return a.createElement(fs,{style:i.list,contentContainerStyle:[i.listContent,o],data:s.channels,onEndReached:s.loadMore,keyExtractor:d.useCallback(c=>c.url,[]),renderItem:d.useCallback(({item:c})=>a.createElement(e,{channel:c,onClick:()=>r==null?void 0:r(c.url,se(c)?"closed":"open")}),[e,r]),loading:!s.initialized,error:!!(n||s.error),empty:s.channels.length===0,LoadingComponent:a.createElement(Ae,{type:"loading"}),EmptyComponent:a.createElement(Ae,{type:"noChannels",label:t.common.placeholder_no_conversations}),ErrorComponent:a.createElement(Ae,{type:"error",label:(n==null?void 0:n.message)??((l=s.error)==null?void 0:l.message)})})},Tc=P.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),wc=()=>{const{strings:e}=F(),{language:t,countryCode:n,context:s,_aiAgentSDK:r}=K(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:l,sdkUser:c}=J(),{onNavigateToConversation:u}=ut(),m=Te(["left","right","bottom"]),h=xc.use();return a.createElement(O,{activeOpacity:.75,disabled:!c,onPress:async()=>{var g;if(o!=null&&o.isMultipleActiveConversationsEnabled){const y=await l({aiAgentId:o.userId,language:t,country:n,context:s});(g=r.session)==null||g._updateActiveChannel({url:y,status:"open"}),u==null||u(y,"open")}else{const y=await i();u==null||u(y,"open")}}},a.createElement(C,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+m.paddingBottom,style:[h.container,m]},a.createElement(k,{variant:"h1",color:({themedColor:g})=>g.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},xc=P.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),kc=()=>{const{aiAgentInfo:e}=J();return e?a.createElement(wc,null):null},Rc=()=>{const{themedColor:e}=z(),{onClose:t}=ut();return t?a.createElement(O,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(B,{color:e.textHighEmphasis,type:"close",size:24})):null},Mc=()=>{const{strings:e}=F();return a.createElement(k,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},Dc=e=>{const{components:t}=we.useContext();return a.createElement(Ts,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},Lc=()=>null,Pc=()=>{const{components:e}=we.useContext();return a.createElement(e.Title,null)},Oc=()=>{const{components:e}=we.useContext();return a.createElement(e.CloseButton,null)},we=te({template:Dc,components:{StartArea:Lc,TitleArea:Pc,EndArea:Oc,Title:Mc,CloseButton:Rc}}),Nc=()=>{const{Template:e}=we.useContext();return a.createElement(e,{titleAlign:"start"})},Hc=()=>{const{components:e}=dt.useContext();return a.createElement(C,{flex:1},a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},dt=te({template:Hc,components:{Header:Nc,Body:Ic,Footer:kc}}),Rs=({children:e,...t})=>{const{Template:n}=dt.useContext();return a.createElement(ks,{...t},a.createElement(n,null),e)},Bc=d.forwardRef(function({logLevel:t=q.LogLevel.WARN,language:n=nt,userSessionInfo:s,children:r,strings:o,...i},l){const[c]=d.useState(()=>new Qn(t));c.level!==t&&(c.level=t);const{nativeModules:u,chatParams:m={},...h}=i;return a.createElement(Is,{config:u},()=>a.createElement(Fc,{logger:c,theme:h.theme,language:n,strings:o},a.createElement(Jr,{language:n,logger:c,chatSDK:h.customChatSDK,chatParams:{...m,useMMKVStorageStore:u.mmkv},...h},a.createElement(aa,{ref:l,userSessionInfo:s},r))))}),Uc=Wr(ct,be,mn,dt,we,ot,rt,at,it,lt),Fc=({children:e,logger:t,theme:n,language:s,strings:r})=>a.createElement(pe.SafeAreaProvider,null,a.createElement(za,{logger:t,...n},a.createElement(Ba,{language:s,logger:t,strings:r},a.createElement(us,null,a.createElement(Ho,null,a.createElement(Uc,null,e)))))),{Provider:zc,useContext:gn}=j("FixedMessengerStyle"),$c={useNativeDriver:!0},We={OPEN_START:"0deg",OPEN_END:"-180deg",CLOSE_START:"180deg",CLOSE_END:"0deg"},Ke={VISIBLE:1,HIDDEN:0},Vc=({isOpened:e})=>{const t=d.useRef(new p.Animated.Value(e?1:0)).current;d.useEffect(()=>{const r=e?1:0;p.Animated.spring(t,{toValue:r,...$c}).start()},[e,t]);const n={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[We.OPEN_START,We.OPEN_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Ke.VISIBLE,Ke.HIDDEN]})}]},s={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[We.CLOSE_START,We.CLOSE_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Ke.HIDDEN,Ke.VISIBLE]})}]};return{openIconStyle:n,closeIconStyle:s}},qc=2/3,jc=({isOpened:e,onPress:t})=>{const n=Kc.use(),{launcherInfo:s,statsTrackers:r}=J();d.useLayoutEffect(()=>{r.initialRender.setPresentMethod("launcher_toggle")},[r]);const{theme:o}=z(),{launcherSize:i,horizontal:l}=gn(),c=Math.round(i*qc),u=o.colors.base.primary,m=o.colors.base.primaryContrastContent,{openIconStyle:h,closeIconStyle:g}=Vc({isOpened:e});return a.createElement(C,{alignSelf:l==="start"?"flex-start":"flex-end"},a.createElement(O,{onPress:t,activeOpacity:.8},({pressed:y})=>a.createElement(C,{style:[n.container({backgroundColor:u,size:i}),y&&n.pressed]},a.createElement(C.Animated,{style:[n.iconWrapper,h]},a.createElement(Gc,{url:(s==null?void 0:s.imageUrl)??"",isDefaultIcon:(s==null?void 0:s.type)==="default_icon",size:c,fillColor:m})),a.createElement(C.Animated,{style:[n.iconWrapper,g]},a.createElement(Wc,{size:c,fillColor:m})))))},Gc=({url:e,isDefaultIcon:t,size:n,fillColor:s})=>e?t?a.createElement(Ie,{source:{uri:e},width:n,height:n,tintColor:s,resizeMode:"contain"}):a.createElement(Ie,{source:{uri:e},width:n,height:n,resizeMode:"cover"}):a.createElement(B,{type:"delight",size:n,color:s}),Wc=({size:e,fillColor:t})=>a.createElement(B,{type:"chevron-down",size:e,color:t}),Kc=P.create(()=>({container:e=>({position:"relative",width:e.size,height:e.size,backgroundColor:e.backgroundColor,borderRadius:e.size/2,justifyContent:"center",alignItems:"center",boxShadow:"0px 8px 16px 0px rgba(33, 33, 33, 0.3)"}),pressed:{transform:[{scale:.9}]},iconWrapper:{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"}})),X={TRANSLATE_OFFSET:40,DURATION:300,OPACITY_DURATION:83,EASING:p.Easing.out(p.Easing.ease)},Yc=e=>e==="entered"?0:X.TRANSLATE_OFFSET,Xc=e=>e==="entered"?1:0,Zc=({transitionState:e,isActive:t})=>{const[n,s]=d.useState(!1),r=d.useRef(new p.Animated.Value(Yc(e))).current,o=d.useRef(new p.Animated.Value(Xc(e))).current;return d.useEffect(()=>{if(!n){e==="entered"?(r.setValue(0),o.setValue(1)):e==="exited"&&(r.setValue(X.TRANSLATE_OFFSET),o.setValue(0)),s(!0);return}e==="entering"?(r.setValue(X.TRANSLATE_OFFSET),o.setValue(0),p.Animated.parallel([p.Animated.timing(r,{toValue:0,duration:X.DURATION,easing:X.EASING,useNativeDriver:!0}),p.Animated.timing(o,{toValue:1,duration:X.OPACITY_DURATION,easing:X.EASING,useNativeDriver:!0})]).start()):e==="exiting"&&p.Animated.parallel([p.Animated.timing(r,{toValue:X.TRANSLATE_OFFSET,duration:X.DURATION,easing:X.EASING,useNativeDriver:!0}),p.Animated.timing(o,{toValue:0,duration:X.OPACITY_DURATION,easing:X.EASING,useNativeDriver:!0})]).start()},[e,r,o,n]),d.useMemo(()=>({position:"absolute",top:0,left:0,width:"100%",height:"100%",transform:[{translateY:r}],opacity:o,zIndex:t?999:1,pointerEvents:t?"auto":"none",display:e==="exited"?"none":"flex"}),[r,o,t,e])},Ms=d.createContext(null),Jc=()=>{const e=d.useContext(Ms);if(!e)throw new Error("useNavigatorContext() must be used within <Navigator />");return e},Ds=({children:e})=>{const t=Jc();return typeof e=="function"?a.createElement(a.Fragment,null,e(t)):a.createElement(a.Fragment,null,e)},Qc=d.memo(({transitionState:e,isActive:t,children:n})=>{const s=Zc({transitionState:e,isActive:t});return a.createElement(p.Animated.View,{style:s},n)}),Vn=300,Xe=({initialId:e,children:t})=>{const[n,s]=d.useState([e]),r=n[n.length-1],o=d.useCallback((_,v)=>{s(A=>[...A,_]),h(A=>({...A,[_]:!0})),v!=null&&v.reset&&E(A=>({...A,[_]:(A[_]||0)+1})),y(A=>({...A,[_]:"entering"})),setTimeout(()=>{y(A=>({...A,[_]:"entered"}))},Vn)},[]),i=d.useCallback(()=>{s(_=>{if(_.length<=1)return _;const v=_[_.length-1];return y(A=>({...A,[v]:"exiting"})),setTimeout(()=>{y(A=>({...A,[v]:"exited"})),s(A=>A.slice(0,-1))},Vn),_})},[]),l=d.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:r}),[o,i,r]),c=d.useMemo(()=>d.Children.toArray(t).filter(_=>_.type===Ds),[t]),u=d.useMemo(()=>{const _={};return c.forEach(v=>{const{id:A,lazy:S,children:T}=v.props;_[A]={lazy:S,element:typeof T=="function"?T(l):T}}),_},[c,l]),[m,h]=d.useState(()=>{const _={};return Object.entries(u).forEach(([v,{lazy:A}])=>{A===!1&&(_[v]=!0)}),_[e]=!0,_}),[g,y]=d.useState(()=>{const _={};return Object.keys(u).forEach(v=>{_[v]=v===e?"entered":"exited"}),_}),[b,E]=d.useState({});return a.createElement(Ms.Provider,{value:l},a.createElement(C,{style:{position:"relative",width:"100%",height:"100%"}},Object.keys(u).map(_=>{var T;if(!m[_])return null;const v=g[_]||"exited",A=_===r,S=`${_}-${b[_]||0}`;return a.createElement(Qc,{key:S,transitionState:v,isActive:A},(T=u[_])==null?void 0:T.element)})))};Xe.Screen=Ds;const{Provider:eu,useContext:hn}=j("PageChildren"),tu=({children:e})=>{const[t,n]=d.useState(null),[s,r]=d.useState(null);return a.createElement(eu,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:s,setConversationListChildren:r}},e)},fe={conv:"conv",convList:"conv-list"},nu=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:s,onClose:r})=>{const{conversationChildren:o,conversationListChildren:i}=hn(),l=t==="ConversationList"?fe.convList:fe.conv;return a.createElement(Xe,{initialId:l},a.createElement(Xe.Screen,{id:fe.conv},({navigation:c,activeScreenId:u})=>a.createElement(xs,{channelUrl:n,onClearChannelUrl:()=>s(void 0),onNavigateToConversationList:()=>c.navigate(fe.convList),onClose:r,shouldMarkAsRead:e&&u===fe.conv},o)),a.createElement(Xe.Screen,{id:fe.convList,lazy:!0},({navigation:c})=>a.createElement(Rs,{onNavigateToConversation:u=>{s(u),c.navigate(fe.conv,{reset:!0})},onClose:r},i)))},Oe=.15,su=150,qn=(e,t)=>e.interpolate({inputRange:[Oe,1],outputRange:[t,0],extrapolate:"clamp"}),ru=(e,t)=>{if(e<=0)return 0;const n=(1-Oe)*e/2,s=t==="start"?-1:1,r=p.I18nManager.isRTL?-1:1;return n*s*r},ou=(e,t)=>e<=0?0:(1-Oe)*e/2*(t==="top"?-1:1),au=({isOpened:e,horizontal:t,vertical:n})=>{const[s,r]=d.useState({width:0,height:0}),o=d.useRef(new p.Animated.Value(e?1:Oe)).current,i=d.useRef(new p.Animated.Value(e?1:0)).current,l=d.useMemo(()=>ru(s.width,t),[s.width,t]),c=d.useMemo(()=>ou(s.height,n),[s.height,n]),{translateXInterpolation:u,translateYInterpolation:m}=d.useMemo(()=>({translateXInterpolation:qn(o,l),translateYInterpolation:qn(o,c)}),[o,l,c]);d.useEffect(()=>{const y=e?"open":"close",b=y==="open"?1:Oe,E=y==="open"?1:0,_=y==="open"?p.Easing.out(p.Easing.quad):p.Easing.in(p.Easing.quad),v={duration:su,useNativeDriver:!0,easing:_};y==="close"&&p.Keyboard.dismiss(),p.Animated.parallel([p.Animated.timing(o,{toValue:b,...v}),p.Animated.timing(i,{toValue:E,...v})]).start()},[e,o,i]);const h=d.useMemo(()=>({opacity:i,transform:[{translateX:u},{translateY:m},{scale:o}]}),[i,u,m,o]),g=d.useMemo(()=>y=>{const{width:b,height:E}=y.nativeEvent.layout;r(_=>_.width===b&&_.height===E?_:{width:b,height:E})},[]);return{animatedStyle:h,handleLayout:g,pointerEvents:e?"auto":"none"}},iu={top:0,left:0,right:0,bottom:0},lu=({children:e,isOpened:t})=>{const n=cu.use(),{horizontal:s,vertical:r}=gn(),{animatedStyle:o,handleLayout:i,pointerEvents:l}=au({isOpened:t,horizontal:s,vertical:r});return a.createElement(pe.SafeAreaInsetsContext.Provider,{value:iu},a.createElement(C,{flex:1},a.createElement(C.Animated,{pointerEvents:l,onLayout:i,style:o},a.createElement(C,{style:n.windowContainer},e))))},cu=P.create(({theme:e})=>({windowContainer:{width:"100%",height:"100%",borderRadius:16,overflow:"hidden",zIndex:999,backgroundColor:e.colors.base.background,boxShadow:"0px 4px 24px 0px rgba(0, 0, 0, 0.12)"}})),Ls=()=>{const[e,t]=d.useState(0);return d.useEffect(()=>{const n=p.Platform.OS==="ios"?"keyboardWillShow":"keyboardDidShow",s=p.Platform.OS==="ios"?"keyboardWillHide":"keyboardDidHide",r=p.Keyboard.addListener(n,i=>{const{endCoordinates:l}=i,c=(l==null?void 0:l.height)||0;t(c)}),o=p.Keyboard.addListener(s,()=>{t(0)});return()=>{r.remove(),o.remove()}},[]),e},uu=e=>{const t=d.useRef(new p.Animated.Value(0)).current,[n,s]=d.useState(!1);return d.useEffect(()=>{const o=e?"open":"close",i={toValue:o==="open"?1:0,useNativeDriver:!0,duration:300};o==="open"&&s(!0),p.Animated.timing(t,i).start(()=>{o==="close"&&(s(!1),p.Keyboard.dismiss())})},[e,t]),{windowAnimatedStyle:{opacity:t,display:n?"flex":"none"},pointerEvents:e?"auto":"none"}},du=({children:e,insets:t,isOpened:n})=>{const s=mu.use(),o={...pe.useSafeAreaInsets(),...t},i=Ls(),{windowAnimatedStyle:l,pointerEvents:c}=uu(n);return a.createElement(pe.SafeAreaInsetsContext.Provider,{value:o},a.createElement(C.Animated,{flex:1,style:[s.bg,l],pointerEvents:c},a.createElement(C,{flex:1},e),a.createElement(C,{height:Math.max(0,i-p.Platform.select({android:0,default:o.bottom})),style:s.bg})))},mu=P.create(({theme:e})=>({bg:{backgroundColor:e.colors.base.background}})),gu="end-bottom",Me={top:24,bottom:24,start:24,end:24},hu=({mode:e,edgeToEdgeEnabled:t})=>{const n=e==="floating"?lu:du,[s,r]=Ht({position:gu,margin:Me,launcherSize:48,spacing:12}),{bottom:o}=pe.useSafeAreaInsets(),i=Ls(),[l,c]=s.position.split("-"),u=(()=>{const g=p.Platform.select({android:t?o:0,default:0}),y=c==="top"?s.spacing:-s.launcherSize,b=i>0?i+y+g:0;return b>0?b:s.margin.bottom})(),m={position:"absolute",zIndex:1e3,...c==="top"?{top:s.margin.top}:{bottom:s.margin.bottom},...l==="start"?{left:s.margin.start}:{right:s.margin.end}},h=(()=>{if(e==="floating"){const g=s.launcherSize+s.spacing;return{position:"absolute",top:s.margin.top+(c==="top"?g:0),bottom:u+(c==="bottom"?g:0),left:s.margin.start,right:s.margin.end,zIndex:999}}return{position:"absolute",top:0,bottom:0,left:0,right:0,zIndex:1001}})();return{Window:n,windowContainerStyle:h,launcherContainerStyle:m,styleContext:{...s,horizontal:l,vertical:c,setPosition:g=>r({position:g}),setMargin:({top:g=Me.top,bottom:y=Me.bottom,start:b=Me.start,end:E=Me.end})=>r({margin:{top:g,bottom:y,start:b,end:E}}),setLauncherSize:g=>r({launcherSize:g}),setSpacing:g=>r({spacing:g})}}},_u=e=>{var o,i,l,c;const{setPosition:t,setMargin:n,setLauncherSize:s,setSpacing:r}=gn();return d.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n(e.margin),e.launcherSize!==void 0&&s(e.launcherSize),e.spacing!==void 0&&r(e.spacing)},[e.position,(o=e.margin)==null?void 0:o.top,(i=e.margin)==null?void 0:i.bottom,(l=e.margin)==null?void 0:l.start,(c=e.margin)==null?void 0:c.end,e.launcherSize,e.spacing]),null},fu=({children:e})=>{const{setConversationChildren:t}=hn();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},pu=({children:e})=>{const{setConversationListChildren:t}=hn();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},yu=({entryPoint:e="Conversation",edgeToEdgeEnabled:t=!0,windowMode:n="floating",fullscreenInsets:s,initialChannelUrl:r,windowContainerProps:o,children:i})=>{const[l,c]=d.useState(!1),[u,m]=d.useState(r),{Window:h,windowContainerStyle:g,launcherContainerStyle:y,styleContext:b}=hu({mode:n,edgeToEdgeEnabled:t});return d.useEffect(()=>{const E=p.BackHandler.addEventListener("hardwareBackPress",()=>l?(c(!1),!0):!1);return()=>E.remove()},[l]),a.createElement(zc,{value:b},a.createElement(tu,null,a.createElement(C,{style:g,backgroundColor:"transparent",pointerEvents:l?"auto":"box-none",...o},a.createElement(h,{isOpened:l,insets:s},a.createElement(nu,{isOpened:l,entryPoint:e,selectedChannelUrl:u,setSelectedChannelUrl:m,onClose:()=>c(!1)}))),a.createElement(C,{style:y,backgroundColor:"transparent",pointerEvents:"box-none"},a.createElement(jc,{isOpened:l,onPress:()=>c(!l)})),i))},bu=Object.assign(yu,{Style:_u,ConversationChildren:fu,ConversationListChildren:pu});var jn,Gn;ns.set(q.SendbirdPlatform.REACT_NATIVE,{deviceOSPlatform:(jn=p.Platform)==null?void 0:jn.select({ios:q.DeviceOsPlatform.IOS,android:q.DeviceOsPlatform.ANDROID,default:q.DeviceOsPlatform.ANDROID}),deviceOSVersion:(Gn=p.Platform)!=null&&Gn.Version?String(p.Platform.Version):void 0,messengerVersion:Ko,keyValueStorage:qr()});exports.AIAgentProviderContainer=Bc;exports.AnonymousSessionInfo=Je;exports.BottomSheet=Z;exports.BottomSheetLayout=rt;exports.Conversation=xs;exports.ConversationContext=ha;exports.ConversationContextProvider=cs;exports.ConversationHeaderLayout=be;exports.ConversationLayout=ct;exports.ConversationList=Rs;exports.ConversationListContext=Ec;exports.ConversationListContextProvider=ks;exports.ConversationListHeaderLayout=we;exports.ConversationListLayout=dt;exports.DeskTicketPriority=tn;exports.DeskTicketStatus=en;exports.FixedMessenger=bu;exports.IncomingMessageLayout=at;exports.ManualSessionInfo=Jt;exports.MessageListUILayout=mn;exports.ModalProvider=us;exports.NativeAdapterProvider=Is;exports.OutgoingMessageLayout=it;exports.PlaceholderLayout=ot;exports.SystemMessageLayout=lt;exports.useConversationContext=oe;exports.useConversationListContext=ut;exports.useMessengerSessionContext=J;exports.useModalContext=st;exports.useNativeAdapterContext=As;
|
|
1
|
+
"use strict";var Or=Object.defineProperty;var Nr=(e,t,n)=>t in e?Or(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var f=(e,t,n)=>Nr(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react-native"),q=require("@sendbird/chat"),d=require("react"),ye=require("react-native-safe-area-context"),X=require("@sendbird/chat/aiAgent"),Ae=require("date-fns"),Ie=require("@sendbird/chat/message"),Ne=require("@sendbird/chat/groupChannel"),Qe=require("@sendbird/uikit-tools"),Hr=require("date-fns/isSameDay"),Br=require("date-fns/locale/de"),Ur=require("date-fns/locale/en-US"),Fr=require("date-fns/locale/es"),zr=require("date-fns/locale/fr"),$r=require("date-fns/locale/hi"),Vr=require("date-fns/locale/it"),qr=require("date-fns/locale/ja"),jr=require("date-fns/locale/ko"),Gr=require("date-fns/locale/pt"),Wr=require("date-fns/locale/tr"),Kr=require("@react-native-clipboard/clipboard"),Yr=require("react-native-code-highlighter"),Xr=require("react-native-markdown-display"),rt=e=>e&&e.__esModule?e:{default:e};function Zr(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 Jr=rt(q),a=Zr(d),Qr=rt(Kr),es=rt(Yr),ts=rt(Xr),Se="sb-agent",Kn="KEY_IMG_ASPECT_RATIO",Yn="*/*",D={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},ce=e=>!!e&&"sender"in e,ns=e=>ce(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),rs=(e,t,n,r=!0)=>{if(!r||!ce(e))return"single";const s=()=>{if(!t||!ce(t))return!1;const c=t.sender.userId===e.sender.userId,u=Ae.isSameMinute(t.createdAt,e.createdAt);return c&&u},o=()=>{if(!n||!ce(n))return!1;const c=n.sender.userId===e.sender.userId,u=Ae.isSameMinute(n.createdAt,e.createdAt);return c&&u},i=s(),l=o();return i&&l?"middle":i?"bottom":l?"top":"single"},Ue=(e,t)=>(()=>{var r;return ce(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,$e={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>ce(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>ce(e)&&(e.sender.userId===t||e.sendingStatus===Ie.SendingStatus.PENDING)},ss=e=>e.startsWith("image/"),Qt=(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"},Xn=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},en=e=>{switch(e){case"top":case"middle":return D.GAP_GROUPED;default:return D.GAP_UNGROUPED}},os=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...i)=>{const[l,c,u]=i;return s<u&&r.push({type:"text",value:e.slice(s,u).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),s=u+o.length,o}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),r},as=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),is=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),ls=e=>e.replace(/~~/g,"\\~\\~"),cs=e=>{let t=e;return t=as(t),t=is(t),t=ls(t),t},us=typeof navigator<"u"&&navigator.product==="ReactNative",bn=(e,t)=>{const n=r=>!t||t.length===0?!0:ce(r)&&t.includes(r.sendingStatus);return us?e.find(n):e.findLast(n)};function Nt(){}function ds(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 Cn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ze={isStreaming(e){const t=Cn(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(Ue(e,t)){const r=Cn(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)}},pt=`@${Se}`,ms=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${pt}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=ds(`${e}/${t}/${s}`);return`${pt}-udata/${o}`},anonUserSession:()=>`${pt}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Zn=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:l=!0}=n,c=(...u)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...u),o=m):(s=u,o=m);else if(s=u,l&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&l&&(e(...s),o=Date.now()),r=null,s=null},h)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},c};class Jn{constructor(t,{filter:n,limit:r=20}){f(this,"filter");f(this,"_sdk");f(this,"_pinnedChannels");f(this,"_channels");f(this,"_isDisposed",!1);f(this,"_handlerId",`handler-id-${Date.now()}`);f(this,"_order",Ne.GroupChannelListOrder.LATEST_LAST_MESSAGE);f(this,"_limit");f(this,"_query");f(this,"_token");f(this,"_timestamp");f(this,"_isSyncing");f(this,"_channelHandler");f(this,"_connectionHandler");f(this,"_collectionEventHandler");f(this,"_throttledOnChannelChanged");var s,o,i,l,c,u,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:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.pinnedChannelUrls,copilotConversationOnly:(u=this.filter)==null?void 0:u.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=Zn(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new Ne.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new q.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,i;const n=new Set(((o=this.filter)==null?void 0:o.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.url));let s;r?s=((i=r.lastMessage)==null?void 0:i.createdAt)??r.createdAt:s=this._query.lastResponseAt,this._timestamp>s&&(this._timestamp=s)}async _syncChannelChangelogs(){if(this._isDisposed)return[];if(this._isSyncing)return[];try{this._isSyncing=!0;let t;for(this._token?t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter):t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByTimestamp(this._timestamp,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls);t.hasMore&&t.token;)t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls)}catch{}finally{this._isSyncing=!1}return[]}_upsertPinnedChannelsToArray(t){var l;const n=((l=this.filter)==null?void 0:l.pinnedChannelUrls)??[],r=new Map(n.map((c,u)=>[c,u])),s=[],o=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const u=r.get(c.url);if(u===void 0)continue;const m=Ht(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),o.push(c)):s.push(c);const g=this._pinnedChannels.findIndex(C=>(r.get(C.url)??1/0)>u),y=g===-1?this._pinnedChannels.length:g;this._pinnedChannels.splice(y,0,c)}return{addedChannels:s,updatedChannels:o,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const r=[],s=[],o=[];for(const i of t){if(!this._query.belongsTo(i)){r.push(i.url);continue}const l=Ht(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=gs(this._channels,i,this._order).place,h=m===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(i),s.push(i)):(this._channels.splice(m,0,i),s.push(i)):(this._channels.splice(m,0,i),o.push(i))}return{addedChannels:s,updatedChannels:o,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var h,g,y,C,E;const r=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),s=[],o=[];for(const _ of t)r.has(_.url)?s.push(_):o.push(_);const i=this._upsertPinnedChannelsToArray(s),l=this._upsertRegularChannelsToArray(o,n),c=i.addedChannels.concat(l.addedChannels),u=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((y=(g=this._collectionEventHandler)==null?void 0:g.onChannelsAdded)==null||y.call(g,{},c)),u.length>0&&((E=(C=this._collectionEventHandler)==null?void 0:C.onChannelsUpdated)==null||E.call(C,{},u)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var s,o,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(u=>u.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(u=>u.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((i=(o=this._collectionEventHandler)==null?void 0:o.onChannelsDeleted)==null||i.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 Ht=(e,t)=>e.findIndex(n=>n.isIdentical(t)),gs=(e,t,n)=>{if(e.length>0){const r=Ht(e,t);let s=0,o=e.length-1,i=Math.floor((s+o)/2);for(;s<o;){const c=En(e[i],t,n);if(c>0)o=i,i=Math.floor((s+o)/2);else if(c<0)s=i+1,i=Math.floor((s+o)/2);else return{place:i,oldPosition:r}}return{place:En(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},En=(e,t,n)=>{switch(n){case Ne.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 hs{constructor(t){f(this,"subscribers",{});this.logger=t}async send(t){const n=_s(),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 _s=()=>{let e=Nt,t=Nt;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var se=(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))(se||{});class Fe{constructor(t={}){f(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const He={CloseConversation:e=>new fs(e),MessengerSettingsUpdated:e=>new ps(e),ActiveChannelUpdated:e=>new ys(e),AnonymousSessionTokenExpired:()=>new bs,AuthTokenRefreshed:()=>new Cs};class fs extends Fe{constructor(){super(...arguments);f(this,"type","conv.close")}}class ps extends Fe{constructor(){super(...arguments);f(this,"type","messenger.settings.updated")}}class ys extends Fe{constructor(){super(...arguments);f(this,"type","active.channel.updated")}}class bs extends Fe{constructor(){super(...arguments);f(this,"type","anon.token.expired")}}class Cs extends Fe{constructor(){super(...arguments);f(this,"type","auth.token.refreshed")}}var tn=(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))(tn||{});class Qn{constructor(t){f(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Se}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Se}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Se}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Se}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Se}/error]`,...t)}}class nn{constructor({userId:t,authToken:n,sessionHandler:r}){f(this,"userId");f(this,"authToken");f(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class et{constructor(){f(this,"userId");f(this,"authToken");f(this,"sessionHandler")}}const Es=e=>({onSessionTokenRequired:t=>{t(null),e.send(He.AnonymousSessionTokenExpired())}}),vs="ai_agent:stats",Ss="conversation_initial_render",As=800220;var $=(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))($||{});class Is{constructor(){f(this,"timers",new Map);f(this,"committed",!1);f(this,"commitCallback",null);f(this,"conversationId",null);f(this,"channelUrl",null);f(this,"errorCode",null);f(this,"errorDescription",null);f(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??As,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(vs,t)):!1}}class Ts extends Is{constructor(){super(...arguments);f(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Ss}buildPayload(){const n=this.getDuration($.AUTH),r=this.getDuration($.GET_CHANNEL),s=this.getDuration($.GET_MESSAGES),o=this.getDuration($.TOTAL_DURATION_FROM_CACHE),i=this.getDuration($.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...s!==null&&{get_messages_duration:s},...o!==null&&{total_duration_from_cache:o}},c={key:this.getMetricKey(),value:i!==null?String(i):"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 ws{constructor(t){f(this,"commitCallback");f(this,"presentMethod","direct_present");f(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Ts().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer($.TOTAL_DURATION).startTimer($.TOTAL_DURATION_FROM_CACHE).startTimer($.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer($.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer($.AUTH).setError(t instanceof q.SendbirdError?t.code:void 0,t.message).stopTimer($.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer($.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer($.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer($.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer($.GET_CHANNEL).setError(t instanceof q.SendbirdError?t.code:void 0,t.message).stopTimer($.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof q.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer($.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof q.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer($.TOTAL_DURATION).stopTimer($.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 xs(){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 he={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}}},vn=e=>{var t,n,r,s,o,i,l,c,u,m,h,g,y,C;return e?{...he,...e,conversation:{...he.conversation,...e==null?void 0:e.conversation,header:{...(t=he.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(r=he.conversation)==null?void 0:r.input,...(s=e==null?void 0:e.conversation)==null?void 0:s.input,camera:{...(i=(o=he.conversation)==null?void 0:o.input)==null?void 0:i.camera,...(c=(l=e==null?void 0:e.conversation)==null?void 0:l.input)==null?void 0:c.camera},gallery:{...(m=(u=he.conversation)==null?void 0:u.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:{...(y=he.conversation)==null?void 0:y.fileViewer,...(C=e==null?void 0:e.conversation)==null?void 0:C.fileViewer}}}:he},ue=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===X.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},er=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===X.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function be(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 ks(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!be(e):!1}function Rs(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Sn(e){return!!e&&e<Date.now()}function Ms(e){return!e.title}function Ds(e,t){var n;if(e)return Ms(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 Ls{constructor(){f(this,"_channelHandlerId",null);f(this,"_connectionHandlerId",null);f(this,"_handleActiveChannelChangedThrottled",null);f(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Zn(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:ue(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 Ne.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new q.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})});f(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")});f(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:ue(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});f(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)}});f(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(se.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(se.MessengerSettingsUpdated,t)}));f(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(se.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(se.ActiveChannelUpdated,t)}));f(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(se.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(se.AuthTokenRefreshed,t)}))}}class Ps{constructor(t){f(this,"_sdkUser");f(this,"_userSession");f(this,"_dispatcher");f(this,"_activeChannel");f(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(He.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});f(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(He.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 Os=e=>JSON.parse(e);var Bt=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Bt||{});const tr=e=>typeof e=="object"&&e!==null,An=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Ns=e=>!tr(e)||!An(e,"channel_url")||!An(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Hs={1:Ns};function Bs(e){if(!tr(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Hs[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Us(e,t,n,r){const s=Jr.default.init({appId:e,modules:[new Ne.GroupChannelModule,new X.AIAgentModule],localCacheEnabled:!0,options:new q.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:q.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Fs(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 zs=[400300,400301,400302,400310];class rn{constructor(t,n,r){f(this,"chatSDK");f(this,"_logger");f(this,"_cache");f(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const o=new q.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(o),this.chatSDK.aiAgent.addEventHandler(Bt.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),i=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",i);const l=Bs(i);(l==null?void 0:l.category)===Bt.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(c=n==null?void 0:n.onExternalAuthTokenExpired)==null||c.call(n,l.data))})}try{return await this.chatSDK.connect(t.userId,t.authToken),await this._syncTemplatesIfNeeded(),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(o){const i=o;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(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",i.message,i.code),i}});f(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")});f(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));f(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));f(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));f(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});f(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,l)=>t==null?void 0:t(i,l)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});f(this,"_isCacheRestrictedError",t=>zs.some(n=>t.code===n));f(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of o){const{key:c}=Os(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(Fs(t.chatSDK),n=t.chatSDK):n=Us(t.appId,t.extensions,t.messengerVersion,t.chatParams),new rn(n,t.logger,t.cache)}}const Ve=new Map,nr={set:(e,t)=>{Ve.set(e,t)},get:e=>{if(Ve.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=Ve.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Ve.entries().next().value;return{platform:t[0],...t[1]}}},$s=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));class In extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);f(this,"status");f(this,"code");f(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var sn=(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))(sn||{}),on=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(on||{}),rr=(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))(rr||{});const Vs=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class qs{constructor(t){f(this,"_appId");f(this,"_apiHost");f(this,"_logger");f(this,"_credential",null);f(this,"_authRefreshPromise",null);f(this,"_onDeskTokenRefreshRequired",async()=>!1);f(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)});f(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});f(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});f(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Vs(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});f(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}});f(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))}:{}}));f(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));f(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));f(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));f(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new In(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new In(t.status,{})}});f(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 tt{constructor(t,n){f(this,"id");f(this,"title");f(this,"status");f(this,"agent");f(this,"priority");f(this,"group");f(this,"firstResponseTime");f(this,"issuedAt");f(this,"customFields");f(this,"_client");f(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 tt({id:t.id,title:t.channelName??null,status:t.status2??sn.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??on.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 an{constructor(t){f(this,"_logger");f(this,"_apiClient");f(this,"_onDeskTokenRefreshRequired");f(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);f(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}});f(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});f(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")});f(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return tt._fromResponse(n,this)});f(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:$s({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 tt._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new qs(t)}static init(t){return new an(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}function js(){const e={};return{get:t=>e[t]??null,set:(t,n)=>{e[t]=n},delete:t=>{delete e[t]},getKeys:t=>Object.keys(e).filter(n=>n.startsWith(t))}}function sr(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 Gs=1440*60*1e3;function fe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Ws(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class nt extends Ls{constructor(n){super();f(this,"appId");f(this,"aiAgentId");f(this,"_chatClient");f(this,"_deskClient");f(this,"_cache");f(this,"_logger");f(this,"_dispatcher");f(this,"_session",null);f(this,"language");f(this,"countryCode");f(this,"context");f(this,"queryParams");f(this,"_config");f(this,"_networkStateAdapter");f(this,"_forceCreateChannel");f(this,"_agentVersion");f(this,"_statsTrackers");f(this,"_operationQueue",xs());f(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"))});f(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));f(this,"authenticate",n=>{const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,l,c,u,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(He.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=s.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=o==null?void 0:o.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let g;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."),g={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:E,session_token:_,expire_at:v}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:E,authToken:_,expireAt:v}),g={userId:E,authToken:_},this._logger.debug("AIAgent.authenticate: anonymous user created",E)}else g={userId:((u=s.userSessionCandidate)==null?void 0:u.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,h),this._dispatcher.send(He.MessengerSettingsUpdated({settings:h,source:"server"}));const y=(()=>{var E;return s.type==="anonymous"?Es(this._dispatcher):(E=s.userSessionCandidate)==null?void 0:E.sessionHandler})(),C=await this._chatClient.connect(g,y,E=>{var _;this._logger.debug("AIAgent: session token refreshed"),(_=this._session)==null||_._updateAuthToken(E),this._deskClient.refreshDeskAuthToken(E)},()=>{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:E})=>{var _;if(E===rr.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const v=(_=this._session)==null?void 0:_.userSession.authToken;return v?await this._deskClient.refreshDeskAuthToken(v):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Ps({sdkUser:C,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}})});f(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")}));f(this,"createConversation",async n=>{fe(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});f(this,"searchConversation",async n=>{if(fe(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:X.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)Ws(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});f(this,"closeConversation",async n=>{var s;fe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===X.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:X.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});f(this,"createConversationListCollection",n=>new Jn(this.chatSDK,n??{}));f(this,"patchContext",async(n,r)=>{fe(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??{}}});f(this,"updateContext",async(n,r)=>{fe(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??{}}});f(this,"getContextObject",async n=>{fe(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??{}}});f(this,"refreshActiveChannel",async n=>{var i,l;fe(this._session);const r=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:r});const s=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:this._session.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:r?(l=(i=this._cache.messenger.getSettings(this._session.userSession.userId))==null?void 0:i.active_channel)==null?void 0:l.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion}),o=s.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,s),this._session._updateActiveChannel({url:o,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",o),o});f(this,"_getSessionCandidate",n=>n instanceof nn?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof et?{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});f(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Gs<=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});f(this,"_getManualSessionInfo",n=>{if(!n||n instanceof et)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=vn(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 ws((r,s)=>this._chatClient.chatSDK.aiAgent.appendStat(r,s))}}static init(n){var h;const r=nr.get(n.platform),s=n.logger??new Qn(n.logLevel??tn.WARN),o=n.dispatcher??new hs(s),i=n.useMMKVStorage?sr(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=ms({appId:n.appId,aiAgentId:n.aiAgentId,storage:i}),u=rn.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:s,cache:c}),m=an.init({appId:n.appId,logger:s,customApiHost:(h=n.deskParams)==null?void 0:h.customApiHost});return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new nt({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:u,deskClient:m,cache:c,logger:s,dispatcher:o})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=vn(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 W=(e,t)=>{const n=d.createContext(null),r=({children:i,value:l})=>a.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),s=({children:i})=>a.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),o=()=>{const i=d.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function oe(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,l]=d.useState(()=>e.template),[c,u]=d.useState(e.components),m={Template:i,updateTemplate:h=>l(()=>h),components:c,updateComponent:(h,g)=>u(y=>({...y,[h]:g}))};return a.createElement(t.Provider,{value:m},o)}function r({template:o,children:i}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{o&&l(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>d.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(o,l)},[l]),null}}),s}function Ks(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function Ys(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage()||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 Xs(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=Ae.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):Ae.isToday(s)?n.hoursAgo(Ae.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Zs=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},qe=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),yt=(e,t)=>{const n=qe(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=Zs(e);return r?`#${qe(r[0])}${qe(r[1])}${qe(r[2])}${n}`:e},or=W("AIAgent"),Js=or.Provider,K=or.useContext;function Qs(e){const t=eo(e);return a.createElement(Js,{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 eo(e){const t=d.useRef(null),n=d.useRef(null);if(!t.current||!n.current)t.current=nt.init(e);else{const s=to(n.current,e);(s.appId||s.aiAgentId||s.chatSDK)&&(t.current.dispose(),t.current=nt.init({...e,chatParams:s.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,d.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 to(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 no=(e,t,n)=>Qe.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),Ut={DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function ar(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function ro(e){const t=ar(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function so(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function oo(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,l=0;const c=(r+s)/2;return r!==s&&(l=c>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,l,c]}function ao(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=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=i(c,l,e+1/3),s=i(c,l,e),o=i(c,l,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function je(e,t,n){const[r,s,o]=ro(e),[i,l,c]=oo(r,s,o),u=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,g,y]=ao(i,m,u);return so([Math.round(h),Math.round(g),Math.round(y)])}function io(e,t="light"){return{extraDark:je(e,.6,1.2),dark:je(e,.85,1.1),main:e,light:je(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:je(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Tn(e){const t=ar(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?Ut.BLACK:Ut.WHITE}function lo(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 co=(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}}),Ge={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, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},bt={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 wn(e){const t=uo(e),{colors:n,aiAgentColorVariables:r}=mo(e,t),s=ho(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:s}}function uo({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ge.primary.main?Ge.primary:io(n,e):Ge.primary;return{...Ge,primary:r,...t}}function mo({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??Tn(o),l=n??Ut.DEFAULT_BOT_MSG_BG,c=r??Tn(l);return{colors:(e==="light"?lo:co)(s,o,i,l,c),aiAgentColorVariables:{primary_color:o,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function go(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function ho({typography:e}){if(!e)return bt;const t={...bt};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=bt[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=go(s,r,o)}}),t}const{Provider:_o,useContext:fo}=W("AIAgentTheme");function po({logger:e,palette:t,typography:n,appearance:r,children:s}){const o=d.useRef(null),[i,l]=d.useState(()=>wn({selectedTheme:(r==null?void 0:r.theme)??"light",palette:t,typography:n,primary:r==null?void 0:r.primaryColor,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor})),c=d.useCallback((u,m)=>{m&&(o.current=m);const h=(r==null?void 0:r.theme)??u,g=o.current?o.current.themes[h]:null,y={primary:r==null?void 0:r.primaryColor,primaryContrast:void 0,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!y.primary&&(g!=null&&g.primary_color)&&(y.primary=g.primary_color,y.primaryContrast=g.primary_contrast_color),!y.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(y.botMessageBackground=g.bot_message_bg_color,y.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const C=wn({selectedTheme:h,palette:t,typography:n,...y});l(C),e==null||e.info("theme.update:",h)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor,t,n,e]);return d.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&c(i.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),a.createElement(_o,{value:{theme:i,updateTheme:c}},s)}const Ct=25*1024*1024,xn=1,kn=new Set(["image/png","image/jpeg","image/jpg"]),Rn=new Set(["application/pdf"]),yo={off:"off",always:"always",handed_off_only:"handed_off_only"},bo=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:xn,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Ct,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:kn,supportedFileMimeTypes:Rn})),n=d.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??xn,attachmentMode:yo[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Ct,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)??kn),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Rn)})},[]),r=d.useCallback(s=>{const{channel:o,uploadSizeLimit:i=Ct}=s,l=(u=!0)=>o!=null&&o.isAIAgent?u?be(o):!1:!0,c=u=>{if(l())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(u)??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 be(o);default:return!0}},get supportedMimeTypes(){return l()?[Yn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:u=>l()?!0:e.supportedImageMimeTypes.has(u)||e.supportedFileMimeTypes.has(u),getUploadSizeLimit:c,getUploadSizeLimitInMB:u=>c(u)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},Mn=(...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)")},Me=e=>({...e,context:e.context??{}}),{Provider:Co,useContext:ze}=W("AIAgentMessengerSession"),Eo=d.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=K(),{updateTheme:l}=fo(),[c,u]=d.useState(void 0),[m,h]=d.useState(void 0),[g,y]=d.useState(null),[C,E]=d.useState(null),[_,v]=d.useState(null),[A,S]=d.useState(null),{updateBaseAttachmentRules:T,createAttachmentRules:w}=bo();d.useEffect(()=>{const x=r.onMessengerSettingsUpdated(({settings:H})=>{const{appearance:j,bot:B,launcher:Ee}=H;l(j.selected_theme,j),v({userId:B.bot_userid,profileUrl:B.bot_profile_url,nickname:B.bot_nickname,replyToFile:B.reply_to_file,specialNotice:B.special_notice,specialNoticeEnabled:B.is_special_notice_enabled,showHandoffButton:B.show_handoff_button??!0,isMultipleActiveConversationsEnabled:B.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:B.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:B.is_user_feedback_comment_option_enabled??!1}),S({type:Ee.image_type||"default_icon",imageUrl:Ee.image_url}),T(H)}),M=r.onActiveChannelUpdated(({channelUrl:H,status:j,conversationStatus:B})=>{h({url:H,status:j,conversationStatus:B})}),I=r.onAuthTokenRefreshed(()=>{var j;const H=(j=r.session)==null?void 0:j.userSession.authToken;H&&E(B=>B?{...B,authToken:H}:null)});return()=>{x(),M(),I()}},[r,l,T]);const R=d.useCallback(async()=>{u(void 0);try{const x=await r.authenticate(e),M=r.session;return y(M.sdkUser),E(M.userSession),h(M.activeChannel),x}catch(x){throw u(x),x}},[r,e]),O=d.useCallback(async()=>{await r.deauthenticate(),y(null),h(void 0),E(null),v(null),S(null)},[r]),Z=d.useCallback(async()=>{if(!r.session)throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready");return h(void 0),await r.refreshActiveChannel()},[r,i]),ne=d.useCallback(async x=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.createConversation(x)},[r]),Y=d.useCallback(async x=>{if(!r.session)throw new Error("Current user is not authenticated. Please authenticate first.");return r.searchConversation(x)},[r]);return d.useImperativeHandle(n,()=>{const x=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:R,deauthenticate:O,updateContext:async(...M)=>{const I=Mn(...M);if(I.type==="active"){const B=await(await x()).updateContext(o,I.context);return Me(B)}const H=await s.aiAgent.updateContext(I.aiAgentId,I.channelUrl,I.context);return Me(H)},patchContext:async(...M)=>{const I=Mn(...M);if(I.type==="active"){const B=await(await x()).patchContext(o,I.context);return Me(B)}const H=await s.aiAgent.patchContext(I.aiAgentId,I.channelUrl,I.context);return Me(H)},getContextObject:async()=>{const I=await(await x()).getContextObject(o);return Me(I)}}},[R,O,m,s,o,i]),a.createElement(Co,{value:{sdkUser:g,userSessionInfo:e,userSession:C,activeChannel:m,setActiveChannel:h,refreshActiveChannel:Z,createConversation:ne,searchConversation:Y,connectionError:c,aiAgentInfo:_,launcherInfo:A,authenticate:R,deauthenticate:O,createAttachmentRules:w,statsTrackers:r.statsTrackers}},t)}),ln=(e,t)=>{const n=d.useId(),r=d.useRef(t);d.useLayoutEffect(()=>{r.current=t}),d.useEffect(()=>{const s=new q.ConnectionHandler({onDisconnected:o=>{var i,l;return(l=(i=r.current).onDisconnected)==null?void 0:l.call(i,o)},onConnected:o=>{var i,l;return(l=(i=r.current).onConnected)==null?void 0:l.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,l;return(l=(i=r.current).onConnectionDelayed)==null?void 0:l.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])};function vo(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:s}=K(),{sdkUser:o,statsTrackers:i}=ze(),l=Qe.useForceUpdate(),[c,u]=d.useState(void 0),[m,h]=d.useState(void 0),[g,y]=d.useState(!1);function C(_){_.isAIAgent&&!_.conversation&&(y(!0),s.initConversationIfNeeded(_).finally(()=>y(!1)))}async function E(){var _,v,A;if(!o){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),u(void 0),h(void 0),y(!1),e){i.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const S=await t.groupChannel.getChannel(e);C(S),u(S),i.initialRender.onGetChannelComplete((_=S.conversation)==null?void 0:_.id),S.url===((v=s.session)==null?void 0:v.activeChannel.url)&&s.session._updateActiveChannel({url:S.url,status:ue(S)?"closed":"open",conversationStatus:(A=S.conversation)==null?void 0:A.status}),n.debug("useChannel.getChannel: fetched channel",S)}catch(S){i.initialRender.onGetChannelError(S),S instanceof q.SendbirdError&&h(S),n.error("useChannel.getChannel: error",S)}}}return d.useEffect(()=>{E()},[t,o,e,r]),ln(t,{async onReconnectSucceeded(){if(!c)return;const _=await c.refresh();C(_),u(_)}}),Qe.useGroupChannelHandler(t,{onChannelChanged:_=>{_.isGroupChannel()&&_.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",_.url),u(_),l())}}),{channel:c,channelFetchError:m,getChannel:E,isInitializingConversation:g}}const So=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload;return n==null?void 0:n.user_input_disabled_by},Ao=e=>{var i;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&&!!((i=e.conversation)!=null&&i.handedOverAt);return s&&!o},Io=()=>{const{chatSDK:e,networkStateAdapter:t}=K(),[n,r]=d.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return ln(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),d.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===q.ConnectionState.OPEN?"connected":o)})},[t,e]),n},To=3e4,wo=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=d.useState(!1),i=d.useRef(null),l=t&&Ue(t,r)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},u=g=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},g)},m=Date.now()-l,h=To-m;return n||h<=0?c():u(h),()=>{i.current&&clearTimeout(i.current)}},[n,l]),s&&e},ir=e=>{const{chatSDK:t}=K(),[n,r]=d.useState([]);return Qe.useGroupChannelHandler(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},xo=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=d.useState(!1),i=ir(e);return d.useEffect(()=>{if(!t)return;const l=i.some(u=>u.userId===n),c=Ue(t,n)&&(Ze.isStreaming(t)||r);o(c||l)},[i,t,n,r]),s},ko=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ze(),i=Io(),l=xo({channel:e,lastMessage:bn(t,[Ie.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),c=wo({shouldApply:!!(e!=null&&e.isAIAgent)&&!be(e),isBlockedWhileAIResponding:l,lastMessage:bn(t,[Ie.SendingStatus.PENDING,Ie.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""});if(!e||i==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(i==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(ue(e))return{disabled:!0,disabledBy:"conversation_closed"};if(ks(e))return{disabled:!0,disabledBy:"handoff_pending"};if(Ao(e))return{disabled:!0,disabledBy:"form_active"};const u=So(e);return u?{disabled:!0,disabledBy:u}:l||c||r?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},Ro=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(s=>{t(o=>{if(o.has(s))return o;const i=new Set(o);return i.add(s),i})},[]),r=d.useCallback(s=>{t(o=>{if(!o.has(s))return o;const i=new Set(o);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Mo}=W("AIAgentConversation");function Do({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Nt,shouldMarkAsRead:u=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var Y;const g=()=>u&&(_==null?void 0:_.markAsRead()),{chatSDK:y,logger:C,dispatcher:E}=K(),{channel:_,channelFetchError:v,getChannel:A,isInitializingConversation:S}=vo(t),{statsTrackers:T}=ze();d.useEffect(()=>{if(t)return T.initialRender.setChannelUrl(t),()=>{T.initialRender.cleanup()}},[t,T]);const w=no(y,_,{replyType:Ie.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:x=>r==null?void 0:r(x),onMessagesUpdated:x=>s==null?void 0:s(x),onCacheResult:x=>T.initialRender.onCacheResult(x),onApiResult:x=>T.initialRender.onApiResult(x),logger:C,markAsRead:g,sortComparator:h}),R=Ro(),O=ko({channel:_,messages:w.messages,isStreamAnimating:R.isAnimating,isInitializingConversation:S});d.useEffect(()=>{g()},[u,_]);const Z=ue(_);d.useEffect(()=>{o==null||o(Z)},[Z,o]),d.useEffect(()=>{const x=async M=>{const I=typeof(M==null?void 0:M.channelUrl)=="string";_&&I&&M.channelUrl!==_.url||(C.debug("conversation.dispatcher: try to close conversation",_),_!=null&&_.conversation&&_.conversation.status===X.ConversationStatus.OPEN&&(await _.closeConversation(),i==null||i()))};return E.subscribe(se.ConversationClose,x),()=>{E.unsubscribe(se.ConversationClose,x)}},[E,_,C,(Y=_==null?void 0:_.conversation)==null?void 0:Y.status,i]);const ne={conversation:(_==null?void 0:_.conversation)??void 0,channelSource:{channel:_,error:v,refetch:()=>A(),closeConversation:async()=>{ue(_)||await(_==null?void 0:_.closeConversation())}},messageSource:{messages:w.messages,newMessages:w.newMessages,initialized:w.initialized,loadPrevious:()=>w.loadPrevious(),loadNext:()=>w.loadNext(),deleteMessage:x=>w.deleteMessage(x),resendMessage:x=>w.resendMessage(x),resetNewMessages:()=>w.resetNewMessages(),sendUserMessage:async x=>{var I;if(((I=_==null?void 0:_.conversation)==null?void 0:I.status)===X.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(x=await l(x));const M=await w.sendUserMessage(x,c);return c==null||c(M),M},sendFileMessage:async x=>{var I;if(((I=_==null?void 0:_.conversation)==null?void 0:I.status)===X.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(x=await l(x));const M=await w.sendFileMessage(x,c);return c==null||c(M),M},sendMultipleFilesMessage:async x=>{var I;if(((I=_==null?void 0:_.conversation)==null?void 0:I.status)===X.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(x=await l(x));const M=await w.sendMultipleFilesMessage(x,c);return c==null||c(M),M}},state:{streamAnimation:R,input:O}};return a.createElement(Mo,{value:ne},e)}function Lo(e,t){var y,C,E,_,v,A,S,T,w,R;const[n,r]=d.useState(!1),[s,o]=d.useState(null),[i,l]=d.useState([]),[c,u]=d.useState(null),m=d.useRef(!1),h=d.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),o(null),l([]);try{c==null||c.dispose();const O=new Jn(e,t);O.setConversationListCollectionHandler({onChannelsAdded:()=>{l(O.channels)},onChannelsUpdated:()=>{l(O.channels)},onChannelsDeleted:()=>{l(O.channels)}}),await O.loadMore(),u(O),o(null)}catch(O){u(null),o(O)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(y=t.filter)==null?void 0:y.aiAgentChannelFilter,(E=(C=t.filter)==null?void 0:C.aiAgentConversationStatusFilter)==null?void 0:E.join(),(v=(_=t.filter)==null?void 0:_.aiAgentIds)==null?void 0:v.join(),(A=t.filter)==null?void 0:A.deskChannelFilter,(T=(S=t.filter)==null?void 0:S.pinnedChannelUrls)==null?void 0:T.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(R=t.filter)==null?void 0:R.copilotSupportChannelUrl,t.limit]),g=d.useCallback(async()=>{if(c)try{await c.loadMore()}catch(O){o(O)}},[c]);return ln(e,{onConnected:()=>h()}),d.useEffect(()=>{h()},[h]),d.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:s,channels:i,loadMore:g}}const{Provider:Po}=W("AIAgentConversationList");function Oo({conversationListLimit:e,conversationListFilter:t,children:n}){var h,g;const{chatSDK:r,aiAgentId:s,queryParams:o}=K(),i={aiAgentIds:[s],aiAgentConversationStatusFilter:[X.ConversationStatus.CLOSED,X.ConversationStatus.OPEN]},l=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c={...i,...(g=o==null?void 0:o.conversationListParams)==null?void 0:g.filter,...t},u=Lo(r,{limit:l,filter:c}),m={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return a.createElement(Po,{value:m},n)}function No(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:Ho}=W("MessageTemplateFetching");function Bo({children:e,internalVariables:t}){const n=d.useRef({}),r=d.useRef({}),[s,o]=d.useState({}),i=d.useCallback((u,m)=>{o(h=>({...h,[u]:{fetching:!1,error:!1,...h[u],...m}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const y=m(h);if(y)return y;const C=r.current[h];if(C)return C;g||i(h,{fetching:!0});const E=u(h).catch(_=>{throw g||i(h,{error:!0}),_}).finally(()=>{g||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=E,E},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(u,m)=>{if(n.current[u])return n.current[u];const h=No(m());return n.current[u]=h,h},getIsFetching:u=>{var m;return((m=s[u])==null?void 0:m.fetching)??!1},getHasError:u=>{var m;return((m=s[u])==null?void 0:m.error)??!1}};return a.createElement(Ho,{value:c},e)}const Uo="remove_powered_by",cn=(e,t)=>{var s,o;const{chatSDK:n}=K(),{aiAgentInfo:r}=ze();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&er(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return d.useMemo(()=>!(Array.isArray(i)&&i.includes(Uo)),[i])}throw new Error("Unsupported feature")},Fo=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},zo=e=>{const{aiAgentInfo:t}=ze(),r=ir(e)[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Fo(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},lr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[o]=e.members.filter(i=>i.userId!==t.userId);return o})(),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?be(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Ft=e=>d.useReducer((t,n)=>({...t,...n}),e);var le=(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))(le||{});const $o=new Set(["free_text","single_choice"]),Vo=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Ft({csatType:t,csat:n,csatReason:r,isResolved:s}),[l,c]=Ft({followUpItem:!1}),u=d.useMemo(()=>{var _;const y=o.csat,C=typeof y=="number",E=(_=e.follow_up)==null?void 0:_.find(v=>C?v.scores.includes(y):v.always_visible??!1);if($o.has(E==null?void 0:E.response_type))return E},[o.csat,e.follow_up]),m=(()=>{var y;if(typeof n=="number")return"submitted";if((t===le.AI_AGENT_CSAT_5||t===le.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===le.AI_AGENT_CSAT_5_WITH_CRE){const C=typeof o.csat=="number",E=!((y=e.cre)!=null&&y.required)||typeof o.isResolved=="boolean";if(C&&E)return"submittable"}return"unsubmittable"})(),h=d.useCallback(()=>typeof o.csat>"u"?!1:u!=null&&u.required&&!o.csatReason?(c({followUpItem:!0}),!1):!0,[o,u,c]);return d.useEffect(()=>{r||(i({csatReason:""}),c({followUpItem:!1}))},[r,u,i,c]),{params:o,setParams:i,error:l,setError:c,followUpItem:u,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Et=5,qo=250,jo=50,Dn=e=>Math.max(0,e-jo),Go=e=>e<1e3?{speed:Et*.5,chunkSize:2}:e<2e3?{speed:Et*.8,chunkSize:2}:{speed:Et*.6,chunkSize:3},Wo=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationProgress:s,onAnimationComplete:o}=e,[i,l]=d.useState(()=>Dn(t.length)),c=d.useRef(null),u=d.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=d.useRef({onStart:r,onProgress:s,onComplete:o}).current,h=d.useRef({startCalled:!1,completeCalled:!1}).current,g=d.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,y=n,C=i<t.length,E=g.initialEnabled&&(y||C);return d.useLayoutEffect(()=>{m.onStart=r,m.onProgress=s,m.onComplete=o,g.textLength=t.length,g.enabled=n}),d.useLayoutEffect(()=>{var _;g.initialEnabled&&(h.startCalled||(h.startCalled=!0,(_=m.onStart)==null||_.call(m)),l(v=>t.length<v?t.length:v))},[t]),d.useEffect(()=>{if(!g.initialEnabled)return;let _=Dn(t.length);u.lastUpdate=0,u.startTime=0,u.lastProgressCall=0;const v=A=>{var Y;u.lastUpdate===0&&(u.lastUpdate=A,u.startTime=A,u.lastProgressCall=A);const S=g.textLength,T=A-u.lastUpdate,w=A-u.startTime,{speed:R,chunkSize:O}=Go(w),Z=R*O;T>=Z&&_<S&&(_=Math.min(_+O,S),l(_),u.lastUpdate=A),A-u.lastProgressCall>=qo&&(u.lastProgressCall=A,(Y=m.onProgress)==null||Y.call(m)),(_<S||g.enabled)&&(c.current=requestAnimationFrame(v))};return c.current=requestAnimationFrame(v),()=>{var A;c.current&&cancelAnimationFrame(c.current),h.startCalled&&!h.completeCalled&&(h.completeCalled=!0,(A=m.onComplete)==null||A.call(m))}},[]),d.useEffect(()=>{var S;const _=g.initialEnabled&&h.startCalled,v=!n,A=i>=t.length&&t.length>0;_&&v&&A&&!h.completeCalled&&(h.completeCalled=!0,(S=m.onComplete)==null||S.call(m))},[n,i,t.length]),{streamText:g.initialEnabled?t.slice(0,i):t,isAnimating:E}},Ko="1.10.1",Yo=Ko,Xo={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",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.",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"},conversation_list:{header_title:"Conversations",ended:"Ended",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`},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."},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"},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"}},zt={language:"en",strings:Xo,dateLocale:Ur.enUS},Zo={conversation:{input_placeholder:"질문하기",input_placeholder_disabled:"이 채널에서는 채팅을 사용할 수 없습니다.",input_placeholder_wait_ai_agent_response:"상담사의 답변을 기다리는 중...",input_placeholder_active_form:"계속 진행하려면 양식을 작성해 주세요.",input_placeholder_reconnecting:"재연결 시도 중. 계속되면 새로고침하세요.",unknown_message_type:"(알 수 없는 메시지 유형)",powered_by:"Powered by",citation_title:"출처",start_new_conversation_label:"대화 시작",scroll_to_new_messages_label:()=>"새 메시지",failed_message_resend:"다시 시도",failed_message_remove:"삭제",file_upload_no_supported_files:"사용 가능한 지원 파일 형식이 없습니다.",a11y_message_list:"채팅 메시지",a11y_scroll_to_bottom:"맨 아래로 스크롤",a11y_scroll_to_new_messages:"새 메시지로 스크롤",a11y_open_conversation_list:"대화 목록 열기"},conversation_list:{header_title:"대화",ended:"종료됨",footer_title:"대화 시작",multiple_files_count:e=>`${e}개의 파일`},date_format:{just_now:"방금",minutes_ago:e=>`${e}분 전`,hours_ago:e=>`${e}시간 전`,date_short:"yyyy/MM/dd",date_separator:"yyyy년 M월 d일",message_timestamp:"p"},csat:{title:"귀하의 피드백은 우리에게 중요합니다.",submitted_label:"성공적으로 제출되었습니다!",cre_question:"문제가 해결되었나요?",cre_positive_label:"네, 감사합니다! 👍",cre_negative_label:"아니요, 도움이 되지 않았어요.",reason_placeholder:"의견을 공유해주세요.",question:"귀하의 경험을 어떻게 평가하시겠습니까?",submit_label:"제출",submission_expired:"죄송합니다. 설문 응답 기간이 종료되었습니다."},form:{optional_label:"선택",validation_required:"이 항목은 필수입니다"},common:{placeholder_something_went_wrong:"문제가 발생했습니다.",placeholder_no_messages:"메시지가 없습니다.",placeholder_no_conversations:"아직 대화가 없습니다",placeholder_something_went_wrong_retry_label:"다시 시도"},feedback:{title:"피드백 제출",good:"좋아요",bad:"별로예요",comment_label:"코멘트 (선택사항)",comment_placeholder:"코멘트를 남겨주세요",cancel:"취소",submit:"제출",save:"저장",edit:"피드백 수정",remove:"피드백 삭제"}},$t={language:"ko",strings:Zo,dateLocale:jr.ko},Jo={conversation:{input_placeholder:"質問する",input_placeholder_disabled:"このチャンネルではチャットを利用できません",input_placeholder_wait_ai_agent_response:"エージェントの返信を待っています…",input_placeholder_active_form:"続行するには、フォームに記入してください。",input_placeholder_reconnecting:"再接続中。続く場合は更新してください。",unknown_message_type:"(不明なメッセージタイプ)",powered_by:"Powered by",citation_title:"出典",start_new_conversation_label:"会話を始める",scroll_to_new_messages_label:()=>"新しいメッセージ",failed_message_resend:"再試行",failed_message_remove:"削除",file_upload_no_supported_files:"サポートされているファイルタイプがありません。",a11y_message_list:"チャットメッセージ",a11y_scroll_to_bottom:"一番下にスクロール",a11y_scroll_to_new_messages:"新しいメッセージにスクロール",a11y_open_conversation_list:"会話リストを開く"},conversation_list:{header_title:"会話",ended:"終了",footer_title:"会話を始める",multiple_files_count:e=>`${e}個のファイル`},date_format:{just_now:"たった今",minutes_ago:e=>`${e}分前`,hours_ago:e=>`${e}時間前`,date_short:"yyyy/MM/dd",date_separator:"yyyy年 M月 d日",message_timestamp:"p"},csat:{title:"あなたのフィードバックは私たちにとって重要です",submitted_label:"正常に送信されました!",cre_question:"問題は解決されましたか?",cre_positive_label:"はい、ありがとうございます! 👍",cre_negative_label:"いいえ、役に立ちませんでした。",reason_placeholder:"フィードバックを共有する",question:"あなたの経験をどう評価しますか?",submit_label:"送信",submission_expired:"申し訳ありません、アンケートの受付期間は終了しました。"},form:{optional_label:"任意",validation_required:"この質問は必須です"},common:{placeholder_something_went_wrong:"問題が発生しました",placeholder_no_messages:"メッセージがありません",placeholder_no_conversations:"まだ会話がありません",placeholder_something_went_wrong_retry_label:"再試行"},feedback:{title:"フィードバックを送信",good:"良い",bad:"悪い",comment_label:"コメント(オプション)",comment_placeholder:"コメントを残してください",cancel:"キャンセル",submit:"送信",save:"保存",edit:"フィードバックを編集",remove:"フィードバックを削除"}},Vt={language:"ja",strings:Jo,dateLocale:qr.ja},Qo={conversation:{input_placeholder:"Hacer una pregunta",input_placeholder_disabled:"El chat no está disponible en este canal",input_placeholder_wait_ai_agent_response:"Esperando la respuesta del agente...",input_placeholder_active_form:"Por favor, complete el formulario para continuar.",input_placeholder_reconnecting:"Reconectando. Actualiza si persiste.",unknown_message_type:"(Tipo de mensaje desconocido)",powered_by:"Desarrollado por",citation_title:"Fuente",start_new_conversation_label:"Iniciar una conversación",scroll_to_new_messages_label:()=>"Nuevo mensaje",failed_message_resend:"Reintentar",failed_message_remove:"Eliminar",file_upload_no_supported_files:"No hay tipos de archivo compatibles disponibles.",a11y_message_list:"Mensajes del chat",a11y_scroll_to_bottom:"Desplazarse hacia abajo",a11y_scroll_to_new_messages:"Desplazarse a nuevos mensajes",a11y_open_conversation_list:"Abrir lista de conversaciones"},conversation_list:{header_title:"Conversaciones",ended:"Finalizado",footer_title:"Iniciar una conversación",multiple_files_count:e=>`${e} ${e===1?"archivo":"archivos"}`},date_format:{just_now:"Ahora mismo",minutes_ago:e=>`Hace ${e} minutos`,hours_ago:e=>`Hace ${e} horas`,date_short:"dd/MM/yyyy",date_separator:"d 'de' MMMM 'de' yyyy",message_timestamp:"p"},csat:{title:"Tus comentarios nos importan",submitted_label:"Enviado con éxito!",cre_question:"¿Se resolvió su problema?",cre_positive_label:"¡Sí, gracias! 👍",cre_negative_label:"No, eso no ayudó.",reason_placeholder:"Comparte tu opinión",question:"¿Cómo calificarías tu experiencia?",submit_label:"Enviar",submission_expired:"Lo sentimos, el período de la encuesta ha terminado."},form:{optional_label:"opcional",validation_required:"Esta pregunta es obligatoria"},common:{placeholder_something_went_wrong:"Algo salió mal",placeholder_no_messages:"No hay mensajes",placeholder_no_conversations:"Aún no hay conversaciones",placeholder_something_went_wrong_retry_label:"Reintentar"},feedback:{title:"Enviar comentarios",good:"Bueno",bad:"Malo",comment_label:"Comentario (opcional)",comment_placeholder:"Deja un comentario",cancel:"Cancelar",submit:"Enviar",save:"Guardar",edit:"Editar comentarios",remove:"Eliminar comentarios"}},qt={language:"es",strings:Qo,dateLocale:Fr.es},ea={conversation:{input_placeholder:"Fazer uma pergunta",input_placeholder_disabled:"O chat não está disponível neste canal",input_placeholder_wait_ai_agent_response:"Aguardando a resposta do agente...",input_placeholder_active_form:"Por favor, preencha o formulário para prosseguir.",input_placeholder_reconnecting:"Reconectando. Atualize se persistir.",unknown_message_type:"(Tipo de mensagem desconhecido)",powered_by:"Desenvolvido por",citation_title:"Fonte",start_new_conversation_label:"Iniciar uma conversa",scroll_to_new_messages_label:()=>"Nova mensagem",failed_message_resend:"Tentar novamente",failed_message_remove:"Remover",file_upload_no_supported_files:"Nenhum tipo de arquivo suportado disponível.",a11y_message_list:"Mensagens do chat",a11y_scroll_to_bottom:"Rolar para baixo",a11y_scroll_to_new_messages:"Rolar para novas mensagens",a11y_open_conversation_list:"Abrir lista de conversas"},conversation_list:{header_title:"Conversas",ended:"Encerrada",footer_title:"Iniciar uma conversa",multiple_files_count:e=>`${e} ${e===1?"arquivo":"arquivos"}`},date_format:{just_now:"Agora mesmo",minutes_ago:e=>`Há ${e} minutos`,hours_ago:e=>`Há ${e} horas`,date_short:"dd/MM/yyyy",date_separator:"d 'de' MMMM 'de' yyyy",message_timestamp:"p"},csat:{title:"Seu feedback é importante para nós",submitted_label:"Enviado com sucesso!",cre_question:"Seu problema foi resolvido?",cre_positive_label:"Sim, obrigado! 👍",cre_negative_label:"Não, isso não ajudou.",reason_placeholder:"Compartilhe seu feedback",question:"Como você avaliaria sua experiência?",submit_label:"Enviar",submission_expired:"Desculpe, o período da pesquisa foi encerrado."},form:{optional_label:"opcional",validation_required:"Esta pergunta é obrigatória"},common:{placeholder_something_went_wrong:"Algo deu errado",placeholder_no_messages:"Nenhuma mensagem",placeholder_no_conversations:"Nenhuma conversa ainda",placeholder_something_went_wrong_retry_label:"Tentar novamente"},feedback:{title:"Enviar feedback",good:"Bom",bad:"Ruim",comment_label:"Comentário (opcional)",comment_placeholder:"Deixe um comentário",cancel:"Cancelar",submit:"Enviar",save:"Salvar",edit:"Editar feedback",remove:"Remover feedback"}},jt={language:"pt",strings:ea,dateLocale:Gr.pt},ta={conversation:{input_placeholder:"Poser une question",input_placeholder_disabled:"Le chat n'est pas disponible dans ce canal",input_placeholder_wait_ai_agent_response:"En attente de la réponse de l'agent...",input_placeholder_active_form:"Veuillez remplir le formulaire pour continuer.",input_placeholder_reconnecting:"Reconnexion. Actualisez si persiste.",unknown_message_type:"(Type de message inconnu)",powered_by:"Propulsé par",citation_title:"Source",start_new_conversation_label:"Démarrer une conversation",scroll_to_new_messages_label:()=>"Nouveau message",failed_message_resend:"Réessayer",failed_message_remove:"Supprimer",file_upload_no_supported_files:"Aucun type de fichier pris en charge disponible.",a11y_message_list:"Messages du chat",a11y_scroll_to_bottom:"Faire défiler vers le bas",a11y_scroll_to_new_messages:"Aller aux nouveaux messages",a11y_open_conversation_list:"Ouvrir la liste des conversations"},conversation_list:{header_title:"Conversations",ended:"Terminée",footer_title:"Démarrer une conversation",multiple_files_count:e=>`${e} fichier${e===1?"":"s"}`},date_format:{just_now:"À l'instant",minutes_ago:e=>`Il y a ${e} minutes`,hours_ago:e=>`Il y a ${e} heures`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Vos commentaires comptent pour nous",submitted_label:"Soumis avec succès!",cre_question:"Votre problème a-t-il été résolu ?",cre_positive_label:"Oui, merci ! 👍",cre_negative_label:"Non, cela n'a pas aidé.",reason_placeholder:"Partagez votre avis",question:"Comment évalueriez-vous votre expérience ?",submit_label:"Envoyer",submission_expired:"Désolé, la période de l'enquête est terminée."},form:{optional_label:"optionnel",validation_required:"Cette question est obligatoire"},common:{placeholder_something_went_wrong:"Une erreur est survenue",placeholder_no_messages:"Aucun message",placeholder_no_conversations:"Aucune conversation pour le moment",placeholder_something_went_wrong_retry_label:"Réessayer"},feedback:{title:"Envoyer des commentaires",good:"Bien",bad:"Mauvais",comment_label:"Commentaire (optionnel)",comment_placeholder:"Laissez un commentaire",cancel:"Annuler",submit:"Envoyer",save:"Enregistrer",edit:"Modifier les commentaires",remove:"Supprimer les commentaires"}},Gt={language:"fr",strings:ta,dateLocale:zr.fr},na={conversation:{input_placeholder:"एक प्रश्न पूछें",input_placeholder_disabled:"इस चैनल में चैट उपलब्ध नहीं है",input_placeholder_wait_ai_agent_response:"एजेंट के उत्तर की प्रतीक्षा कर रहे हैं...",input_placeholder_active_form:"आगे बढ़ने के लिए कृपया फॉर्म भरें।",input_placeholder_reconnecting:"पुनः कनेक्ट हो रहा है। जारी रहे तो रिफ्रेश करें।",unknown_message_type:"(अज्ञात संदेश प्रकार)",powered_by:"द्वारा संचालित",citation_title:"स्रोत",start_new_conversation_label:"एक बातचीत शुरू करें",scroll_to_new_messages_label:()=>"नया संदेश",failed_message_resend:"पुनः प्रयास करें",failed_message_remove:"हटाएं",file_upload_no_supported_files:"कोई समर्थित फ़ाइल प्रकार उपलब्ध नहीं हैं।",a11y_message_list:"चैट संदेश",a11y_scroll_to_bottom:"नीचे स्क्रॉल करें",a11y_scroll_to_new_messages:"नए संदेशों पर स्क्रॉल करें",a11y_open_conversation_list:"बातचीत सूची खोलें"},conversation_list:{header_title:"बातचीत",ended:"समाप्त",footer_title:"एक बातचीत शुरू करें",multiple_files_count:e=>`${e} फ़ाइलें`},date_format:{just_now:"अभी",minutes_ago:e=>`${e} मिनट पहले`,hours_ago:e=>`${e} घंटे पहले`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"आपकी प्रतिक्रिया हमारे लिए मायने रखती है",submitted_label:"सफलतापूर्वक सबमिट किया गया!",cre_question:"क्या आपकी समस्या का समाधान हुआ?",cre_positive_label:"हाँ, धन्यवाद! 👍",cre_negative_label:"नहीं, इससे मदद नहीं मिली।",reason_placeholder:"अपनी प्रतिक्रिया साझा करें",question:"आप अपने अनुभव का मूल्यांकन कैसे करेंगे?",submit_label:"सबमिट करें",submission_expired:"क्षमा करें, सर्वेक्षण अवधि समाप्त हो गई है।"},form:{optional_label:"वैकल्पिक",validation_required:"यह प्रश्न आवश्यक है"},common:{placeholder_something_went_wrong:"कुछ गलत हो गया",placeholder_no_messages:"कोई संदेश नहीं",placeholder_no_conversations:"अभी तक कोई बातचीत नहीं",placeholder_something_went_wrong_retry_label:"पुनः प्रयास करें"},feedback:{title:"प्रतिक्रिया भेजें",good:"अच्छा",bad:"बुरा",comment_label:"टिप्पणी (वैकल्पिक)",comment_placeholder:"एक टिप्पणी छोड़ें",cancel:"रद्द करें",submit:"भेजें",save:"सहेजें",edit:"प्रतिक्रिया संपादित करें",remove:"प्रतिक्रिया हटाएं"}},Wt={language:"hi",strings:na,dateLocale:$r.hi},ra={conversation:{input_placeholder:"Fai una domanda",input_placeholder_disabled:"La chat non è disponibile in questo canale",input_placeholder_wait_ai_agent_response:"In attesa della risposta dell'agente...",input_placeholder_active_form:"Compila il modulo per procedere.",input_placeholder_reconnecting:"Riconnessione. Aggiorna se persiste.",unknown_message_type:"(Tipo di messaggio sconosciuto)",powered_by:"Powered by",citation_title:"Fonte",start_new_conversation_label:"Inizia una conversazione",scroll_to_new_messages_label:()=>"Nuovo messaggio",failed_message_resend:"Riprova",failed_message_remove:"Rimuovi",file_upload_no_supported_files:"Nessun tipo di file supportato disponibile.",a11y_message_list:"Messaggi della chat",a11y_scroll_to_bottom:"Scorri in basso",a11y_scroll_to_new_messages:"Scorri ai nuovi messaggi",a11y_open_conversation_list:"Apri elenco conversazioni"},conversation_list:{header_title:"Conversazioni",ended:"Terminata",footer_title:"Inizia una conversazione",multiple_files_count:e=>`${e} file`},date_format:{just_now:"Proprio ora",minutes_ago:e=>`${e} minuti fa`,hours_ago:e=>`${e} ore fa`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Il tuo feedback è importante per noi",submitted_label:"Inviato con successo!",cre_question:"Il tuo problema è stato risolto?",cre_positive_label:"Sì, grazie! 👍",cre_negative_label:"No, non è servito.",reason_placeholder:"Condividi il tuo feedback",question:"Come valuteresti la tua esperienza?",submit_label:"Invia",submission_expired:"Ci dispiace, il periodo per partecipare al sondaggio è terminato."},form:{optional_label:"opzionale",validation_required:"Questa domanda è obbligatoria"},common:{placeholder_something_went_wrong:"Qualcosa è andato storto",placeholder_no_messages:"Nessun messaggio",placeholder_no_conversations:"Nessuna conversazione ancora",placeholder_something_went_wrong_retry_label:"Riprova"},feedback:{title:"Invia feedback",good:"Buono",bad:"Cattivo",comment_label:"Commento (opzionale)",comment_placeholder:"Lascia un commento",cancel:"Annulla",submit:"Invia",save:"Salva",edit:"Modifica feedback",remove:"Rimuovi feedback"}},Kt={language:"it",strings:ra,dateLocale:Vr.it},sa={conversation:{input_placeholder:"Eine Frage stellen",input_placeholder_disabled:"Chat ist in diesem Kanal nicht verfügbar",input_placeholder_wait_ai_agent_response:"Warten auf die Antwort des Agenten...",input_placeholder_active_form:"Bitte fülle das Formular aus, um fortzufahren.",input_placeholder_reconnecting:"Neu verbinden. Aktualisieren falls anhaltend.",unknown_message_type:"(Unbekannter Nachrichtentyp)",powered_by:"Unterstützt von",citation_title:"Quelle",start_new_conversation_label:"Ein Gespräch starten",scroll_to_new_messages_label:()=>"Neue Nachricht",failed_message_resend:"Erneut versuchen",failed_message_remove:"Entfernen",file_upload_no_supported_files:"Keine unterstützten Dateitypen verfügbar.",a11y_message_list:"Chat-Nachrichten",a11y_scroll_to_bottom:"Nach unten scrollen",a11y_scroll_to_new_messages:"Zu neuen Nachrichten scrollen",a11y_open_conversation_list:"Konversationsliste öffnen"},conversation_list:{header_title:"Gespräche",ended:"Beendet",footer_title:"Ein Gespräch starten",multiple_files_count:e=>`${e} ${e===1?"Datei":"Dateien"}`},date_format:{just_now:"Gerade eben",minutes_ago:e=>`Vor ${e} Minuten`,hours_ago:e=>`Vor ${e} Stunden`,date_short:"dd.MM.yyyy",date_separator:"d. MMMM yyyy",message_timestamp:"p"},csat:{title:"Ihr Feedback ist uns wichtig",submitted_label:"Erfolgreich gesendet!",cre_question:"Wurde Ihr Problem gelöst?",cre_positive_label:"Ja, danke! 👍",cre_negative_label:"Nein, das hat nicht geholfen.",reason_placeholder:"Dein Feedback teilen",question:"Wie würden Sie Ihre Erfahrung bewerten?",submit_label:"Absenden",submission_expired:"Die Umfrage ist leider nicht mehr verfügbar."},form:{optional_label:"optional",validation_required:"Diese Frage ist erforderlich"},common:{placeholder_something_went_wrong:"Etwas ist schiefgelaufen",placeholder_no_messages:"Keine Nachrichten",placeholder_no_conversations:"Noch keine Unterhaltungen",placeholder_something_went_wrong_retry_label:"Erneut versuchen"},feedback:{title:"Feedback senden",good:"Gut",bad:"Schlecht",comment_label:"Kommentar (optional)",comment_placeholder:"Hinterlasse einen Kommentar",cancel:"Abbrechen",submit:"Senden",save:"Speichern",edit:"Feedback bearbeiten",remove:"Feedback entfernen"}},Yt={language:"de",strings:sa,dateLocale:Br.de},oa={conversation:{input_placeholder:"Bir soru sor",input_placeholder_disabled:"Bu kanalda sohbet mevcut değil",input_placeholder_wait_ai_agent_response:"Temsilcinin yanıtını bekliyor...",input_placeholder_active_form:"İlerlemek için lütfen formu doldurun.",input_placeholder_reconnecting:"Yeniden bağlanıyor. Devam ederse yenile.",unknown_message_type:"(Bilinmeyen mesaj türü)",powered_by:"Tarafından desteklenmektedir",citation_title:"Kaynak",start_new_conversation_label:"Bir sohbet başlat",scroll_to_new_messages_label:()=>"Yeni mesaj",failed_message_resend:"Tekrar dene",failed_message_remove:"Kaldır",file_upload_no_supported_files:"Desteklenen dosya türü mevcut değil.",a11y_message_list:"Sohbet mesajları",a11y_scroll_to_bottom:"Aşağı kaydır",a11y_scroll_to_new_messages:"Yeni mesajlara kaydır",a11y_open_conversation_list:"Görüşme listesini aç"},conversation_list:{header_title:"Görüşmeler",ended:"Sona erdi",footer_title:"Bir sohbet başlat",multiple_files_count:e=>`${e} dosya`},date_format:{just_now:"Az önce",minutes_ago:e=>`${e} dakika önce`,hours_ago:e=>`${e} saat önce`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Görüşleriniz bizim için önemli",submitted_label:"Başarıyla gönderildi!",cre_question:"Sorununuz çözüldü mü?",cre_positive_label:"Evet, teşekkürler! 👍",cre_negative_label:"Hayır, bu yardımcı olmadı.",reason_placeholder:"Geri bildiriminizi paylaşın",question:"Deneyiminizi nasıl değerlendirirsiniz?",submit_label:"Gönder",submission_expired:"Üzgünüz, anket süresi sona erdi."},form:{optional_label:"İsteğe bağlı",validation_required:"Bu soru gereklidir"},common:{placeholder_something_went_wrong:"Bir şeyler ters gitti",placeholder_no_messages:"Mesaj yok",placeholder_no_conversations:"Henüz görüşme yok",placeholder_something_went_wrong_retry_label:"Tekrar dene"},feedback:{title:"Geri bildirim gönder",good:"İyi",bad:"Kötü",comment_label:"Yorum (isteğe bağlı)",comment_placeholder:"Bir yorum bırakın",cancel:"İptal",submit:"Gönder",save:"Kaydet",edit:"Geri bildirimi düzenle",remove:"Geri bildirimi kaldır"}},Xt={language:"tr",strings:oa,dateLocale:Wr.tr},de=e=>({conversation:e.conversation,conversation_list:e.conversation_list,date_format:e.date_format,csat:e.csat,form:e.form,common:e.common,feedback:e.feedback}),Ln=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??st},st="en",un={borderColor:"red",borderWidth:p.StyleSheet.hairlineWidth},b=({debug:e=!1,style:t,children:n,...r})=>a.createElement(p.View,{style:[t,r,e&&un],...r},n);b.Animated=({debug:e=!1,style:t,children:n,...r})=>a.createElement(p.Animated.View,{style:[t,r,e&&un],...r},n);const{Provider:aa,useContext:te}=W("MessengerSession"),ia=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof et||t.userSessionInfo instanceof nn))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return a.createElement(Eo,{ref:n,...t},r=>a.createElement(la,{...r},e))}),la=({children:e,...t})=>{const{dispatcher:n}=K(),{userSession:r,aiAgentInfo:s,launcherInfo:o,deauthenticate:i}=t;return d.useEffect(()=>{const l=()=>{p.Alert.alert("Session timed out","Start a new conversation.",[{text:"OK",onPress:()=>i()}])};return n.subscribe(se.AnonymousSessionTokenExpired,l),()=>n.unsubscribe(se.AnonymousSessionTokenExpired,l)},[n,i]),a.createElement(aa,{value:{...t,userSession:r,aiAgentInfo:s,launcherInfo:o}},e)},De=50,ca=500,{Provider:ua,useContext:da}=W("ConversationScroll"),ma=({children:e})=>{var Re;const{config:t}=K(),n=((Re=t==null?void 0:t.conversation)==null?void 0:Re.scrollMode)??"auto",r=d.useRef(null),s=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),o=d.useRef(0),i=d.useRef(!1),l=d.useRef(null),[c,u]=d.useState(0),[m,h]=d.useState(0),[g,y]=d.useState(!1),[C,E]=d.useState(!1),_=d.useMemo(()=>C?"auto":n,[C,n]),v=d.useCallback(()=>{const{shouldUpdate:V,shouldRecalc:G,contentHeight:J,contentSnapshotHeight:ae,viewport:_e}=s.current;V&&ae<J&&u(U=>{s.current.shouldUpdate=!1;const re=J-U-ae,ie=Math.max(0,_e-re);return U===0||ie<U||G?(s.current.shouldRecalc=!1,ie):U})},[]),A=d.useCallback(V=>{const G=V.nativeEvent.layout.height;s.current.viewport=G,y(s.current.contentHeight>G)},[]),S=d.useCallback((V,G)=>{s.current.contentHeight=G;const J=s.current.viewport;y(G>J),v()},[v]),T=d.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]),w=d.useCallback(()=>{T(),i.current=!1,h(o.current)},[T]),R=d.useCallback(()=>{T(),i.current=!0,l.current=setTimeout(w,ca)},[T,w]);d.useEffect(()=>()=>{T()},[T]);const O=d.useCallback(V=>{const G=V.nativeEvent.contentOffset.y;o.current=G,!i.current&&h(G)},[]),Z=d.useCallback(()=>{i.current&&w()},[w]),ne=d.useCallback(()=>{i.current&&w()},[w]),Y=d.useCallback(()=>{i.current&&w()},[w]),x=d.useMemo(()=>{if(_==="fixed")return{minIndexForVisible:0,autoscrollToTopThreshold:De};if(g)return{minIndexForVisible:0}},[_,g]),M=d.useCallback((V=!0)=>{r.current&&(V&&R(),r.current.scrollToOffset({offset:0,animated:V}),o.current=0,h(0))},[R]),I=d.useCallback((V,G=!0)=>{r.current&&(G&&R(),r.current.scrollToIndex({index:V,animated:G,viewPosition:1}))},[R]),H=d.useCallback(()=>{_==="fixed"&&(s.current.contentSnapshotHeight=s.current.contentHeight-c,s.current.shouldUpdate=!0,s.current.shouldRecalc=!0)},[_,c]),j=d.useCallback(()=>{_==="fixed"?I(0):M()},[_,M,I]),B=d.useCallback(()=>{_==="fixed"?s.current.shouldUpdate=!0:o.current<=De&&M()},[_,M]),Ee=d.useCallback(V=>{E(V)},[]),ht=d.useCallback(V=>{_==="auto"&&V&&o.current<=De&&M()},[_,M]),_t=m<=De,ft=g&&!_t,ve=d.useCallback(()=>o.current>De,[]);return a.createElement(ua,{value:{ref:r,state:{bottomSpace:c,isAwayFromBottom:ft,shouldCountNewMessages:ve},props:{maintainVisibleContentPosition:x,onLayout:A,onContentSizeChange:S,onScroll:O,onScrollBeginDrag:Z,onScrollEndDrag:ne,onMomentumScrollEnd:Y},actions:{scrollToBottom:M,scrollToIndex:I,onBeforeMessageSend:H,onAfterMessageSend:j,onStreamingUpdate:B,onConversationClosed:Ee,onTypingIndicatorUpdate:ht}}},e)};function cr(e){return new Promise((t,n)=>{p.Image.getSize(e,(r,s)=>{t({width:String(r),height:String(s)})},r=>{n(r)})})}async function ga(e){var t;if("file"in e&&e.file&&typeof e.file=="object"){const n=e.file;if(n.uri&&((t=n.type)!=null&&t.startsWith("image/")))try{const{width:r,height:s}=await cr(n.uri);return new Ie.MessageMetaArray({key:Kn,value:[r,s]})}catch{return}}}function ha(e,t){let n=0,r=0;return ce(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),ce(t)&&t.sendingStatus!=="succeeded"&&(r=Number.MAX_SAFE_INTEGER),t.createdAt+r-(e.createdAt+n)}const{Provider:_a,Context:fa,useContext:me}=W("Conversation"),ur=e=>a.createElement(ma,null,a.createElement(pa,{...e})),pa=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:r,shouldMarkAsRead:s,children:o})=>{const i=da(),{activeChannel:l,refreshActiveChannel:c,sdkUser:u,authenticate:m}=te();d.useEffect(()=>{u||m()},[]);const h=d.useCallback(async E=>{i.actions.onBeforeMessageSend();const _=await ga(E);return{...E,metaArrays:_?[_]:void 0}},[i.actions.onBeforeMessageSend]),g=d.useCallback(()=>{i.actions.onAfterMessageSend()},[i.actions.onAfterMessageSend]),y=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]),C=e??(l==null?void 0:l.url);return a.createElement(Do,{key:C,channelUrl:C,onBeforeSendMessage:h,onAfterSendMessage:g,onMessagesUpdated:i.actions.onStreamingUpdate,onMessagesReceived:i.actions.onStreamingUpdate,onChannelDeleted:y,onConversationClosedStatusChanged:i.actions.onConversationClosed,sortComparator:ha,shouldMarkAsRead:s,shouldCountNewMessages:i.state.shouldCountNewMessages},E=>a.createElement(_a,{value:{...E,scrollSource:i,onClose:n,onNavigateToConversationList:r,updateActiveChannel:y}},o))},vt=de(Yt.strings),ya={...vt,conversation:{...vt.conversation,attachment_camera:"Kamera",attachment_photo:"Fotobibliothek",attachment_document:"Dateien",file_upload_notification_count_limit:e=>`Sie können nur ${e} Datei${e>1?"en":""} gleichzeitig hochladen.`,file_upload_notification_size_limit:e=>`Die maximale Dateigröße beträgt ${e} MB.`,file_upload_not_supported_file:"Bitte wählen Sie einen unterstützten Dateityp aus."},conversation_list:{...vt.conversation_list}},ba={language:Yt.language,dateLocale:Yt.dateLocale,strings:ya},St=de(zt.strings),Ca={...St,conversation:{...St.conversation,attachment_camera:"Camera",attachment_photo:"Photo library",attachment_document:"Files",file_upload_notification_count_limit:e=>`You can only upload ${e} file${e>1?"s":""} at a time.`,file_upload_notification_size_limit:e=>`Maximum file size is ${e} MB.`,file_upload_not_supported_file:"Please select a supported file type."},conversation_list:{...St.conversation_list}},Ea={language:zt.language,dateLocale:zt.dateLocale,strings:Ca},At=de(qt.strings),va={...At,conversation:{...At.conversation,attachment_camera:"Cámara",attachment_photo:"Biblioteca de fotos",attachment_document:"Archivos",file_upload_notification_count_limit:e=>`Solo puede cargar ${e} archivo${e>1?"s":""} a la vez.`,file_upload_notification_size_limit:e=>`El tamaño máximo del archivo es ${e} MB.`,file_upload_not_supported_file:"Por favor, seleccione un tipo de archivo compatible."},conversation_list:{...At.conversation_list}},Sa={language:qt.language,dateLocale:qt.dateLocale,strings:va},It=de(Gt.strings),Aa={...It,conversation:{...It.conversation,attachment_camera:"Caméra",attachment_photo:"Photothèque",attachment_document:"Fichiers",file_upload_notification_count_limit:e=>`Vous ne pouvez télécharger que ${e} fichier${e>1?"s":""} à la fois.`,file_upload_notification_size_limit:e=>`La taille maximale du fichier est de ${e} MB.`,file_upload_not_supported_file:"Veuillez sélectionner un type de fichier pris en charge."},conversation_list:{...It.conversation_list}},Ia={language:Gt.language,dateLocale:Gt.dateLocale,strings:Aa},Tt=de(Wt.strings),Ta={...Tt,conversation:{...Tt.conversation,attachment_camera:"कैमरा",attachment_photo:"फोटो लाइब्रेरी",attachment_document:"फाइलें",file_upload_notification_count_limit:e=>`आप एक बार में केवल ${e} फ़ाइल${e>1?"ें":""} अपलोड कर सकते हैं।`,file_upload_notification_size_limit:e=>`अधिकतम फ़ाइल आकार ${e} MB है।`,file_upload_not_supported_file:"कृपया समर्थित फ़ाइल प्रकार चुनें।"},conversation_list:{...Tt.conversation_list}},wa={language:Wt.language,dateLocale:Wt.dateLocale,strings:Ta},wt=de(Kt.strings),xa={...wt,conversation:{...wt.conversation,attachment_camera:"Fotocamera",attachment_photo:"Libreria foto",attachment_document:"File",file_upload_notification_count_limit:e=>`Puoi caricare solo ${e} file alla volta.`,file_upload_notification_size_limit:e=>`La dimensione massima del file è ${e} MB.`,file_upload_not_supported_file:"Seleziona un tipo di file supportato."},conversation_list:{...wt.conversation_list}},ka={language:Kt.language,dateLocale:Kt.dateLocale,strings:xa},xt=de(Vt.strings),Ra={...xt,conversation:{...xt.conversation,attachment_camera:"カメラ",attachment_photo:"フォトライブラリ",attachment_document:"ファイル",file_upload_notification_count_limit:e=>`一度にアップロードできるのは${e}ファイルまでです。`,file_upload_notification_size_limit:e=>`ファイルの最大サイズは${e}MBです。`,file_upload_not_supported_file:"サポートされているファイル形式を選択してください。"},conversation_list:{...xt.conversation_list}},Ma={language:Vt.language,dateLocale:Vt.dateLocale,strings:Ra},kt=de($t.strings),Da={...kt,conversation:{...kt.conversation,attachment_camera:"카메라",attachment_photo:"사진 라이브러리",attachment_document:"파일",file_upload_notification_count_limit:e=>`한 번에 ${e}개의 파일만 업로드할 수 있습니다.`,file_upload_notification_size_limit:e=>`파일당 최대 크기는 ${e} MB입니다.`,file_upload_not_supported_file:"지원되는 파일 형식을 선택해 주세요."},conversation_list:{...kt.conversation_list}},La={language:$t.language,dateLocale:$t.dateLocale,strings:Da},Rt=de(jt.strings),Pa={...Rt,conversation:{...Rt.conversation,attachment_camera:"Câmera",attachment_photo:"Biblioteca de fotos",attachment_document:"Arquivos",file_upload_notification_count_limit:e=>`Você só pode carregar ${e} arquivo${e>1?"s":""} por vez.`,file_upload_notification_size_limit:e=>`O tamanho máximo do arquivo é ${e} MB.`,file_upload_not_supported_file:"Por favor, selecione um tipo de arquivo suportado."},conversation_list:{...Rt.conversation_list}},Oa={language:jt.language,dateLocale:jt.dateLocale,strings:Pa},Mt=de(Xt.strings),Na={...Mt,conversation:{...Mt.conversation,attachment_camera:"Kamera",attachment_photo:"Fotoğraf kitaplığı",attachment_document:"Dosyalar",file_upload_notification_count_limit:e=>`Bir seferde yalnızca ${e} dosya yükleyebilirsiniz.`,file_upload_notification_size_limit:e=>`Maksimum dosya boyutu ${e} MB'dir.`,file_upload_not_supported_file:"Lütfen desteklenen bir dosya türü seçin."},conversation_list:{...Mt.conversation_list}},Ha={language:Xt.language,dateLocale:Xt.dateLocale,strings:Na},Pn=new Map([["en",Ea],["ko",La],["ja",Ma],["es",Sa],["pt",Oa],["fr",Ia],["hi",wa],["it",ka],["de",ba],["tr",Ha]]),On=e=>Pn.get(e)??Pn.get(st),Ba=(e,t)=>t?{conversation:{...e.conversation,...t.conversation},conversation_list:{...e.conversation_list,...t.conversation_list},date_format:{...e.date_format,...t.date_format},csat:{...e.csat,...t.csat},form:{...e.form,...t.form},common:{...e.common,...t.common},feedback:{...e.feedback,...t.feedback}}:e,{Provider:Ua,useContext:F}=W("Localization"),Fa=({language:e=st,logger:t,strings:n,children:r})=>{const[s,o]=d.useState(()=>{const i=Ln(e);return On(i)});return d.useEffect(()=>{var l;const i=Ln(e);if(s.language!==i){const c=On(i);o(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:s.language,to:c.language})}},[e,t]),a.createElement(Ua,{value:{language:s.language,strings:Ba(s.strings,n),dateLocale:s.dateLocale,format:(i,l,c)=>Ae.format(i,l,{locale:s.dateLocale,...c})}},r)},{Provider:za,useContext:ot}=W("Modal");function dr({children:e}){const[t,n]=d.useState([]),[r,s]=d.useState(null),o=d.useRef(0);d.useEffect(()=>{if(!r&&t.length>0){const[u,...m]=t;u&&(s(u),n(m))}},[r,t]);const i=d.useCallback(u=>new Promise(m=>{const g={id:`modal-${++o.current}`,render:u,resolve:m};n(y=>[...y,g])}),[]),l=d.useCallback((u,m)=>{s(h=>(h==null?void 0:h.id)===u?(h.resolve(m),null):h)},[]),c={openModal:i,currentModal:r};return a.createElement(za,{value:c},e,r&&a.createElement(p.Modal,{visible:!0,supportedOrientations:["landscape","portrait"],transparent:!0,animationType:"fade",onRequestClose:()=>l(r.id,null),style:{height:0}},r.render(u=>l(r.id,u??null))))}const{Provider:$a,useContext:z}=W("MessengerTheme"),Va=({children:e,...t})=>a.createElement(po,{...t,appearance:{theme:t.mode??"light"}},n=>{const r=qa(n.theme);return a.createElement($a,{value:{...n,themedColor:r}},e)});function qa(e){const t=n=>n[e.selectedTheme];return{textHighEmphasis:t({light:e.palette.onlight.textHighEmphasis,dark:e.palette.ondark.textHighEmphasis}),textMidEmphasis:t({light:e.palette.onlight.textMidEmphasis,dark:e.palette.ondark.textMidEmphasis}),textLowEmphasis:t({light:e.palette.onlight.textLowEmphasis,dark:e.palette.ondark.textLowEmphasis}),textDisabled:t({light:e.palette.onlight.textDisabled,dark:e.palette.ondark.textDisabled}),textHighEmphasisInverse:t({light:e.palette.ondark.textHighEmphasis,dark:e.palette.onlight.textHighEmphasis}),textMidEmphasisInverse:t({light:e.palette.ondark.textMidEmphasis,dark:e.palette.onlight.textMidEmphasis}),textLowEmphasisInverse:t({light:e.palette.ondark.textLowEmphasis,dark:e.palette.onlight.textLowEmphasis}),textDisabledInverse:t({light:e.palette.ondark.textDisabled,dark:e.palette.onlight.textDisabled}),bg_50_600:t({light:e.palette.background50,dark:e.palette.background600}),bg_100_500:t({light:e.palette.background100,dark:e.palette.background500}),bg_200_400:t({light:e.palette.background200,dark:e.palette.background400}),primary:t({light:e.palette.primary.main,dark:e.palette.primary.light}),secondary:t({light:e.palette.secondary.main,dark:e.palette.secondary.light}),error:t({light:e.palette.error.main,dark:e.palette.error.light}),information:t({light:e.palette.information.light,dark:e.palette.information.light}),overlay:t({light:e.palette.overlay.light,dark:e.palette.overlay.dark})}}const L={create:e=>{const t=new WeakMap,n=r=>{const s=t.get(r.theme);if(s)return s;const o=e(r),i={},l={};for(const m in o)typeof o[m]=="function"?l[m]=o[m]:i[m]=o[m];const u={...p.StyleSheet.create(i),...l};return t.set(r.theme,u),u};return{use:()=>{const r=z(),s=ye.useSafeAreaInsets();return n({...r,edgeInsets:s,select:o=>o[r.theme.selectedTheme]})}}}},ja={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},xe=(e,t=p.I18nManager.isRTL?"rtl":"ltr")=>{const n=ye.useSafeAreaInsets();return e.reduce((r,s)=>{const o=ja[t][s];return r[o]=n[s],r},{})},Ga={send:require("./icons/icon-send.png"),close:require("./icons/icon-close.png"),menu:require("./icons/icon-menu.png"),chat:require("./icons/icon-chat.png"),message:require("./icons/icon-message.png"),spinner:require("./icons/icon-spinner.png"),error:require("./icons/icon-error.png"),refresh:require("./icons/icon-refresh.png"),"chevron-down":require("./icons/icon-chevron-down.png"),done:require("./icons/icon-done.png"),"done-all":require("./icons/icon-done-all.png"),user:require("./icons/icon-user.png"),"file-document":require("./icons/icon-file-document.png"),remove:require("./icons/icon-remove.png"),add:require("./icons/icon-add.png"),agent:require("./icons/icon-agent.png"),camera:require("./icons/icon-camera.png"),photo:require("./icons/icon-photo.png"),document:require("./icons/icon-document.png"),"bot-filled":require("./icons/icon-bot-filled.png"),copy:require("./icons/icon-copy.png"),source:require("./icons/icon-source.png"),"radio-on":require("./icons/icon-radio-on.png"),"radio-off":require("./icons/icon-radio-off.png"),good:require("./icons/icon-good.png"),bad:require("./icons/icon-bad.png"),"good-filled":require("./icons/icon-good-filled.png"),"bad-filled":require("./icons/icon-bad-filled.png"),delight:require("./icons/icon-delight.png"),"thumbnail-none":require("./icons/icon-thumbnail-none.png")},Wa={send:!0,chat:!0,message:!0,good:!0,bad:!0,"good-filled":!0,"bad-filled":!0},N=({customSource:e,type:t,color:n,size:r=24,style:s})=>{const o=Ka.use(),i=p.I18nManager.isRTL&&!!Wa[t];return a.createElement(b,{alignItems:"center",justifyContent:"center"},a.createElement(p.Image,{resizeMode:"contain",source:e??Ga[t],style:[o.icon({color:n,size:r,mirror:i}),s]}))},Ka=L.create(({theme:e,themedColor:t})=>({icon:n=>({tintColor:typeof n.color=="function"?n.color({theme:e,themedColor:t}):n.color??e.colors.base.primary,width:n.size,height:n.size,transform:n.mirror?[{scaleX:-1}]:void 0})})),dn=(e,t)=>{if(!t||t.length===0)return!1;const n=t.trimStart();if(n.length===0)return!1;const r=e==="start"?Array.from(n)[0]:Array.from(n).pop(),s=r==null?void 0:r.codePointAt(0);return s===void 0?!1:Za(s)},mr=e=>dn("start",e),Ya=e=>dn("end",e),Xa=e=>{const{text:t,style:n,isTextInput:r}=e;return n!=null&&n.textAlign&&n.textAlign!=="left"&&n.textAlign!=="right"?n.textAlign:p.I18nManager.isRTL&&typeof t=="string"&&mr(t)?r?"right":p.I18nManager.doLeftAndRightSwapInRTL?"left":"right":n==null?void 0:n.textAlign},Za=e=>{for(const[t,n]of Ja)if(e>=t&&e<=n)return!0;return!1},Ja=[[1424,1535],[1536,1791],[1872,1919],[2208,2303],[64285,64335],[65136,65279],[126464,126719]],mn={isStartsWithRTL:mr,isEndsWithRTL:Ya,isRTLString:dn,useTextAlign:Xa},k=({variant:e="body1",color:t,style:n,...r})=>{const{theme:s,themedColor:o}=z(),i=d.useMemo(()=>{if(typeof t=="function")return t({theme:s,themedColor:o});if(typeof t=="string")return t;const u=p.StyleSheet.flatten(n);return u&&u.color?u.color:t??o.textHighEmphasis},[n,t,o.textHighEmphasis]),l=d.useMemo(()=>{const u=s.typography[e]??s.typography.body1;return p.StyleSheet.flatten([{includeFontPadding:!1,...u,color:i},n])},[e,i,s.typography,o.textHighEmphasis]),c=mn.useTextAlign({text:r.children,style:l});return a.createElement(p.Text,{style:[l,{textAlign:c}],...r})},gr=350,Qa=({children:e,...t})=>a.createElement(p.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:gr,...t},n=>typeof e=="function"?e(n):e),ei=({children:e,style:t,...n})=>{const[r,s]=d.useState(!1),o={pressed:r};return a.createElement(p.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:gr,style:typeof t=="function"?t(o):t,onPressIn:()=>s(!0),onPressOut:()=>s(!1),...n},typeof e=="function"?e(o):e)},P=e=>e.activeOpacity&&e.activeOpacity<1?a.createElement(ei,{...e}):a.createElement(Qa,{...e}),{Provider:ti,useContext:hr}=W("BottomSheetAnimation");function ni({onClose:e,children:t}){const n=d.useRef(new p.Animated.Value(500)).current;d.useEffect(()=>{p.Animated.timing(n,{toValue:0,duration:300,useNativeDriver:!0}).start()},[n]);const r=d.useCallback(o=>async()=>{p.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(async()=>{try{await(o==null?void 0:o())}catch{e==null||e()}})},[n]),s=d.useRef(p.PanResponder.create({onMoveShouldSetPanResponder:(o,i)=>i.dy>5,onPanResponderMove:(o,i)=>{i.dy>0&&n.setValue(i.dy)},onPanResponderRelease:(o,i)=>{i.dy>100||i.vy>.5?p.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(()=>{e==null||e()}):p.Animated.timing(n,{toValue:0,duration:200,useNativeDriver:!0}).start()}})).current;return a.createElement(ti,{value:{wrapWithAnimation:r,translateY:n,panHandlers:s.panHandlers}},t)}const ri=({icon:e,label:t="",destructive:n=!1,onPress:r})=>{const s=_r.use(),{themedColor:o}=z();return a.createElement(P,{onPress:r,style:s.actionItem,activeOpacity:.75},e&&a.createElement(N,{type:e,size:24,color:o.primary}),a.createElement(k,{variant:"body3",color:n?o.error:o.textHighEmphasis,numberOfLines:1},t))},si=({onClose:e,children:t})=>{const n=_r.use(),{translateY:r,panHandlers:s,wrapWithAnimation:o}=hr(),i=xe(["left","right"]);return a.createElement(P,{onPress:o(e),style:n.overlay},a.createElement(b.Animated,{style:[n.container,i,{transform:[{translateY:r}]}],...s},t))},at=oe({template:si,components:{ActionItem:ri}}),ee=e=>{const{Template:t}=at.useContext();return a.createElement(ni,{onClose:e.onClose},a.createElement(t,{...e}))};ee.ActionItem=e=>{const{components:t}=at.useContext(),{wrapWithAnimation:n}=hr();return a.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const _r=L.create(({theme:e,edgeInsets:t})=>({overlay:{flex:1,backgroundColor:e.palette.overlay.dark,justifyContent:"flex-end"},container:{backgroundColor:e.colors.base.modalContentBackground,borderTopStartRadius:8,borderTopEndRadius:8,paddingBottom:t.bottom,maxHeight:"80%"},actionItem:{height:48,flexDirection:"row",alignItems:"center",justifyContent:"flex-start",gap:24,paddingHorizontal:16}})),oi=({style:e,label:t,accessibilityLabel:n,onPress:r})=>{const s=ai.use(),{theme:o}=z();return a.createElement(P,{style:[s.button,e],onPress:r,accessibilityLabel:n,accessibilityRole:"button"},a.createElement(b,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(k,{variant:"button",color:o.colors.base.primaryContrastContent},t),a.createElement(N,{size:16,type:"chevron-down",color:o.colors.base.primaryContrastContent})))},ai=L.create(({theme:e})=>({button:{flexDirection:"row",alignItems:"center",paddingVertical:10,paddingStart:16,paddingEnd:12,borderRadius:24,backgroundColor:e.colors.base.primary,boxShadow:[{color:"rgba(13, 13, 13, 0.12)",offsetX:0,offsetY:8,blurRadius:10,spreadDistance:1},{color:"rgba(13, 13, 13, 0.08)",offsetX:0,offsetY:3,blurRadius:14,spreadDistance:2},{color:"rgba(13, 13, 13, 0.04)",offsetX:0,offsetY:3,blurRadius:5,spreadDistance:-3}]}})),gn=({iconSize:e=64,icon:t,style:n,label:r,children:s})=>{const{themedColor:o}=z();return a.createElement(b,{style:[fr.body,n]},t&&a.createElement(N,{type:t,size:e,color:o.textLowEmphasis}),r&&a.createElement(k,{variant:"body1",color:o.textMidEmphasis},r),s)},ii=({children:e})=>{const{theme:t}=z();return a.createElement(b,{backgroundColor:t.colors.base.background,style:fr.container},e)},fr=p.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),li=({label:e,icon:t="error",action:n,...r})=>{const{strings:s}=F();return a.createElement(gn,{icon:t,label:e??s.common.placeholder_something_went_wrong,...r},n&&a.createElement(ci,{onPress:n.onPress,label:n.label??s.common.placeholder_something_went_wrong_retry_label}))},ci=({label:e,onPress:t})=>{const{themedColor:n}=z();return a.createElement(P,{onPress:t},a.createElement(b,{style:ui.button},a.createElement(N,{type:"refresh",size:20}),a.createElement(k,{variant:"button",color:n.primary},e)))},ui=p.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),di=({iconSize:e=48,style:t})=>{const n=d.useRef(new p.Animated.Value(0)).current;d.useEffect(()=>{const s=p.Animated.loop(p.Animated.timing(n,{toValue:1,duration:1e3,easing:p.Easing.linear,useNativeDriver:!0}));return s.start(),()=>{s.stop()}},[n]);const r=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(b.Animated,{style:[{transform:[{rotate:r}]},t]},a.createElement(N,{type:"spinner",size:e}))},mi=({label:e,icon:t="chat",...n})=>{const{strings:r}=F();return a.createElement(gn,{icon:t,label:e??r.common.placeholder_no_conversations,...n})},gi=({label:e,icon:t="message",...n})=>{const{strings:r}=F();return a.createElement(gn,{icon:t,label:e??r.common.placeholder_no_messages,...n})},hi=e=>{const{components:t}=it.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(ii,null,n)},it=oe({template:hi,components:{Loading:di,Error:li,NoChannels:mi,NoMessages:gi}}),Te=e=>{const{Template:t}=it.useContext();return a.createElement(t,{...e})},_i=({loading:e,error:t,empty:n,stackDirection:r,data:s=[],LoadingComponent:o,ErrorComponent:i,EmptyComponent:l,...c},u)=>{if(t)return i;if(e)return o;const{contentContainerStyle:m,...h}=c,g=r==="top"&&!n;return a.createElement(p.FlatList,{ref:u,data:s,ListEmptyComponent:n?l:null,contentContainerStyle:[m,g&&Nn.stackTop,n&&Nn.emptyContainer],...h})},Nn=p.StyleSheet.create({stackTop:{flexGrow:1,justifyContent:"flex-end"},emptyContainer:{flex:1}}),pr=d.memo(d.forwardRef(_i)),hn=({name:e,type:t="FILE",onPress:n})=>{const r=fi.use();return a.createElement(P,{onPress:n,style:r.container,activeOpacity:.75},a.createElement(b,{style:r.iconWrapper},a.createElement(N,{type:"file-document",size:24,color:r.icon.tintColor})),a.createElement(b,{flex:1,flexDirection:"column",gap:4,style:r.info},a.createElement(k,{variant:"button",color:({themedColor:s})=>s.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),a.createElement(k,{variant:"caption3",color:({themedColor:s})=>s.textMidEmphasis},t)))},fi=L.create(({theme:e,themedColor:t})=>({container:{width:220,borderRadius:12,gap:8,height:64,flexDirection:"row",alignItems:"center",padding:12,borderWidth:1,borderColor:t.textDisabled,backgroundColor:t.bg_50_600},iconWrapper:{borderRadius:8,width:40,height:40,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary},icon:{tintColor:e.colors.base.primaryContrastContent},info:{alignItems:"flex-start",minWidth:0}})),pi=({file:e,children:t,onClickFile:n=({url:r})=>p.Linking.openURL(r)})=>a.createElement(b,{gap:D.GAP_GROUPED,width:D.BODY_MAX_WIDTH,maxWidth:D.BODY_MAX_WIDTH},a.createElement(hn,{name:e.name,type:Qt(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),we=({style:e,...t})=>a.createElement(p.Image,{style:[e,t],...t}),yi=({file:e,onClickMedia:t=({url:r})=>p.Linking.openURL(r),children:n})=>{const r=bi.use();return a.createElement(b,{gap:D.GAP_GROUPED},a.createElement(P,{style:r.mediaContainer,onPress:()=>t==null?void 0:t(e)},a.createElement(we,{source:{uri:e.url},style:r.media,resizeMode:"cover"})),n)},bi=L.create(({select:e,theme:t})=>({mediaContainer:{width:D.BODY_MAX_WIDTH,height:160,borderRadius:12,overflow:"hidden",backgroundColor:e({light:t.palette.background100,dark:t.palette.background400})},media:{width:"100%",height:"100%"}})),yr=({code:e,language:t})=>{const[n,r]=d.useState(!1),s=async()=>{Qr.default.setString(e),r(!0),setTimeout(()=>r(!1),2e3)};return a.createElement(b,{style:We.container,flexDirection:"row"},a.createElement(p.Pressable,{style:We.copyButton,onPress:s},a.createElement(N,{type:n?"done":"copy",size:16,color:"#fff"})),a.createElement(b,null,a.createElement(es.default,{hljsStyle:Ci,scrollViewProps:{contentContainerStyle:We.codeContainer,bounces:!1},textStyle:We.codeText,language:t},e)))},We=p.StyleSheet.create({container:{marginVertical:4},copyButton:{opacity:.6,position:"absolute",top:8,right:8,zIndex:1,backgroundColor:"#000",borderRadius:4,width:28,height:28,justifyContent:"center",alignItems:"center"},copyButtonText:{fontSize:12},codeContainer:{minWidth:"100%",padding:12},codeText:{fontSize:13,lineHeight:19}}),Ci={hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:"#abb2bf",background:"#282c34"},"hljs-keyword":{color:"#F92672"},"hljs-operator":{color:"#F92672"},"hljs-pattern-match":{color:"#F92672"},"hljs-pattern-match .hljs-constructor":{color:"#61aeee"},"hljs-function":{color:"#61aeee"},"hljs-function .hljs-params":{color:"#A6E22E"},"hljs-function .hljs-params .hljs-typing":{color:"#FD971F"},"hljs-module-access .hljs-module":{color:"#7e57c2"},"hljs-constructor":{color:"#e2b93d"},"hljs-constructor .hljs-string":{color:"#9CCC65"},"hljs-comment":{color:"#b18eb1",fontStyle:"italic"},"hljs-quote":{color:"#b18eb1",fontStyle:"italic"},"hljs-doctag":{color:"#c678dd"},"hljs-formula":{color:"#c678dd"},"hljs-section":{color:"#e06c75"},"hljs-name":{color:"#e06c75"},"hljs-selector-tag":{color:"#e06c75"},"hljs-deletion":{color:"#e06c75"},"hljs-subst":{color:"#e06c75"},"hljs-literal":{color:"#56b6c2"},"hljs-string":{color:"#98c379"},"hljs-regexp":{color:"#98c379"},"hljs-addition":{color:"#98c379"},"hljs-attribute":{color:"#98c379"},"hljs-meta-string":{color:"#98c379"},"hljs-built_in":{color:"#e6c07b"},"hljs-class .hljs-title":{color:"#e6c07b"},"hljs-attr":{color:"#d19a66"},"hljs-variable":{color:"#d19a66"},"hljs-template-variable":{color:"#d19a66"},"hljs-type":{color:"#d19a66"},"hljs-selector-class":{color:"#d19a66"},"hljs-selector-attr":{color:"#d19a66"},"hljs-selector-pseudo":{color:"#d19a66"},"hljs-number":{color:"#d19a66"},"hljs-symbol":{color:"#61aeee"},"hljs-bullet":{color:"#61aeee"},"hljs-link":{color:"#61aeee",textDecoration:"underline"},"hljs-meta":{color:"#61aeee"},"hljs-selector-id":{color:"#61aeee"},"hljs-title":{color:"#61aeee"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},br=d.memo(({src:e,onPress:t})=>{const[n,r]=d.useState("1/1"),[s,o]=d.useState(!1),i=Ei.use();return d.useLayoutEffect(()=>{e&&cr(e).then(({width:l,height:c})=>r(`${l}/${c}`))},[e]),a.createElement(p.Pressable,{style:{marginTop:8},onPress:t},a.createElement(b,{style:[i.container,{aspectRatio:n}]},s?a.createElement(N,{size:28,type:"thumbnail-none",color:({themedColor:l})=>l.textHighEmphasisInverse}):a.createElement(p.Image,{source:{uri:e},style:p.StyleSheet.absoluteFillObject,onError:()=>o(!0)})))}),Ei=L.create(({themedColor:e})=>({container:{width:"100%",backgroundColor:e.textDisabled,borderRadius:4,overflow:"hidden",justifyContent:"center",alignItems:"center"}}));br.displayName="MarkdownImage";const Le=e=>d.isValidElement(e)&&"children"in e.props,Zt=(e=.75)=>`rgba(0, 0, 0, ${e})`,vi=({children:e})=>{var i;const t=p.useWindowDimensions(),n=Zt(.3),r=d.useMemo(()=>{try{if(!Array.isArray(e)||e.length<2)return null;const l=e[0],c=e[1],u=Le(c)?c.props.children:void 0;if(!u||!Array.isArray(u)||u.length===0)return null;const m=u,h=m[0],g=Le(h)?h.props.children:void 0;if(!g||!Array.isArray(g)||g.length===0)return null;const y=m.length,C=g.length,E=Array(C).fill(null).map(()=>[]);for(let S=0;S<y;S++){const T=m[S],w=Le(T)?T.props.children:void 0;if(!(!w||!Array.isArray(w)))for(let R=0;R<C;R++){const O=E[R];O&&R<w.length&&(O[S]=w[R])}}const _=Le(l)?l.props.children:void 0,v=Array.isArray(_)?_[0]:void 0,A=Le(v)?v.props.children:void 0;if(A&&Array.isArray(A))for(let S=0;S<C;S++){const T=E[S];T&&S<A.length&&T.unshift(A[S])}return E}catch{return null}},[e]),[s,o]=d.useState(Array(((i=r==null?void 0:r[0])==null?void 0:i.length)??0).fill(0));return r?a.createElement(p.View,{style:{flexDirection:"row"}},r.map((l,c)=>{const u=c===0,m=c===r.length-1;return a.createElement(p.View,{key:c,style:{flexDirection:"column",borderStartWidth:1,borderEndWidth:m?1:0,borderTopWidth:1,borderBottomWidth:1,borderColor:n,borderTopStartRadius:u?6:0,borderBottomStartRadius:u?6:0,borderTopEndRadius:m?6:0,borderBottomEndRadius:m?6:0}},l.map((h,g)=>{const y=g===0,C=g===l.length-1;return a.createElement(p.View,{key:g,onLayout:({nativeEvent:{layout:E}})=>{const _=E.height;(s[g]??0)<_&&(s[g]=_,o([...s]))},style:{borderBottomWidth:C?0:1,borderColor:n,backgroundColor:y?Zt(.15):"transparent",maxWidth:t.width*2/3,minHeight:(s[g]??0)>0?s[g]:void 0,padding:8}},h)}))})):a.createElement(p.View,null,e)},_n=d.memo(({children:e,textStyle:t,linkStyle:n,onPressImage:r})=>{const{themedColor:s}=z(),o=p.StyleSheet.compose({fontSize:14,color:s.textHighEmphasis,textAlign:"left"},t),i=p.StyleSheet.flatten(o),l=i.fontSize||14,c=i.lineHeight||l*1.286,u=Zt(.3),m={color:i.color,textAlign:mn.useTextAlign({text:e,style:i}),fontSize:l,lineHeight:c,fontWeight:i.fontWeight,fontFamily:i.fontFamily,fontStyle:i.fontStyle,letterSpacing:i.letterSpacing,textDecorationLine:i.textDecorationLine,textDecorationStyle:i.textDecorationStyle,textDecorationColor:i.textDecorationColor},h=d.useMemo(()=>({image:g=>{var C,E;const y=((C=g.attributes)==null?void 0:C.src)||((E=g.attributes)==null?void 0:E.href);return y?a.createElement(br,{key:g.key,src:y,onPress:()=>r==null?void 0:r(y)}):null},code_block:g=>a.createElement(yr,{code:g.content,language:"text"}),table:(g,y)=>a.createElement(p.View,{key:g.key,style:{marginTop:8}},a.createElement(p.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},a.createElement(vi,null,y)))}),[r]);return a.createElement(b,{flexDirection:"row",marginTop:-8},a.createElement(ts.default,{style:{body:{...m,width:e.length>50?"100%":void 0,marginBottom:0},paragraph:{...m,marginTop:8,marginBottom:0},heading1:{...m,marginTop:8,marginBottom:0,fontSize:l*1.429,lineHeight:l*1.429*1.4,fontWeight:"700"},heading2:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.286,lineHeight:l*1.286*1.333},heading3:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading4:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading5:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading6:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},link:p.StyleSheet.flatten(p.StyleSheet.compose({...m,fontWeight:"700",textDecorationLine:"underline"},n)),code_inline:{...m,fontSize:l*.929,lineHeight:l*.929*1.538,fontWeight:"600",backgroundColor:u},code_block:{...m,borderWidth:0,backgroundColor:u,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538},fence:{...m,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538,backgroundColor:s.textDisabled},bullet_list:{marginTop:4,marginBottom:0},bullet_list_icon:{marginLeft:0,marginRight:4,fontWeight:"900"},ordered_list:{marginTop:4,marginBottom:0},ordered_list_icon:{marginLeft:0,marginRight:4},list_item:{...m,marginTop:4,marginBottom:0},blockquote:{...m,paddingStart:8,marginTop:8,marginBottom:0,paddingVertical:4,borderStartWidth:4,borderStartColor:u,backgroundColor:"transparent",fontWeight:"500",fontSize:l,lineHeight:c},hr:{backgroundColor:u,height:1,marginTop:8,marginBottom:0},th:{...m,padding:4,fontSize:l,lineHeight:l*1.143,fontWeight:"700"},td:{...m,padding:2,fontSize:l,lineHeight:l*1.429},image:{maxHeight:300,maxWidth:"100%"}},rules:h},cs(e)))});_n.displayName="MarkdownText";const Hn=({maxBodyWidth:e,customStyle:t,message:n,children:r})=>{const s=Si.use(),o=e??D.BODY_MAX_WIDTH,i=d.useMemo(()=>os(n),[n]),l=d.useCallback(c=>p.Linking.openURL(c),[]);return i.length===0&&!r?null:a.createElement(b,{alignSelf:"flex-start",maxWidth:o,borderRadius:12,paddingVertical:12,style:[s.container,(t==null?void 0:t.bubbleBackgroundColor)&&{backgroundColor:t==null?void 0:t.bubbleBackgroundColor}]},i.map((c,u)=>c.type==="text"?a.createElement(b,{key:u,paddingHorizontal:12},a.createElement(_n,{onPressImage:l,textStyle:s.text},c.value)):c.type==="code"?a.createElement(yr,{key:u,code:c.value,language:c.language}):null),r)},Si=L.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),Ai=e=>{const{strings:t}=F(),n=()=>{const r=Xn(e)?a.createElement(Hn,{...e}):null;return e.messageType==="user"?r:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(yi,{...e},r):a.createElement(pi,{...e},r):a.createElement(Hn,{...e,message:t.conversation.unknown_message_type})};return a.createElement(b,{style:e.containerStyle},n())};function Cr({id:e,src:t,size:n=56,onClick:r,style:s}){const o=Ii.use(),i=a.createElement(p.View,{style:[o.container(n),s],testID:e},t?a.createElement(p.Image,{source:{uri:t},style:o.image}):a.createElement(N,{type:"user",size:n}));return r?a.createElement(P,{onPress:r,activeOpacity:.75},i):i}const Ii=L.create(({themedColor:e})=>({container:t=>({borderRadius:t/2,overflow:"hidden",position:"relative",height:t,width:t,backgroundColor:e.bg_100_500,alignItems:"center",justifyContent:"center"}),image:{width:"100%",height:"100%",position:"absolute"}})),Ti=({sender:e,isBotMessage:t})=>{const n=wi.use();return t&&!e.profileUrl?a.createElement(b,{style:n.botContainer},a.createElement(N,{type:"delight",color:({theme:r})=>r.colors.base.primaryContrastContent,size:D.AVATAR_SIZE-8})):a.createElement(Cr,{src:e.profileUrl,size:D.AVATAR_SIZE})},wi=L.create(({theme:e})=>({botContainer:{width:D.AVATAR_SIZE,height:D.AVATAR_SIZE,borderRadius:D.AVATAR_SIZE/2,padding:4,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary}})),xi=({sender:e})=>a.createElement(b,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7,alignItems:"flex-start"},a.createElement(k,{variant:"caption1",color:({themedColor:t})=>t.textMidEmphasis,numberOfLines:1},e.nickname)),ki=({createdAt:e,containerStyle:t})=>{const{strings:n,format:r}=F();return e?a.createElement(b,{alignItems:"flex-start",style:t},a.createElement(k,{variant:"caption4",color:({themedColor:s})=>s.textLowEmphasis},r(e,n.date_format.message_timestamp))):null},Ri=()=>{var e;return p.Platform.OS==="web"?{major:0,minor:0,patch:0}:((e=p.Platform.constants)==null?void 0:e.reactNativeVersion)??{major:0,minor:0,patch:0}},Mi=.33,Bn=e=>{var t;(t=e.current)==null||t.stop(),e.current=null},Di=e=>{const[t,n]=d.useState(0),r=d.useRef(new p.Animated.Value(0)).current,s=d.useRef(new p.Animated.Value(0)).current,o=d.useRef(null),i=d.useCallback(u=>{const{width:m}=u.nativeEvent.layout;n(h=>h===m?h:m)},[]),l=t*Mi,c=d.useMemo(()=>s.interpolate({inputRange:[0,1],outputRange:p.I18nManager.isRTL?[t+l,-l]:[-l,t+l]}),[l,t,s]);return d.useEffect(()=>{if(!e){Bn(o),r.setValue(0),s.setValue(0);return}r.setValue(0),s.setValue(0),p.Animated.timing(r,{toValue:1,duration:400,easing:p.Easing.inOut(p.Easing.ease),useNativeDriver:!0}).start();const u=p.Animated.loop(p.Animated.timing(s,{toValue:1,duration:1600,easing:p.Easing.linear,useNativeDriver:!0}));return o.current=u,u.start(),()=>{Bn(o)}},[e,s,r]),{bandWidth:l,onLayout:i,shimmerTranslateX:c,textFadeAnim:r}},{major:Li,minor:Pi}=Ri(),Oi=Li>0||Pi>=76,Ni=e=>{if(Oi){const t=yt(e,.5),n=yt(e,0),r=`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`;return{experimental_backgroundImage:r,backgroundImage:r}}return{backgroundColor:yt(e,.3)}},Hi=e=>{var t,n;(t=e.current)==null||t.stop(),(n=e.current)==null||n.reset(),e.current=null},Bi=({thinkingMessage:e,customStyle:t,containerStyle:n})=>{const{theme:r,themedColor:s}=z(),o=d.useRef(new p.Animated.Value(0)).current,i=d.useRef(null),l=d.useMemo(()=>Ui.map(([g,y,C])=>[o.interpolate({inputRange:g,outputRange:y,extrapolate:"clamp"}),o.interpolate({inputRange:g,outputRange:C,extrapolate:"clamp"})]),[o]),{bandWidth:c,onLayout:u,shimmerTranslateX:m,textFadeAnim:h}=Di(!!e);return d.useEffect(()=>{if(e)return;const g=p.Animated.loop(p.Animated.timing(o,{toValue:1.4,duration:1400,easing:p.Easing.linear,useNativeDriver:!0}));return i.current=g,g.start(),()=>{Hi(i),o.setValue(0)}},[o,e]),e?a.createElement(b,{style:n},a.createElement(b.Animated,{style:{opacity:h}},a.createElement(b,{style:Dt.thinkingMessageContainer,onLayout:u},a.createElement(k,{variant:"body3",color:s.textHighEmphasis},e),a.createElement(b.Animated,{style:[Dt.shimmerOverlay,{width:c||p.StyleSheet.hairlineWidth,...Ni(r.colors.base.background),transform:[{translateX:m}]}],pointerEvents:"none"})))):a.createElement(b,{style:n},a.createElement(b,{width:60,flexDirection:"row",alignItems:"center",justifyContent:"center",borderRadius:16,paddingHorizontal:12,height:26,backgroundColor:(t==null?void 0:t.bubbleBackgroundColor)??r.colors.messageIncoming.background},l.map(([g,y],C)=>a.createElement(b.Animated,{key:C,style:[Dt.dot,{marginEnd:C===l.length-1?0:6,opacity:y,transform:[{scale:g}],backgroundColor:(t==null?void 0:t.bubbleContentColor)??r.colors.messageIncoming.text}]}))))},Ui=[[[.4,.7,1],[1,1.2,1],[.12,.38,.12]],[[.6,.9,1.2],[1,1.2,1],[.12,.38,.12]],[[.8,1.1,1.4],[1,1.2,1],[.12,.38,.12]]],Dt=p.StyleSheet.create({dot:{width:8,height:8,borderRadius:4},thinkingMessageContainer:{position:"relative",overflow:"hidden",alignSelf:"flex-start"},shimmerOverlay:{position:"absolute",top:0,left:0,height:"100%"}}),Fi=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>p.Linking.openURL(n)})=>{const n=zi.use(),r=e==null?void 0:e.cta_button;return r?a.createElement(P,{onPress:()=>t(r),activeOpacity:.75,style:n.button},a.createElement(k,{variant:"button",color:({themedColor:s})=>s.textHighEmphasis,numberOfLines:1},r.label)):null},zi=L.create(({select:e,themedColor:t})=>({button:{alignItems:"center",justifyContent:"center",borderRadius:6,paddingVertical:8,paddingHorizontal:8,backgroundColor:e({light:t.bg_50_600,dark:t.textDisabled})}})),$i=({extendedMessagePayload:e,onClickCitation:t=n=>p.Linking.openURL(n.link)})=>{const{strings:n}=F(),{theme:r}=z(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(b,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},a.createElement(k,{variant:"caption1",color:r.colors.messageIncoming.text,style:Un.sourceLabel},n.conversation.citation_title),a.createElement(b,{gap:8},s.map(o=>a.createElement(P,{key:o.embedding_id,onPress:()=>t(o),activeOpacity:.5},a.createElement(b,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(N,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(b,{flex:1},a.createElement(k,{variant:"body3",color:r.colors.messageIncoming.text,numberOfLines:1,style:Un.citationText},o.title)))))))},Un=p.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),Vi=e=>a.createElement(a.Fragment,null),Jt=e=>`${e}-filled`,qi=e=>e==="good"?X.AIAgentMessageFeedbackRating.GOOD:X.AIAgentMessageFeedbackRating.BAD,Fn=({onClose:e,isEdit:t,initialRating:n,initialComment:r="",isCommentEnabled:s=!1})=>{const{strings:o}=F(),{themedColor:i,theme:l}=z(),c=ji.use(),[u,m]=d.useState(r),[h,g]=d.useState(n),y=()=>{h&&e({rating:h,comment:u.trim()||void 0})},C=()=>{e()},E={good:i.secondary,bad:i.error};return a.createElement(p.KeyboardAvoidingView,{style:{flex:1},behavior:"padding"},a.createElement(P,{onPress:C,style:c.overlay},a.createElement(b,{width:280,backgroundColor:l.colors.base.modalContentBackground,borderRadius:12,overflow:"hidden",onStartShouldSetResponder:()=>!0},a.createElement(b,{padding:24},a.createElement(k,{variant:"h2",color:i.textHighEmphasis},o.feedback.title)),a.createElement(b,{paddingHorizontal:24,gap:24},a.createElement(b,{flexDirection:"row",gap:4},["good","bad"].map(_=>{const v=h===_,A=_==="good"?o.feedback.good:o.feedback.bad;return a.createElement(P,{key:_,onPress:()=>g(_),activeOpacity:.6,style:c.ratingButton(v)},a.createElement(N,{type:v?Jt(_):_,size:24,color:v?E[_]:i.textLowEmphasis}),a.createElement(k,{variant:"caption1",color:v?E[_]:i.textLowEmphasis},A))})),s&&a.createElement(b,{gap:6},a.createElement(k,{variant:"caption3",color:i.textHighEmphasis},o.feedback.comment_label),a.createElement(p.TextInput,{value:u,onChangeText:_=>m(_),placeholder:o.feedback.comment_placeholder,placeholderTextColor:i.textLowEmphasis,multiline:!0,maxLength:100,style:c.commentInput}))),a.createElement(b,{paddingHorizontal:24,paddingVertical:16,flexDirection:"row",justifyContent:"flex-end",gap:4},a.createElement(P,{onPress:C,activeOpacity:.6,style:c.cancelButton},a.createElement(k,{variant:"button",color:i.textHighEmphasis},o.feedback.cancel)),a.createElement(P,{onPress:y,disabled:!h,activeOpacity:.6,style:c.submitButton(!h)},a.createElement(k,{variant:"button",color:l.colors.base.primaryContrastContent},t?o.feedback.save:o.feedback.submit))))))},ji=L.create(({select:e,theme:t,themedColor:n})=>({overlay:{flex:1,backgroundColor:t.palette.overlay.dark,alignItems:"center",justifyContent:"center"},ratingButton:r=>({width:114,height:64,borderRadius:12,borderWidth:1,borderColor:n.textDisabled,alignItems:"center",justifyContent:"center",gap:0,backgroundColor:r?e({light:t.palette.background100,dark:t.palette.background600}):"transparent"}),commentInput:{width:"100%",maxHeight:118,borderRadius:4,borderWidth:1,borderColor:n.textDisabled,backgroundColor:n.textLowEmphasisInverse,color:n.textHighEmphasis,paddingHorizontal:12,paddingVertical:6,fontSize:12,lineHeight:16,textAlignVertical:"top"},cancelButton:{width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},submitButton:r=>({width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center",backgroundColor:t.colors.base.primary,opacity:r?.4:1})})),Gi=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i,containerStyle:l})=>{const{strings:c}=F(),{themedColor:u}=z(),{openModal:m}=ot(),h=Wi.use(),g=o==null?void 0:o.feedback,y=(g==null?void 0:g.rating)??"none";if(y!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const E={good:u.secondary,bad:u.error},_=async S=>{const T=await m(w=>a.createElement(Fn,{onClose:w,isEdit:!1,initialRating:S,initialComment:"",isCommentEnabled:s}));T&&(i==null||i(T))},v=async()=>{const S=await m(T=>a.createElement(ee,{onClose:()=>T()},a.createElement(ee.ActionItem,{onPress:()=>T("edit"),label:c.feedback.edit}),a.createElement(ee.ActionItem,{onPress:()=>T("remove"),label:c.feedback.remove,destructive:!0})));if(S==="edit"){const T=await m(w=>a.createElement(Fn,{onClose:w,isEdit:!0,initialRating:g==null?void 0:g.rating,initialComment:g==null?void 0:g.comment,isCommentEnabled:s}));T&&(i==null||i(T))}else S==="remove"&&(i==null||i(null))},A=()=>t&&y!=="none"?a.createElement(b,{flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:D.BODY_MAX_WIDTH},a.createElement(b,{padding:2,flexShrink:0,alignItems:"center"},a.createElement(N,{type:Jt(y),size:12,color:E[y]})),(g==null?void 0:g.comment)&&a.createElement(k,{variant:"caption2",style:h.commentText},g.comment)):a.createElement(b,{gap:4,maxWidth:D.BODY_MAX_WIDTH},a.createElement(b,{flexDirection:"row",gap:2},["good","bad"].map(S=>{const T=y===S;return a.createElement(P,{key:S,onPress:()=>{y==="none"?_(S):v()},activeOpacity:.6,style:h.feedbackButton(T)},a.createElement(N,{type:T?Jt(S):S,size:14,color:T?E[S]:u.textMidEmphasis}))})),y!=="none"&&(g==null?void 0:g.comment)&&a.createElement(k,{variant:"caption2",style:h.commentText},g.comment));return a.createElement(b,{style:l},A())},Wi=L.create(({select:e,theme:t,themedColor:n})=>({feedbackButton:r=>({width:38,height:20,borderRadius:18,alignItems:"center",justifyContent:"center",borderWidth:1,borderColor:e({light:t.palette.background200,dark:t.palette.background400}),backgroundColor:r?e({light:t.palette.background100,dark:t.palette.background500}):"transparent"}),commentText:{lineHeight:16,color:e({light:n.textMidEmphasis,dark:n.textHighEmphasis})}})),Ki=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},Yi=e=>null,Er=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:r,...s})=>a.createElement(p.ScrollView,{style:[t,s,e&&un],showsHorizontalScrollIndicator:n,...s},r),Xi=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const r=Zi.use(),[s,o]=d.useState(!1),i=(e==null?void 0:e.suggested_replies)??[];if(i.length===0||s)return null;const l=n==="vertical",c=m=>{t==null||t({reply:m}),o(!0)},u=()=>i.map((m,h)=>a.createElement(P,{key:h,style:r.itemContainer,onPress:()=>c(m)},a.createElement(k,{variant:"body3",color:({themedColor:g})=>g.primary},m)));return l?a.createElement(b,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:D.HORIZONTAL_PADDING},u()):a.createElement(Er,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:r.horizontalContainer},u())},Zi=L.create(({themedColor:e})=>({itemContainer:{maxWidth:336,paddingHorizontal:12,paddingVertical:8,borderRadius:16,borderWidth:1,borderColor:e.primary,backgroundColor:e.bg_50_600},horizontalContainer:{gap:8,paddingHorizontal:D.HORIZONTAL_PADDING,paddingVertical:16}})),Ji=e=>{var _,v,A,S,T,w,R;const{components:t}=lt.useContext(),{streamText:n,isAnimating:r}=Wo({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,i=!!s.isSenderAvatarVisible,l=!!((_=s.extendedMessagePayload)!=null&&_.form)&&!((v=s.extendedMessagePayload)!=null&&v.form.canceled_at),c=!!((A=s.extendedMessagePayload)!=null&&A.message_template),u=!!((S=s.extendedMessagePayload)!=null&&S.cta_button),m=!!((T=s.extendedMessagePayload)!=null&&T.citations)&&s.extendedMessagePayload.citations.length>0,h=!!s.createdAt,g=s.groupType==="top"||s.groupType==="single",y=s.groupType==="bottom"||s.groupType==="single",C=i?D.AVATAR_SIZE:0,E=Qi.use();return a.createElement(b,{marginBottom:o?0:en(s.groupType)},g&&a.createElement(b,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:D.HORIZONTAL_PADDING},i&&a.createElement(t.SenderAvatar,{...s}),a.createElement(t.SenderName,{...s})),a.createElement(b,{gap:D.GAP_GROUPED},o?a.createElement(t.TypingIndicator,{...s,containerStyle:E.middleArea(C)}):a.createElement(t.MessageBody,{...s,containerStyle:E.middleArea(C)},u&&a.createElement(b,{marginTop:12,marginHorizontal:12},a.createElement(t.CTAButton,{...s})),m&&a.createElement(t.Citation,{...s})),c&&a.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??a.createElement(t.MessageBody,{...s,messageType:"user",message:((R=(w=s.extendedMessagePayload)==null?void 0:w.message_template)==null?void 0:R.fallback_message)??"Cannot read this template.",containerStyle:E.middleArea(C)}),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??a.createElement(t.TypingIndicator,{...s,containerStyle:E.middleArea(C)})}),a.createElement(t.CustomMessageTemplate,{...s}),l&&a.createElement(t.Form,{...s,containerStyle:E.middleArea(C)})),y&&h&&a.createElement(t.SentTime,{...s,containerStyle:E.bottomArea(C)}),a.createElement(d.Fragment,null,!o&&a.createElement(t.Feedback,{...s,containerStyle:E.feedbackArea(C)}),s.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...s})))},lt=oe({template:Ji,components:{SenderName:xi,SenderAvatar:Ti,SentTime:ki,MessageBody:Ai,TypingIndicator:Bi,SuggestedReplies:Xi,MessageTemplate:Yi,CustomMessageTemplate:Vi,CTAButton:Fi,Citation:$i,Form:Ki,Feedback:Gi}}),Qi=L.create(()=>({middleArea:e=>({paddingStart:D.HORIZONTAL_PADDING+e,paddingEnd:D.HORIZONTAL_PADDING}),bottomArea:e=>({marginTop:D.BODY_TIME_GAP,paddingStart:D.HORIZONTAL_PADDING+e+8,paddingEnd:D.HORIZONTAL_PADDING}),feedbackArea:e=>({marginTop:8,paddingStart:D.HORIZONTAL_PADDING+e+8,paddingEnd:D.HORIZONTAL_PADDING})})),el=({file:e,children:t,sendingStatus:n,onClickFile:r=({url:s})=>p.Linking.openURL(s)})=>{const s=(()=>{if(!(!r||n!=="succeeded"))return()=>r(e)})();return a.createElement(b,{flexDirection:"column",alignItems:"flex-end",gap:D.GAP_GROUPED,width:D.BODY_MAX_WIDTH,maxWidth:D.BODY_MAX_WIDTH},a.createElement(hn,{name:e.name,type:Qt(e.name,e.type),onPress:s}),t)},vr=({size:e=26,children:t})=>{const n=d.useRef(new p.Animated.Value(0)).current;d.useEffect(()=>{const s=p.Animated.loop(p.Animated.timing(n,{toValue:1,duration:1e3,easing:p.Easing.linear,useNativeDriver:!0}));return s.start(),()=>{s.stop()}},[n]);const r=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(b.Animated,{style:{transform:[{rotate:r}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??a.createElement(N,{type:"spinner",size:e}))};function tl(e){return typeof e=="object"&&e!==null&&"uri"in e}const nl=({file:e,metadata:t,sendingStatus:n,onClickMedia:r=({url:o})=>p.Linking.openURL(o),children:s})=>{const o=rl.use(),{aspectRatio:i,localFile:l}=t,[c]=d.useState(()=>tl(l)?l.uri:e.url),[u,m]=d.useState(!1),h=(()=>{if(!(!r||n!=="succeeded"))return()=>r(e)})();return a.createElement(b,{flexDirection:"column",alignItems:"flex-end",gap:D.GAP_GROUPED},a.createElement(P,{onPress:h,style:[o.imageContainer,{aspectRatio:i}],activeOpacity:.75},!u&&a.createElement(b,{alignItems:"center",justifyContent:"center"},a.createElement(vr,{size:26},a.createElement(N,{type:"spinner",color:({themedColor:g})=>g.textLowEmphasis,size:26}))),a.createElement(we,{source:{uri:c},style:[o.image,{opacity:u?1:0}],resizeMode:"cover",onLoad:()=>m(!0)})),s)},rl=L.create(({themedColor:e})=>({imageContainer:{width:D.BODY_MAX_WIDTH,borderRadius:12,overflow:"hidden",position:"relative",alignItems:"center",justifyContent:"center",backgroundColor:e.bg_100_500},image:{position:"absolute",width:"100%",height:"100%",top:0,left:0}})),zn=e=>{var n,r;const t=sl.use();return a.createElement(b,{style:[t.container({maxWidth:e.maxBodyWidth??D.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},a.createElement(k,{variant:"body3",style:[t.text,((r=e.customStyle)==null?void 0:r.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},sl=L.create(({theme:e})=>({container:t=>({flexDirection:"column",borderRadius:12,overflow:"hidden",maxWidth:t.maxWidth,backgroundColor:e.colors.messageOutgoing.background,paddingVertical:12}),text:{textAlign:"left",lineHeight:20,paddingHorizontal:12,color:e.colors.messageOutgoing.text}})),ol=e=>{const{strings:t}=F(),n=()=>{const r=Xn(e)?a.createElement(zn,{...e}):null;return e.messageType==="user"?r:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(nl,{...e},r):a.createElement(el,{...e},r):a.createElement(zn,{...e,message:t.unknown_message_type})};return a.createElement(P,{onPress:e.sendingStatus==="failed"?e.onClickFailedMessage:void 0,activeOpacity:.75},a.createElement(b,{style:e.containerStyle},n()))},al=({sendingStatus:e,containerStyle:t})=>{const{themedColor:n}=z(),r=()=>{switch(e){case"pending":return a.createElement(b,{marginBottom:2},a.createElement(vr,{size:16},a.createElement(N,{type:"spinner",color:n.primary,size:16})));case"failed":return a.createElement(b,{marginBottom:2},a.createElement(N,{type:"error",color:n.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement(b,{marginBottom:2},a.createElement(N,{type:"done",color:n.secondary,size:16}))}};return a.createElement(b,{style:t},r())},il=({createdAt:e,containerStyle:t})=>{const{format:n,strings:r}=F();return e?a.createElement(b,{style:t},a.createElement(k,{variant:"caption4",color:({themedColor:s})=>s.textLowEmphasis},n(e,r.date_format.message_timestamp))):null},ll=e=>{const{components:t}=ct.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(b,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:en(e.groupType)},a.createElement(t.MessageBody,{...e,containerStyle:Lt.middleArea}),r&&(n?a.createElement(t.SentTime,{...e,containerStyle:Lt.bottomArea}):a.createElement(t.SendingStatus,{...e,containerStyle:Lt.bottomArea})))},ct=oe({template:ll,components:{SendingStatus:al,SentTime:il,MessageBody:ol}}),Lt=p.StyleSheet.create({middleArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:D.HORIZONTAL_PADDING},bottomArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingStart:D.HORIZONTAL_PADDING,paddingEnd:D.HORIZONTAL_PADDING+8,marginTop:D.BODY_TIME_GAP}}),cl=e=>e.messageType!=="admin"?null:a.createElement(k,{variant:"caption2",color:({themedColor:t})=>t.textMidEmphasis,style:{textAlign:"center"}},ul(e.message)),ul=e=>{try{const t=[];let n=e,r=0;for(;n;){const s=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),o=n.match(/\*\*([^*]+)\*\*/),i=[s&&{match:s,type:"link"},o&&{match:o,type:"bold"}].filter(h=>!!h);if(!i.length){t.push(n);break}const l=i.reduce((h,g)=>g.match.index<h.match.index?g:h),{match:c,type:u}=l,m=c.index;m>0&&t.push(n.slice(0,m)),u==="link"?t.push(a.createElement(p.Text,{key:r++,onPress:()=>p.Linking.openURL((c==null?void 0:c[2])??""),style:{textDecorationLine:"underline"}},c[1])):u==="bold"&&t.push(a.createElement(p.Text,{key:r++,style:{fontWeight:"bold"}},c[1])),n=n.slice(m+c[0].length)}return t.filter(s=>s!=="")}catch{return[e]}},dl=({children:e,style:t})=>a.createElement(k,{variant:"caption4",color:({themedColor:n})=>n.error,style:t},e),ml=({children:e,style:t,required:n})=>{const{strings:r}=F();return a.createElement(k,{variant:"caption3",color:({themedColor:s})=>s.textMidEmphasis,style:t},e,!n&&a.createElement(k,{variant:"caption3",color:({themedColor:s})=>s.textLowEmphasis},` (${r.form.optional_label})`))},gl=({style:e})=>{const t=hl.use();return a.createElement(b,{style:[t.separator,e]})},hl=L.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),_l=({value:e="",onChange:t,placeholder:n,variant:r="single-line",error:s=!1,submitted:o=!1,style:i,disabled:l=!1,maxLength:c})=>{const[u,m]=d.useState(!1),h=fl.use(),{themedColor:g}=z(),y=C=>{c&&C.length>c||t==null||t(C)};return a.createElement(p.TextInput,{value:e,onChangeText:y,placeholder:n,editable:!l&&!o,maxLength:c,multiline:r==="multi-line",style:[h.input(r,s,o,u),i],placeholderTextColor:g.textLowEmphasis,onFocus:()=>m(!0),onBlur:()=>m(!1)})},fl=L.create(({select:e,theme:t,themedColor:n})=>({input:(r,s,o,i)=>{let l,c;o?(l="transparent",c=e({light:t.palette.ondark.textMidEmphasis,dark:t.palette.onlight.textLowEmphasis})):s?(l=n.error,c=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis})):(l=i?n.primary:n.textDisabled,c=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis}));const u={width:"100%",padding:8,paddingHorizontal:12,borderRadius:6,fontSize:14,fontWeight:"400",lineHeight:20,borderWidth:1,borderColor:l,backgroundColor:c,color:o?n.textLowEmphasis:n.textHighEmphasis};return r==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),Oe={Label:ml,ErrorLabel:dl,TextInput:_l,Separator:gl},Sr=({onClick:e,checked:t,label:n,disabled:r,labelVariant:s="caption2"})=>{const{themedColor:o}=z(),i=pl.use(),l=t?o.primary:r?o.textDisabled:o.textLowEmphasis;return a.createElement(P,{disabled:r||!e,onPress:e},a.createElement(b,{style:i.container},a.createElement(b,{style:i.iconContainer},a.createElement(N,{size:20,type:t?"radio-on":"radio-off",color:l})),a.createElement(k,{variant:s,style:i.label(t,r)},n)))},pl=L.create(({themedColor:e})=>({container:{flexDirection:"row",alignItems:"flex-start",justifyContent:"flex-start",width:"100%",gap:2},iconContainer:{width:20,height:20},label:(t,n)=>{let r;return t?r=e.textHighEmphasis:n?r=e.textLowEmphasis:r=e.textHighEmphasis,{flex:1,color:r,lineHeight:20}}})),yl=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>(d.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n,s]),e.cre?a.createElement(b,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(Oe.Label,{required:e.cre.required},e.cre.question),a.createElement(b,{flexDirection:"column",gap:8,width:"100%"},[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(o=>a.createElement(Sr,{key:o.label,checked:r===o.value,label:o.label,disabled:t,onClick:()=>s==null?void 0:s(o.value)})))):null),bl=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{strings:o}=F();return a.createElement(b,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(Oe.Label,{required:e.required},e.question),e.response_type==="free_text"&&a.createElement(Oe.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>r(i),error:s}),e.response_type==="single_choice"&&a.createElement(b,{flexDirection:"column",gap:8,width:"100%"},e.options.map(i=>a.createElement(Sr,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>r==null?void 0:r(i),labelVariant:"body3"}))),s&&a.createElement(Oe.ErrorLabel,null,o.form.validation_required))},Cl=e=>null,El=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",o=Ar.use(),[i,l]=d.useState(16);return a.createElement(b,{onLayout:c=>{c.nativeEvent.layout.width<300&&l(0)},flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(k,{variant:"caption3",color:({themedColor:c})=>c.textMidEmphasis},e.csat_question),a.createElement(b,{style:[o.scoresContainer,{gap:i}]},e.csat_scores.map(({label:c,image_url:u},m)=>{const h=m+1,g=n===h;return a.createElement(P,{key:m,disabled:t,onPress:()=>r(h),style:o.scoreButton},a.createElement(vl,{value:h,selected:s||g,label:c,src:u}),!!c&&a.createElement(k,{style:{textAlign:"center"},variant:"caption3",color:({themedColor:y})=>g?y.textHighEmphasis:y.textLowEmphasis,lineBreakStrategyIOS:"standard",textBreakStrategy:"simple"},c))})))},vl=({value:e,src:t,label:n,selected:r})=>{const[s,o]=d.useState(!1),i=Ar.use();return s?a.createElement(Cl,{value:e,selected:r,label:n}):a.createElement(we,{source:{uri:t},style:i.emojiImage(r),onError:()=>o(!0),accessibilityLabel:n})},Ar=L.create(()=>({scoresContainer:{flexDirection:"row",justifyContent:"space-between",alignSelf:"center",width:"100%",maxWidth:400},scoreButton:{backgroundColor:"transparent",gap:4,flexDirection:"column",alignItems:"center",justifyContent:"flex-start",minWidth:48,maxWidth:68,flex:1},emojiImage:e=>({width:40,height:40,opacity:e?1:.38})})),Sl=({csatPayload:e})=>a.createElement(k,{style:{textAlign:"left"},variant:"button",color:({themedColor:t})=>t.textHighEmphasis},e.title),Pt=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:i,setParams:l,error:c,setError:u,followUpItem:m,state:h,validateParams:g,itemProps:y}=Vo({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(b,{flexDirection:"column",gap:12},a.createElement(Sl,{...y}),t===le.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(yl,{...y,defaultValue:o,value:i.isResolved,onChange:C=>l({isResolved:C})}),a.createElement(El,{...y,value:i.csat,onChange:C=>l({csat:C})}),m&&a.createElement(bl,{...y,followUpItem:m,value:i.csatReason,onChange:C=>{l({csatReason:C}),u({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Oe.Separator,null),n({state:h,params:i,validateParams:g})))},Al=e=>{const{strings:t}=F();return Ds(e,{title:t.csat.title,question:t.csat.question,cre:{question:t.csat.cre_question,positive_label:t.csat.cre_positive_label,negative_label:t.csat.cre_negative_label},followUp:{question:t.csat.reason_placeholder},submit_label:t.csat.submit_label,submitted_label:t.csat.submitted_label})},Il=()=>{const{strings:e}=F();return a.createElement(k,{variant:"body2",color:({themedColor:t})=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},Tl=({onMount:e,children:t})=>(d.useEffect(()=>{e==null||e()},[]),a.createElement(a.Fragment,null,t)),wl=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n,onScrollToBottom:r}=e,{csat:s,csatReason:o,csatExpireAt:i,isResolvedWhenDeterminedByUser:l}=e,[,c]=d.useState(0),u=Al(t==null?void 0:t.csat),m=d.useRef(!1),h=xl.use();if(!u||!u.visibility||!le[u.type])return null;const g=u.type===le.AI_AGENT_CSAT_5||u.type===le.AI_AGENT_CSAT_5_WITH_CRE||u.type===le.HELPDESK_CSAT_5?Pt:()=>null;return a.createElement(b,{style:h.container},!s&&Sn(i)?a.createElement(Il,null):a.createElement(g,{csatPayload:u,type:u.type,initialCsat:s,initialCsatReason:o,initialIsResolved:l,renderSubmitButton:({state:y,params:C,validateParams:E})=>a.createElement(Tl,{onMount:r},a.createElement(P,{activeOpacity:.75,disabled:y==="submitted",onPress:async()=>{m.current||(!Sn(i)&&E()?(m.current=!0,await n(C).finally(()=>{m.current=!1})):c(_=>_+1))},style:h.submitButton(y)},a.createElement(k,{variant:"button",style:h.submitButtonText(y)},y==="submitted"?u.csat_submitted_label:u.csat_submit_label)))}))},xl=L.create(({theme:e,themedColor:t})=>({container:{flexDirection:"column",backgroundColor:e.colors.csat.background,borderRadius:16,gap:16,padding:16},submitButton:n=>{let r;return n==="submitted"||n==="unsubmittable"?r=t.textDisabled:r=e.colors.base.primary,{backgroundColor:r,borderRadius:6,padding:10,paddingHorizontal:20,alignItems:"center",justifyContent:"center"}},submitButtonText:n=>{let r;return n==="submitted"?r=t.textHighEmphasis:n==="unsubmittable"?r=t.textLowEmphasis:r=e.colors.base.primaryContrastContent,{color:r}}})),kl=e=>{const{components:t}=ut.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(b,{paddingHorizontal:D.HORIZONTAL_PADDING,marginBottom:en(e.groupType)},n)},ut=oe({template:kl,components:{AdminMessage:cl,CSATMessage:wl}}),Rl=({style:e,...t})=>{const{strings:n}=F();if(!cn("powered-by"))return null;const s=()=>{p.Linking.openURL("https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby")};return a.createElement(b,{style:[Ml.container,e],...t},a.createElement(k,{variant:"caption2",color:({themedColor:o})=>o.textLowEmphasis},n.conversation.powered_by+" "),a.createElement(P,{onPress:s},a.createElement(k,{variant:"caption2",color:({themedColor:o})=>o.textLowEmphasis},"Sendbird")))},Ml=p.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),Dl=()=>{var l;const{strings:e}=F(),{channelSource:t,scrollSource:n,updateActiveChannel:r}=me(),s=Ll.use(),o=ue(t.channel),i=d.useRef(o);return d.useEffect(()=>{const c=i.current;i.current=o,!c&&o&&n.actions.scrollToBottom()},[o,n]),!((l=t.channel)!=null&&l.isAIAgent)||!o?null:a.createElement(b,{justifyContent:"center",flexDirection:"row",style:s.wrapper},a.createElement(P,{activeOpacity:.75,onPress:()=>r(),style:s.button},a.createElement(k,{variant:"button",role:"button",color:({themedColor:c})=>c.textHighEmphasis},e.conversation.start_new_conversation_label)))},Ll=L.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),Pl=({date:e=Date.now(),style:t,...n})=>{const{format:r,strings:s}=F();return a.createElement(b,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},a.createElement(k,{variant:"caption4",color:({themedColor:o})=>o.textMidEmphasis},r(e,s.date_format.date_separator)))},Ol=({style:e,onPress:t})=>{const n=Nl.use(),{theme:r}=z();return a.createElement(P,{style:[n.button,e],onPress:t},a.createElement(b,{alignItems:"center",justifyContent:"center"},a.createElement(N,{size:24,type:"chevron-down",color:r.colors.base.primary})))},Nl=L.create(({select:e,theme:t})=>({button:{width:40,height:40,borderRadius:24,alignItems:"center",justifyContent:"center",backgroundColor:e({light:t.palette.background50,dark:t.palette.background400}),boxShadow:[{color:"rgba(0, 0, 0, 0.08)",offsetX:0,offsetY:2,blurRadius:8,spreadDistance:0},{color:"rgba(0, 0, 0, 0.12)",offsetX:0,offsetY:4,blurRadius:6,spreadDistance:0}]}})),Hl=()=>null,fn=oe({template:Hl,components:{DateSeparator:Pl,ScrollToBottomButton:Ol}}),Bl=(e,t)=>!Hr.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Ul=({messageStackDirection:e="top"})=>{var x,M;const{Template:t}=lt.useContext(),{Template:n}=ct.useContext(),{Template:r}=ut.useContext(),{components:s}=fn.useContext(),{openModal:o}=ot(),{strings:i}=F(),{config:l,cache:c,chatSDK:u}=K(),{aiAgentInfo:m,userSession:h,connectionError:g}=te(),{conversation:y,messageSource:C,channelSource:E,scrollSource:_,state:{input:v,streamAnimation:A}}=me(),S=Fl.use(),T=xe(["left","right"]),w=zo(E.channel);d.useEffect(()=>{_.state.isAwayFromBottom||C.resetNewMessages()},[_.state.isAwayFromBottom]),d.useEffect(()=>{_.actions.onTypingIndicatorUpdate(!!w)},[!!w,_.actions.onTypingIndicatorUpdate]);const R=(I,H=!1)=>{var j;return H?m??{nickname:"",profileUrl:""}:((j=E.channel)==null?void 0:j.members.find(B=>B.userId===I.sender.userId))??I.sender},O=I=>{if(I.sendingStatus==="failed"&&!v.disabled)return()=>{o(H=>a.createElement(ee,{onClose:()=>H()},a.createElement(ee.ActionItem,{label:i.conversation.failed_message_resend,onPress:async()=>{C.resendMessage(I),H()}}),a.createElement(ee.ActionItem,{destructive:!0,label:i.conversation.failed_message_remove,onPress:async()=>{C.deleteMessage(I),H()}})))}},Z=({item:I,index:H})=>{const j=C.messages[H+1],B=C.messages[H-1],Ee=(()=>{var Re,V,G;const _t=!(m!=null&&m.isUserFeedbackEnabled&&Ue(I,m==null?void 0:m.userId)&&!Ze.isWelcomeMessage(I)),ft=rs(I,j,B,_t),ve={data:I.data,extendedMessagePayload:I.extendedMessagePayload,message:I.message,createdAt:I.createdAt,groupType:ft};if($e.isAdmin(I))return $e.isCSAT(I)?y?a.createElement(r,{...ve,...y,messageType:"admin.csat",isResolvedWhenDeterminedByUser:Rs(y),onSubmitCSAT:async J=>{var ae;await((ae=E.channel)==null?void 0:ae.submitCSAT(J))},onScrollToBottom:()=>_.actions.scrollToBottom()}):null:a.createElement(r,{...ve,messageType:"admin"});if($e.isOutgoing(I,(h==null?void 0:h.userId)??"")){const J={...ve,sender:R(I),sendingStatus:I.sendingStatus,onClickFailedMessage:O(I)};if(I.isUserMessage())return a.createElement(n,{...J,messageType:"user"});if(I.isFileMessage()){const[ae,_e]=((Re=I.metaArrays.find(U=>U.key===Kn))==null?void 0:Re.value)??[];return a.createElement(n,{...J,messageType:"file",file:I,metadata:{aspectRatio:ae&&_e?`${ae}/${_e}`:"1/1",localFile:(V=I.messageParams)==null?void 0:V.file}})}}if($e.isIncoming(I,(h==null?void 0:h.userId)??"")){const J=I.sender.userId===(m==null?void 0:m.userId),ae=H===0,_e={...ve,sender:R(I,J),suggestedRepliesVisible:ae,isBotMessage:J,isStreaming:Ze.isStreaming(I),isHandedOff:be(E.channel),isConversationClosed:ue(E.channel),isFeedbackEnabled:m==null?void 0:m.isUserFeedbackEnabled,isFeedbackCommentEnabled:m==null?void 0:m.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(G=l==null?void 0:l.conversation)==null?void 0:G.senderAvatarEnabled,onClickSuggestedReply:async({reply:U})=>{C.sendUserMessage({message:U})},onRequestMessageTemplate:async U=>{const{template:re}=await u.aiAgent.getMessageTemplate(U);return c.template.set(U,re),re},onGetCachedMessageTemplate:U=>c.template.get(U),onHandleTemplateInternalAction:U=>{if(U.type==="internal"&&U.internalData){const{method:re,payload:ie}=U.internalData;re==="message.send"&&(ie!=null&&ie.message)&&C.sendUserMessage({message:ie.message})}},onFeedbackUpdate:U=>{const re={messageId:I.messageId,channelUrl:I.channelUrl};if(!U)return u.aiAgent.deleteMessageFeedback(re);const ie={...re,rating:qi(U.rating),comment:U.comment};return Ze.hasFeedback(I)?u.aiAgent.updateMessageFeedback(ie):u.aiAgent.createMessageFeedback(ie)},onSubmitForm:({key:U,data:re})=>u.aiAgent.submitForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:U,formData:re}),onCancelForm:({key:U})=>u.aiAgent.cancelForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:U}),onStreamAnimationStart:()=>{A.start(I.messageId)},onStreamAnimationProgress:()=>{_.actions.onStreamingUpdate()},onStreamAnimationComplete:()=>{A.stop(I.messageId),_.actions.onStreamingUpdate()}};if(I.isUserMessage())return a.createElement(t,{..._e,messageType:"user"});if(I.isFileMessage())return a.createElement(t,{..._e,messageType:"file",file:I})}return null})(),ht=Bl(I,j)&&a.createElement(s.DateSeparator,{date:I.createdAt,style:S.dateSeparator});return a.createElement(b,null,ht,Ee)},ne=()=>a.createElement(Rl,{style:S.poweredBy}),Y=()=>{var I,H;return a.createElement(a.Fragment,null,w&&a.createElement(b,{marginTop:C.messages.length===0?8:0},a.createElement(t,{isTyping:!0,isBotMessage:w.isBot,sender:w.user,thinkingMessage:w.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(I=l==null?void 0:l.conversation)==null?void 0:I.senderAvatarEnabled})),((H=l==null?void 0:l.conversation)==null?void 0:H.isTalkToAgentViewEnabled)&&a.createElement(Dl,null),_.state.bottomSpace?a.createElement(b,{height:_.state.bottomSpace}):null)};return a.createElement(b,{flex:1},a.createElement(pr,{ref:_.ref,style:S.list,contentContainerStyle:[S.listContent,T],stackDirection:e,data:C.messages,onEndReached:C.loadPrevious,keyExtractor:ns,renderItem:Z,loading:!C.initialized||!E.channel,empty:C.messages.length===0&&!w,error:!!(g||E.error),LoadingComponent:a.createElement(Te,{type:"loading"}),EmptyComponent:a.createElement(Te,{type:"noMessages",label:i.common.placeholder_no_messages}),ErrorComponent:a.createElement(Te,{type:"error",label:(g==null?void 0:g.message)??((x=E.error)==null?void 0:x.message),action:E.error?{label:i.common.placeholder_something_went_wrong_retry_label,onPress:()=>E.refetch()}:void 0}),ListFooterComponent:ne(),ListHeaderComponent:Y(),inverted:!0,..._.props}),((M=l==null?void 0:l.conversation)==null?void 0:M.newMessageIndicatorEnabled)&&_.state.isAwayFromBottom&&C.newMessages.length>0&&a.createElement(b,{style:S.newMessagesButtonContainer},a.createElement(oi,{label:i.conversation.scroll_to_new_messages_label(C.newMessages),accessibilityLabel:i.conversation.a11y_scroll_to_new_messages,onPress:()=>_.actions.scrollToBottom()})),_.state.isAwayFromBottom&&C.newMessages.length===0&&a.createElement(s.ScrollToBottomButton,{style:S.scrollButtonContainer,onPress:()=>_.actions.scrollToBottom()}))},Fl=L.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background},dateSeparator:{marginVertical:16},poweredBy:{marginTop:16},scrollButtonContainer:{position:"absolute",bottom:12,end:16},newMessagesButtonContainer:{position:"absolute",bottom:12,alignSelf:"center"}})),ge={CAMERA_PERMISSION_DENIED:"Camera permission is not granted",GALLERY_PERMISSION_DENIED:"Photo library permission is not granted",IMAGE_PICKER_NOT_CONFIGURED:"Image picker is not configured. Please provide imagePicker in NativeAdapterConfig to use camera or gallery features.",DOCUMENT_PICKER_NOT_CONFIGURED:"Document picker is not configured. Please provide documentPicker in NativeAdapterConfig to use file selection features."};function zl(e){return{captureCamera:async()=>{if(e.requestCameraPermissionsAsync&&!(await e.requestCameraPermissionsAsync()).granted)throw new Error(ge.CAMERA_PERMISSION_DENIED);const t=await e.launchCameraAsync({mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});return t.canceled||!t.assets||t.assets.length===0?null:t.assets.map($n)},selectFromGallery:async t=>{if(e.requestMediaLibraryPermissionsAsync&&!(await e.requestMediaLibraryPermissionsAsync()).granted)throw new Error(ge.GALLERY_PERMISSION_DENIED);const n=await e.launchImageLibraryAsync({selectionLimit:(t==null?void 0:t.selectionLimit)??1,allowsMultipleSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});return n.canceled||!n.assets||n.assets.length===0?null:n.assets.map($n)}}}function $l(e,t){const n=async()=>{const s=p.Platform.select({ios:t.PERMISSIONS.IOS.CAMERA,android:t.PERMISSIONS.ANDROID.CAMERA});if(!s)return;const o=await t.request(s);if(o!=="granted"&&o!=="limited")throw new Error(ge.CAMERA_PERMISSION_DENIED)},r=async()=>{const s=p.Platform.select({ios:[t.PERMISSIONS.IOS.PHOTO_LIBRARY],android:typeof p.Platform.Version=="number"&&p.Platform.Version>32?[]:typeof p.Platform.Version=="number"&&p.Platform.Version>28?[t.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]:[t.PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,t.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]});if(!s||s.length===0)return;const o=await t.requestMultiple(s);if(!Object.values(o).every(l=>l==="granted"||l==="limited"))throw new Error(ge.GALLERY_PERMISSION_DENIED)};return{captureCamera:async()=>{await n();const s=await e.launchCamera({mediaType:"photo",assetRepresentationMode:"compatible"});if(s.didCancel)return null;if(s.errorCode)throw s.errorCode==="permission"?new Error(ge.CAMERA_PERMISSION_DENIED):new Error(s.errorMessage||`Camera error: ${s.errorCode}`);return!s.assets||s.assets.length===0?null:s.assets.map(Vn)},selectFromGallery:async s=>{await r();const o=await e.launchImageLibrary({mediaType:"photo",selectionLimit:(s==null?void 0:s.selectionLimit)??1,assetRepresentationMode:"compatible"});if(o.didCancel)return null;if(o.errorCode)throw o.errorCode==="permission"?new Error(ge.GALLERY_PERMISSION_DENIED):new Error(o.errorMessage||`Gallery error: ${o.errorCode}`);return!o.assets||o.assets.length===0?null:o.assets.map(Vn)}}}function Vl(e){return{selectFile:async t=>{const n=(t==null?void 0:t.mimeTypes)??["*/*"],r=await e.getDocumentAsync({multiple:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:n});return r.canceled||!r.assets||r.assets.length===0?null:r.assets.map(jl)}}}function ql(e){return{selectFile:async t=>{try{const n=(t==null?void 0:t.mimeTypes)??["*/*"],r=p.Platform.select({android:n,ios:void 0}),s=await e.pick({mode:"open",allowMultiSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:r});return(Array.isArray(s)?s:[s]).map(Gl)}catch(n){if(n&&typeof n=="object"&&"message"in n){const r=String(n.message).toLowerCase();if(r.includes("cancel")||r.includes("user cancelled"))return null;throw new Error(String(n.message))}throw new Error("File selection failed")}}}}function $n(e){return{uri:e.uri,type:e.mimeType||"image/jpeg",size:e.fileSize||0,name:e.fileName||"image.jpg",width:e.width,height:e.height}}function jl(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function Vn(e){return{uri:e.uri,type:e.type||"image/jpeg",size:e.fileSize||0,name:e.fileName||"image.jpg",width:e.width,height:e.height}}function Gl(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function Wl(){return{captureCamera:async()=>{throw new Error(ge.IMAGE_PICKER_NOT_CONFIGURED)},selectFromGallery:async()=>{throw new Error(ge.IMAGE_PICKER_NOT_CONFIGURED)}}}function Kl(){return{selectFile:async()=>{throw new Error(ge.DOCUMENT_PICKER_NOT_CONFIGURED)}}}const{Provider:Yl,useContext:Ir}=W("NativeAdapter"),Tr=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:r,documentPicker:s,mmkv:o}=e,i=r?(Xl(e),"launchCameraAsync"in r?zl(r):$l(r,e.permissions)):Wl(),l=s?"getDocumentAsync"in s?Vl(s):ql(s):Kl();return{...i,...l,keyValueStorage:sr(o)}},[e.imagePicker,e.documentPicker,e.mmkv,e.permissions]);return a.createElement(Yl,{value:n},t)};function Xl(e){if(!e.imagePicker)return;if(!("launchCameraAsync"in e.imagePicker)&&!e.permissions)throw new Error("react-native-permissions is required when using react-native-image-picker. Please install react-native-permissions and provide it in nativeModules.permissions")}const Zl=({onPressAddAttachment:e,disabled:t})=>a.createElement(P,{disabled:t,style:Jl.container,activeOpacity:.75,onPress:e},a.createElement(N,{type:"add",size:24,color:({themedColor:n})=>t?n.textDisabled:n.primary})),Jl=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Ql=({name:e,type:t,url:n,onRemove:r})=>{const s=ec.use();return a.createElement(b,{style:s.wrapper},ss(t)?a.createElement(we,{source:{uri:n},style:s.image,resizeMode:"cover"}):a.createElement(hn,{name:e,type:Qt(e,t)}),r&&a.createElement(P,{onPress:r,style:s.removeButton},a.createElement(N,{type:"remove",size:20,color:s.removeIcon.tintColor})))},Ke=7,ec=L.create(({themedColor:e})=>({wrapper:{marginTop:Ke,marginRight:Ke,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-Ke,right:-Ke,width:22,height:22,borderRadius:11,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),tc=e=>{const{theme:t,themedColor:n}=z(),r=nc.use(),s=mn.useTextAlign({text:e.value??e.placeholder,style:r.input,isTextInput:!0});return a.createElement(b,{style:r.container},e.attachments&&a.createElement(Er,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),a.createElement(b,null,a.createElement(p.TextInput,{multiline:!0,style:[r.input,{textAlign:s}],placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},nc=L.create(({theme:e})=>({container:{backgroundColor:e.colors.messageInput.background,gap:16,flex:1,paddingHorizontal:16,paddingVertical:8,justifyContent:"center",borderRadius:20,minHeight:36},input:{...rc(e.typography.body3),color:e.colors.messageInput.text,includeFontPadding:!1,padding:0,margin:0,textAlignVertical:"center"}}));function rc(e){const t={maxHeight:52};return e.fontFamily&&(t.fontFamily=e.fontFamily),typeof e.fontSize=="number"&&(t.fontSize=e.fontSize,t.maxHeight=e.fontSize*3.5),typeof e.lineHeight=="number"&&(t.lineHeight=e.lineHeight,t.maxHeight=e.lineHeight*3.5),e.fontWeight&&(t.fontWeight=e.fontWeight),t}const sc=({onPressSend:e})=>a.createElement(P,{style:oc.container,activeOpacity:.75,onPress:e},a.createElement(N,{type:"send",size:24})),oc=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),ac=()=>{const e=ic.use(),{aiAgentInfo:t,userSession:n}=te(),{messageSource:r,channelSource:s}=me(),[o,i]=d.useState(null),l=cn("special-notice",s.channel),c=d.useCallback(()=>s.channel?l?r.messages.some(u=>Ue(u,(n==null?void 0:n.userId)??"")):!0:null,[s.channel,l,r.messages,n==null?void 0:n.userId]);return d.useEffect(()=>{o||i(c())},[c,o]),o||!(t!=null&&t.specialNotice)?null:a.createElement(b,{style:e.container},a.createElement(_n,{textStyle:e.text,linkStyle:e.link},(t==null?void 0:t.specialNotice)??""))},ic=L.create(({theme:e,themedColor:t,select:n})=>({container:{backgroundColor:e.colors.base.background,paddingVertical:8,paddingHorizontal:16,alignItems:"center"},text:{...e.typography.body3,color:t.textLowEmphasis,textAlign:"center"},link:{fontWeight:"700",textDecorationLine:"none",color:n({light:e.palette.information.light,dark:e.palette.information.main})}})),lc=()=>{var E;const{chatSDK:e}=K(),{strings:t}=F(),{createAttachmentRules:n}=te(),{channelSource:r,state:s}=me(),[o,i]=d.useState(""),[l,c]=d.useState([]),u=n({channel:r.channel,uploadSizeLimit:(E=e.appInfo)==null?void 0:E.uploadSizeLimit}),m=(_,v)=>{const A=v.filter(R=>u.isSupportedMimeType(R.type));if(A.length===0&&v.length>0)return p.Alert.alert("",t.conversation.file_upload_not_supported_file),_;const S=R=>{const O=u.getUploadSizeLimit(R.type);return R.size&&R.size>O},T=A.find(R=>S(R));if(T){const R=u.getUploadSizeLimitInMB(T.type);return p.Alert.alert("",t.conversation.file_upload_notification_size_limit(R)),_}return _.length+A.length>u.maxAttachmentCount?(p.Alert.alert("",t.conversation.file_upload_notification_count_limit(u.maxAttachmentCount)),_):[..._,...A]},h=_=>{c(v=>m(v,_))},g=_=>{c(v=>v.filter((A,S)=>S!==_))},y=()=>{c([])},C=(()=>{if(!s.input.disabled)return t.conversation.input_placeholder;switch(s.input.disabledBy){case"form_active":return t.conversation.input_placeholder_active_form;case"ai_responding":return t.conversation.input_placeholder_wait_ai_agent_response;case"reconnecting":return t.conversation.input_placeholder_reconnecting;case"unavailable":case"conversation_closed":default:return t.conversation.input_placeholder_disabled}})();return d.useEffect(()=>{s.input.disabled&&(i(""),y())},[s.input.disabled]),{files:l,addFiles:h,removeFile:g,clearFiles:y,value:o,onChangeText:i,editable:!s.input.disabled,placeholder:C,sendButtonVisible:!s.input.disabled&&(!!o.trim()||l.length>0),addAttachmentButtonVisible:u.isEnabled(),addAttachmentButtonDisabled:s.input.disabled||l.length>=u.maxAttachmentCount,hasImageMimeTypes:()=>u.supportedMimeTypes.filter(v=>v.startsWith("image/")||v===Yn).length>0,hasFileMimeTypes:()=>u.supportedMimeTypes.length>0,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount}},cc=()=>{const{config:e}=K(),t=Ir(),{strings:n}=F(),{messageSource:r}=me(),{openModal:s}=ot(),o=xe(["left","right","bottom"]),i=uc.use(),{maxAttachmentCount:l,sendButtonVisible:c,addAttachmentButtonVisible:u,addAttachmentButtonDisabled:m,acceptableMimeTypes:h,hasImageMimeTypes:g,hasFileMimeTypes:y,...C}=lc(),v={...C,onPressAddAttachment:async()=>{const A=await s(S=>{var T,w,R,O,Z,ne,Y,x;return a.createElement(ee,{onClose:()=>S()},((R=(w=(T=e==null?void 0:e.conversation)==null?void 0:T.input)==null?void 0:w.camera)==null?void 0:R.photoEnabled)&&a.createElement(ee.ActionItem,{icon:"camera",label:n.conversation.attachment_camera,onPress:async()=>{if(!g())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),S(null);const M=await t.captureCamera();S(M)}}),((ne=(Z=(O=e==null?void 0:e.conversation)==null?void 0:O.input)==null?void 0:Z.gallery)==null?void 0:ne.photoEnabled)&&a.createElement(ee.ActionItem,{icon:"photo",label:n.conversation.attachment_photo,onPress:async()=>{if(!g())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),S(null);const M=await t.selectFromGallery({selectionLimit:l-C.files.length});S(M)}}),((x=(Y=e==null?void 0:e.conversation)==null?void 0:Y.input)==null?void 0:x.fileEnabled)&&a.createElement(ee.ActionItem,{icon:"document",label:n.conversation.attachment_document,onPress:async()=>{if(!y())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),S(null);const M=await t.selectFile({selectionLimit:l-C.files.length,mimeTypes:h});S(M)}}))});A&&C.addFiles(A)},onPressSend:()=>{C.files.length>0?r.sendFileMessage({message:C.value.trim(),file:C.files[0]}):r.sendUserMessage({message:C.value}),C.clearFiles(),C.onChangeText("")}};return a.createElement(p.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-o.paddingBottom},a.createElement(ac,null),a.createElement(b,{style:i.container(o)},u&&a.createElement(Zl,{...v,disabled:m}),a.createElement(tc,{...v,value:v.editable?v.value:"",attachments:v.files.length===0?null:v.files.map((A,S)=>a.createElement(Ql,{key:S,name:A.name,type:A.type,url:A.uri,onRemove:()=>v.removeFile(S)}))}),c&&a.createElement(sc,{...v})))},uc=L.create(({theme:e})=>({container:({paddingStart:t,paddingEnd:n,paddingBottom:r})=>({alignItems:"center",flexDirection:"row",gap:8,paddingTop:10,paddingBottom:10+r,paddingStart:12+t,paddingEnd:12+n,backgroundColor:e.colors.base.background})})),wr=({start:e,title:t,titleAlign:n="start",end:r})=>{const s=xe(["left","right","top"]),[o,i]=d.useState(0),[l,c]=d.useState(0),u=g=>{i(g.nativeEvent.layout.width)},m=g=>{c(g.nativeEvent.layout.width)},h=dc.use();return a.createElement(b,{style:h.container},a.createElement(b,{height:s.paddingTop}),a.createElement(b,{style:h.contentContainer(s)},n==="center"&&t&&a.createElement(b,{style:h.centerTitleContainer(Math.max(o,l))},a.createElement(b,{style:h.centerTitle},t)),a.createElement(b,{style:h.rowContainer},a.createElement(b,{style:h.startSide,onLayout:u},e),(n==="start"||n==="end")&&t&&a.createElement(b,{style:h.titleSide(n,e,r)},t),a.createElement(b,{style:h.endSide,onLayout:m},r))))},dc=L.create(({theme:e,themedColor:t})=>({container:{width:"100%",backgroundColor:e.colors.base.headerBackground,borderBottomWidth:1,borderBottomColor:t.textDisabled},contentContainer:n=>({position:"relative",height:56,paddingStart:n.paddingStart+12,paddingEnd:n.paddingEnd+12}),centerTitleContainer:n=>({position:"absolute",left:n,right:n,top:0,bottom:0,alignItems:"center",justifyContent:"center"}),centerTitle:{maxWidth:"100%",overflow:"hidden"},rowContainer:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",height:"100%",zIndex:1},startSide:{flexShrink:0},endSide:{flexShrink:0},titleSide:(n,r,s)=>({flex:1,overflow:"hidden",alignItems:`flex-${n}`,marginStart:r?8:0,marginEnd:s?8:0})})),mc=()=>{const{themedColor:e}=z(),{onClose:t}=me();return t?a.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(N,{color:e.textHighEmphasis,type:"close",size:24})):null},gc=()=>{const{themedColor:e}=z(),{channelSource:{channel:t}}=me(),n=cn("handoff-button",t),r=!er(t)||be(t);return n?a.createElement(P,{hitSlop:4,disabled:r,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},a.createElement(N,{color:r?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},hc=()=>{const{strings:e}=F(),{themedColor:t}=z(),{onNavigateToConversationList:n}=me();return n?a.createElement(P,{hitSlop:4,onPress:n,activeOpacity:.75,"aria-label":e.conversation.a11y_open_conversation_list},a.createElement(N,{color:t.textHighEmphasis,type:"menu",size:24})):null},xr=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=te(),{fallbackIcon:s,url:o}=lr({channel:e,aiAgentInfo:r,userSession:n}),{theme:i}=z();return o?a.createElement(Cr,{src:o,size:t}):a.createElement(b,{width:t,height:t,borderRadius:t/2,alignItems:"center",justifyContent:"center",flexShrink:0,style:{backgroundColor:i.colors.base.primary}},a.createElement(N,{type:s,size:t*.55,color:i.colors.base.primaryContrastContent}))},_c=()=>{var i,l;const{channelSource:{channel:e}}=me(),{userSession:t,aiAgentInfo:n}=te(),{config:r}=K(),s=lr({channel:e,userSession:t,aiAgentInfo:n}),o=(l=(i=r==null?void 0:r.conversation)==null?void 0:i.header)==null?void 0:l.avatarEnabled;return a.createElement(b,{gap:6,flexDirection:"row",alignItems:"center",maxWidth:"100%"},o&&a.createElement(xr,{channel:e,size:34}),a.createElement(b,{flexShrink:1},a.createElement(k,{numberOfLines:1,variant:"h1"},s.title)))},fc=e=>{const{components:t}=Ce.useContext();return a.createElement(wr,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},pc=()=>{const{components:e}=Ce.useContext();return a.createElement(e.MenuButton,null)},yc=()=>{const{components:e}=Ce.useContext();return a.createElement(e.Title,null)},bc=()=>{const{components:e}=Ce.useContext();return a.createElement(b,{flexDirection:"row",alignItems:"center",gap:10},a.createElement(e.HandoffButton,null),a.createElement(e.CloseButton,null))},Ce=oe({template:fc,components:{StartArea:pc,TitleArea:yc,EndArea:bc,MenuButton:hc,Title:_c,HandoffButton:gc,CloseButton:mc}}),Cc=()=>{const{Template:e}=Ce.useContext();return a.createElement(e,{titleAlign:"start"})},Ec=e=>{const{components:t}=dt.useContext();return a.createElement(b,{flex:1},a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},dt=oe({template:Ec,components:{Header:Cc,Body:Ul,Footer:cc}}),kr=({children:e,...t})=>{const{Template:n}=dt.useContext();return a.createElement(ur,{...t},a.createElement(n,null),e)},{Provider:vc,Context:Sc,useContext:mt}=W("ConversationList"),Rr=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:r,children:s})=>{const{sdkUser:o,authenticate:i}=te();return d.useEffect(()=>{o||i()},[]),a.createElement(Oo,{conversationListLimit:e,conversationListFilter:t},l=>a.createElement(vc,{value:{...l,onClose:r,onNavigateToConversation:n}},s))},Ot=99,Ac=d.memo(function(t){const{channel:n,onClick:r}=t,{strings:s,format:o}=F(),{themedColor:i}=z(),l=Tc.use(),c=Ys(n,{formatMultipleFilesCount:s.conversation_list.multiple_files_count}),u=Xs(n,o,{justNow:s.date_format.just_now,minutesAgo:s.date_format.minutes_ago,hoursAgo:s.date_format.hours_ago,dateShortFormat:s.date_format.date_short}),m=n.unreadMessageCount;return a.createElement(P,{onPress:r,activeOpacity:.75},a.createElement(b,{flexDirection:"row",alignItems:"center",width:"100%",height:72,gap:16},a.createElement(b,{marginStart:16,alignItems:"center",justifyContent:"center"},a.createElement(xr,{channel:n})),a.createElement(b,{flexDirection:"row",alignItems:"center",flex:1,paddingEnd:16,height:"100%",gap:8,style:l.rightContainer},a.createElement(b,{flexDirection:"column",justifyContent:"center",flex:1,gap:4},a.createElement(k,{variant:"subtitle1",color:i.textHighEmphasis,numberOfLines:1},c),a.createElement(b,{flexDirection:"row",alignItems:"center",gap:6},ue(n)&&a.createElement(a.Fragment,null,a.createElement(k,{variant:"caption1",color:i.textMidEmphasis,numberOfLines:1},s.conversation_list.ended),a.createElement(b,{width:2,height:2,borderRadius:1,backgroundColor:i.textLowEmphasis})),a.createElement(k,{variant:"caption2",color:i.textLowEmphasis,numberOfLines:1},u))),m>0&&a.createElement(b,{alignItems:"center",justifyContent:"center",height:20,width:m<=Ot?20:void 0,padding:4,borderRadius:10,backgroundColor:i.error},a.createElement(k,{variant:"caption3",color:i.textHighEmphasisInverse,style:{lineHeight:12}},m<=Ot?m:`${Ot}+`)))))}),Ic=oe({template:Ac,components:{}}),Tc=L.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),wc=()=>{var l;const{Template:e}=Ic.useContext(),{strings:t}=F(),{connectionError:n}=te(),{listSource:r,onNavigateToConversation:s}=mt(),o=xe(["left","right"]),i=xc.use();return a.createElement(pr,{style:i.list,contentContainerStyle:[i.listContent,o],data:r.channels,onEndReached:r.loadMore,keyExtractor:d.useCallback(c=>c.url,[]),renderItem:d.useCallback(({item:c})=>a.createElement(e,{channel:c,onClick:()=>s==null?void 0:s(c.url,ue(c)?"closed":"open")}),[e,s]),loading:!r.initialized,error:!!(n||r.error),empty:r.channels.length===0,LoadingComponent:a.createElement(Te,{type:"loading"}),EmptyComponent:a.createElement(Te,{type:"noChannels",label:t.common.placeholder_no_conversations}),ErrorComponent:a.createElement(Te,{type:"error",label:(n==null?void 0:n.message)??((l=r.error)==null?void 0:l.message)})})},xc=L.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),kc=()=>{const{strings:e}=F(),{language:t,countryCode:n,context:r,_aiAgentSDK:s}=K(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:l,sdkUser:c}=te(),{onNavigateToConversation:u}=mt(),m=xe(["left","right","bottom"]),h=Rc.use();return a.createElement(P,{activeOpacity:.75,disabled:!c,onPress:async()=>{var g;if(o!=null&&o.isMultipleActiveConversationsEnabled){const y=await l({aiAgentId:o.userId,language:t,country:n,context:r});(g=s.session)==null||g._updateActiveChannel({url:y,status:"open"}),u==null||u(y,"open")}else{const y=await i();u==null||u(y,"open")}}},a.createElement(b,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+m.paddingBottom,style:[h.container,m]},a.createElement(k,{variant:"h1",color:({themedColor:g})=>g.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},Rc=L.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),Mc=()=>{const{aiAgentInfo:e}=te();return e?a.createElement(kc,null):null},Dc=()=>{const{themedColor:e}=z(),{onClose:t}=mt();return t?a.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(N,{color:e.textHighEmphasis,type:"close",size:24})):null},Lc=()=>{const{strings:e}=F();return a.createElement(k,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},Pc=e=>{const{components:t}=ke.useContext();return a.createElement(wr,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},Oc=()=>null,Nc=()=>{const{components:e}=ke.useContext();return a.createElement(e.Title,null)},Hc=()=>{const{components:e}=ke.useContext();return a.createElement(e.CloseButton,null)},ke=oe({template:Pc,components:{StartArea:Oc,TitleArea:Nc,EndArea:Hc,Title:Lc,CloseButton:Dc}}),Bc=()=>{const{Template:e}=ke.useContext();return a.createElement(e,{titleAlign:"start"})},Uc=()=>{const{components:e}=gt.useContext();return a.createElement(b,{flex:1},a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},gt=oe({template:Uc,components:{Header:Bc,Body:wc,Footer:Mc}}),Mr=({children:e,...t})=>{const{Template:n}=gt.useContext();return a.createElement(Rr,{...t},a.createElement(n,null),e)},Fc=d.forwardRef(function({logLevel:t=q.LogLevel.WARN,language:n=st,userSessionInfo:r,children:s,strings:o,...i},l){const[c]=d.useState(()=>new Qn(t));c.level!==t&&(c.level=t);const{nativeModules:u,chatParams:m={},...h}=i,{useMMKVStorageStore:g,...y}=m;return d.useEffect(()=>{g!==void 0&&c.warn("`chatParams.useMMKVStorageStore` is not supported in `AIAgentProviderContainer`. Use `nativeModules.mmkv` instead.")},[c,g]),a.createElement(Tr,{config:u},()=>a.createElement($c,{logger:c,theme:h.theme,language:n,strings:o},a.createElement(Qs,{...h,language:n,logger:c,chatSDK:h.customChatSDK,useMMKVStorage:u.mmkv,chatParams:y},a.createElement(ia,{ref:l,userSessionInfo:r},s))))}),zc=Ks(dt,Ce,fn,gt,ke,it,at,lt,ct,ut),$c=({children:e,logger:t,theme:n,language:r,strings:s})=>a.createElement(ye.SafeAreaProvider,null,a.createElement(Va,{logger:t,...n},a.createElement(Fa,{language:r,logger:t,strings:s},a.createElement(dr,null,a.createElement(Bo,null,a.createElement(zc,null,e)))))),{Provider:Vc,useContext:pn}=W("FixedMessengerStyle"),qc={useNativeDriver:!0},Ye={OPEN_START:"0deg",OPEN_END:"-180deg",CLOSE_START:"180deg",CLOSE_END:"0deg"},Xe={VISIBLE:1,HIDDEN:0},jc=({isOpened:e})=>{const t=d.useRef(new p.Animated.Value(e?1:0)).current;d.useEffect(()=>{const s=e?1:0;p.Animated.spring(t,{toValue:s,...qc}).start()},[e,t]);const n={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[Ye.OPEN_START,Ye.OPEN_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Xe.VISIBLE,Xe.HIDDEN]})}]},r={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[Ye.CLOSE_START,Ye.CLOSE_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Xe.HIDDEN,Xe.VISIBLE]})}]};return{openIconStyle:n,closeIconStyle:r}},Gc=2/3,Wc=({isOpened:e,onPress:t})=>{const n=Xc.use(),{launcherInfo:r,statsTrackers:s}=te();d.useLayoutEffect(()=>{s.initialRender.setPresentMethod("launcher_toggle")},[s]);const{theme:o}=z(),{launcherSize:i,horizontal:l}=pn(),c=Math.round(i*Gc),u=o.colors.base.primary,m=o.colors.base.primaryContrastContent,{openIconStyle:h,closeIconStyle:g}=jc({isOpened:e});return a.createElement(b,{alignSelf:l==="start"?"flex-start":"flex-end"},a.createElement(P,{onPress:t,activeOpacity:.8},({pressed:y})=>a.createElement(b,{style:[n.container({backgroundColor:u,size:i}),y&&n.pressed]},a.createElement(b.Animated,{style:[n.iconWrapper,h]},a.createElement(Kc,{url:(r==null?void 0:r.imageUrl)??"",isDefaultIcon:(r==null?void 0:r.type)==="default_icon",size:c,fillColor:m})),a.createElement(b.Animated,{style:[n.iconWrapper,g]},a.createElement(Yc,{size:c,fillColor:m})))))},Kc=({url:e,isDefaultIcon:t,size:n,fillColor:r})=>e?t?a.createElement(we,{source:{uri:e},width:n,height:n,tintColor:r,resizeMode:"contain"}):a.createElement(we,{source:{uri:e},width:n,height:n,resizeMode:"cover"}):a.createElement(N,{type:"delight",size:n,color:r}),Yc=({size:e,fillColor:t})=>a.createElement(N,{type:"chevron-down",size:e,color:t}),Xc=L.create(()=>({container:e=>({position:"relative",width:e.size,height:e.size,backgroundColor:e.backgroundColor,borderRadius:e.size/2,justifyContent:"center",alignItems:"center",boxShadow:"0px 8px 16px 0px rgba(33, 33, 33, 0.3)"}),pressed:{transform:[{scale:.9}]},iconWrapper:{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"}})),Q={TRANSLATE_OFFSET:40,DURATION:300,OPACITY_DURATION:83,EASING:p.Easing.out(p.Easing.ease)},Zc=e=>e==="entered"?0:Q.TRANSLATE_OFFSET,Jc=e=>e==="entered"?1:0,Qc=({transitionState:e,isActive:t})=>{const[n,r]=d.useState(!1),s=d.useRef(new p.Animated.Value(Zc(e))).current,o=d.useRef(new p.Animated.Value(Jc(e))).current;return d.useEffect(()=>{if(!n){e==="entered"?(s.setValue(0),o.setValue(1)):e==="exited"&&(s.setValue(Q.TRANSLATE_OFFSET),o.setValue(0)),r(!0);return}e==="entering"?(s.setValue(Q.TRANSLATE_OFFSET),o.setValue(0),p.Animated.parallel([p.Animated.timing(s,{toValue:0,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),p.Animated.timing(o,{toValue:1,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()):e==="exiting"&&p.Animated.parallel([p.Animated.timing(s,{toValue:Q.TRANSLATE_OFFSET,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),p.Animated.timing(o,{toValue:0,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()},[e,s,o,n]),d.useMemo(()=>({position:"absolute",top:0,left:0,width:"100%",height:"100%",transform:[{translateY:s}],opacity:o,zIndex:t?999:1,pointerEvents:t?"auto":"none",display:e==="exited"?"none":"flex"}),[s,o,t,e])},Dr=d.createContext(null),eu=()=>{const e=d.useContext(Dr);if(!e)throw new Error("useNavigatorContext() must be used within <Navigator />");return e},Lr=({children:e})=>{const t=eu();return typeof e=="function"?a.createElement(a.Fragment,null,e(t)):a.createElement(a.Fragment,null,e)},tu=d.memo(({transitionState:e,isActive:t,children:n})=>{const r=Qc({transitionState:e,isActive:t});return a.createElement(p.Animated.View,{style:r},n)}),qn=300,Je=({initialId:e,children:t})=>{const[n,r]=d.useState([e]),s=n[n.length-1],o=d.useCallback((_,v)=>{r(A=>[...A,_]),h(A=>({...A,[_]:!0})),v!=null&&v.reset&&E(A=>({...A,[_]:(A[_]||0)+1})),y(A=>({...A,[_]:"entering"})),setTimeout(()=>{y(A=>({...A,[_]:"entered"}))},qn)},[]),i=d.useCallback(()=>{r(_=>{if(_.length<=1)return _;const v=_[_.length-1];return y(A=>({...A,[v]:"exiting"})),setTimeout(()=>{y(A=>({...A,[v]:"exited"})),r(A=>A.slice(0,-1))},qn),_})},[]),l=d.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),c=d.useMemo(()=>d.Children.toArray(t).filter(_=>_.type===Lr),[t]),u=d.useMemo(()=>{const _={};return c.forEach(v=>{const{id:A,lazy:S,children:T}=v.props;_[A]={lazy:S,element:typeof T=="function"?T(l):T}}),_},[c,l]),[m,h]=d.useState(()=>{const _={};return Object.entries(u).forEach(([v,{lazy:A}])=>{A===!1&&(_[v]=!0)}),_[e]=!0,_}),[g,y]=d.useState(()=>{const _={};return Object.keys(u).forEach(v=>{_[v]=v===e?"entered":"exited"}),_}),[C,E]=d.useState({});return a.createElement(Dr.Provider,{value:l},a.createElement(b,{style:{position:"relative",width:"100%",height:"100%"}},Object.keys(u).map(_=>{var T;if(!m[_])return null;const v=g[_]||"exited",A=_===s,S=`${_}-${C[_]||0}`;return a.createElement(tu,{key:S,transitionState:v,isActive:A},(T=u[_])==null?void 0:T.element)})))};Je.Screen=Lr;const{Provider:nu,useContext:yn}=W("PageChildren"),ru=({children:e})=>{const[t,n]=d.useState(null),[r,s]=d.useState(null);return a.createElement(nu,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:s}},e)},pe={conv:"conv",convList:"conv-list"},su=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onClose:s})=>{const{conversationChildren:o,conversationListChildren:i}=yn(),l=t==="ConversationList"?pe.convList:pe.conv;return a.createElement(Je,{initialId:l},a.createElement(Je.Screen,{id:pe.conv},({navigation:c,activeScreenId:u})=>a.createElement(kr,{channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>c.navigate(pe.convList),onClose:s,shouldMarkAsRead:e&&u===pe.conv},o)),a.createElement(Je.Screen,{id:pe.convList,lazy:!0},({navigation:c})=>a.createElement(Mr,{onNavigateToConversation:u=>{r(u),c.navigate(pe.conv,{reset:!0})},onClose:s},i)))},Be=.15,ou=150,jn=(e,t)=>e.interpolate({inputRange:[Be,1],outputRange:[t,0],extrapolate:"clamp"}),au=(e,t)=>{if(e<=0)return 0;const n=(1-Be)*e/2,r=t==="start"?-1:1,s=p.I18nManager.isRTL?-1:1;return n*r*s},iu=(e,t)=>e<=0?0:(1-Be)*e/2*(t==="top"?-1:1),lu=({isOpened:e,horizontal:t,vertical:n})=>{const[r,s]=d.useState({width:0,height:0}),o=d.useRef(new p.Animated.Value(e?1:Be)).current,i=d.useRef(new p.Animated.Value(e?1:0)).current,l=d.useMemo(()=>au(r.width,t),[r.width,t]),c=d.useMemo(()=>iu(r.height,n),[r.height,n]),{translateXInterpolation:u,translateYInterpolation:m}=d.useMemo(()=>({translateXInterpolation:jn(o,l),translateYInterpolation:jn(o,c)}),[o,l,c]);d.useEffect(()=>{const y=e?"open":"close",C=y==="open"?1:Be,E=y==="open"?1:0,_=y==="open"?p.Easing.out(p.Easing.quad):p.Easing.in(p.Easing.quad),v={duration:ou,useNativeDriver:!0,easing:_};y==="close"&&p.Keyboard.dismiss(),p.Animated.parallel([p.Animated.timing(o,{toValue:C,...v}),p.Animated.timing(i,{toValue:E,...v})]).start()},[e,o,i]);const h=d.useMemo(()=>({opacity:i,transform:[{translateX:u},{translateY:m},{scale:o}]}),[i,u,m,o]),g=d.useMemo(()=>y=>{const{width:C,height:E}=y.nativeEvent.layout;s(_=>_.width===C&&_.height===E?_:{width:C,height:E})},[]);return{animatedStyle:h,handleLayout:g,pointerEvents:e?"auto":"none"}},cu={top:0,left:0,right:0,bottom:0},uu=({children:e,isOpened:t})=>{const n=du.use(),{horizontal:r,vertical:s}=pn(),{animatedStyle:o,handleLayout:i,pointerEvents:l}=lu({isOpened:t,horizontal:r,vertical:s});return a.createElement(ye.SafeAreaInsetsContext.Provider,{value:cu},a.createElement(b,{flex:1},a.createElement(b.Animated,{pointerEvents:l,onLayout:i,style:o},a.createElement(b,{style:n.windowContainer},e))))},du=L.create(({theme:e})=>({windowContainer:{width:"100%",height:"100%",borderRadius:16,overflow:"hidden",zIndex:999,backgroundColor:e.colors.base.background,boxShadow:"0px 4px 24px 0px rgba(0, 0, 0, 0.12)"}})),Pr=()=>{const[e,t]=d.useState(0);return d.useEffect(()=>{const n=p.Platform.OS==="ios"?"keyboardWillShow":"keyboardDidShow",r=p.Platform.OS==="ios"?"keyboardWillHide":"keyboardDidHide",s=p.Keyboard.addListener(n,i=>{const{endCoordinates:l}=i,c=(l==null?void 0:l.height)||0;t(c)}),o=p.Keyboard.addListener(r,()=>{t(0)});return()=>{s.remove(),o.remove()}},[]),e},mu=e=>{const t=d.useRef(new p.Animated.Value(0)).current,[n,r]=d.useState(!1);return d.useEffect(()=>{const o=e?"open":"close",i={toValue:o==="open"?1:0,useNativeDriver:!0,duration:300};o==="open"&&r(!0),p.Animated.timing(t,i).start(()=>{o==="close"&&(r(!1),p.Keyboard.dismiss())})},[e,t]),{windowAnimatedStyle:{opacity:t,display:n?"flex":"none"},pointerEvents:e?"auto":"none"}},gu=({children:e,insets:t,isOpened:n})=>{const r=hu.use(),o={...ye.useSafeAreaInsets(),...t},i=Pr(),{windowAnimatedStyle:l,pointerEvents:c}=mu(n);return a.createElement(ye.SafeAreaInsetsContext.Provider,{value:o},a.createElement(b.Animated,{flex:1,style:[r.bg,l],pointerEvents:c},a.createElement(b,{flex:1},e),a.createElement(b,{height:Math.max(0,i-p.Platform.select({android:0,default:o.bottom})),style:r.bg})))},hu=L.create(({theme:e})=>({bg:{backgroundColor:e.colors.base.background}})),_u="end-bottom",Pe={top:24,bottom:24,start:24,end:24},fu=({mode:e,edgeToEdgeEnabled:t})=>{const n=e==="floating"?uu:gu,[r,s]=Ft({position:_u,margin:Pe,launcherSize:48,spacing:12}),{bottom:o}=ye.useSafeAreaInsets(),i=Pr(),[l,c]=r.position.split("-"),u=(()=>{const g=p.Platform.select({android:t?o:0,default:0}),y=c==="top"?r.spacing:-r.launcherSize,C=i>0?i+y+g:0;return C>0?C:r.margin.bottom})(),m={position:"absolute",zIndex:1e3,...c==="top"?{top:r.margin.top}:{bottom:r.margin.bottom},...l==="start"?{left:r.margin.start}:{right:r.margin.end}},h=(()=>{if(e==="floating"){const g=r.launcherSize+r.spacing;return{position:"absolute",top:r.margin.top+(c==="top"?g:0),bottom:u+(c==="bottom"?g:0),left:r.margin.start,right:r.margin.end,zIndex:999}}return{position:"absolute",top:0,bottom:0,left:0,right:0,zIndex:1001}})();return{Window:n,windowContainerStyle:h,launcherContainerStyle:m,styleContext:{...r,horizontal:l,vertical:c,setPosition:g=>s({position:g}),setMargin:({top:g=Pe.top,bottom:y=Pe.bottom,start:C=Pe.start,end:E=Pe.end})=>s({margin:{top:g,bottom:y,start:C,end:E}}),setLauncherSize:g=>s({launcherSize:g}),setSpacing:g=>s({spacing:g})}}},pu=e=>{var o,i,l,c;const{setPosition:t,setMargin:n,setLauncherSize:r,setSpacing:s}=pn();return d.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n(e.margin),e.launcherSize!==void 0&&r(e.launcherSize),e.spacing!==void 0&&s(e.spacing)},[e.position,(o=e.margin)==null?void 0:o.top,(i=e.margin)==null?void 0:i.bottom,(l=e.margin)==null?void 0:l.start,(c=e.margin)==null?void 0:c.end,e.launcherSize,e.spacing]),null},yu=({children:e})=>{const{setConversationChildren:t}=yn();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},bu=({children:e})=>{const{setConversationListChildren:t}=yn();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Cu=({entryPoint:e="Conversation",edgeToEdgeEnabled:t=!0,windowMode:n="floating",fullscreenInsets:r,initialChannelUrl:s,windowContainerProps:o,children:i})=>{const[l,c]=d.useState(!1),[u,m]=d.useState(s),{Window:h,windowContainerStyle:g,launcherContainerStyle:y,styleContext:C}=fu({mode:n,edgeToEdgeEnabled:t});return d.useEffect(()=>{const E=p.BackHandler.addEventListener("hardwareBackPress",()=>l?(c(!1),!0):!1);return()=>E.remove()},[l]),a.createElement(Vc,{value:C},a.createElement(ru,null,a.createElement(b,{style:g,backgroundColor:"transparent",pointerEvents:l?"auto":"box-none",...o},a.createElement(h,{isOpened:l,insets:r},a.createElement(su,{isOpened:l,entryPoint:e,selectedChannelUrl:u,setSelectedChannelUrl:m,onClose:()=>c(!1)}))),a.createElement(b,{style:y,backgroundColor:"transparent",pointerEvents:"box-none"},a.createElement(Wc,{isOpened:l,onPress:()=>c(!l)})),i))},Eu=Object.assign(Cu,{Style:pu,ConversationChildren:yu,ConversationListChildren:bu});var Gn,Wn;nr.set(q.SendbirdPlatform.REACT_NATIVE,{deviceOSPlatform:(Gn=p.Platform)==null?void 0:Gn.select({ios:q.DeviceOsPlatform.IOS,android:q.DeviceOsPlatform.ANDROID,default:q.DeviceOsPlatform.ANDROID}),deviceOSVersion:(Wn=p.Platform)!=null&&Wn.Version?String(p.Platform.Version):void 0,messengerVersion:Yo,keyValueStorage:js()});exports.AIAgentProviderContainer=Fc;exports.AnonymousSessionInfo=et;exports.BottomSheet=ee;exports.BottomSheetLayout=at;exports.CSATType=le;exports.Conversation=kr;exports.ConversationContext=fa;exports.ConversationContextProvider=ur;exports.ConversationHeaderLayout=Ce;exports.ConversationLayout=dt;exports.ConversationList=Mr;exports.ConversationListContext=Sc;exports.ConversationListContextProvider=Rr;exports.ConversationListHeaderLayout=ke;exports.ConversationListLayout=gt;exports.DeskTicketPriority=on;exports.DeskTicketStatus=sn;exports.FixedMessenger=Eu;exports.IncomingMessageLayout=lt;exports.LogLevel=tn;exports.ManualSessionInfo=nn;exports.MessageListUILayout=fn;exports.ModalProvider=dr;exports.NativeAdapterProvider=Tr;exports.OutgoingMessageLayout=ct;exports.PlaceholderLayout=it;exports.SystemMessageLayout=ut;exports.useAIAgentContext=K;exports.useConversationContext=me;exports.useConversationListContext=mt;exports.useMessengerSessionContext=te;exports.useModalContext=ot;exports.useNativeAdapterContext=Ir;
|