@sendbird/ai-agent-messenger-react-native 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +411 -26
- package/dist/index.js +2535 -2441
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var fo=Object.defineProperty;var po=(e,t,n)=>t in e?fo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var L=(e,t,n)=>po(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react-native"),V=require("@sendbird/chat"),d=require("react"),Ee=require("react-native-safe-area-context"),se=require("@sendbird/chat/aiAgent"),jt=require("@sendbird/uikit-tools"),Se=require("date-fns"),Ae=require("@sendbird/chat/message"),Xe=require("@sendbird/chat/groupChannel"),_o=require("date-fns/isSameDay"),yo=require("date-fns/locale/de"),bo=require("date-fns/locale/en-US"),Eo=require("date-fns/locale/es"),Co=require("date-fns/locale/fr"),vo=require("date-fns/locale/hi"),So=require("date-fns/locale/it"),Ao=require("date-fns/locale/ja"),To=require("date-fns/locale/ko"),wo=require("date-fns/locale/pt"),xo=require("date-fns/locale/tr"),Io=require("@react-native-clipboard/clipboard"),ko=require("react-native-code-highlighter"),Mo=require("react-native-markdown-display"),Je=e=>e&&e.__esModule?e:{default:e};function Ro(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 o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Lo=Je(V),a=Ro(d),Do=Je(Io),Po=Je(ko),Oo=Je(Mo),ve="sb-agent",kn="KEY_IMG_ASPECT_RATIO",Mn="*/*",R={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},ie=e=>!!e&&"sender"in e,No=e=>ie(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Bo=(e,t,n,o=!0)=>{if(!o||!ie(e))return"single";const r=()=>{if(!t||!ie(t))return!1;const c=t.sender.userId===e.sender.userId,u=Se.isSameMinute(t.createdAt,e.createdAt);return c&&u},s=()=>{if(!n||!ie(n))return!1;const c=n.sender.userId===e.sender.userId,u=Se.isSameMinute(n.createdAt,e.createdAt);return c&&u},i=r(),l=s();return i&&l?"middle":i?"bottom":l?"top":"single"},Be=(e,t)=>(()=>{var o;return ie(e)?e.sender.userId:((o=e==null?void 0:e.sender)==null?void 0:o.userId)??void 0})()===t,ze={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>ie(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>ie(e)&&(e.sender.userId===t||e.sendingStatus===Ae.SendingStatus.PENDING)},Ho=e=>e.startsWith("image/"),Gt=(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"},Rn=e=>e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.message.length>0,Vt=e=>{switch(e){case"top":case"middle":return R.GAP_GROUPED;default:return R.GAP_UNGROUPED}},zo=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,o=[];let r=0;return e.replace(n,(s,...i)=>{const[l,c,u]=i;return r<u&&o.push({type:"text",value:e.slice(r,u).trim()}),o.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),r=u+s.length,s}),r<e.length&&o.push({type:"text",value:e.slice(r).trim()}),o},Uo=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Fo=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),$o=e=>e.replace(/~~/g,"\\~\\~"),jo=e=>{let t=e;return t=Uo(t),t=Fo(t),t=$o(t),t},Go=typeof navigator<"u"&&navigator.product==="ReactNative",rn=(e,t)=>{const n=o=>!t||t.length===0?!0:ie(o)&&t.includes(o.sendingStatus);return Go?e.find(n):e.findLast(n)};function Tt(){}function Vo(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function qo(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 sn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ke={isStreaming(e){const t=sn(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(Be(e,t)){const o=sn(e.data);return!(o!=null&&o.respond_mesg_id)&&!(o!=null&&o.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)}},ct=`@${ve}`,an=({appId:e,aiAgentId:t,storage:n})=>{const o={templateBase:`${ct}-template`,template:r=>`${o.templateBase}/templates/${r}`,templateToken:()=>`${o.templateBase}-template/message-template/tokens`,messengerSession:r=>{const s=qo(`${e}/${t}/${r}`);return`${ct}-udata/${s}`},anonUserSession:()=>`${ct}-session/${e}/${t}`};return{template:{set:(r,s)=>n.set(o.template(r),s),get:r=>n.get(o.template(r)),setCachedToken:r=>n.set(o.templateToken(),r),getCachedToken:()=>n.get(o.templateToken()),clear:()=>{n.getKeys(o.templateBase).forEach(n.delete)}},messenger:{getSettings:r=>{try{const s=n.get(o.messengerSession(r));return s?JSON.parse(s):null}catch{return null}},setSettings:(r,s)=>{try{delete s.auto_created_user;const i=JSON.stringify(s);n.set(o.messengerSession(r),i)}catch{return}},getAnonUser:()=>{try{const r=n.get(o.anonUserSession());return r?JSON.parse(r):null}catch{return null}},setAnonUser:r=>{try{const s=JSON.stringify(r);n.set(o.anonUserSession(),s)}catch{return}},clear:r=>{try{r&&n.delete(o.messengerSession(r)),n.delete(o.anonUserSession())}catch{return}}}}},Ln=(e,t,n={})=>{let o=null,r=null,s=null;const{leading:i=!0,trailing:l=!0}=n,c=(...u)=>{const m=Date.now();if(s===null||m-s>=t)i?(e(...u),s=m):(r=u,s=m);else if(r=u,l&&!o){const h=t-(m-s);o=setTimeout(()=>{r&&l&&(e(...r),s=Date.now()),o=null,r=null},h)}};return c.cancel=()=>{o&&(clearTimeout(o),o=null),r=null,s=null},c};class Wo{constructor(t,{filter:n,limit:o=20}){L(this,"filter");L(this,"_sdk");L(this,"_pinnedChannels");L(this,"_channels");L(this,"_isDisposed",!1);L(this,"_handlerId",`handler-id-${Date.now()}`);L(this,"_order",Xe.GroupChannelListOrder.LATEST_LAST_MESSAGE);L(this,"_limit");L(this,"_query");L(this,"_token");L(this,"_timestamp");L(this,"_isSyncing");L(this,"_channelHandler");L(this,"_connectionHandler");L(this,"_collectionEventHandler");L(this,"_throttledOnChannelChanged");var r,s,i,l,c,u,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=o,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(r=this.filter)==null?void 0:r.aiAgentChannelFilter,aiAgentConversationStatusFilter:(s=this.filter)==null?void 0:s.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=Ln(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new Xe.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new V.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var s,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),o=t.find(l=>!n.has(l.url));let r;o?r=((i=o.lastMessage)==null?void 0:i.createdAt)??o.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)??[],o=new Map(n.map((c,u)=>[c,u])),r=[],s=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const u=o.get(c.url);if(u===void 0)continue;const m=wt(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),s.push(c)):r.push(c);const g=this._pinnedChannels.findIndex(y=>(o.get(y.url)??1/0)>u),_=g===-1?this._pinnedChannels.length:g;this._pinnedChannels.splice(_,0,c)}return{addedChannels:r,updatedChannels:s,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const o=[],r=[],s=[];for(const i of t){if(!this._query.belongsTo(i)){o.push(i.url);continue}const l=wt(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=Ko(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),s.push(i))}return{addedChannels:r,updatedChannels:s,unmatchedChannelUrls:o}}_addChannelsToView(t,n=!1){var h,g,_,y,v;const o=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),r=[],s=[];for(const f of t)o.has(f.url)?r.push(f):s.push(f);const i=this._upsertPinnedChannelsToArray(r),l=this._upsertRegularChannelsToArray(s,n),c=i.addedChannels.concat(l.addedChannels),u=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((_=(g=this._collectionEventHandler)==null?void 0:g.onChannelsAdded)==null||_.call(g,{},c)),u.length>0&&((v=(y=this._collectionEventHandler)==null?void 0:y.onChannelsUpdated)==null||v.call(y,{},u)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var r,s,i;const n=new Set(((r=this.filter)==null?void 0:r.pinnedChannelUrls)??[]),o=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(u=>u.url===l);c>=0&&(o.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(u=>u.url===l);c>=0&&(o.push(l),this._channels.splice(c,1))}o.length>0&&((i=(s=this._collectionEventHandler)==null?void 0:s.onChannelsDeleted)==null||i.call(s,{},o))}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 wt=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Ko=(e,t,n)=>{if(e.length>0){const o=wt(e,t);let r=0,s=e.length-1,i=Math.floor((r+s)/2);for(;r<s;){const c=ln(e[i],t,n);if(c>0)s=i,i=Math.floor((r+s)/2);else if(c<0)r=i+1,i=Math.floor((r+s)/2);else return{place:i,oldPosition:o}}return{place:ln(e[i],t,n)>=0?i:i+1,oldPosition:o}}return{place:e.length,oldPosition:-1}},ln=(e,t,n)=>{switch(n){case Xe.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const o=t.lastMessage.createdAt-e.lastMessage.createdAt;return o===0?t.createdAt-e.createdAt:o}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};class Yo{constructor(t){L(this,"subscribers",{});this.logger=t}async send(t){const n=Xo(),o=this.subscribers[t.type];if(o){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const r=o.map(s=>s(t.payload));await Promise.all(r).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const o=this.subscribers[t];o&&(this.subscribers[t]=o.filter(r=>r!==n))}}const Xo=()=>{let e=Tt,t=Tt;return{promise:new Promise((o,r)=>{e=o,t=r}),resolve:e,reject:t}};var xt=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e))(xt||{}),Dn=(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))(Dn||{});class Pn{constructor(t){L(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${ve}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${ve}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${ve}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${ve}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${ve}/error]`,...t)}}class qt{constructor({userId:t,authToken:n,sessionHandler:o}){L(this,"userId");L(this,"authToken");L(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=o}}class Ze{constructor(){L(this,"userId");L(this,"authToken");L(this,"sessionHandler")}}const _e={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}}},Zo=e=>{var t,n,o,r,s,i,l,c,u,m,h,g,_,y;return e?{..._e,...e,conversation:{..._e.conversation,...e==null?void 0:e.conversation,header:{...(t=_e.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(o=_e.conversation)==null?void 0:o.input,...(r=e==null?void 0:e.conversation)==null?void 0:r.input,camera:{...(i=(s=_e.conversation)==null?void 0:s.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=_e.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:{...(_=_e.conversation)==null?void 0:_.fileViewer,...(y=e==null?void 0:e.conversation)==null?void 0:y.fileViewer}}}:_e},le=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===se.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},On=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===se.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function we(e){var n,o,r;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((r=(o=e==null?void 0:e.conversation)==null?void 0:o.handoff)==null?void 0:r.timestamp))=="number"}function Jo(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function cn(e){return!!e&&e<Date.now()}function Qo(e){return!e.title}function er(e,t){var n;if(e)return Qo(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}const tr=e=>JSON.parse(e);var It=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(It||{});const Nn=e=>typeof e=="object"&&e!==null,un=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",nr=e=>!Nn(e)||!un(e,"channel_url")||!un(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},or={1:nr};function rr(e){if(!Nn(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=or[t];if(!n)return null;const o=n(e.data);return o?{category:t,data:o}:null}function dn(e,t,n,o){const r=Lo.default.init({appId:e,modules:[new Xe.GroupChannelModule,new se.AIAgentModule],localCacheEnabled:!0,options:new V.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...o});return r.addSendbirdExtensions([{version:n,product:V.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),r}function sr(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 Ue=new Map,ar={set:(e,t)=>{Ue.set(e,t)},get:e=>{if(Ue.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=Ue.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Ue.entries().next().value;return{platform:t[0],...t[1]}}};function ir(){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 lr(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 X=(e,t)=>{const n=d.createContext(null),o=({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),s=()=>{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`,o.displayName=`${e}Provider`,r.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:o,Consumer:r,useContext:s}};function ae(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){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(_=>({..._,[h]:g}))};return a.createElement(t.Provider,{value:m},s)}function o({template:s,children:i}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{s&&l(s)},[s]),a.createElement(a.Fragment,null,i)}function r({children:s}){return a.createElement(n,null,s)}return r.defaults=e,r.useContext=()=>d.useContext(t),r.Context=t,r.Template=o,Object.keys(e.components).forEach(s=>{r[s]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),r}function cr(...e){return function({children:n}){return e.reduce((o,r)=>a.createElement(r,null,o),n)}}function ur(e){const t=e.lastMessage;return t!=null&&t.isUserMessage()||t!=null&&t.isAdminMessage()?t.message||"":t!=null&&t.isFileMessage()?t.message||t.name||"FILE":e.name}function dr(e,t,n){var i;const o=new Date,r=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),s=Se.differenceInMinutes(o,r);return s<1?n.justNow:s<60?n.minutesAgo(s):Se.isToday(r)?n.hoursAgo(Se.differenceInHours(o,r)):t(r,n.dateShortFormat)}const{Provider:mr,useContext:Y}=X("AIAgent");function gr({appId:e,aiAgentId:t,keyValueStorage:n,networkStateAdapter:o,language:r,countryCode:s,context:i,queryParams:l,config:c,chatSDK:u,chatParams:m,children:h,logger:g,dispatcher:_,messengerVersion:y,extensions:v={platform:V.SendbirdPlatform.JS,deviceOSPlatform:Vo()?V.DeviceOsPlatform.MOBILE_WEB:V.DeviceOsPlatform.WEB}}){const[f,E]=d.useState(()=>{const C=g??new Pn(Dn.WARN),A=_??new Yo(C);return{logger:C,dispatcher:A,chatSDK:u??dn(e,v,y,m),cache:an({appId:e,aiAgentId:t,storage:n})}});return d.useEffect(()=>{E(C=>{let A=C.logger,S=C.dispatcher,w=C.chatSDK;return g&&g!==C.logger&&(A=g),_&&_!==C.dispatcher&&(S=_),u&&u!==C.chatSDK?w=u:!u&&C.chatSDK.appId!==e&&(w=dn(e,v,y,{newInstance:!0,...m})),{...C,logger:A,dispatcher:S,chatSDK:w,cache:an({appId:e,aiAgentId:t,storage:n})}})},[e,t,g,_,u,n]),d.useEffect(()=>()=>{f.chatSDK.connectionState==="OPEN"&&f.chatSDK.disconnectWebSocket()},[f.chatSDK]),sr(f.chatSDK),a.createElement(mr,{value:{...f,appId:e,aiAgentId:t,context:i,language:r,countryCode:s,queryParams:l,config:Zo(c),networkStateAdapter:o}},h)}const hr=(e,t,n)=>jt.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),fr="ai_agent:stats",pr="conversation_initial_render",_r=800220;var K=(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))(K||{});class yr{constructor(){L(this,"timers",new Map);L(this,"committed",!1);L(this,"commitCallback",null);L(this,"conversationId",null);L(this,"channelUrl",null);L(this,"errorCode",null);L(this,"errorDescription",null);L(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??_r,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(fr,t)):!1}}class br extends yr{constructor(n){super();L(this,"presentMethod");this.presentMethod=n}getMetricKey(){return pr}buildPayload(){const n=this.getDuration(K.AUTH),o=this.getDuration(K.GET_CHANNEL),r=this.getDuration(K.GET_MESSAGES),s=this.getDuration(K.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(K.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...o!==null&&{get_channel_duration:o},...r!==null&&{get_messages_duration:r},...s!==null&&{total_duration_from_cache:s}},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 Er{constructor(t,n){L(this,"commitCallback");L(this,"presentMethod");L(this,"stats",null);this.commitCallback=t,this.presentMethod=n}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new br(this.presentMethod),this.stats.setCommitCallback(this.commitCallback)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(K.TOTAL_DURATION).startTimer(K.TOTAL_DURATION_FROM_CACHE).startTimer(K.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(K.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(K.AUTH).setError(t instanceof V.SendbirdError?t.code:void 0,t.message).stopTimer(K.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(K.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(K.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(K.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(K.GET_CHANNEL).setError(t instanceof V.SendbirdError?t.code:void 0,t.message).stopTimer(K.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof V.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(K.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof V.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(K.TOTAL_DURATION).stopTimer(K.GET_MESSAGES).commit())}setChannelUrl(t){var n;(n=this.stats)==null||n.setChannelUrl(t)}cleanup(){var t;(t=this.stats)==null||t.commit()}clear(){this.stats=null}}const kt={DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Bn(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Cr(e){const t=Bn(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function vr(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Sr(e,t,n){e/=255,t/=255,n/=255;const o=Math.max(e,t,n),r=Math.min(e,t,n),s=o-r;let i=0,l=0;const c=(o+r)/2;return o!==r&&(l=c>.5?s/(2-o-r):s/(o+r)),o===e?i=(t-n)/s+(t<n?6:0):o===t?i=(n-e)/s+2:o===n&&(i=(e-t)/s+4),i/=6,[i,l,c]}function Ar(e,t,n){let o,r,s;if(t===0)o=r=s=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;o=i(c,l,e+1/3),r=i(c,l,e),s=i(c,l,e-1/3)}return[Math.round(o*255),Math.round(r*255),Math.round(s*255)]}function Fe(e,t,n){const[o,r,s]=Cr(e),[i,l,c]=Sr(o,r,s),u=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,g,_]=Ar(i,m,u);return vr([Math.round(h),Math.round(g),Math.round(_)])}function Tr(e,t="light"){return{extraDark:Fe(e,.6,1.2),dark:Fe(e,.85,1.1),main:e,light:Fe(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Fe(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function mn(e){const t=Bn(e),n=149,o=+`0x${t[1]}${t[2]}`,r=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return o*.299+r*.587+s*.114>n?kt.BLACK:kt.WHITE}function wr(e,t,n,o,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:o},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const xr=(e,t,n,o,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:o},messageOutgoing:{text:n,background:t},csat:{background:e.background400}}),$e={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)"}},ut={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 gn(e){const t=Ir(e),{colors:n,aiAgentColorVariables:o}=kr(e,t),r=Rr(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:o,typography:r}}function Ir({selectedTheme:e,palette:t,primary:n}){const o=t!=null&&t.primary?t.primary:n?n===$e.primary.main?$e.primary:Tr(n,e):$e.primary;return{...$e,primary:o,...t}}function kr({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:o},r){const s=r.primary.main,i=t??mn(s),l=n??kt.DEFAULT_BOT_MSG_BG,c=o??mn(l);return{colors:(e==="light"?wr:xr)(r,s,i,l,c),aiAgentColorVariables:{primary_color:s,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function Mr(e,t,n){const o={...e};return n.forEach(r=>{const s=t[r];s!=null&&(o[r]=s)}),o}function Rr({typography:e}){if(!e)return ut;const t={...ut};return Object.keys(e).forEach(n=>{const o=e[n];if(o&&typeof o=="object"){const r=ut[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Mr(r,o,s)}}),t}const{Provider:Lr,useContext:Dr}=X("AIAgentTheme");function Pr({logger:e,palette:t,typography:n,appearance:o,children:r}){const s=d.useRef(null),[i,l]=d.useState(()=>gn({selectedTheme:(o==null?void 0:o.theme)??"light",palette:t,typography:n,primary:o==null?void 0:o.primaryColor,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor})),c=d.useCallback((u,m)=>{m&&(s.current=m);const h=(o==null?void 0:o.theme)??u,g=s.current?s.current.themes[h]:null,_={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!_.primary&&(g!=null&&g.primary_color)&&(_.primary=g.primary_color,_.primaryContrast=g.primary_contrast_color),!_.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(_.botMessageBackground=g.bot_message_bg_color,_.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const y=gn({selectedTheme:h,palette:t,typography:n,..._});l(y),e==null||e.info("theme.update:",h)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor,t,n,e]);return d.useEffect(()=>{(o!=null&&o.theme||o!=null&&o.primaryColor||o!=null&&o.botMessageBackgroundColor)&&c(i.selectedTheme)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor]),a.createElement(Lr,{value:{theme:i,updateTheme:c}},r)}const hn=25*1024*1024,Or={off:"off",always:"always",handed_off_only:"handed_off_only"},Nr=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:1,attachmentMode:"handed_off_only",defaultUploadSizeLimit:hn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:new Set(["image/png","image/jpeg","image/jpg"]),supportedFileMimeTypes:new Set(["application/pdf"])})),n=d.useCallback(({active_channel:r,upload_restriction:s})=>{const{maxAttachmentCount:i,attachmentMode:l,defaultUploadSizeLimit:c,supportedImageMimeTypes:u,supportedFileMimeTypes:m}=e;t({maxAttachmentCount:i,attachmentMode:Or[r.attachment_mode]??l,defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??c,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??u),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??m)})},[]),o=d.useCallback(r=>{const{channel:s,uploadSizeLimit:i=hn}=r,l=(u=!0)=>s!=null&&s.isAIAgent?u?we(s):!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 we(s);default:return!0}},get supportedMimeTypes(){return l()?[Mn]:[...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:o}};function Hn(){const{chatSDK:e,logger:t}=Y();return d.useCallback(async n=>{if(n.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw t.error("requestMessengerSettings: invalid userId",o),o}return await e.aiAgent.requestMessengerSettings({...n,shouldSendFirstMessage:!1})},[e,t])}function Br(){const{chatSDK:e,logger:t}=Y(),n=d.useCallback(async(r,s,i)=>{if(t.debug("useChatConnection.connect: start, session",r.userId),s){const l=new V.SessionHandler({...s,onSessionTokenRequired:Hr(s.onSessionTokenRequired,i)});e.setSessionHandler(l),e.aiAgent.addEventHandler(It.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),c=>{var m;t.debug("useChatConnection: EXTERNAL_AUTH_TOKEN_EXPIRED event received",c);const u=rr(c);(u==null?void 0:u.category)===It.EXTERNAL_AUTH_TOKEN_EXPIRED&&(t.debug("useChatConnection: calling onExternalAuthTokenExpired handler",u.data),(m=s==null?void 0:s.onExternalAuthTokenExpired)==null||m.call(s,u.data))})}try{return await e.connect(r.userId,r.authToken),t.debug("useChatConnection.connect: end, currentUser",e.currentUser),e.currentUser}catch(l){const c=l;if(e.isCacheEnabled){if(Ur(c))t.warn("useChatConnection.connect","offline connect restricted",c.message,c.code),t.warn("useChatConnection.connect","clear cached-data"),await e.clearCachedData().catch(u=>t.warn("useChatConnection.connect","clear cached-data failure",u));else if(e.currentUser)return t.debug("useChatConnection.connect: end (offline), currentUser",e.currentUser),e.currentUser}throw t.warn("useChatConnection.connect","connect failure",c.message,c.code),c}},[e,t]),o=d.useCallback(async()=>{t.debug("useChatConnection.disconnect: start"),e.aiAgent.removeAllEventHandlers(),await e.disconnect(),t.debug("useChatConnection.disconnect: end")},[e,t]);return{connect:n,disconnect:o}}function Hr(e,t){if(e)return async(n,o)=>{new Promise((r,s)=>e==null?void 0:e(r,s)).then(r=>{r&&(t==null||t(r)),n(r)}).catch(r=>{o(r)})}}const zr=[400300,400301,400302,400310];function Ur(e){return zr.some(t=>e.code===t)}const Fr=1440*60*1e3,$r=e=>{const{logger:t,cache:n}=Y(),o=()=>{const s=n.messenger.getAnonUser();return s?s.expireAt-Fr<=Date.now()?(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session expired, clear cache"),n.messenger.clear(s.userId),null):(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session info detected"),s):null},r=()=>{if(!e||e instanceof Ze)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof e.userId!="string")throw new Error("userSessionInfo.userId must be a string");const s=["userId","authToken","sessionHandler"].filter(i=>!(i in e));return s.length>0&&t.error(`useUserSessionCandidate.getManualSessionInfo: missing required keys in userSessionInfo: ${s.join(", ")}`),t.debug("useUserSessionCandidate.getManualSessionInfo: manual session info detected"),e};return d.useMemo(()=>e instanceof qt?{type:"manual",userSessionCandidate:r()}:e instanceof Ze?{type:"anonymous",userSessionCandidate:o()}:e&&typeof e=="object"?(t.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:r()}):e===void 0?(t.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:o()}):{type:"anonymous",userSessionCandidate:null},[t,e==null?void 0:e.userId,e==null?void 0:e.authToken,e==null?void 0:e.sessionHandler,n.messenger.getAnonUser,n.messenger.clear])};function jr({userSessionInfo:e,onUpdateMessengerSettings:t,onPreAuth:n,onPostAuth:o,onErrorAuth:r,onAuthTokenRefreshed:s,onPostDeauth:i,forceCreateChannel:l}){const{aiAgentId:c,language:u,context:m,countryCode:h,logger:g,cache:_}=Y(),{connect:y,disconnect:v}=Br(),{type:f,userSessionCandidate:E}=$r(e),C=Hn(),A=d.useCallback(async()=>{var Z;g.debug("useAuthentication.authenticate: start");const w=E!=null&&E.userId?_.messenger.getSettings(E.userId):null;w!=null&&w.bot&&(t(w),g.debug("useAuthentication.authenticate: cached messenger settings",w));const x=await C({aiAgentId:c,userId:E==null?void 0:E.userId,language:u,country:h,context:m,forceCreateChannel:l,knownActiveChannelUrl:(Z=w==null?void 0:w.active_channel)==null?void 0:Z.channel_url});g.debug("useAuthentication.authenticate: messenger settings response",x);let M=null;if(x.auto_created_user)if(f==="manual")g.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),M={userId:E.userId,authToken:E.authToken};else{const{user_id:q,session_token:U,expire_at:P}=x.auto_created_user;_.messenger.setAnonUser({userId:q,authToken:U,expireAt:P}),M={userId:q,authToken:U}}else M={userId:(E==null?void 0:E.userId)??"",authToken:(E==null?void 0:E.authToken)??""};_.messenger.setSettings(M.userId,x),t(x);try{await n(x,M),await y(M,E==null?void 0:E.sessionHandler,s),await o(x,M)}catch(q){throw q instanceof Error&&(r(q),g.error("useAuthentication.authenticate: failed to connect",q)),q}return x},[C,y,f,E==null?void 0:E.userId,E==null?void 0:E.sessionHandler,E==null?void 0:E.authToken,c,u,m,h,l,_.messenger.setAnonUser,_.messenger.getSettings,_.messenger.setSettings,t,n,o,r,s]),S=d.useCallback(async()=>{g.debug("useAuthentication.deauthenticate: start"),await v(),i(),g.debug("useAuthentication.deauthenticate: completed")},[v,g,i]);return{authenticate:A,deauthenticate:S,userSessionCandidate:E}}const Gr=()=>{const{chatSDK:e,logger:t,cache:n}=Y(),o=d.useCallback(()=>{var l,c;const s=(c=(l=e.appInfo)==null?void 0:l.aiAgentInfo)==null?void 0:c.templateListToken;if(!s)return!1;const i=n.template.getCachedToken();return i?s!==i:!0},[e,n.template.getCachedToken]),r=d.useCallback(async()=>{try{const{templates:s,token:i}=await e.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=tr(l);n.template.set(c,l)}n.template.setCachedToken(i)}catch(s){t==null||t.error("messageTemplateContext.syncCachedTemplates: error:",s)}},[e,t,n.template.set,n.template.setCachedToken]);return{shouldSyncCachedTemplate:o,syncCachedTemplates:r}},fn=(...e)=>{const[t,n,o]=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 o=="object"&&o!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:o};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},Le=e=>({...e,context:e.context??{}}),{Provider:Vr,useContext:He}=X("AIAgentMessengerSession"),qr=d.forwardRef(function({userSessionInfo:e,forceCreateChannel:t,presentMethod:n="direct_present",children:o},r){const{appId:s,aiAgentId:i,chatSDK:l,language:c,countryCode:u,context:m,cache:h,logger:g}=Y(),{updateTheme:_}=Dr(),[y,v]=d.useState(void 0),[f,E]=d.useState(void 0),[C,A]=d.useState(null),[S,w]=d.useState(null),[x,M]=d.useState(null),[Z,q]=d.useState(null),[U]=d.useState(()=>({initialRender:new Er((k,N)=>l.aiAgent.appendStat(k,N),n)})),{updateBaseAttachmentRules:P,createAttachmentRules:j}=Nr(),{shouldSyncCachedTemplate:T,syncCachedTemplates:z}=Gr(),G=Hn(),{authenticate:Q,deauthenticate:fe}=jr({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(k=>{const{appearance:N,bot:H,launcher:J}=k;_(N.selected_theme,N),M({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:k.bot.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:k.bot.is_user_feedback_comment_option_enabled??!1}),q({type:J.image_type||"default_icon",imageUrl:J.image_url}),P(k)},[_]),onPreAuth:d.useCallback((k,N)=>{v(void 0),w(N),U.initialRender.onAuthStart()},[U]),onPostAuth:d.useCallback(async k=>{U.initialRender.onAuthComplete(),A(l.currentUser),T()&&await z(),E({url:k.active_channel.channel_url,status:"open"})},[l,T,z,U]),onErrorAuth:d.useCallback(k=>{U.initialRender.onAuthError(k),v(k)},[U]),onAuthTokenRefreshed:d.useCallback(k=>{w(N=>N?{...N,authToken:k}:null)},[]),onPostDeauth:d.useCallback(()=>{h.template.clear(),h.messenger.clear(S==null?void 0:S.userId),U.initialRender.clear(),A(null),E(void 0),w(null),M(null),q(null)},[h.template.clear,h.messenger.clear,S,U])}),Me=d.useCallback(async()=>{var k;if(S){g.debug("agentMessengerSession.refreshActiveChannel: try to refresh active channel"),E(void 0);const N=await G({aiAgentId:i,userId:S.userId,language:c,country:u,context:m,forceCreateChannel:t,knownActiveChannelUrl:(k=h.messenger.getSettings(S.userId))==null?void 0:k.active_channel.channel_url});return h.messenger.setSettings(S.userId,N),E({url:N.active_channel.channel_url,status:"open"}),g.info("agentMessengerSession.refreshActiveChannel: refreshed active channel",N.active_channel.channel_url),N.active_channel.channel_url}else throw g.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")},[G,s,i,S==null?void 0:S.userId,c,u,m,t,h.messenger.getSettings,h.messenger.setSettings]),pe=d.useCallback(async k=>{if(!(S!=null&&S.userId))throw new Error("Current user is not authenticated. Please authenticate first.");const N=await G({...k,userId:S.userId,knownActiveChannelUrl:void 0}),H=N.active_channel.channel_url;return h.messenger.setSettings(S.userId,N),H},[S==null?void 0:S.userId,G]),Re=d.useCallback(async k=>{if(!l.currentUser)throw new Error("Current user is not authenticated. Please authenticate first.");if(Object.entries(k.context).length===0)return[];const N=l.aiAgent.createConversationListQuery({aiAgentId:k.aiAgentId,status:se.ConversationStatus.OPEN,limit:100}),H=[];for(;N.hasNext;){const J=await N.next();for(const ee of J)Wr(ee.context??{},k.context)&&H.push(ee.channelInfo.url)}return H},[l]),[re]=d.useState(()=>Ln(k=>{var N;g.info("agentMessengerSession.channelChanged: channel.conversation",k.conversation),E({url:k.url,status:le(k)?"closed":"open",conversationStatus:(N=k.conversation)==null?void 0:N.status})},250,{trailing:!1,leading:!0}));return jt.useGroupChannelHandler(l,{onChannelChanged:k=>{k.isGroupChannel()&&k.url===(f==null?void 0:f.url)&&re(k)}}),d.useEffect(()=>()=>{re.cancel()},[re]),d.useImperativeHandle(r,()=>{const k=async()=>{if(!f)throw new Error("No active conversation. Please start a conversation first.");return await l.groupChannel.getChannel(f.url)};return{activeChannel:f,chatSDK:l,authenticate:Q,deauthenticate:fe,updateContext:async(...N)=>{const H=fn(...N);if(H.type==="active"){const de=await(await k()).updateContext(i,H.context);return Le(de)}const J=await l.aiAgent.updateContext(H.aiAgentId,H.channelUrl,H.context);return Le(J)},patchContext:async(...N)=>{const H=fn(...N);if(H.type==="active"){const de=await(await k()).patchContext(i,H.context);return Le(de)}const J=await l.aiAgent.patchContext(H.aiAgentId,H.channelUrl,H.context);return Le(J)},getContextObject:async()=>{const H=await(await k()).getContextObject(i);return Le(H)}}},[Q,fe,f,l,i,g]),a.createElement(Vr,{value:{sdkUser:C,userSessionInfo:e,userSession:S,activeChannel:f,setActiveChannel:E,refreshActiveChannel:Me,createConversation:pe,searchConversation:Re,connectionError:y,aiAgentInfo:x,launcherInfo:Z,presentMethod:n,authenticate:Q,deauthenticate:fe,createAttachmentRules:j,statsTrackers:U}},o)}),Wr=(e,t)=>Object.entries(t).every(([n,o])=>e[n]===o),Wt=(e,t)=>{const n=d.useId(),o=d.useRef(t);d.useLayoutEffect(()=>{o.current=t}),d.useEffect(()=>{const r=new V.ConnectionHandler({onDisconnected:s=>{var i,l;return(l=(i=o.current).onDisconnected)==null?void 0:l.call(i,s)},onConnected:s=>{var i,l;return(l=(i=o.current).onConnected)==null?void 0:l.call(i,s)},onReconnectStarted:()=>{var s,i;return(i=(s=o.current).onReconnectStarted)==null?void 0:i.call(s)},onReconnectSucceeded:()=>{var s,i;return(i=(s=o.current).onReconnectSucceeded)==null?void 0:i.call(s)},onReconnectFailed:()=>{var s,i;return(i=(s=o.current).onReconnectFailed)==null?void 0:i.call(s)},onConnectionLost:()=>{var s,i;return(i=(s=o.current).onConnectionLost)==null?void 0:i.call(s)},onConnectionDelayed:s=>{var i,l;return(l=(i=o.current).onConnectionDelayed)==null?void 0:l.call(i,s)}});return e.addConnectionHandler(n,r),()=>{e.removeConnectionHandler(n)}},[e,n])};function Kr(e){const{chatSDK:t,logger:n,aiAgentId:o}=Y(),{sdkUser:r,activeChannel:s,setActiveChannel:i,statsTrackers:l}=He(),[c,u]=d.useState(void 0),[m,h]=d.useState(void 0),[g,_]=d.useState(!1);function y(f){if(f.isAIAgent&&!f.conversation){_(!0);const E=f.initConversation({aiAgentId:o});E.catch(C=>n.warn("useChannel.initConversation: initialization failed",C)),E.finally(()=>_(!1))}}async function v(){var f,E;if(!r){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),u(void 0),h(void 0),_(!1),e){l.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const C=await t.groupChannel.getChannel(e);y(C),u(C),l.initialRender.onGetChannelComplete((f=C.conversation)==null?void 0:f.id),C.url===(s==null?void 0:s.url)&&i({url:C.url,status:le(C)?"closed":"open",conversationStatus:(E=C.conversation)==null?void 0:E.status}),n.debug("useChannel.getChannel: fetched channel",C)}catch(C){l.initialRender.onGetChannelError(C),C instanceof V.SendbirdError&&h(C),n.error("useChannel.getChannel: error",C)}}}return d.useEffect(()=>{v()},[t,r,e,o]),Wt(t,{async onReconnectSucceeded(){var E;if(!c)return;const f=await c.refresh();y(f),u(f),f.url===(s==null?void 0:s.url)&&i({url:f.url,status:le(f)?"closed":"open",conversationStatus:(E=f.conversation)==null?void 0:E.status})}}),{channel:c,channelFetchError:m,getChannel:v,isInitializingConversation:g}}const Yr=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},Xr=e=>{var i;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,o=n==null?void 0:n.form,r=!!o&&!o.submitted_at&&!o.canceled_at,s=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return r&&!s},Zr=()=>{const{chatSDK:e,networkStateAdapter:t}=Y(),[n,o]=d.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Wt(e,{onConnected:()=>o("connected"),onDisconnected:()=>o("disconnected"),onReconnectStarted:()=>o("reconnecting"),onReconnectSucceeded:()=>o("connected"),onReconnectFailed:()=>o("disconnected"),onConnectionLost:()=>o("reconnecting")}),d.useEffect(()=>{if(t)return t.subscribe(()=>{o("reconnecting")})},[t]),n},Jr=3e4,Qr=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:o})=>{const[r,s]=d.useState(!1),i=d.useRef(null),l=t&&Be(t,o)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),s(!1)},u=g=>{i.current&&clearTimeout(i.current),s(!0),i.current=setTimeout(()=>{s(!1),i.current=null},g)},m=Date.now()-l,h=Jr-m;return n||h<=0?c():u(h),()=>{i.current&&clearTimeout(i.current)}},[n,l]),r&&e},zn=e=>{const{chatSDK:t}=Y(),[n,o]=d.useState([]);return jt.useGroupChannelHandler(t,{onTypingStatusUpdated(r){if(r.url===(e==null?void 0:e.url)){const s=r.getTypingUsers();o(s)}}}),n},es=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:o})=>{const[r,s]=d.useState(!1),i=zn(e);return d.useEffect(()=>{if(!t)return;const l=i.some(u=>u.userId===n),c=Be(t,n)&&(Ke.isStreaming(t)||o);s(c||l)},[i,t,n,o]),r},ts=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:o})=>{const{aiAgentInfo:r,userSession:s}=He(),i=Zr(),l=es({channel:e,lastMessage:rn(t,[Ae.SendingStatus.SUCCEEDED]),aiAgentUserId:(r==null?void 0:r.userId)??"",isStreamAnimating:n}),c=Qr({shouldApply:!!(e!=null&&e.isAIAgent)&&!we(e),isBlockedWhileAIResponding:l,lastMessage:rn(t,[Ae.SendingStatus.PENDING,Ae.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""});if(!e||i==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(i==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(le(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Xr(e))return{disabled:!0,disabledBy:"form_active"};const u=Yr(e);return u?{disabled:!0,disabledBy:u}:l||c||o?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},ns=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(r=>{t(s=>{if(s.has(r))return s;const i=new Set(s);return i.add(r),i})},[]),o=d.useCallback(r=>{t(s=>{if(!s.has(r))return s;const i=new Set(s);return i.delete(r),i})},[]);return{isAnimating:e.size>0,start:n,stop:o}},{Provider:os}=X("AIAgentConversation");function rs({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:o,onMessagesUpdated:r,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Tt,shouldMarkAsRead:u=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var U;const g=()=>u&&(f==null?void 0:f.markAsRead()),{chatSDK:_,logger:y,dispatcher:v}=Y(),{channel:f,channelFetchError:E,getChannel:C,isInitializingConversation:A}=Kr(t),{statsTrackers:S}=He();d.useEffect(()=>{if(t)return S.initialRender.setChannelUrl(t),()=>{S.initialRender.cleanup()}},[t,S]);const w=hr(_,f,{replyType:Ae.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:P=>o==null?void 0:o(P),onMessagesUpdated:P=>r==null?void 0:r(P),onCacheResult:P=>S.initialRender.onCacheResult(P),onApiResult:P=>S.initialRender.onApiResult(P),logger:y,markAsRead:g,sortComparator:h}),x=ns(),M=ts({channel:f,messages:w.messages,isStreamAnimating:x.isAnimating,isInitializingConversation:A});d.useEffect(()=>{g()},[u]);const Z=le(f);d.useEffect(()=>{s==null||s(Z)},[Z,s]),d.useEffect(()=>{const P=async j=>{const T=typeof(j==null?void 0:j.channelUrl)=="string";f&&T&&j.channelUrl!==f.url||(y.debug("conversation.dispatcher: try to close conversation",f),f!=null&&f.conversation&&f.conversation.status===se.ConversationStatus.OPEN&&(await f.closeConversation(),i==null||i()))};return v.subscribe(xt.ConversationClose,P),()=>{v.unsubscribe(xt.ConversationClose,P)}},[v,(U=f==null?void 0:f.conversation)==null?void 0:U.status,i]);const q={conversation:(f==null?void 0:f.conversation)??void 0,channelSource:{channel:f,error:E,refetch:()=>C(),closeConversation:async()=>{le(f)||await(f==null?void 0:f.closeConversation())}},messageSource:{messages:w.messages,newMessages:w.newMessages,initialized:w.initialized,loadPrevious:()=>w.loadPrevious(),loadNext:()=>w.loadNext(),deleteMessage:P=>w.deleteMessage(P),resendMessage:P=>w.resendMessage(P),resetNewMessages:()=>w.resetNewMessages(),sendUserMessage:async P=>{var T;if(((T=f==null?void 0:f.conversation)==null?void 0:T.status)===se.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(P=await l(P));const j=await w.sendUserMessage(P,c);return c==null||c(j),j},sendFileMessage:async P=>{var T;if(((T=f==null?void 0:f.conversation)==null?void 0:T.status)===se.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(P=await l(P));const j=await w.sendFileMessage(P,c);return c==null||c(j),j}},state:{streamAnimation:x,input:M}};return a.createElement(os,{value:q},e)}function ss(e,t){var _,y,v,f,E,C,A,S,w,x;const[n,o]=d.useState(!1),[r,s]=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,o(!1),s(null),l([]);try{c==null||c.dispose();const M=new Wo(e,t);M.setConversationListCollectionHandler({onChannelsAdded:()=>{l(M.channels)},onChannelsUpdated:()=>{l(M.channels)},onChannelsDeleted:()=>{l(M.channels)}}),await M.loadMore(),u(M),s(null)}catch(M){u(null),s(M)}finally{o(!0),m.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(v=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:v.join(),(E=(f=t.filter)==null?void 0:f.aiAgentIds)==null?void 0:E.join(),(C=t.filter)==null?void 0:C.deskChannelFilter,(S=(A=t.filter)==null?void 0:A.pinnedChannelUrls)==null?void 0:S.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(x=t.filter)==null?void 0:x.copilotSupportChannelUrl,t.limit]),g=d.useCallback(async()=>{if(c)try{await c.loadMore()}catch(M){s(M)}},[c]);return Wt(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:as}=X("AIAgentConversationList");function is({conversationListLimit:e,conversationListFilter:t,children:n}){var h,g;const{chatSDK:o,aiAgentId:r,queryParams:s}=Y(),i={aiAgentIds:[r],aiAgentConversationStatusFilter:[se.ConversationStatus.CLOSED,se.ConversationStatus.OPEN]},l=e??((h=s==null?void 0:s.conversationListParams)==null?void 0:h.limit),c={...i,...(g=s==null?void 0:s.conversationListParams)==null?void 0:g.filter,...t},u=ss(o,{limit:l,filter:c}),m={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return a.createElement(as,{value:m},n)}function ls(e){let t="pending",n=e.then(o=>{t="resolved",n=o}).catch(o=>{t="rejected",n=o});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:cs}=X("MessageTemplateFetching");function us({children:e,internalVariables:t}){const n=d.useRef({}),o=d.useRef({}),[r,s]=d.useState({}),i=d.useCallback((u,m)=>{s(h=>({...h,[u]:{fetching:!1,error:!1,...h[u],...m}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const _=m(h);if(_)return _;const y=o.current[h];if(y)return y;g||i(h,{fetching:!0});const v=u(h).catch(f=>{throw g||i(h,{error:!0}),f}).finally(()=>{g||i(h,{fetching:!1}),delete o.current[h]});return o.current[h]=v,v},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(u,m)=>{if(n.current[u])return n.current[u];const h=ls(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(cs,{value:c},e)}const ds="remove_powered_by",Kt=(e,t)=>{var r,s;const{chatSDK:n}=Y(),{aiAgentInfo:o}=He();if(e==="handoff-button"){const i=!!((r=t==null?void 0:t.conversation)!=null&&r.handoff);return!!(t!=null&&t.isAIAgent)&&!!(o!=null&&o.showHandoffButton)&&i&&On(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(o!=null&&o.specialNoticeEnabled)&&!!(o!=null&&o.specialNotice);if(e==="powered-by"){const i=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return d.useMemo(()=>!(Array.isArray(i)&&i.includes(ds)),[i])}throw new Error("Unsupported feature")},ms=e=>{const{aiAgentInfo:t}=He(),o=zn(e)[0];if(!o)return null;const r=o.userId===(t==null?void 0:t.userId);return{user:r?t:o,isBot:r}},Un=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const o=(()=>{const[s]=e.members.filter(i=>i.userId!==t.userId);return s})(),r={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:o==null?void 0:o.profileUrl,title:(o==null?void 0:o.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?we(e)?r.human("agent"):r.ai("delight"):e.isDesk?r.human("agent"):r.channel("user")},Mt=e=>d.useReducer((t,n)=>({...t,...n}),e);var ge=(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))(ge||{});const gs=new Set(["free_text","single_choice"]),hs=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:o,initialIsResolved:r})=>{const[s,i]=Mt({csatType:t,csat:n,csatReason:o,isResolved:r}),[l,c]=Mt({followUpItem:!1}),u=d.useMemo(()=>{var f;const _=s.csat,y=typeof _=="number",v=(f=e.follow_up)==null?void 0:f.find(E=>y?E.scores.includes(_):E.always_visible??!1);if(gs.has(v==null?void 0:v.response_type))return v},[s.csat,e.follow_up]),m=(()=>{var _;if(typeof n=="number")return"submitted";if((t===ge.AI_AGENT_CSAT_5||t===ge.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===ge.AI_AGENT_CSAT_5_WITH_CRE){const y=typeof s.csat=="number",v=!((_=e.cre)!=null&&_.required)||typeof s.isResolved=="boolean";if(y&&v)return"submittable"}return"unsubmittable"})(),h=d.useCallback(()=>typeof s.csat>"u"?!1:u!=null&&u.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,u,c]);return d.useEffect(()=>{o||(i({csatReason:""}),c({followUpItem:!1}))},[o,u,i,c]),{params:s,setParams:i,error:l,setError:c,followUpItem:u,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},dt=5,fs=250,ps=50,pn=e=>Math.max(0,e-ps),_s=e=>e<1e3?{speed:dt*.5,chunkSize:2}:e<2e3?{speed:dt*.8,chunkSize:2}:{speed:dt*.6,chunkSize:3},ys=e=>{const{text:t,enabled:n=!1,onAnimationStart:o,onAnimationProgress:r,onAnimationComplete:s}=e,[i,l]=d.useState(()=>pn(t.length)),c=d.useRef(null),u=d.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=d.useRef({onStart:o,onProgress:r,onComplete:s}).current,h=d.useRef({startCalled:!1,completeCalled:!1}).current,g=d.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,_=n,y=i<t.length,v=g.initialEnabled&&(_||y);return d.useLayoutEffect(()=>{m.onStart=o,m.onProgress=r,m.onComplete=s,g.textLength=t.length,g.enabled=n}),d.useLayoutEffect(()=>{var f;g.initialEnabled&&(h.startCalled||(h.startCalled=!0,(f=m.onStart)==null||f.call(m)),l(E=>t.length<E?t.length:E))},[t]),d.useEffect(()=>{if(!g.initialEnabled)return;let f=pn(t.length);u.lastUpdate=0,u.startTime=0,u.lastProgressCall=0;const E=C=>{var U;u.lastUpdate===0&&(u.lastUpdate=C,u.startTime=C,u.lastProgressCall=C);const A=g.textLength,S=C-u.lastUpdate,w=C-u.startTime,{speed:x,chunkSize:M}=_s(w),Z=x*M;S>=Z&&f<A&&(f=Math.min(f+M,A),l(f),u.lastUpdate=C),C-u.lastProgressCall>=fs&&(u.lastProgressCall=C,(U=m.onProgress)==null||U.call(m)),(f<A||g.enabled)&&(c.current=requestAnimationFrame(E))};return c.current=requestAnimationFrame(E),()=>{c.current&&cancelAnimationFrame(c.current)}},[]),d.useEffect(()=>{var A;const f=g.initialEnabled&&h.startCalled,E=!n,C=i>=t.length&&t.length>0;f&&E&&C&&!h.completeCalled&&(h.completeCalled=!0,(A=m.onComplete)==null||A.call(m))},[n,i,t.length]),{streamText:g.initialEnabled?t.slice(0,i):t,isAnimating:v}},bs="1.7.0",Fn=bs,Es={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"},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"}},Rt={language:"en",strings:Es,dateLocale:bo.enUS},Cs={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:"대화 시작"},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:"피드백 삭제"}},Lt={language:"ko",strings:Cs,dateLocale:To.ko},vs={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:"会話を始める"},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:"フィードバックを削除"}},Dt={language:"ja",strings:vs,dateLocale:Ao.ja},Ss={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"},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"}},Pt={language:"es",strings:Ss,dateLocale:Eo.es},As={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"},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"}},Ot={language:"pt",strings:As,dateLocale:wo.pt},Ts={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"},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"}},Nt={language:"fr",strings:Ts,dateLocale:Co.fr},ws={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:"एक बातचीत शुरू करें"},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:"प्रतिक्रिया हटाएं"}},Bt={language:"hi",strings:ws,dateLocale:vo.hi},xs={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"},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"}},Ht={language:"it",strings:xs,dateLocale:So.it},Is={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"},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"}},zt={language:"de",strings:Is,dateLocale:yo.de},ks={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"},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"}},Ut={language:"tr",strings:ks,dateLocale:xo.tr},ce=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}),_n=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Qe},Qe="en",Yt={borderColor:"red",borderWidth:p.StyleSheet.hairlineWidth},b=({debug:e=!1,style:t,children:n,...o})=>a.createElement(p.View,{style:[t,o,e&&Yt],...o},n);b.Animated=({debug:e=!1,style:t,children:n,...o})=>a.createElement(p.Animated.View,{style:[t,o,e&&Yt],...o},n);const{Provider:Ms,useContext:oe}=X("MessengerSession"),Rs=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof Ze||t.userSessionInfo instanceof qt))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return a.createElement(qr,{ref:n,...t},o=>a.createElement(Ls,{...o},e))}),Ls=({children:e,...t})=>{const{userSession:n,aiAgentInfo:o,launcherInfo:r}=t;return a.createElement(Ms,{value:{...t,userSession:n,aiAgentInfo:o,launcherInfo:r}},e)},je=50,{Provider:Ds,useContext:Ps}=X("ConversationScroll"),Os=({children:e})=>{var T;const{config:t}=Y(),n=((T=t==null?void 0:t.conversation)==null?void 0:T.scrollMode)??"auto",o=d.useRef(null),r=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),s=d.useRef(0),[i,l]=d.useState(0),[c,u]=d.useState(0),[m,h]=d.useState(!1),[g,_]=d.useState(!1),y=d.useMemo(()=>g?"auto":n,[g,n]),v=d.useCallback(()=>{const{shouldUpdate:z,shouldRecalc:G,contentHeight:Q,contentSnapshotHeight:fe,viewport:Me}=r.current;z&&fe<Q&&l(pe=>{r.current.shouldUpdate=!1;const Re=Q-pe-fe,re=Math.max(0,Me-Re);return pe===0||re<pe||G?(r.current.shouldRecalc=!1,re):pe})},[]),f=d.useCallback(z=>{r.current.viewport=z.nativeEvent.layout.height},[]),E=d.useCallback((z,G)=>{r.current.contentHeight=G;const Q=r.current.viewport;h(G>Q),v()},[v]),C=d.useCallback(z=>{const G=z.nativeEvent.contentOffset.y;s.current=G,u(G)},[]),A=d.useMemo(()=>({minIndexForVisible:0,autoscrollToTopThreshold:je}),[]),S=d.useCallback((z=!0)=>{var G;(G=o.current)==null||G.scrollToOffset({offset:0,animated:z})},[]),w=d.useCallback((z,G=!0)=>{var Q;(Q=o.current)==null||Q.scrollToIndex({index:z,animated:G,viewPosition:1})},[]),x=d.useCallback(()=>{y==="fixed"&&(r.current.contentSnapshotHeight=r.current.contentHeight-i,r.current.shouldUpdate=!0,r.current.shouldRecalc=!0)},[y,i]),M=d.useCallback(()=>{y==="fixed"?w(0):S()},[y,S,w]),Z=d.useCallback(()=>{y==="fixed"?r.current.shouldUpdate=!0:s.current<=je&&S()},[y,S]),q=d.useCallback(z=>{_(z)},[]),U=c<=je,P=m&&!U,j=d.useCallback(()=>s.current>je,[]);return a.createElement(Ds,{value:{ref:o,state:{bottomSpace:i,isAwayFromBottom:P,shouldCountNewMessages:j},props:{maintainVisibleContentPosition:A,onLayout:f,onContentSizeChange:E,onScroll:C},actions:{scrollToBottom:S,scrollToIndex:w,onBeforeMessageSend:x,onAfterMessageSend:M,onStreamingUpdate:Z,onConversationClosed:q}}},e)};function $n(e){return new Promise((t,n)=>{p.Image.getSize(e,(o,r)=>{t({width:String(o),height:String(r)})},o=>{n(o)})})}async function Ns(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:o,height:r}=await $n(n.uri);return new Ae.MessageMetaArray({key:kn,value:[o,r]})}catch{return}}}function Bs(e,t){let n=0,o=0;return ie(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),ie(t)&&t.sendingStatus!=="succeeded"&&(o=Number.MAX_SAFE_INTEGER),t.createdAt+o-(e.createdAt+n)}const{Provider:Hs,Context:zs,useContext:ue}=X("Conversation"),jn=e=>a.createElement(Os,null,a.createElement(Us,{...e})),Us=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:o,shouldMarkAsRead:r,children:s})=>{const i=Ps(),{activeChannel:l,refreshActiveChannel:c,sdkUser:u,authenticate:m}=oe();d.useEffect(()=>{u||m()},[]);const h=d.useCallback(async v=>{i.actions.onBeforeMessageSend();const f=await Ns(v);return{...v,metaArrays:f?[f]:void 0}},[i.actions.onBeforeMessageSend]),g=d.useCallback(()=>{i.actions.onAfterMessageSend()},[i.actions.onAfterMessageSend]),_=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]),y=e??(l==null?void 0:l.url);return a.createElement(rs,{key:y,channelUrl:y,onBeforeSendMessage:h,onAfterSendMessage:g,onMessagesUpdated:i.actions.onStreamingUpdate,onMessagesReceived:i.actions.onStreamingUpdate,onChannelDeleted:_,onConversationClosedStatusChanged:i.actions.onConversationClosed,sortComparator:Bs,shouldMarkAsRead:r,shouldCountNewMessages:i.state.shouldCountNewMessages},v=>a.createElement(Hs,{value:{...v,scrollSource:i,onClose:n,onNavigateToConversationList:o,updateActiveChannel:_}},s))},mt=ce(zt.strings),Fs={...mt,conversation:{...mt.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:{...mt.conversation_list}},$s={language:zt.language,dateLocale:zt.dateLocale,strings:Fs},gt=ce(Rt.strings),js={...gt,conversation:{...gt.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:{...gt.conversation_list}},Gs={language:Rt.language,dateLocale:Rt.dateLocale,strings:js},ht=ce(Pt.strings),Vs={...ht,conversation:{...ht.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:{...ht.conversation_list}},qs={language:Pt.language,dateLocale:Pt.dateLocale,strings:Vs},ft=ce(Nt.strings),Ws={...ft,conversation:{...ft.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:{...ft.conversation_list}},Ks={language:Nt.language,dateLocale:Nt.dateLocale,strings:Ws},pt=ce(Bt.strings),Ys={...pt,conversation:{...pt.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:{...pt.conversation_list}},Xs={language:Bt.language,dateLocale:Bt.dateLocale,strings:Ys},_t=ce(Ht.strings),Zs={..._t,conversation:{..._t.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:{..._t.conversation_list}},Js={language:Ht.language,dateLocale:Ht.dateLocale,strings:Zs},yt=ce(Dt.strings),Qs={...yt,conversation:{...yt.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:{...yt.conversation_list}},ea={language:Dt.language,dateLocale:Dt.dateLocale,strings:Qs},bt=ce(Lt.strings),ta={...bt,conversation:{...bt.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:{...bt.conversation_list}},na={language:Lt.language,dateLocale:Lt.dateLocale,strings:ta},Et=ce(Ot.strings),oa={...Et,conversation:{...Et.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:{...Et.conversation_list}},ra={language:Ot.language,dateLocale:Ot.dateLocale,strings:oa},Ct=ce(Ut.strings),sa={...Ct,conversation:{...Ct.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:{...Ct.conversation_list}},aa={language:Ut.language,dateLocale:Ut.dateLocale,strings:sa},yn=new Map([["en",Gs],["ko",na],["ja",ea],["es",qs],["pt",ra],["fr",Ks],["hi",Xs],["it",Js],["de",$s],["tr",aa]]),bn=e=>yn.get(e)??yn.get(Qe),ia=(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:la,useContext:F}=X("Localization"),ca=({language:e=Qe,logger:t,strings:n,children:o})=>{const[r,s]=d.useState(()=>{const i=_n(e);return bn(i)});return d.useEffect(()=>{var l;const i=_n(e);if(r.language!==i){const c=bn(i);s(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:r.language,to:c.language})}},[e,t]),a.createElement(la,{value:{language:r.language,strings:ia(r.strings,n),dateLocale:r.dateLocale,format:(i,l,c)=>Se.format(i,l,{locale:r.dateLocale,...c})}},o)},{Provider:ua,useContext:et}=X("Modal");function Gn({children:e}){const[t,n]=d.useState([]),[o,r]=d.useState(null),s=d.useRef(0);d.useEffect(()=>{if(!o&&t.length>0){const[u,...m]=t;u&&(r(u),n(m))}},[o,t]);const i=d.useCallback(u=>new Promise(m=>{const g={id:`modal-${++s.current}`,render:u,resolve:m};n(_=>[..._,g])}),[]),l=d.useCallback((u,m)=>{r(h=>(h==null?void 0:h.id)===u?(h.resolve(m),null):h)},[]),c={openModal:i,currentModal:o};return a.createElement(ua,{value:c},e,o&&a.createElement(p.Modal,{visible:!0,supportedOrientations:["landscape","portrait"],transparent:!0,animationType:"fade",onRequestClose:()=>l(o.id,null),style:{height:0}},o.render(u=>l(o.id,u??null))))}const{Provider:da,useContext:$}=X("MessengerTheme"),ma=({children:e,...t})=>a.createElement(Pr,{...t,appearance:{theme:t.mode??"light"}},n=>{const o=ga(n.theme);return a.createElement(da,{value:{...n,themedColor:o}},e)});function ga(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 D={create:e=>{const t=new WeakMap,n=o=>{const r=t.get(o.theme);if(r)return r;const s=e(o),i={},l={};for(const m in s)typeof s[m]=="function"?l[m]=s[m]:i[m]=s[m];const u={...p.StyleSheet.create(i),...l};return t.set(o.theme,u),u};return{use:()=>{const o=$(),r=Ee.useSafeAreaInsets();return n({...o,edgeInsets:r,select:s=>s[o.theme.selectedTheme]})}}}},ha={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},Ie=(e,t=p.I18nManager.isRTL?"rtl":"ltr")=>{const n=Ee.useSafeAreaInsets();return e.reduce((o,r)=>{const s=ha[t][r];return o[s]=n[r],o},{})},fa={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")},pa={send:!0,chat:!0,message:!0,good:!0,bad:!0,"good-filled":!0,"bad-filled":!0},B=({customSource:e,type:t,color:n,size:o=24,style:r})=>{const s=_a.use(),i=p.I18nManager.isRTL&&!!pa[t];return a.createElement(b,{alignItems:"center",justifyContent:"center"},a.createElement(p.Image,{resizeMode:"contain",source:e??fa[t],style:[s.icon({color:n,size:o,mirror:i}),r]}))},_a=D.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})})),Xt=(e,t)=>{if(!t||t.length===0)return!1;const n=t.trimStart();if(n.length===0)return!1;const o=e==="start"?Array.from(n)[0]:Array.from(n).pop(),r=o==null?void 0:o.codePointAt(0);return r===void 0?!1:Ea(r)},Vn=e=>Xt("start",e),ya=e=>Xt("end",e),ba=e=>{const{text:t,style:n,isTextInput:o}=e;return n!=null&&n.textAlign&&n.textAlign!=="left"&&n.textAlign!=="right"?n.textAlign:p.I18nManager.isRTL&&typeof t=="string"&&Vn(t)?o?"right":p.I18nManager.doLeftAndRightSwapInRTL?"left":"right":n==null?void 0:n.textAlign},Ea=e=>{for(const[t,n]of Ca)if(e>=t&&e<=n)return!0;return!1},Ca=[[1424,1535],[1536,1791],[1872,1919],[2208,2303],[64285,64335],[65136,65279],[126464,126719]],Zt={isStartsWithRTL:Vn,isEndsWithRTL:ya,isRTLString:Xt,useTextAlign:ba},I=({variant:e="body1",color:t,style:n,...o})=>{const{theme:r,themedColor:s}=$(),i=d.useMemo(()=>{if(typeof t=="function")return t({theme:r,themedColor:s});if(typeof t=="string")return t;const u=p.StyleSheet.flatten(n);return u&&u.color?u.color:t??s.textHighEmphasis},[n,t,s.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,s.textHighEmphasis]),c=Zt.useTextAlign({text:o.children,style:l});return a.createElement(p.Text,{style:[l,{textAlign:c}],...o})},qn=350,va=({children:e,...t})=>a.createElement(p.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:qn,...t},n=>typeof e=="function"?e(n):e),Sa=({children:e,style:t,...n})=>{const[o,r]=d.useState(!1),s={pressed:o};return a.createElement(p.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:qn,style:typeof t=="function"?t(s):t,onPressIn:()=>r(!0),onPressOut:()=>r(!1),...n},typeof e=="function"?e(s):e)},O=e=>e.activeOpacity&&e.activeOpacity<1?a.createElement(Sa,{...e}):a.createElement(va,{...e}),{Provider:Aa,useContext:Wn}=X("BottomSheetAnimation");function Ta({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 o=d.useCallback(s=>async()=>{p.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(async()=>{try{await(s==null?void 0:s())}catch{e==null||e()}})},[n]),r=d.useRef(p.PanResponder.create({onMoveShouldSetPanResponder:(s,i)=>i.dy>5,onPanResponderMove:(s,i)=>{i.dy>0&&n.setValue(i.dy)},onPanResponderRelease:(s,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(Aa,{value:{wrapWithAnimation:o,translateY:n,panHandlers:r.panHandlers}},t)}const wa=({icon:e,label:t="",destructive:n=!1,onPress:o})=>{const r=Kn.use(),{themedColor:s}=$();return a.createElement(O,{onPress:o,style:r.actionItem,activeOpacity:.75},e&&a.createElement(B,{type:e,size:24,color:s.primary}),a.createElement(I,{variant:"body3",color:n?s.error:s.textHighEmphasis,numberOfLines:1},t))},xa=({onClose:e,children:t})=>{const n=Kn.use(),{translateY:o,panHandlers:r,wrapWithAnimation:s}=Wn(),i=Ie(["left","right"]);return a.createElement(O,{onPress:s(e),style:n.overlay},a.createElement(b.Animated,{style:[n.container,i,{transform:[{translateY:o}]}],...r},t))},tt=ae({template:xa,components:{ActionItem:wa}}),ne=e=>{const{Template:t}=tt.useContext();return a.createElement(Ta,{onClose:e.onClose},a.createElement(t,{...e}))};ne.ActionItem=e=>{const{components:t}=tt.useContext(),{wrapWithAnimation:n}=Wn();return a.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const Kn=D.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}})),Ia=({style:e,label:t,accessibilityLabel:n,onPress:o})=>{const r=ka.use(),{theme:s}=$();return a.createElement(O,{style:[r.button,e],onPress:o,accessibilityLabel:n,accessibilityRole:"button"},a.createElement(b,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(I,{variant:"button",color:s.colors.base.primaryContrastContent},t),a.createElement(B,{size:16,type:"chevron-down",color:s.colors.base.primaryContrastContent})))},ka=D.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}]}})),Jt=({iconSize:e=64,icon:t,style:n,label:o,children:r})=>{const{themedColor:s}=$();return a.createElement(b,{style:[Yn.body,n]},t&&a.createElement(B,{type:t,size:e,color:s.textLowEmphasis}),o&&a.createElement(I,{variant:"body1",color:s.textMidEmphasis},o),r)},Ma=({children:e})=>{const{theme:t}=$();return a.createElement(b,{backgroundColor:t.colors.base.background,style:Yn.container},e)},Yn=p.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),Ra=({label:e,icon:t="error",action:n,...o})=>{const{strings:r}=F();return a.createElement(Jt,{icon:t,label:e??r.common.placeholder_something_went_wrong,...o},n&&a.createElement(La,{onPress:n.onPress,label:n.label??r.common.placeholder_something_went_wrong_retry_label}))},La=({label:e,onPress:t})=>{const{themedColor:n}=$();return a.createElement(O,{onPress:t},a.createElement(b,{style:Da.button},a.createElement(B,{type:"refresh",size:20}),a.createElement(I,{variant:"button",color:n.primary},e)))},Da=p.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),Pa=({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 o=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(b.Animated,{style:[{transform:[{rotate:o}]},t]},a.createElement(B,{type:"spinner",size:e}))},Oa=({label:e,icon:t="chat",...n})=>{const{strings:o}=F();return a.createElement(Jt,{icon:t,label:e??o.common.placeholder_no_conversations,...n})},Na=({label:e,icon:t="message",...n})=>{const{strings:o}=F();return a.createElement(Jt,{icon:t,label:e??o.common.placeholder_no_messages,...n})},Ba=e=>{const{components:t}=nt.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(Ma,null,n)},nt=ae({template:Ba,components:{Loading:Pa,Error:Ra,NoChannels:Oa,NoMessages:Na}}),Te=e=>{const{Template:t}=nt.useContext();return a.createElement(t,{...e})},Ha=({loading:e,error:t,empty:n,stackDirection:o,data:r=[],LoadingComponent:s,ErrorComponent:i,EmptyComponent:l,...c},u)=>{if(t)return i;if(e)return s;const{contentContainerStyle:m,...h}=c,g=o==="top"&&!n;return a.createElement(p.FlatList,{ref:u,data:r,ListEmptyComponent:n?l:null,contentContainerStyle:[m,g&&En.stackTop,n&&En.emptyContainer],...h})},En=p.StyleSheet.create({stackTop:{flexGrow:1,justifyContent:"flex-end"},emptyContainer:{flex:1}}),Xn=d.memo(d.forwardRef(Ha)),Qt=({name:e,type:t="FILE",onPress:n})=>{const o=za.use();return a.createElement(O,{onPress:n,style:o.container,activeOpacity:.75},a.createElement(b,{style:o.iconWrapper},a.createElement(B,{type:"file-document",size:24,color:o.icon.tintColor})),a.createElement(b,{flex:1,flexDirection:"column",gap:4,style:o.info},a.createElement(I,{variant:"button",color:({themedColor:r})=>r.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),a.createElement(I,{variant:"caption3",color:({themedColor:r})=>r.textMidEmphasis},t)))},za=D.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}})),Ua=({file:e,children:t,onClickFile:n=({url:o})=>p.Linking.openURL(o)})=>a.createElement(b,{gap:R.GAP_GROUPED,width:R.BODY_MAX_WIDTH,maxWidth:R.BODY_MAX_WIDTH},a.createElement(Qt,{name:e.name,type:Gt(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),xe=({style:e,...t})=>a.createElement(p.Image,{style:[e,t],...t}),Fa=({file:e,onClickMedia:t=({url:o})=>p.Linking.openURL(o),children:n})=>{const o=$a.use();return a.createElement(b,{gap:R.GAP_GROUPED},a.createElement(O,{style:o.mediaContainer,onPress:()=>t==null?void 0:t(e)},a.createElement(xe,{source:{uri:e.url},style:o.media,resizeMode:"cover"})),n)},$a=D.create(({select:e,theme:t})=>({mediaContainer:{width:R.BODY_MAX_WIDTH,height:160,borderRadius:12,overflow:"hidden",backgroundColor:e({light:t.palette.background100,dark:t.palette.background400})},media:{width:"100%",height:"100%"}})),Zn=({code:e,language:t})=>{const[n,o]=d.useState(!1),r=async()=>{Do.default.setString(e),o(!0),setTimeout(()=>o(!1),2e3)};return a.createElement(b,{style:Ge.container,flexDirection:"row"},a.createElement(p.Pressable,{style:Ge.copyButton,onPress:r},a.createElement(B,{type:n?"done":"copy",size:16,color:"#fff"})),a.createElement(b,null,a.createElement(Po.default,{hljsStyle:ja,scrollViewProps:{contentContainerStyle:Ge.codeContainer,bounces:!1},textStyle:Ge.codeText,language:t},e)))},Ge=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}}),ja={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"}},Jn=d.memo(({src:e,onPress:t})=>{const[n,o]=d.useState("1/1"),[r,s]=d.useState(!1),i=Ga.use();return d.useLayoutEffect(()=>{e&&$n(e).then(({width:l,height:c})=>o(`${l}/${c}`))},[e]),a.createElement(p.Pressable,{style:{marginTop:8},onPress:t},a.createElement(b,{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:()=>s(!0)})))}),Ga=D.create(({themedColor:e})=>({container:{width:"100%",backgroundColor:e.textDisabled,borderRadius:4,overflow:"hidden",justifyContent:"center",alignItems:"center"}}));Jn.displayName="MarkdownImage";const De=e=>d.isValidElement(e)&&"children"in e.props,Ft=(e=.75)=>`rgba(0, 0, 0, ${e})`,Va=({children:e})=>{var i;const t=p.useWindowDimensions(),n=Ft(.3),o=d.useMemo(()=>{try{if(!Array.isArray(e)||e.length<2)return null;const l=e[0],c=e[1],u=De(c)?c.props.children:void 0;if(!u||!Array.isArray(u)||u.length===0)return null;const m=u,h=m[0],g=De(h)?h.props.children:void 0;if(!g||!Array.isArray(g)||g.length===0)return null;const _=m.length,y=g.length,v=Array(y).fill(null).map(()=>[]);for(let A=0;A<_;A++){const S=m[A],w=De(S)?S.props.children:void 0;if(!(!w||!Array.isArray(w)))for(let x=0;x<y;x++){const M=v[x];M&&x<w.length&&(M[A]=w[x])}}const f=De(l)?l.props.children:void 0,E=Array.isArray(f)?f[0]:void 0,C=De(E)?E.props.children:void 0;if(C&&Array.isArray(C))for(let A=0;A<y;A++){const S=v[A];S&&A<C.length&&S.unshift(C[A])}return v}catch{return null}},[e]),[r,s]=d.useState(Array(((i=o==null?void 0:o[0])==null?void 0:i.length)??0).fill(0));return o?a.createElement(p.View,{style:{flexDirection:"row"}},o.map((l,c)=>{const u=c===0,m=c===o.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 _=g===0,y=g===l.length-1;return a.createElement(p.View,{key:g,onLayout:({nativeEvent:{layout:v}})=>{const f=v.height;(r[g]??0)<f&&(r[g]=f,s([...r]))},style:{borderBottomWidth:y?0:1,borderColor:n,backgroundColor:_?Ft(.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)},en=d.memo(({children:e,textStyle:t,linkStyle:n,onPressImage:o})=>{const{themedColor:r}=$(),s=p.StyleSheet.compose({fontSize:14,color:r.textHighEmphasis,textAlign:"left"},t),i=p.StyleSheet.flatten(s),l=i.fontSize||14,c=i.lineHeight||l*1.286,u=Ft(.3),m={color:i.color,textAlign:Zt.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 y,v;const _=((y=g.attributes)==null?void 0:y.src)||((v=g.attributes)==null?void 0:v.href);return _?a.createElement(Jn,{key:g.key,src:_,onPress:()=>o==null?void 0:o(_)}):null},code_block:g=>a.createElement(Zn,{code:g.content,language:"text"}),table:(g,_)=>a.createElement(p.View,{key:g.key,style:{marginTop:8}},a.createElement(p.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},a.createElement(Va,null,_)))}),[o]);return a.createElement(b,{flexDirection:"row",marginTop:-8},a.createElement(Oo.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},jo(e)))});en.displayName="MarkdownText";const Cn=({maxBodyWidth:e,customStyle:t,message:n,children:o})=>{const r=qa.use(),s=e??R.BODY_MAX_WIDTH,i=d.useMemo(()=>zo(n),[n]),l=d.useCallback(c=>p.Linking.openURL(c),[]);return i.length===0&&!o?null:a.createElement(b,{alignSelf:"flex-start",maxWidth:s,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(b,{key:u,paddingHorizontal:12},a.createElement(en,{onPressImage:l,textStyle:r.text},c.value)):c.type==="code"?a.createElement(Zn,{key:u,code:c.value,language:c.language}):null),o)},qa=D.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),Wa=e=>{const{strings:t}=F(),n=()=>{const o=Rn(e)?a.createElement(Cn,{...e}):null;return e.messageType==="user"?o:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(Fa,{...e},o):a.createElement(Ua,{...e},o):a.createElement(Cn,{...e,message:t.conversation.unknown_message_type})};return a.createElement(b,{style:e.containerStyle},n())};function Qn({id:e,src:t,size:n=56,onClick:o,style:r}){const s=Ka.use(),i=a.createElement(p.View,{style:[s.container(n),r],testID:e},t?a.createElement(p.Image,{source:{uri:t},style:s.image}):a.createElement(B,{type:"user",size:n}));return o?a.createElement(O,{onPress:o,activeOpacity:.75},i):i}const Ka=D.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"}})),Ya=({sender:e,isBotMessage:t})=>{const n=Xa.use();return t&&!e.profileUrl?a.createElement(b,{style:n.botContainer},a.createElement(B,{type:"delight",color:({theme:o})=>o.colors.base.primaryContrastContent,size:R.AVATAR_SIZE-8})):a.createElement(Qn,{src:e.profileUrl,size:R.AVATAR_SIZE})},Xa=D.create(({theme:e})=>({botContainer:{width:R.AVATAR_SIZE,height:R.AVATAR_SIZE,borderRadius:R.AVATAR_SIZE/2,padding:4,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary}})),Za=({sender:e})=>a.createElement(b,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7,alignItems:"flex-start"},a.createElement(I,{variant:"caption1",color:({themedColor:t})=>t.textMidEmphasis,numberOfLines:1},e.nickname)),Ja=({createdAt:e,containerStyle:t})=>{const{strings:n,format:o}=F();return e?a.createElement(b,{alignItems:"flex-start",style:t},a.createElement(I,{variant:"caption4",color:({themedColor:r})=>r.textLowEmphasis},o(e,n.date_format.message_timestamp))):null},Qa=({customStyle:e,containerStyle:t})=>{const{theme:n}=$(),o=d.useRef(new p.Animated.Value(0)).current,r=ei.map(([s,i,l])=>[o.interpolate({inputRange:s,outputRange:i,extrapolate:"clamp"}),o.interpolate({inputRange:s,outputRange:l,extrapolate:"clamp"})]);return d.useEffect(()=>{const s=p.Animated.loop(p.Animated.timing(o,{toValue:1.4,duration:1400,easing:p.Easing.linear,useNativeDriver:!0}));return s.start(),()=>s.reset()},[]),a.createElement(b,{style:t},a.createElement(b,{width:60,flexDirection:"row",alignItems:"center",justifyContent:"center",borderRadius:16,paddingHorizontal:12,height:34,backgroundColor:(e==null?void 0:e.bubbleBackgroundColor)??n.colors.messageIncoming.background},r.map(([s,i],l)=>a.createElement(b.Animated,{key:l,style:[ti.dot,{marginEnd:l===r.length-1?0:6,opacity:i,transform:[{scale:s}],backgroundColor:(e==null?void 0:e.bubbleContentColor)??n.colors.messageIncoming.text}]}))))},ei=[[[.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]]],ti=p.StyleSheet.create({dot:{width:8,height:8,borderRadius:4}}),ni=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>p.Linking.openURL(n)})=>{const n=oi.use(),o=e==null?void 0:e.cta_button;return o?a.createElement(O,{onPress:()=>t(o),activeOpacity:.75,style:n.button},a.createElement(I,{variant:"button",color:({themedColor:r})=>r.textHighEmphasis,numberOfLines:1},o.label)):null},oi=D.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})}})),ri=({extendedMessagePayload:e,onClickCitation:t=n=>p.Linking.openURL(n.link)})=>{const{strings:n}=F(),{theme:o}=$(),r=e==null?void 0:e.citations;return!r||r.length===0?null:a.createElement(b,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},a.createElement(I,{variant:"caption1",color:o.colors.messageIncoming.text,style:vn.sourceLabel},n.conversation.citation_title),a.createElement(b,{gap:8},r.map(s=>a.createElement(O,{key:s.embedding_id,onPress:()=>t(s),activeOpacity:.5},a.createElement(b,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(B,{type:"source",size:16,color:o.colors.messageIncoming.text}),a.createElement(b,{flex:1},a.createElement(I,{variant:"body3",color:o.colors.messageIncoming.text,numberOfLines:1,style:vn.citationText},s.title)))))))},vn=p.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),si=e=>a.createElement(a.Fragment,null),$t=e=>`${e}-filled`,ai=e=>e==="good"?se.AIAgentMessageFeedbackRating.GOOD:se.AIAgentMessageFeedbackRating.BAD,Sn=({onClose:e,isEdit:t,initialRating:n,initialComment:o="",isCommentEnabled:r=!1})=>{const{strings:s}=F(),{themedColor:i,theme:l}=$(),c=ii.use(),[u,m]=d.useState(o),[h,g]=d.useState(n),_=()=>{h&&e({rating:h,comment:u.trim()||void 0})},y=()=>{e()},v={good:i.secondary,bad:i.error};return a.createElement(p.KeyboardAvoidingView,{style:{flex:1},behavior:"padding"},a.createElement(O,{onPress:y,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(I,{variant:"h2",color:i.textHighEmphasis},s.feedback.title)),a.createElement(b,{paddingHorizontal:24,gap:24},a.createElement(b,{flexDirection:"row",gap:4},["good","bad"].map(f=>{const E=h===f,C=f==="good"?s.feedback.good:s.feedback.bad;return a.createElement(O,{key:f,onPress:()=>g(f),activeOpacity:.6,style:c.ratingButton(E)},a.createElement(B,{type:E?$t(f):f,size:24,color:E?v[f]:i.textLowEmphasis}),a.createElement(I,{variant:"caption1",color:E?v[f]:i.textLowEmphasis},C))})),r&&a.createElement(b,{gap:6},a.createElement(I,{variant:"caption3",color:i.textHighEmphasis},s.feedback.comment_label),a.createElement(p.TextInput,{value:u,onChangeText:f=>m(f),placeholder:s.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(O,{onPress:y,activeOpacity:.6,style:c.cancelButton},a.createElement(I,{variant:"button",color:i.textHighEmphasis},s.feedback.cancel)),a.createElement(O,{onPress:_,disabled:!h,activeOpacity:.6,style:c.submitButton(!h)},a.createElement(I,{variant:"button",color:l.colors.base.primaryContrastContent},t?s.feedback.save:s.feedback.submit))))))},ii=D.create(({select:e,theme:t,themedColor:n})=>({overlay:{flex:1,backgroundColor:t.palette.overlay.dark,alignItems:"center",justifyContent:"center"},ratingButton:o=>({width:114,height:64,borderRadius:12,borderWidth:1,borderColor:n.textDisabled,alignItems:"center",justifyContent:"center",gap:0,backgroundColor:o?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:o=>({width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center",backgroundColor:t.colors.base.primary,opacity:o?.4:1})})),li=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:o,isFeedbackCommentEnabled:r,extendedMessagePayload:s,onFeedbackUpdate:i,containerStyle:l})=>{const{strings:c}=F(),{themedColor:u}=$(),{openModal:m}=et(),h=ci.use(),g=s==null?void 0:s.feedback,_=(g==null?void 0:g.rating)??"none";if(_!=="none"?!1:!!(n||!e||!o||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const v={good:u.secondary,bad:u.error},f=async A=>{const S=await m(w=>a.createElement(Sn,{onClose:w,isEdit:!1,initialRating:A,initialComment:"",isCommentEnabled:r}));S&&(i==null||i(S))},E=async()=>{const A=await m(S=>a.createElement(ne,{onClose:()=>S()},a.createElement(ne.ActionItem,{onPress:()=>S("edit"),label:c.feedback.edit}),a.createElement(ne.ActionItem,{onPress:()=>S("remove"),label:c.feedback.remove,destructive:!0})));if(A==="edit"){const S=await m(w=>a.createElement(Sn,{onClose:w,isEdit:!0,initialRating:g==null?void 0:g.rating,initialComment:g==null?void 0:g.comment,isCommentEnabled:r}));S&&(i==null||i(S))}else A==="remove"&&(i==null||i(null))},C=()=>t&&_!=="none"?a.createElement(b,{flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:R.BODY_MAX_WIDTH},a.createElement(b,{padding:2,flexShrink:0,alignItems:"center"},a.createElement(B,{type:$t(_),size:12,color:v[_]})),(g==null?void 0:g.comment)&&a.createElement(I,{variant:"caption2",style:h.commentText},g.comment)):a.createElement(b,{gap:4,maxWidth:R.BODY_MAX_WIDTH},a.createElement(b,{flexDirection:"row",gap:2},["good","bad"].map(A=>{const S=_===A;return a.createElement(O,{key:A,onPress:()=>{_==="none"?f(A):E()},activeOpacity:.6,style:h.feedbackButton(S)},a.createElement(B,{type:S?$t(A):A,size:14,color:S?v[A]:u.textMidEmphasis}))})),_!=="none"&&(g==null?void 0:g.comment)&&a.createElement(I,{variant:"caption2",style:h.commentText},g.comment));return a.createElement(b,{style:l},C())},ci=D.create(({select:e,theme:t,themedColor:n})=>({feedbackButton:o=>({width:38,height:20,borderRadius:18,alignItems:"center",justifyContent:"center",borderWidth:1,borderColor:e({light:t.palette.background200,dark:t.palette.background400}),backgroundColor:o?e({light:t.palette.background100,dark:t.palette.background500}):"transparent"}),commentText:{lineHeight:16,color:e({light:n.textMidEmphasis,dark:n.textHighEmphasis})}})),ui=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},di=e=>null,eo=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:o,...r})=>a.createElement(p.ScrollView,{style:[t,r,e&&Yt],showsHorizontalScrollIndicator:n,...r},o),mi=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const o=gi.use(),[r,s]=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}),s(!0)},u=()=>i.map((m,h)=>a.createElement(O,{key:h,style:o.itemContainer,onPress:()=>c(m)},a.createElement(I,{variant:"body3",color:({themedColor:g})=>g.primary},m)));return l?a.createElement(b,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:R.HORIZONTAL_PADDING},u()):a.createElement(eo,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:o.horizontalContainer},u())},gi=D.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:R.HORIZONTAL_PADDING,paddingVertical:16}})),hi=e=>{var f,E,C,A,S,w,x;const{components:t}=ot.useContext(),{streamText:n,isAnimating:o}=ys({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),r={...e,message:n,extendedMessagePayload:o?{}:e.extendedMessagePayload},s=!!r.isTyping,i=!!r.isSenderAvatarVisible,l=!!((f=r.extendedMessagePayload)!=null&&f.form)&&!((E=r.extendedMessagePayload)!=null&&E.form.canceled_at),c=!!((C=r.extendedMessagePayload)!=null&&C.message_template),u=!!((A=r.extendedMessagePayload)!=null&&A.cta_button),m=!!((S=r.extendedMessagePayload)!=null&&S.citations)&&r.extendedMessagePayload.citations.length>0,h=!!r.createdAt,g=r.groupType==="top"||r.groupType==="single",_=r.groupType==="bottom"||r.groupType==="single",y=i?R.AVATAR_SIZE:0,v=fi.use();return a.createElement(b,{marginBottom:s?0:Vt(r.groupType)},g&&a.createElement(b,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:R.HORIZONTAL_PADDING},i&&a.createElement(t.SenderAvatar,{...r}),a.createElement(t.SenderName,{...r})),a.createElement(b,{gap:R.GAP_GROUPED},s?a.createElement(t.TypingIndicator,{...r,containerStyle:v.middleArea(y)}):a.createElement(t.MessageBody,{...r,containerStyle:v.middleArea(y)},u&&a.createElement(b,{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:((x=(w=r.extendedMessagePayload)==null?void 0:w.message_template)==null?void 0:x.fallback_message)??"Cannot read this template.",containerStyle:v.middleArea(y)}),messageTemplateLoadingFallback:r.messageTemplateLoadingFallback??a.createElement(t.TypingIndicator,{...r,containerStyle:v.middleArea(y)})}),a.createElement(t.CustomMessageTemplate,{...r}),l&&a.createElement(t.Form,{...r,containerStyle:v.middleArea(y)})),_&&h&&a.createElement(t.SentTime,{...r,containerStyle:v.bottomArea(y)}),a.createElement(d.Fragment,null,!s&&a.createElement(t.Feedback,{...r,containerStyle:v.feedbackArea(y)}),r.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...r})))},ot=ae({template:hi,components:{SenderName:Za,SenderAvatar:Ya,SentTime:Ja,MessageBody:Wa,TypingIndicator:Qa,SuggestedReplies:mi,MessageTemplate:di,CustomMessageTemplate:si,CTAButton:ni,Citation:ri,Form:ui,Feedback:li}}),fi=D.create(()=>({middleArea:e=>({paddingStart:R.HORIZONTAL_PADDING+e,paddingEnd:R.HORIZONTAL_PADDING}),bottomArea:e=>({marginTop:R.BODY_TIME_GAP,paddingStart:R.HORIZONTAL_PADDING+e+8,paddingEnd:R.HORIZONTAL_PADDING}),feedbackArea:e=>({marginTop:8,paddingStart:R.HORIZONTAL_PADDING+e+8,paddingEnd:R.HORIZONTAL_PADDING})})),pi=({file:e,children:t,sendingStatus:n,onClickFile:o=({url:r})=>p.Linking.openURL(r)})=>{const r=(()=>{if(!(!o||n!=="succeeded"))return()=>o(e)})();return a.createElement(b,{flexDirection:"column",alignItems:"flex-end",gap:R.GAP_GROUPED,width:R.BODY_MAX_WIDTH,maxWidth:R.BODY_MAX_WIDTH},a.createElement(Qt,{name:e.name,type:Gt(e.name,e.type),onPress:r}),t)},to=({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 o=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(b.Animated,{style:{transform:[{rotate:o}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??a.createElement(B,{type:"spinner",size:e}))};function _i(e){return typeof e=="object"&&e!==null&&"uri"in e}const yi=({file:e,metadata:t,sendingStatus:n,onClickMedia:o=({url:s})=>p.Linking.openURL(s),children:r})=>{const s=bi.use(),{aspectRatio:i,localFile:l}=t,[c]=d.useState(()=>_i(l)?l.uri:e.url),[u,m]=d.useState(!1),h=(()=>{if(!(!o||n!=="succeeded"))return()=>o(e)})();return a.createElement(b,{flexDirection:"column",alignItems:"flex-end",gap:R.GAP_GROUPED},a.createElement(O,{onPress:h,style:[s.imageContainer,{aspectRatio:i}],activeOpacity:.75},!u&&a.createElement(b,{alignItems:"center",justifyContent:"center"},a.createElement(to,{size:26},a.createElement(B,{type:"spinner",color:({themedColor:g})=>g.textLowEmphasis,size:26}))),a.createElement(xe,{source:{uri:c},style:[s.image,{opacity:u?1:0}],resizeMode:"cover",onLoad:()=>m(!0)})),r)},bi=D.create(({themedColor:e})=>({imageContainer:{width:R.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}})),An=e=>{var n,o;const t=Ei.use();return a.createElement(b,{style:[t.container({maxWidth:e.maxBodyWidth??R.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},a.createElement(I,{variant:"body3",style:[t.text,((o=e.customStyle)==null?void 0:o.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},Ei=D.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}})),Ci=e=>{const{strings:t}=F(),n=()=>{const o=Rn(e)?a.createElement(An,{...e}):null;return e.messageType==="user"?o:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(yi,{...e},o):a.createElement(pi,{...e},o):a.createElement(An,{...e,message:t.unknown_message_type})};return a.createElement(O,{onPress:e.sendingStatus==="failed"?e.onClickFailedMessage:void 0,activeOpacity:.75},a.createElement(b,{style:e.containerStyle},n()))},vi=({sendingStatus:e,containerStyle:t})=>{const{themedColor:n}=$(),o=()=>{switch(e){case"pending":return a.createElement(b,{marginBottom:2},a.createElement(to,{size:16},a.createElement(B,{type:"spinner",color:n.primary,size:16})));case"failed":return a.createElement(b,{marginBottom:2},a.createElement(B,{type:"error",color:n.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement(b,{marginBottom:2},a.createElement(B,{type:"done",color:n.secondary,size:16}))}};return a.createElement(b,{style:t},o())},Si=({createdAt:e,containerStyle:t})=>{const{format:n,strings:o}=F();return e?a.createElement(b,{style:t},a.createElement(I,{variant:"caption4",color:({themedColor:r})=>r.textLowEmphasis},n(e,o.date_format.message_timestamp))):null},Ai=e=>{const{components:t}=rt.useContext(),n=e.sendingStatus==="succeeded",o=e.groupType==="bottom"||e.groupType==="single";return a.createElement(b,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:Vt(e.groupType)},a.createElement(t.MessageBody,{...e,containerStyle:vt.middleArea}),o&&(n?a.createElement(t.SentTime,{...e,containerStyle:vt.bottomArea}):a.createElement(t.SendingStatus,{...e,containerStyle:vt.bottomArea})))},rt=ae({template:Ai,components:{SendingStatus:vi,SentTime:Si,MessageBody:Ci}}),vt=p.StyleSheet.create({middleArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:R.HORIZONTAL_PADDING},bottomArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingStart:R.HORIZONTAL_PADDING,paddingEnd:R.HORIZONTAL_PADDING+8,marginTop:R.BODY_TIME_GAP}}),Ti=e=>e.messageType!=="admin"?null:a.createElement(I,{variant:"caption2",color:({themedColor:t})=>t.textMidEmphasis,style:{textAlign:"center"}},wi(e.message)),wi=e=>{try{const t=[];let n=e,o=0;for(;n;){const r=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),s=n.match(/\*\*([^*]+)\*\*/),i=[r&&{match:r,type:"link"},s&&{match:s,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:o++,onPress:()=>p.Linking.openURL((c==null?void 0:c[2])??""),style:{textDecorationLine:"underline"}},c[1])):u==="bold"&&t.push(a.createElement(p.Text,{key:o++,style:{fontWeight:"bold"}},c[1])),n=n.slice(m+c[0].length)}return t.filter(r=>r!=="")}catch{return[e]}},xi=({children:e,style:t})=>a.createElement(I,{variant:"caption4",color:({themedColor:n})=>n.error,style:t},e),Ii=({children:e,style:t,required:n})=>{const{strings:o}=F();return a.createElement(I,{variant:"caption3",color:({themedColor:r})=>r.textMidEmphasis,style:t},e,!n&&a.createElement(I,{variant:"caption3",color:({themedColor:r})=>r.textLowEmphasis},` (${o.form.optional_label})`))},ki=({style:e})=>{const t=Mi.use();return a.createElement(b,{style:[t.separator,e]})},Mi=D.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),Ri=({value:e="",onChange:t,placeholder:n,variant:o="single-line",error:r=!1,submitted:s=!1,style:i,disabled:l=!1,maxLength:c})=>{const[u,m]=d.useState(!1),h=Li.use(),{themedColor:g}=$(),_=y=>{c&&y.length>c||t==null||t(y)};return a.createElement(p.TextInput,{value:e,onChangeText:_,placeholder:n,editable:!l&&!s,maxLength:c,multiline:o==="multi-line",style:[h.input(o,r,s,u),i],placeholderTextColor:g.textLowEmphasis,onFocus:()=>m(!0),onBlur:()=>m(!1)})},Li=D.create(({select:e,theme:t,themedColor:n})=>({input:(o,r,s,i)=>{let l,c;s?(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:s?n.textLowEmphasis:n.textHighEmphasis};return o==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),Oe={Label:Ii,ErrorLabel:xi,TextInput:Ri,Separator:ki},no=({onClick:e,checked:t,label:n,disabled:o,labelVariant:r="caption2"})=>{const{themedColor:s}=$(),i=Di.use(),l=t?s.primary:o?s.textDisabled:s.textLowEmphasis;return a.createElement(O,{disabled:o||!e,onPress:e},a.createElement(b,{style:i.container},a.createElement(b,{style:i.iconContainer},a.createElement(B,{size:20,type:t?"radio-on":"radio-off",color:l})),a.createElement(I,{variant:r,style:i.label(t,o)},n)))},Di=D.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 o;return t?o=e.textHighEmphasis:n?o=e.textLowEmphasis:o=e.textHighEmphasis,{flex:1,color:o,lineHeight:20}}})),Pi=({csatPayload:e,submitted:t,defaultValue:n,value:o,onChange:r})=>(d.useEffect(()=>{typeof o>"u"&&typeof n=="boolean"&&(r==null||r(n))},[o,n,r]),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(s=>a.createElement(no,{key:s.label,checked:o===s.value,label:s.label,disabled:t,onClick:()=>r==null?void 0:r(s.value)})))):null),Oi=({followUpItem:e,submitted:t,value:n="",onChange:o,hasError:r})=>{const{strings:s}=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=>o(i),error:r}),e.response_type==="single_choice"&&a.createElement(b,{flexDirection:"column",gap:8,width:"100%"},e.options.map(i=>a.createElement(no,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>o==null?void 0:o(i),labelVariant:"body3"}))),r&&a.createElement(Oe.ErrorLabel,null,s.form.validation_required))},Ni=e=>null,Bi=({csatPayload:e,submitted:t,value:n,onChange:o})=>{const r=typeof n>"u",s=oo.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(I,{variant:"caption3",color:({themedColor:c})=>c.textMidEmphasis},e.csat_question),a.createElement(b,{style:[s.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:()=>o(h),style:s.scoreButton},a.createElement(Hi,{value:h,selected:r||g,label:c,src:u}),!!c&&a.createElement(I,{style:{textAlign:"center"},variant:"caption3",color:({themedColor:_})=>g?_.textHighEmphasis:_.textLowEmphasis,lineBreakStrategyIOS:"standard",textBreakStrategy:"simple"},c))})))},Hi=({value:e,src:t,label:n,selected:o})=>{const[r,s]=d.useState(!1),i=oo.use();return r?a.createElement(Ni,{value:e,selected:o,label:n}):a.createElement(xe,{source:{uri:t},style:i.emojiImage(o),onError:()=>s(!0),accessibilityLabel:n})},oo=D.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})})),zi=({csatPayload:e})=>a.createElement(I,{style:{textAlign:"left"},variant:"button",color:({themedColor:t})=>t.textHighEmphasis},e.title),St=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:o,initialCsatReason:r,initialIsResolved:s})=>{const{params:i,setParams:l,error:c,setError:u,followUpItem:m,state:h,validateParams:g,itemProps:_}=hs({csatPayload:e,type:t,initialCsat:o,initialCsatReason:r,initialIsResolved:s});return a.createElement(a.Fragment,null,a.createElement(b,{flexDirection:"column",gap:12},a.createElement(zi,{..._}),t===ge.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(Pi,{..._,defaultValue:s,value:i.isResolved,onChange:y=>l({isResolved:y})}),a.createElement(Bi,{..._,value:i.csat,onChange:y=>l({csat:y})}),m&&a.createElement(Oi,{..._,followUpItem:m,value:i.csatReason,onChange:y=>{l({csatReason:y}),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})))},Ui=e=>{const{strings:t}=F();return er(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})},Fi=()=>{const{strings:e}=F();return a.createElement(I,{variant:"body2",color:({themedColor:t})=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},$i=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n}=e,{csat:o,csatReason:r,csatExpireAt:s,isResolvedWhenDeterminedByUser:i}=e,[,l]=d.useState(0),c=Ui(t==null?void 0:t.csat),u=d.useRef(!1),m=ji.use();if(!c||!c.visibility||!ge[c.type])return null;const h=c.type===ge.AI_AGENT_CSAT_5||c.type===ge.AI_AGENT_CSAT_5_WITH_CRE||c.type===ge.HELPDESK_CSAT_5?St:()=>null;return a.createElement(b,{style:m.container},!o&&cn(s)?a.createElement(Fi,null):a.createElement(h,{csatPayload:c,type:c.type,initialCsat:o,initialCsatReason:r,initialIsResolved:i,renderSubmitButton:({state:g,params:_,validateParams:y})=>a.createElement(O,{activeOpacity:.75,disabled:g==="submitted",onPress:async()=>{u.current||(!cn(s)&&y()?(u.current=!0,await n(_).finally(()=>{u.current=!1})):l(v=>v+1))},style:m.submitButton(g)},a.createElement(I,{variant:"button",style:m.submitButtonText(g)},g==="submitted"?c.csat_submitted_label:c.csat_submit_label))}))},ji=D.create(({theme:e,themedColor:t})=>({container:{flexDirection:"column",backgroundColor:e.colors.csat.background,borderRadius:16,gap:16,padding:16},submitButton:n=>{let o;return n==="submitted"||n==="unsubmittable"?o=t.textDisabled:o=e.colors.base.primary,{backgroundColor:o,borderRadius:6,padding:10,paddingHorizontal:20,alignItems:"center",justifyContent:"center"}},submitButtonText:n=>{let o;return n==="submitted"?o=t.textHighEmphasis:n==="unsubmittable"?o=t.textLowEmphasis:o=e.colors.base.primaryContrastContent,{color:o}}})),Gi=e=>{const{components:t}=st.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:R.HORIZONTAL_PADDING,marginBottom:Vt(e.groupType)},n)},st=ae({template:Gi,components:{AdminMessage:Ti,CSATMessage:$i}}),Vi=({style:e,...t})=>{const{strings:n}=F();if(!Kt("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(b,{style:[qi.container,e],...t},a.createElement(I,{variant:"caption2",color:({themedColor:s})=>s.textLowEmphasis},n.conversation.powered_by+" "),a.createElement(O,{onPress:r},a.createElement(I,{variant:"caption2",color:({themedColor:s})=>s.textLowEmphasis},"Sendbird")))},qi=p.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),Wi=()=>{var l;const{strings:e}=F(),{channelSource:t,scrollSource:n,updateActiveChannel:o}=ue(),r=Ki.use(),s=le(t.channel),i=d.useRef(s);return d.useEffect(()=>{const c=i.current;i.current=s,!c&&s&&n.actions.scrollToBottom()},[s,n]),!((l=t.channel)!=null&&l.isAIAgent)||!s?null:a.createElement(b,{justifyContent:"center",flexDirection:"row",style:r.wrapper},a.createElement(O,{activeOpacity:.75,onPress:()=>o(),style:r.button},a.createElement(I,{variant:"button",role:"button",color:({themedColor:c})=>c.textHighEmphasis},e.conversation.start_new_conversation_label)))},Ki=D.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),Yi=({date:e=Date.now(),style:t,...n})=>{const{format:o,strings:r}=F();return a.createElement(b,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},a.createElement(I,{variant:"caption4",color:({themedColor:s})=>s.textMidEmphasis},o(e,r.date_format.date_separator)))},Xi=({style:e,onPress:t})=>{const n=Zi.use(),{theme:o}=$();return a.createElement(O,{style:[n.button,e],onPress:t},a.createElement(b,{alignItems:"center",justifyContent:"center"},a.createElement(B,{size:24,type:"chevron-down",color:o.colors.base.primary})))},Zi=D.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}]}})),Ji=()=>null,tn=ae({template:Ji,components:{DateSeparator:Yi,ScrollToBottomButton:Xi}}),Qi=(e,t)=>!_o.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),el=({messageStackDirection:e="top"})=>{var P,j;const{Template:t}=ot.useContext(),{Template:n}=rt.useContext(),{Template:o}=st.useContext(),{components:r}=tn.useContext(),{openModal:s}=et(),{strings:i}=F(),{config:l,cache:c,chatSDK:u}=Y(),{aiAgentInfo:m,userSession:h,connectionError:g}=oe(),{conversation:_,messageSource:y,channelSource:v,scrollSource:f,state:{input:E,streamAnimation:C}}=ue(),A=tl.use(),S=Ie(["left","right"]),w=ms(v.channel);d.useEffect(()=>{f.state.isAwayFromBottom||y.resetNewMessages()},[f.state.isAwayFromBottom]);const x=(T,z=!1)=>{var G;return z?m??{nickname:"",profileUrl:""}:((G=v.channel)==null?void 0:G.members.find(Q=>Q.userId===T.sender.userId))??T.sender},M=T=>{if(T.sendingStatus==="failed"&&!E.disabled)return()=>{s(z=>a.createElement(ne,{onClose:()=>z()},a.createElement(ne.ActionItem,{label:i.conversation.failed_message_resend,onPress:async()=>{y.resendMessage(T),z()}}),a.createElement(ne.ActionItem,{destructive:!0,label:i.conversation.failed_message_remove,onPress:async()=>{y.deleteMessage(T),z()}})))}},Z=({item:T,index:z})=>{const G=y.messages[z+1],Q=y.messages[z-1],fe=(()=>{var k,N,H;const pe=!(m!=null&&m.isUserFeedbackEnabled&&Be(T,m==null?void 0:m.userId)&&!Ke.isWelcomeMessage(T)),Re=Bo(T,G,Q,pe),re={data:T.data,extendedMessagePayload:T.extendedMessagePayload,message:T.message,createdAt:T.createdAt,groupType:Re};if(ze.isAdmin(T))return ze.isCSAT(T)?_?a.createElement(o,{...re,..._,messageType:"admin.csat",isResolvedWhenDeterminedByUser:Jo(_),onSubmitCSAT:async J=>{var ee;await((ee=v.channel)==null?void 0:ee.submitCSAT(J))}}):null:a.createElement(o,{...re,messageType:"admin"});if(ze.isOutgoing(T,(h==null?void 0:h.userId)??"")){const J={...re,sender:x(T),sendingStatus:T.sendingStatus,onClickFailedMessage:M(T)};if(T.isUserMessage())return a.createElement(n,{...J,messageType:"user"});if(T.isFileMessage()){const[ee,de]=((k=T.metaArrays.find(W=>W.key===kn))==null?void 0:k.value)??[];return a.createElement(n,{...J,messageType:"file",file:T,metadata:{aspectRatio:ee&&de?`${ee}/${de}`:"1/1",localFile:(N=T.messageParams)==null?void 0:N.file}})}}if(ze.isIncoming(T,(h==null?void 0:h.userId)??"")){const J=T.sender.userId===(m==null?void 0:m.userId),ee=z===0,de={...re,sender:x(T,J),suggestedRepliesVisible:ee,isBotMessage:J,isStreaming:Ke.isStreaming(T),isHandedOff:we(v.channel),isConversationClosed:le(v.channel),isFeedbackEnabled:m==null?void 0:m.isUserFeedbackEnabled,isFeedbackCommentEnabled:m==null?void 0:m.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(H=l==null?void 0:l.conversation)==null?void 0:H.senderAvatarEnabled,onClickSuggestedReply:async({reply:W})=>{y.sendUserMessage({message:W})},onRequestMessageTemplate:async W=>{const{template:me}=await u.aiAgent.getMessageTemplate(W);return c.template.set(W,me),me},onGetCachedMessageTemplate:W=>c.template.get(W),onHandleTemplateInternalAction:W=>{if(W.type==="internal"&&W.internalData){const{method:me,payload:ye}=W.internalData;me==="message.send"&&(ye!=null&&ye.message)&&y.sendUserMessage({message:ye.message})}},onFeedbackUpdate:W=>{const me={messageId:T.messageId,channelUrl:T.channelUrl};if(!W)return u.aiAgent.deleteMessageFeedback(me);const ye={...me,rating:ai(W.rating),comment:W.comment};return Ke.hasFeedback(T)?u.aiAgent.updateMessageFeedback(ye):u.aiAgent.createMessageFeedback(ye)},onSubmitForm:({key:W,data:me})=>u.aiAgent.submitForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:W,formData:me}),onCancelForm:({key:W})=>u.aiAgent.cancelForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:W}),onStreamAnimationStart:()=>{C.start(T.messageId)},onStreamAnimationProgress:()=>{f.actions.onStreamingUpdate()},onStreamAnimationComplete:()=>{C.stop(T.messageId),f.actions.onStreamingUpdate()}};if(T.isUserMessage())return a.createElement(t,{...de,messageType:"user"});if(T.isFileMessage())return a.createElement(t,{...de,messageType:"file",file:T})}return null})(),Me=Qi(T,G)&&a.createElement(r.DateSeparator,{date:T.createdAt,style:A.dateSeparator});return a.createElement(b,null,Me,fe)},q=()=>a.createElement(Vi,{style:A.poweredBy}),U=()=>{var T,z;return a.createElement(a.Fragment,null,w&&a.createElement(b,{marginTop:y.messages.length===0?8:0},a.createElement(t,{isTyping:!0,isBotMessage:w.isBot,sender:w.user,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(T=l==null?void 0:l.conversation)==null?void 0:T.senderAvatarEnabled})),((z=l==null?void 0:l.conversation)==null?void 0:z.isTalkToAgentViewEnabled)&&a.createElement(Wi,null),f.state.bottomSpace?a.createElement(b,{height:f.state.bottomSpace}):null)};return a.createElement(b,{flex:1},a.createElement(Xn,{ref:f.ref,style:A.list,contentContainerStyle:[A.listContent,S],stackDirection:e,data:y.messages,onEndReached:y.loadPrevious,keyExtractor:No,renderItem:Z,loading:!y.initialized||!v.channel,empty:y.messages.length===0&&!w,error:!!(g||v.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)??((P=v.error)==null?void 0:P.message),action:v.error?{label:i.common.placeholder_something_went_wrong_retry_label,onPress:()=>v.refetch()}:void 0}),ListFooterComponent:q(),ListHeaderComponent:U(),inverted:!0,...f.props}),((j=l==null?void 0:l.conversation)==null?void 0:j.newMessageIndicatorEnabled)&&f.state.isAwayFromBottom&&y.newMessages.length>0&&a.createElement(b,{style:A.newMessagesButtonContainer},a.createElement(Ia,{label:i.conversation.scroll_to_new_messages_label(y.newMessages),accessibilityLabel:i.conversation.a11y_scroll_to_new_messages,onPress:()=>f.actions.scrollToBottom()})),f.state.isAwayFromBottom&&y.newMessages.length===0&&a.createElement(r.ScrollToBottomButton,{style:A.scrollButtonContainer,onPress:()=>f.actions.scrollToBottom()}))},tl=D.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"}})),he={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 nl(e){return{captureCamera:async()=>{if(e.requestCameraPermissionsAsync&&!(await e.requestCameraPermissionsAsync()).granted)throw new Error(he.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(Tn)},selectFromGallery:async t=>{if(e.requestMediaLibraryPermissionsAsync&&!(await e.requestMediaLibraryPermissionsAsync()).granted)throw new Error(he.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(Tn)}}}function ol(e,t){const n=async()=>{const r=p.Platform.select({ios:t.PERMISSIONS.IOS.CAMERA,android:t.PERMISSIONS.ANDROID.CAMERA});if(!r)return;const s=await t.request(r);if(s!=="granted"&&s!=="limited")throw new Error(he.CAMERA_PERMISSION_DENIED)},o=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 s=await t.requestMultiple(r);if(!Object.values(s).every(l=>l==="granted"||l==="limited"))throw new Error(he.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(he.CAMERA_PERMISSION_DENIED):new Error(r.errorMessage||`Camera error: ${r.errorCode}`);return!r.assets||r.assets.length===0?null:r.assets.map(wn)},selectFromGallery:async r=>{await o();const s=await e.launchImageLibrary({mediaType:"photo",selectionLimit:(r==null?void 0:r.selectionLimit)??1,assetRepresentationMode:"compatible"});if(s.didCancel)return null;if(s.errorCode)throw s.errorCode==="permission"?new Error(he.GALLERY_PERMISSION_DENIED):new Error(s.errorMessage||`Gallery error: ${s.errorCode}`);return!s.assets||s.assets.length===0?null:s.assets.map(wn)}}}function rl(e){return{selectFile:async t=>{const n=(t==null?void 0:t.mimeTypes)??["*/*"],o=await e.getDocumentAsync({multiple:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:n});return o.canceled||!o.assets||o.assets.length===0?null:o.assets.map(al)}}}function sl(e){return{selectFile:async t=>{try{const n=(t==null?void 0:t.mimeTypes)??["*/*"],o=p.Platform.select({android:n,ios:void 0}),r=await e.pick({mode:"open",allowMultiSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:o});return(Array.isArray(r)?r:[r]).map(il)}catch(n){if(n&&typeof n=="object"&&"message"in n){const o=String(n.message).toLowerCase();if(o.includes("cancel")||o.includes("user cancelled"))return null;throw new Error(String(n.message))}throw new Error("File selection failed")}}}}function Tn(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 al(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function wn(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 il(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function ll(){return{captureCamera:async()=>{throw new Error(he.IMAGE_PICKER_NOT_CONFIGURED)},selectFromGallery:async()=>{throw new Error(he.IMAGE_PICKER_NOT_CONFIGURED)}}}function cl(){return{selectFile:async()=>{throw new Error(he.DOCUMENT_PICKER_NOT_CONFIGURED)}}}const{Provider:ul,useContext:ro}=X("NativeAdapter"),so=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:o,documentPicker:r,mmkv:s}=e,i=o?(dl(e),"launchCameraAsync"in o?nl(o):ol(o,e.permissions)):ll(),l=r?"getDocumentAsync"in r?rl(r):sl(r):cl();return{...i,...l,keyValueStorage:lr(s)}},[e.imagePicker,e.documentPicker,e.mmkv,e.permissions]);return a.createElement(ul,{value:n},t)};function dl(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 ml=({onPressAddAttachment:e,disabled:t})=>a.createElement(O,{disabled:t,style:gl.container,activeOpacity:.75,onPress:e},a.createElement(B,{type:"add",size:24,color:({themedColor:n})=>t?n.textDisabled:n.primary})),gl=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),hl=({name:e,type:t,url:n,onRemove:o})=>{const r=fl.use();return a.createElement(b,{style:r.wrapper},Ho(t)?a.createElement(xe,{source:{uri:n},style:r.image,resizeMode:"cover"}):a.createElement(Qt,{name:e,type:Gt(e,t)}),o&&a.createElement(O,{onPress:o,style:r.removeButton},a.createElement(B,{type:"remove",size:20,color:r.removeIcon.tintColor})))},Ve=7,fl=D.create(({themedColor:e})=>({wrapper:{marginTop:Ve,marginRight:Ve,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-Ve,right:-Ve,width:22,height:22,borderRadius:11,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),pl=e=>{const{theme:t,themedColor:n}=$(),o=_l.use(),r=Zt.useTextAlign({text:e.value??e.placeholder,style:o.input,isTextInput:!0});return a.createElement(b,{style:o.container},e.attachments&&a.createElement(eo,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),a.createElement(b,null,a.createElement(p.TextInput,{multiline:!0,style:[o.input,{textAlign:r}],placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},_l=D.create(({theme:e})=>({container:{backgroundColor:e.colors.messageInput.background,gap:16,flex:1,paddingHorizontal:16,paddingVertical:8,justifyContent:"center",borderRadius:20,minHeight:36},input:{...yl(e.typography.body3),color:e.colors.messageInput.text,includeFontPadding:!1,padding:0,margin:0,textAlignVertical:"center"}}));function yl(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 bl=({onPressSend:e})=>a.createElement(O,{style:El.container,activeOpacity:.75,onPress:e},a.createElement(B,{type:"send",size:24})),El=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Cl=()=>{const e=vl.use(),{aiAgentInfo:t,userSession:n}=oe(),{messageSource:o,channelSource:r}=ue(),[s,i]=d.useState(null),l=Kt("special-notice",r.channel),c=d.useCallback(()=>r.channel?l?o.messages.some(u=>Be(u,(n==null?void 0:n.userId)??"")):!0:null,[r.channel,l,o.messages,n==null?void 0:n.userId]);return d.useEffect(()=>{s||i(c())},[c,s]),s||!(t!=null&&t.specialNotice)?null:a.createElement(b,{style:e.container},a.createElement(en,{textStyle:e.text,linkStyle:e.link},(t==null?void 0:t.specialNotice)??""))},vl=D.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})}})),Sl=()=>{var v;const{chatSDK:e}=Y(),{strings:t}=F(),{createAttachmentRules:n}=oe(),{channelSource:o,state:r}=ue(),[s,i]=d.useState(""),[l,c]=d.useState([]),u=n({channel:o.channel,uploadSizeLimit:(v=e.appInfo)==null?void 0:v.uploadSizeLimit}),m=(f,E)=>{const C=E.filter(x=>u.isSupportedMimeType(x.type));if(C.length===0&&E.length>0)return p.Alert.alert("",t.conversation.file_upload_not_supported_file),f;const A=x=>{const M=u.getUploadSizeLimit(x.type);return x.size&&x.size>M},S=C.find(x=>A(x));if(S){const x=u.getUploadSizeLimitInMB(S.type);return p.Alert.alert("",t.conversation.file_upload_notification_size_limit(x)),f}return f.length+C.length>u.maxAttachmentCount?(p.Alert.alert("",t.conversation.file_upload_notification_count_limit(u.maxAttachmentCount)),f):[...f,...C]},h=f=>{c(E=>m(E,f))},g=f=>{c(E=>E.filter((C,A)=>A!==f))},_=()=>{c([])},y=(()=>{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(""),_())},[r.input.disabled]),{files:l,addFiles:h,removeFile:g,clearFiles:_,value:s,onChangeText:i,editable:!r.input.disabled,placeholder:y,sendButtonVisible:!r.input.disabled&&(!!s.trim()||l.length>0),addAttachmentButtonVisible:u.isEnabled(),addAttachmentButtonDisabled:r.input.disabled||l.length>=u.maxAttachmentCount,hasImageMimeTypes:()=>u.supportedMimeTypes.filter(E=>E.startsWith("image/")||E===Mn).length>0,hasFileMimeTypes:()=>u.supportedMimeTypes.length>0,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount}},Al=()=>{const{config:e}=Y(),t=ro(),{strings:n}=F(),{messageSource:o}=ue(),{openModal:r}=et(),s=Ie(["left","right","bottom"]),i=Tl.use(),{maxAttachmentCount:l,sendButtonVisible:c,addAttachmentButtonVisible:u,addAttachmentButtonDisabled:m,acceptableMimeTypes:h,hasImageMimeTypes:g,hasFileMimeTypes:_,...y}=Sl(),E={...y,onPressAddAttachment:async()=>{const C=await r(A=>{var S,w,x,M,Z,q,U,P;return a.createElement(ne,{onClose:()=>A()},((x=(w=(S=e==null?void 0:e.conversation)==null?void 0:S.input)==null?void 0:w.camera)==null?void 0:x.photoEnabled)&&a.createElement(ne.ActionItem,{icon:"camera",label:n.conversation.attachment_camera,onPress:async()=>{if(!g())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),A(null);const j=await t.captureCamera();A(j)}}),((q=(Z=(M=e==null?void 0:e.conversation)==null?void 0:M.input)==null?void 0:Z.gallery)==null?void 0:q.photoEnabled)&&a.createElement(ne.ActionItem,{icon:"photo",label:n.conversation.attachment_photo,onPress:async()=>{if(!g())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),A(null);const j=await t.selectFromGallery({selectionLimit:l-y.files.length});A(j)}}),((P=(U=e==null?void 0:e.conversation)==null?void 0:U.input)==null?void 0:P.fileEnabled)&&a.createElement(ne.ActionItem,{icon:"document",label:n.conversation.attachment_document,onPress:async()=>{if(!_())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),A(null);const j=await t.selectFile({selectionLimit:l-y.files.length,mimeTypes:h});A(j)}}))});C&&y.addFiles(C)},onPressSend:()=>{y.files.length>0?o.sendFileMessage({message:y.value.trim(),file:y.files[0]}):o.sendUserMessage({message:y.value}),y.clearFiles(),y.onChangeText("")}};return a.createElement(p.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-s.paddingBottom},a.createElement(Cl,null),a.createElement(b,{style:i.container(s)},u&&a.createElement(ml,{...E,disabled:m}),a.createElement(pl,{...E,value:E.editable?E.value:"",attachments:E.files.length===0?null:E.files.map((C,A)=>a.createElement(hl,{key:A,name:C.name,type:C.type,url:C.uri,onRemove:()=>E.removeFile(A)}))}),c&&a.createElement(bl,{...E})))},Tl=D.create(({theme:e})=>({container:({paddingStart:t,paddingEnd:n,paddingBottom:o})=>({alignItems:"center",flexDirection:"row",gap:8,paddingTop:10,paddingBottom:10+o,paddingStart:12+t,paddingEnd:12+n,backgroundColor:e.colors.base.background})})),ao=({start:e,title:t,titleAlign:n="start",end:o})=>{const r=Ie(["left","right","top"]),[s,i]=d.useState(0),[l,c]=d.useState(0),u=g=>{i(g.nativeEvent.layout.width)},m=g=>{c(g.nativeEvent.layout.width)},h=wl.use();return a.createElement(b,{style:h.container},a.createElement(b,{height:r.paddingTop}),a.createElement(b,{style:h.contentContainer(r)},n==="center"&&t&&a.createElement(b,{style:h.centerTitleContainer(Math.max(s,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,o)},t),a.createElement(b,{style:h.endSide,onLayout:m},o))))},wl=D.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,o,r)=>({flex:1,overflow:"hidden",alignItems:`flex-${n}`,marginStart:o?8:0,marginEnd:r?8:0})})),xl=()=>{const{themedColor:e}=$(),{onClose:t}=ue();return t?a.createElement(O,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(B,{color:e.textHighEmphasis,type:"close",size:24})):null},Il=()=>{const{themedColor:e}=$(),{channelSource:{channel:t}}=ue(),n=Kt("handoff-button",t),o=!On(t)||we(t);return n?a.createElement(O,{hitSlop:4,disabled:o,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},a.createElement(B,{color:o?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},kl=()=>{const{strings:e}=F(),{themedColor:t}=$(),{onNavigateToConversationList:n}=ue();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},io=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:o}=oe(),{fallbackIcon:r,url:s}=Un({channel:e,aiAgentInfo:o,userSession:n}),{theme:i}=$();return s?a.createElement(Qn,{src:s,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(B,{type:r,size:t*.55,color:i.colors.base.primaryContrastContent}))},Ml=()=>{var i,l;const{channelSource:{channel:e}}=ue(),{userSession:t,aiAgentInfo:n}=oe(),{config:o}=Y(),r=Un({channel:e,userSession:t,aiAgentInfo:n}),s=(l=(i=o==null?void 0:o.conversation)==null?void 0:i.header)==null?void 0:l.avatarEnabled;return a.createElement(b,{gap:6,flexDirection:"row",alignItems:"center",maxWidth:"100%"},s&&a.createElement(io,{channel:e,size:34}),a.createElement(b,{flexShrink:1},a.createElement(I,{numberOfLines:1,variant:"h1"},r.title)))},Rl=e=>{const{components:t}=Ce.useContext();return a.createElement(ao,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},Ll=()=>{const{components:e}=Ce.useContext();return a.createElement(e.MenuButton,null)},Dl=()=>{const{components:e}=Ce.useContext();return a.createElement(e.Title,null)},Pl=()=>{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=ae({template:Rl,components:{StartArea:Ll,TitleArea:Dl,EndArea:Pl,MenuButton:kl,Title:Ml,HandoffButton:Il,CloseButton:xl}}),Ol=()=>{const{Template:e}=Ce.useContext();return a.createElement(e,{titleAlign:"start"})},Nl=e=>{const{components:t}=at.useContext();return a.createElement(b,{flex:1},a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},at=ae({template:Nl,components:{Header:Ol,Body:el,Footer:Al}}),lo=({children:e,...t})=>{const{Template:n}=at.useContext();return a.createElement(jn,{...t},a.createElement(n,null),e)},{Provider:Bl,Context:Hl,useContext:it}=X("ConversationList"),co=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:o,children:r})=>{const{sdkUser:s,authenticate:i}=oe();return d.useEffect(()=>{s||i()},[]),a.createElement(is,{conversationListLimit:e,conversationListFilter:t},l=>a.createElement(Bl,{value:{...l,onClose:o,onNavigateToConversation:n}},r))},At=99,zl=d.memo(function(t){const{channel:n,onClick:o}=t,{strings:r,format:s}=F(),{themedColor:i}=$(),l=Fl.use(),c=ur(n),u=dr(n,s,{justNow:r.date_format.just_now,minutesAgo:r.date_format.minutes_ago,hoursAgo:r.date_format.hours_ago,dateShortFormat:r.date_format.date_short}),m=n.unreadMessageCount;return a.createElement(O,{onPress:o,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(io,{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(I,{variant:"subtitle1",color:i.textHighEmphasis,numberOfLines:1},c),a.createElement(b,{flexDirection:"row",alignItems:"center",gap:6},le(n)&&a.createElement(a.Fragment,null,a.createElement(I,{variant:"caption1",color:i.textMidEmphasis,numberOfLines:1},r.conversation_list.ended),a.createElement(b,{width:2,height:2,borderRadius:1,backgroundColor:i.textLowEmphasis})),a.createElement(I,{variant:"caption2",color:i.textLowEmphasis,numberOfLines:1},u))),m>0&&a.createElement(b,{alignItems:"center",justifyContent:"center",height:20,width:m<=At?20:void 0,padding:4,borderRadius:10,backgroundColor:i.error},a.createElement(I,{variant:"caption3",color:i.textHighEmphasisInverse,style:{lineHeight:12}},m<=At?m:`${At}+`)))))}),Ul=ae({template:zl,components:{}}),Fl=D.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),$l=()=>{var l;const{Template:e}=Ul.useContext(),{strings:t}=F(),{connectionError:n}=oe(),{listSource:o,onNavigateToConversation:r}=it(),s=Ie(["left","right"]),i=jl.use();return a.createElement(Xn,{style:i.list,contentContainerStyle:[i.listContent,s],data:o.channels,onEndReached:o.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,le(c)?"closed":"open")}),[e,r]),loading:!o.initialized,error:!!(n||o.error),empty:o.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=o.error)==null?void 0:l.message)})})},jl=D.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),Gl=()=>{const{strings:e}=F(),{language:t,countryCode:n,context:o}=Y(),{aiAgentInfo:r,refreshActiveChannel:s,createConversation:i,setActiveChannel:l,sdkUser:c}=oe(),{onNavigateToConversation:u}=it(),m=Ie(["left","right","bottom"]),h=Vl.use();return a.createElement(O,{activeOpacity:.75,disabled:!c,onPress:async()=>{if(r!=null&&r.isMultipleActiveConversationsEnabled){const g=await i({aiAgentId:r.userId,language:t,country:n,context:o});l({url:g,status:"open"}),u==null||u(g,"open")}else{const g=await s();u==null||u(g,"open")}}},a.createElement(b,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+m.paddingBottom,style:[h.container,m]},a.createElement(I,{variant:"h1",color:({themedColor:g})=>g.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},Vl=D.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),ql=()=>{const{aiAgentInfo:e}=oe();return e?a.createElement(Gl,null):null},Wl=()=>{const{themedColor:e}=$(),{onClose:t}=it();return t?a.createElement(O,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(B,{color:e.textHighEmphasis,type:"close",size:24})):null},Kl=()=>{const{strings:e}=F();return a.createElement(I,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},Yl=e=>{const{components:t}=ke.useContext();return a.createElement(ao,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},Xl=()=>null,Zl=()=>{const{components:e}=ke.useContext();return a.createElement(e.Title,null)},Jl=()=>{const{components:e}=ke.useContext();return a.createElement(e.CloseButton,null)},ke=ae({template:Yl,components:{StartArea:Xl,TitleArea:Zl,EndArea:Jl,Title:Kl,CloseButton:Wl}}),Ql=()=>{const{Template:e}=ke.useContext();return a.createElement(e,{titleAlign:"start"})},ec=()=>{const{components:e}=lt.useContext();return a.createElement(b,{flex:1},a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},lt=ae({template:ec,components:{Header:Ql,Body:$l,Footer:ql}}),uo=({children:e,...t})=>{const{Template:n}=lt.useContext();return a.createElement(co,{...t},a.createElement(n,null),e)},tc=d.forwardRef(function({logLevel:t=V.LogLevel.WARN,language:n=Qe,userSessionInfo:o,children:r,strings:s,...i},l){const[c]=d.useState(()=>new Pn(t));c.level!==t&&(c.level=t);const{nativeModules:u,chatParams:m={},...h}=i;return a.createElement(so,{config:u},({keyValueStorage:g})=>{var _,y;return a.createElement(oc,{logger:c,theme:h.theme,language:n,strings:s},a.createElement(gr,{language:n,logger:c,chatSDK:h.customChatSDK,keyValueStorage:g,chatParams:{...m,useMMKVStorageStore:u.mmkv},messengerVersion:Fn,extensions:{platform:V.SendbirdPlatform.REACT_NATIVE,deviceOSPlatform:(_=p.Platform)==null?void 0:_.select({web:V.DeviceOsPlatform.WEB,ios:V.DeviceOsPlatform.IOS,default:V.DeviceOsPlatform.ANDROID}),deviceOSVersion:(y=p.Platform)!=null&&y.Version?String(p.Platform.Version):void 0},...h},a.createElement(Rs,{ref:l,userSessionInfo:o,presentMethod:i.presentMethod},r)))})}),nc=cr(at,Ce,tn,lt,ke,nt,tt,ot,rt,st),oc=({children:e,logger:t,theme:n,language:o,strings:r})=>a.createElement(Ee.SafeAreaProvider,null,a.createElement(ma,{logger:t,...n},a.createElement(ca,{language:o,logger:t,strings:r},a.createElement(Gn,null,a.createElement(us,null,a.createElement(nc,null,e)))))),{Provider:rc,useContext:nn}=X("FixedMessengerStyle"),sc={useNativeDriver:!0},qe={OPEN_START:"0deg",OPEN_END:"-180deg",CLOSE_START:"180deg",CLOSE_END:"0deg"},We={VISIBLE:1,HIDDEN:0},ac=({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,...sc}).start()},[e,t]);const n={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[qe.OPEN_START,qe.OPEN_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[We.VISIBLE,We.HIDDEN]})}]},o={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[qe.CLOSE_START,qe.CLOSE_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[We.HIDDEN,We.VISIBLE]})}]};return{openIconStyle:n,closeIconStyle:o}},ic=2/3,lc=({isOpened:e,onPress:t})=>{const n=dc.use(),{launcherInfo:o}=oe(),{theme:r}=$(),{launcherSize:s,horizontal:i}=nn(),l=Math.round(s*ic),c=r.colors.base.primary,u=r.colors.base.primaryContrastContent,{openIconStyle:m,closeIconStyle:h}=ac({isOpened:e});return a.createElement(b,{alignSelf:i==="start"?"flex-start":"flex-end"},a.createElement(O,{onPress:t,activeOpacity:.8},({pressed:g})=>a.createElement(b,{style:[n.container({backgroundColor:c,size:s}),g&&n.pressed]},a.createElement(b.Animated,{style:[n.iconWrapper,m]},a.createElement(cc,{url:(o==null?void 0:o.imageUrl)??"",isDefaultIcon:(o==null?void 0:o.type)==="default_icon",size:l,fillColor:u})),a.createElement(b.Animated,{style:[n.iconWrapper,h]},a.createElement(uc,{size:l,fillColor:u})))))},cc=({url:e,isDefaultIcon:t,size:n,fillColor:o})=>e?t?a.createElement(xe,{source:{uri:e},width:n,height:n,tintColor:o,resizeMode:"contain"}):a.createElement(xe,{source:{uri:e},width:n,height:n,resizeMode:"cover"}):a.createElement(B,{type:"delight",size:n,color:o}),uc=({size:e,fillColor:t})=>a.createElement(B,{type:"chevron-down",size:e,color:t}),dc=D.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"}})),te={TRANSLATE_OFFSET:40,DURATION:300,OPACITY_DURATION:83,EASING:p.Easing.out(p.Easing.ease)},mc=e=>e==="entered"?0:te.TRANSLATE_OFFSET,gc=e=>e==="entered"?1:0,hc=({transitionState:e,isActive:t})=>{const[n,o]=d.useState(!1),r=d.useRef(new p.Animated.Value(mc(e))).current,s=d.useRef(new p.Animated.Value(gc(e))).current;return d.useEffect(()=>{if(!n){e==="entered"?(r.setValue(0),s.setValue(1)):e==="exited"&&(r.setValue(te.TRANSLATE_OFFSET),s.setValue(0)),o(!0);return}e==="entering"?(r.setValue(te.TRANSLATE_OFFSET),s.setValue(0),p.Animated.parallel([p.Animated.timing(r,{toValue:0,duration:te.DURATION,easing:te.EASING,useNativeDriver:!0}),p.Animated.timing(s,{toValue:1,duration:te.OPACITY_DURATION,easing:te.EASING,useNativeDriver:!0})]).start()):e==="exiting"&&p.Animated.parallel([p.Animated.timing(r,{toValue:te.TRANSLATE_OFFSET,duration:te.DURATION,easing:te.EASING,useNativeDriver:!0}),p.Animated.timing(s,{toValue:0,duration:te.OPACITY_DURATION,easing:te.EASING,useNativeDriver:!0})]).start()},[e,r,s,n]),d.useMemo(()=>({position:"absolute",top:0,left:0,width:"100%",height:"100%",transform:[{translateY:r}],opacity:s,zIndex:t?999:1,pointerEvents:t?"auto":"none",display:e==="exited"?"none":"flex"}),[r,s,t,e])},mo=d.createContext(null),fc=()=>{const e=d.useContext(mo);if(!e)throw new Error("useNavigatorContext() must be used within <Navigator />");return e},go=({children:e})=>{const t=fc();return typeof e=="function"?a.createElement(a.Fragment,null,e(t)):a.createElement(a.Fragment,null,e)},pc=d.memo(({transitionState:e,isActive:t,children:n})=>{const o=hc({transitionState:e,isActive:t});return a.createElement(p.Animated.View,{style:o},n)}),xn=300,Ye=({initialId:e,children:t})=>{const[n,o]=d.useState([e]),r=n[n.length-1],s=d.useCallback((f,E)=>{o(C=>[...C,f]),h(C=>({...C,[f]:!0})),E!=null&&E.reset&&v(C=>({...C,[f]:(C[f]||0)+1})),_(C=>({...C,[f]:"entering"})),setTimeout(()=>{_(C=>({...C,[f]:"entered"}))},xn)},[]),i=d.useCallback(()=>{o(f=>{if(f.length<=1)return f;const E=f[f.length-1];return _(C=>({...C,[E]:"exiting"})),setTimeout(()=>{_(C=>({...C,[E]:"exited"})),o(C=>C.slice(0,-1))},xn),f})},[]),l=d.useMemo(()=>({navigation:{navigate:s,pop:i},activeScreenId:r}),[s,i,r]),c=d.useMemo(()=>d.Children.toArray(t).filter(f=>f.type===go),[t]),u=d.useMemo(()=>{const f={};return c.forEach(E=>{const{id:C,lazy:A,children:S}=E.props;f[C]={lazy:A,element:typeof S=="function"?S(l):S}}),f},[c,l]),[m,h]=d.useState(()=>{const f={};return Object.entries(u).forEach(([E,{lazy:C}])=>{C===!1&&(f[E]=!0)}),f[e]=!0,f}),[g,_]=d.useState(()=>{const f={};return Object.keys(u).forEach(E=>{f[E]=E===e?"entered":"exited"}),f}),[y,v]=d.useState({});return a.createElement(mo.Provider,{value:l},a.createElement(b,{style:{position:"relative",width:"100%",height:"100%"}},Object.keys(u).map(f=>{var S;if(!m[f])return null;const E=g[f]||"exited",C=f===r,A=`${f}-${y[f]||0}`;return a.createElement(pc,{key:A,transitionState:E,isActive:C},(S=u[f])==null?void 0:S.element)})))};Ye.Screen=go;const{Provider:_c,useContext:on}=X("PageChildren"),yc=({children:e})=>{const[t,n]=d.useState(null),[o,r]=d.useState(null);return a.createElement(_c,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:o,setConversationListChildren:r}},e)},be={conv:"conv",convList:"conv-list"},bc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:o,onClose:r})=>{const{conversationChildren:s,conversationListChildren:i}=on(),l=t==="ConversationList"?be.convList:be.conv;return a.createElement(Ye,{initialId:l},a.createElement(Ye.Screen,{id:be.conv},({navigation:c,activeScreenId:u})=>a.createElement(lo,{channelUrl:n,onClearChannelUrl:()=>o(void 0),onNavigateToConversationList:()=>c.navigate(be.convList),onClose:r,shouldMarkAsRead:e&&u===be.conv},s)),a.createElement(Ye.Screen,{id:be.convList,lazy:!0},({navigation:c})=>a.createElement(uo,{onNavigateToConversation:u=>{o(u),c.navigate(be.conv,{reset:!0})},onClose:r},i)))},Ne=.15,Ec=150,In=(e,t)=>e.interpolate({inputRange:[Ne,1],outputRange:[t,0],extrapolate:"clamp"}),Cc=(e,t)=>{if(e<=0)return 0;const n=(1-Ne)*e/2,o=t==="start"?-1:1,r=p.I18nManager.isRTL?-1:1;return n*o*r},vc=(e,t)=>e<=0?0:(1-Ne)*e/2*(t==="top"?-1:1),Sc=({isOpened:e,horizontal:t,vertical:n})=>{const[o,r]=d.useState({width:0,height:0}),s=d.useRef(new p.Animated.Value(e?1:Ne)).current,i=d.useRef(new p.Animated.Value(e?1:0)).current,l=d.useMemo(()=>Cc(o.width,t),[o.width,t]),c=d.useMemo(()=>vc(o.height,n),[o.height,n]),{translateXInterpolation:u,translateYInterpolation:m}=d.useMemo(()=>({translateXInterpolation:In(s,l),translateYInterpolation:In(s,c)}),[s,l,c]);d.useEffect(()=>{const _=e?"open":"close",y=_==="open"?1:Ne,v=_==="open"?1:0,f=_==="open"?p.Easing.out(p.Easing.quad):p.Easing.in(p.Easing.quad),E={duration:Ec,useNativeDriver:!0,easing:f};_==="close"&&p.Keyboard.dismiss(),p.Animated.parallel([p.Animated.timing(s,{toValue:y,...E}),p.Animated.timing(i,{toValue:v,...E})]).start()},[e,s,i]);const h=d.useMemo(()=>({opacity:i,transform:[{translateX:u},{translateY:m},{scale:s}]}),[i,u,m,s]),g=d.useMemo(()=>_=>{const{width:y,height:v}=_.nativeEvent.layout;r(f=>f.width===y&&f.height===v?f:{width:y,height:v})},[]);return{animatedStyle:h,handleLayout:g,pointerEvents:e?"auto":"none"}},Ac={top:0,left:0,right:0,bottom:0},Tc=({children:e,isOpened:t})=>{const n=wc.use(),{horizontal:o,vertical:r}=nn(),{animatedStyle:s,handleLayout:i,pointerEvents:l}=Sc({isOpened:t,horizontal:o,vertical:r});return a.createElement(Ee.SafeAreaInsetsContext.Provider,{value:Ac},a.createElement(b,{flex:1},a.createElement(b.Animated,{pointerEvents:l,onLayout:i,style:s},a.createElement(b,{style:n.windowContainer},e))))},wc=D.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)"}})),ho=()=>{const[e,t]=d.useState(0);return d.useEffect(()=>{const n=p.Platform.OS==="ios"?"keyboardWillShow":"keyboardDidShow",o=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)}),s=p.Keyboard.addListener(o,()=>{t(0)});return()=>{r.remove(),s.remove()}},[]),e},xc=e=>{const t=d.useRef(new p.Animated.Value(0)).current,[n,o]=d.useState(!1);return d.useEffect(()=>{const s=e?"open":"close",i={toValue:s==="open"?1:0,useNativeDriver:!0,duration:300};s==="open"&&o(!0),p.Animated.timing(t,i).start(()=>{s==="close"&&(o(!1),p.Keyboard.dismiss())})},[e,t]),{windowAnimatedStyle:{opacity:t,display:n?"flex":"none"},pointerEvents:e?"auto":"none"}},Ic=({children:e,insets:t,isOpened:n})=>{const o=kc.use(),s={...Ee.useSafeAreaInsets(),...t},i=ho(),{windowAnimatedStyle:l,pointerEvents:c}=xc(n);return a.createElement(Ee.SafeAreaInsetsContext.Provider,{value:s},a.createElement(b.Animated,{flex:1,style:[o.bg,l],pointerEvents:c},a.createElement(b,{flex:1},e),a.createElement(b,{height:Math.max(0,i-p.Platform.select({android:0,default:s.bottom})),style:o.bg})))},kc=D.create(({theme:e})=>({bg:{backgroundColor:e.colors.base.background}})),Mc="end-bottom",Pe={top:24,bottom:24,start:24,end:24},Rc=({mode:e,edgeToEdgeEnabled:t})=>{const n=e==="floating"?Tc:Ic,[o,r]=Mt({position:Mc,margin:Pe,launcherSize:48,spacing:12}),{bottom:s}=Ee.useSafeAreaInsets(),i=ho(),[l,c]=o.position.split("-"),u=(()=>{const g=p.Platform.select({android:t?s:0,default:0}),_=c==="top"?o.spacing:-o.launcherSize,y=i>0?i+_+g:0;return y>0?y:o.margin.bottom})(),m={position:"absolute",zIndex:1e3,...c==="top"?{top:o.margin.top}:{bottom:o.margin.bottom},...l==="start"?{left:o.margin.start}:{right:o.margin.end}},h=(()=>{if(e==="floating"){const g=o.launcherSize+o.spacing;return{position:"absolute",top:o.margin.top+(c==="top"?g:0),bottom:u+(c==="bottom"?g:0),left:o.margin.start,right:o.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:{...o,horizontal:l,vertical:c,setPosition:g=>r({position:g}),setMargin:({top:g=Pe.top,bottom:_=Pe.bottom,start:y=Pe.start,end:v=Pe.end})=>r({margin:{top:g,bottom:_,start:y,end:v}}),setLauncherSize:g=>r({launcherSize:g}),setSpacing:g=>r({spacing:g})}}},Lc=e=>{var s,i,l,c;const{setPosition:t,setMargin:n,setLauncherSize:o,setSpacing:r}=nn();return d.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n(e.margin),e.launcherSize!==void 0&&o(e.launcherSize),e.spacing!==void 0&&r(e.spacing)},[e.position,(s=e.margin)==null?void 0:s.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},Dc=({children:e})=>{const{setConversationChildren:t}=on();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Pc=({children:e})=>{const{setConversationListChildren:t}=on();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Oc=({entryPoint:e="Conversation",edgeToEdgeEnabled:t=!0,windowMode:n="floating",fullscreenInsets:o,initialChannelUrl:r,windowContainerProps:s,children:i})=>{const[l,c]=d.useState(!1),[u,m]=d.useState(r),{Window:h,windowContainerStyle:g,launcherContainerStyle:_,styleContext:y}=Rc({mode:n,edgeToEdgeEnabled:t});return d.useEffect(()=>{const v=p.BackHandler.addEventListener("hardwareBackPress",()=>l?(c(!1),!0):!1);return()=>v.remove()},[l]),a.createElement(rc,{value:y},a.createElement(yc,null,a.createElement(b,{style:g,backgroundColor:"transparent",pointerEvents:l?"auto":"box-none",...s},a.createElement(h,{isOpened:l,insets:o},a.createElement(bc,{isOpened:l,entryPoint:e,selectedChannelUrl:u,setSelectedChannelUrl:m,onClose:()=>c(!1)}))),a.createElement(b,{style:_,backgroundColor:"transparent",pointerEvents:"box-none"},a.createElement(lc,{isOpened:l,onPress:()=>c(!l)})),i))},Nc=Object.assign(Oc,{Style:Lc,ConversationChildren:Dc,ConversationListChildren:Pc});ar.set(V.SendbirdPlatform.REACT_NATIVE,{deviceOSPlatform:p.Platform.select({ios:V.DeviceOsPlatform.IOS,android:V.DeviceOsPlatform.ANDROID,default:V.DeviceOsPlatform.ANDROID}),messengerVersion:Fn,keyValueStorage:ir()});exports.AIAgentProviderContainer=tc;exports.AnonymousSessionInfo=Ze;exports.BottomSheet=ne;exports.BottomSheetLayout=tt;exports.Conversation=lo;exports.ConversationContext=zs;exports.ConversationContextProvider=jn;exports.ConversationHeaderLayout=Ce;exports.ConversationLayout=at;exports.ConversationList=uo;exports.ConversationListContext=Hl;exports.ConversationListContextProvider=co;exports.ConversationListHeaderLayout=ke;exports.ConversationListLayout=lt;exports.FixedMessenger=Nc;exports.IncomingMessageLayout=ot;exports.ManualSessionInfo=qt;exports.MessageListUILayout=tn;exports.ModalProvider=Gn;exports.NativeAdapterProvider=so;exports.OutgoingMessageLayout=rt;exports.PlaceholderLayout=nt;exports.SystemMessageLayout=st;exports.useConversationContext=ue;exports.useConversationListContext=it;exports.useMessengerSessionContext=oe;exports.useModalContext=et;exports.useNativeAdapterContext=ro;
|
|
1
|
+
"use strict";var Co=Object.defineProperty;var vo=(e,t,n)=>t in e?Co(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var k=(e,t,n)=>vo(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react-native"),G=require("@sendbird/chat"),d=require("react"),be=require("react-native-safe-area-context"),te=require("@sendbird/chat/aiAgent"),Ne=require("@sendbird/uikit-tools"),Se=require("date-fns"),Ae=require("@sendbird/chat/message"),Je=require("@sendbird/chat/groupChannel"),So=require("date-fns/isSameDay"),Ao=require("date-fns/locale/de"),To=require("date-fns/locale/en-US"),wo=require("date-fns/locale/es"),xo=require("date-fns/locale/fr"),Io=require("date-fns/locale/hi"),ko=require("date-fns/locale/it"),Mo=require("date-fns/locale/ja"),Ro=require("date-fns/locale/ko"),Lo=require("date-fns/locale/pt"),Do=require("date-fns/locale/tr"),Po=require("@react-native-clipboard/clipboard"),Oo=require("react-native-code-highlighter"),No=require("react-native-markdown-display"),et=e=>e&&e.__esModule?e:{default:e};function Bo(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 o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Ho=et(G),a=Bo(d),zo=et(Po),Fo=et(Oo),Uo=et(No),ve="sb-agent",On="KEY_IMG_ASPECT_RATIO",Nn="*/*",D={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},ie=e=>!!e&&"sender"in e,$o=e=>ie(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),jo=(e,t,n,o=!0)=>{if(!o||!ie(e))return"single";const r=()=>{if(!t||!ie(t))return!1;const c=t.sender.userId===e.sender.userId,u=Se.isSameMinute(t.createdAt,e.createdAt);return c&&u},s=()=>{if(!n||!ie(n))return!1;const c=n.sender.userId===e.sender.userId,u=Se.isSameMinute(n.createdAt,e.createdAt);return c&&u},i=r(),l=s();return i&&l?"middle":i?"bottom":l?"top":"single"},ze=(e,t)=>(()=>{var o;return ie(e)?e.sender.userId:((o=e==null?void 0:e.sender)==null?void 0:o.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)=>ie(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>ie(e)&&(e.sender.userId===t||e.sendingStatus===Ae.SendingStatus.PENDING)},Go=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"},Bn=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},Wt=e=>{switch(e){case"top":case"middle":return D.GAP_GROUPED;default:return D.GAP_UNGROUPED}},Vo=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,o=[];let r=0;return e.replace(n,(s,...i)=>{const[l,c,u]=i;return r<u&&o.push({type:"text",value:e.slice(r,u).trim()}),o.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),r=u+s.length,s}),r<e.length&&o.push({type:"text",value:e.slice(r).trim()}),o},qo=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Wo=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Ko=e=>e.replace(/~~/g,"\\~\\~"),Yo=e=>{let t=e;return t=qo(t),t=Wo(t),t=Ko(t),t},Xo=typeof navigator<"u"&&navigator.product==="ReactNative",an=(e,t)=>{const n=o=>!t||t.length===0?!0:ie(o)&&t.includes(o.sendingStatus);return Xo?e.find(n):e.findLast(n)};function kt(){}function Zo(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Jo(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 ln=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Xe={isStreaming(e){const t=ln(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(ze(e,t)){const o=ln(e.data);return!(o!=null&&o.respond_mesg_id)&&!(o!=null&&o.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)}},mt=`@${ve}`,cn=({appId:e,aiAgentId:t,storage:n})=>{const o={templateBase:`${mt}-template`,template:r=>`${o.templateBase}/templates/${r}`,templateToken:()=>`${o.templateBase}/tokens`,messengerSession:r=>{const s=Jo(`${e}/${t}/${r}`);return`${mt}-udata/${s}`},anonUserSession:()=>`${mt}-session/${e}/${t}`};return{template:{set:(r,s)=>n.set(o.template(r),s),get:r=>n.get(o.template(r)),setCachedToken:r=>n.set(o.templateToken(),r),getCachedToken:()=>n.get(o.templateToken()),clear:()=>{n.getKeys(o.templateBase).forEach(n.delete)}},messenger:{getSettings:r=>{try{const s=n.get(o.messengerSession(r));return s?JSON.parse(s):null}catch{return null}},setSettings:(r,s)=>{try{delete s.auto_created_user;const i=JSON.stringify(s);n.set(o.messengerSession(r),i)}catch{return}},getAnonUser:()=>{try{const r=n.get(o.anonUserSession());return r?JSON.parse(r):null}catch{return null}},setAnonUser:r=>{try{const s=JSON.stringify(r);n.set(o.anonUserSession(),s)}catch{return}},clear:r=>{try{r&&n.delete(o.messengerSession(r)),n.delete(o.anonUserSession())}catch{return}}}}},Hn=(e,t,n={})=>{let o=null,r=null,s=null;const{leading:i=!0,trailing:l=!0}=n,c=(...u)=>{const m=Date.now();if(s===null||m-s>=t)i?(e(...u),s=m):(r=u,s=m);else if(r=u,l&&!o){const h=t-(m-s);o=setTimeout(()=>{r&&l&&(e(...r),s=Date.now()),o=null,r=null},h)}};return c.cancel=()=>{o&&(clearTimeout(o),o=null),r=null,s=null},c};class Qo{constructor(t,{filter:n,limit:o=20}){k(this,"filter");k(this,"_sdk");k(this,"_pinnedChannels");k(this,"_channels");k(this,"_isDisposed",!1);k(this,"_handlerId",`handler-id-${Date.now()}`);k(this,"_order",Je.GroupChannelListOrder.LATEST_LAST_MESSAGE);k(this,"_limit");k(this,"_query");k(this,"_token");k(this,"_timestamp");k(this,"_isSyncing");k(this,"_channelHandler");k(this,"_connectionHandler");k(this,"_collectionEventHandler");k(this,"_throttledOnChannelChanged");var r,s,i,l,c,u,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=o,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(r=this.filter)==null?void 0:r.aiAgentChannelFilter,aiAgentConversationStatusFilter:(s=this.filter)==null?void 0:s.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=Hn(h=>{this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url])},250,{trailing:!1,leading:!0}),this._channelHandler=new Je.GroupChannelHandler({onChannelChanged:h=>{h.isGroupChannel()&&this._throttledOnChannelChanged(h)},onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new G.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var s,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),o=t.find(l=>!n.has(l.url));let r;o?r=((i=o.lastMessage)==null?void 0:i.createdAt)??o.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)??[],o=new Map(n.map((c,u)=>[c,u])),r=[],s=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const u=o.get(c.url);if(u===void 0)continue;const m=Mt(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),s.push(c)):r.push(c);const g=this._pinnedChannels.findIndex(y=>(o.get(y.url)??1/0)>u),_=g===-1?this._pinnedChannels.length:g;this._pinnedChannels.splice(_,0,c)}return{addedChannels:r,updatedChannels:s,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const o=[],r=[],s=[];for(const i of t){if(!this._query.belongsTo(i)){o.push(i.url);continue}const l=Mt(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=er(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),s.push(i))}return{addedChannels:r,updatedChannels:s,unmatchedChannelUrls:o}}_addChannelsToView(t,n=!1){var h,g,_,y,v;const o=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),r=[],s=[];for(const f of t)o.has(f.url)?r.push(f):s.push(f);const i=this._upsertPinnedChannelsToArray(r),l=this._upsertRegularChannelsToArray(s,n),c=i.addedChannels.concat(l.addedChannels),u=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((_=(g=this._collectionEventHandler)==null?void 0:g.onChannelsAdded)==null||_.call(g,{},c)),u.length>0&&((v=(y=this._collectionEventHandler)==null?void 0:y.onChannelsUpdated)==null||v.call(y,{},u)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var r,s,i;const n=new Set(((r=this.filter)==null?void 0:r.pinnedChannelUrls)??[]),o=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(u=>u.url===l);c>=0&&(o.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(u=>u.url===l);c>=0&&(o.push(l),this._channels.splice(c,1))}o.length>0&&((i=(s=this._collectionEventHandler)==null?void 0:s.onChannelsDeleted)==null||i.call(s,{},o))}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 Mt=(e,t)=>e.findIndex(n=>n.isIdentical(t)),er=(e,t,n)=>{if(e.length>0){const o=Mt(e,t);let r=0,s=e.length-1,i=Math.floor((r+s)/2);for(;r<s;){const c=un(e[i],t,n);if(c>0)s=i,i=Math.floor((r+s)/2);else if(c<0)r=i+1,i=Math.floor((r+s)/2);else return{place:i,oldPosition:o}}return{place:un(e[i],t,n)>=0?i:i+1,oldPosition:o}}return{place:e.length,oldPosition:-1}},un=(e,t,n)=>{switch(n){case Je.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const o=t.lastMessage.createdAt-e.lastMessage.createdAt;return o===0?t.createdAt-e.createdAt:o}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};class tr{constructor(t){k(this,"subscribers",{});this.logger=t}async send(t){const n=nr(),o=this.subscribers[t.type];if(o){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const r=o.map(s=>s(t.payload));await Promise.all(r).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const o=this.subscribers[t];o&&(this.subscribers[t]=o.filter(r=>r!==n))}}const nr=()=>{let e=kt,t=kt;return{promise:new Promise((o,r)=>{e=o,t=r}),resolve:e,reject:t}};var Be=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e))(Be||{});class tt{constructor(t={}){k(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const or={CloseConversation:e=>new rr(e),MessengerSettingsUpdated:e=>new sr(e),ActiveChannelUpdated:e=>new ar(e),AnonymousSessionTokenExpired:()=>new ir};class rr extends tt{constructor(){super(...arguments);k(this,"type","conv.close")}}class sr extends tt{constructor(){super(...arguments);k(this,"type","messenger.settings.updated")}}class ar extends tt{constructor(){super(...arguments);k(this,"type","active.channel.updated")}}class ir extends tt{constructor(){super(...arguments);k(this,"type","anon.token.expired")}}var zn=(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))(zn||{});class Fn{constructor(t){k(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${ve}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${ve}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${ve}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${ve}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${ve}/error]`,...t)}}class Kt{constructor({userId:t,authToken:n,sessionHandler:o}){k(this,"userId");k(this,"authToken");k(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=o}}class Qe{constructor(){k(this,"userId");k(this,"authToken");k(this,"sessionHandler")}}const lr=e=>({onSessionTokenRequired:t=>{t(null),e.send(or.AnonymousSessionTokenExpired())}}),cr="ai_agent:stats",ur="conversation_initial_render",dr=800220;var Y=(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))(Y||{});class mr{constructor(){k(this,"timers",new Map);k(this,"committed",!1);k(this,"commitCallback",null);k(this,"conversationId",null);k(this,"channelUrl",null);k(this,"errorCode",null);k(this,"errorDescription",null);k(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??dr,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(cr,t)):!1}}class gr extends mr{constructor(){super(...arguments);k(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return ur}buildPayload(){const n=this.getDuration(Y.AUTH),o=this.getDuration(Y.GET_CHANNEL),r=this.getDuration(Y.GET_MESSAGES),s=this.getDuration(Y.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(Y.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...o!==null&&{get_channel_duration:o},...r!==null&&{get_messages_duration:r},...s!==null&&{total_duration_from_cache:s}},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 hr{constructor(t){k(this,"commitCallback");k(this,"presentMethod","direct_present");k(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new gr().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(Y.TOTAL_DURATION).startTimer(Y.TOTAL_DURATION_FROM_CACHE).startTimer(Y.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(Y.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(Y.AUTH).setError(t instanceof G.SendbirdError?t.code:void 0,t.message).stopTimer(Y.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(Y.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(Y.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(Y.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(Y.GET_CHANNEL).setError(t instanceof G.SendbirdError?t.code:void 0,t.message).stopTimer(Y.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof G.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(Y.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof G.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(Y.TOTAL_DURATION).stopTimer(Y.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}}const fe={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}}},fr=e=>{var t,n,o,r,s,i,l,c,u,m,h,g,_,y;return e?{...fe,...e,conversation:{...fe.conversation,...e==null?void 0:e.conversation,header:{...(t=fe.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(o=fe.conversation)==null?void 0:o.input,...(r=e==null?void 0:e.conversation)==null?void 0:r.input,camera:{...(i=(s=fe.conversation)==null?void 0:s.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=fe.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:{...(_=fe.conversation)==null?void 0:_.fileViewer,...(y=e==null?void 0:e.conversation)==null?void 0:y.fileViewer}}}:fe},le=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===te.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Un=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===te.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function we(e){var n,o,r;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((r=(o=e==null?void 0:e.conversation)==null?void 0:o.handoff)==null?void 0:r.timestamp))=="number"}function pr(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function dn(e){return!!e&&e<Date.now()}function _r(e){return!e.title}function yr(e,t){var n;if(e)return _r(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}const br=e=>JSON.parse(e);var Rt=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Rt||{});const $n=e=>typeof e=="object"&&e!==null,mn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Er=e=>!$n(e)||!mn(e,"channel_url")||!mn(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Cr={1:Er};function vr(e){if(!$n(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Cr[t];if(!n)return null;const o=n(e.data);return o?{category:t,data:o}:null}function gn(e,t,n,o){const r=Ho.default.init({appId:e,modules:[new Je.GroupChannelModule,new te.AIAgentModule],localCacheEnabled:!0,options:new G.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...o});return r.addSendbirdExtensions([{version:n,product:G.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),r}function Sr(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 $e=new Map,Ar={set:(e,t)=>{$e.set(e,t)},get:e=>{if($e.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=$e.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=$e.entries().next().value;return{platform:t[0],...t[1]}}};function Tr(){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 wr(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 Z=(e,t)=>{const n=d.createContext(null),o=({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),s=()=>{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`,o.displayName=`${e}Provider`,r.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:o,Consumer:r,useContext:s}};function ae(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){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(_=>({..._,[h]:g}))};return a.createElement(t.Provider,{value:m},s)}function o({template:s,children:i}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{s&&l(s)},[s]),a.createElement(a.Fragment,null,i)}function r({children:s}){return a.createElement(n,null,s)}return r.defaults=e,r.useContext=()=>d.useContext(t),r.Context=t,r.Template=o,Object.keys(e.components).forEach(s=>{r[s]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),r}function xr(...e){return function({children:n}){return e.reduce((o,r)=>a.createElement(r,null,o),n)}}function Ir(e,t){var o;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((o=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:o.call(t,r))??`${r} photos`}return e.name}function kr(e,t,n){var i;const o=new Date,r=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),s=Se.differenceInMinutes(o,r);return s<1?n.justNow:s<60?n.minutesAgo(s):Se.isToday(r)?n.hoursAgo(Se.differenceInHours(o,r)):t(r,n.dateShortFormat)}const{Provider:Mr,useContext:X}=Z("AIAgent");function Rr({appId:e,aiAgentId:t,keyValueStorage:n,networkStateAdapter:o,language:r,countryCode:s,context:i,queryParams:l,config:c,chatSDK:u,chatParams:m,children:h,logger:g,dispatcher:_,messengerVersion:y,extensions:v={platform:G.SendbirdPlatform.JS,deviceOSPlatform:Zo()?G.DeviceOsPlatform.MOBILE_WEB:G.DeviceOsPlatform.WEB}}){const[f,S]=d.useState(()=>{const b=g??new Fn(zn.WARN),C=_??new tr(b);return{logger:b,dispatcher:C,chatSDK:u??gn(e,v,y,m),cache:cn({appId:e,aiAgentId:t,storage:n})}});return d.useEffect(()=>{S(b=>{let C=b.logger,A=b.dispatcher,w=b.chatSDK;return g&&g!==b.logger&&(C=g),_&&_!==b.dispatcher&&(A=_),u&&u!==b.chatSDK?w=u:!u&&b.chatSDK.appId!==e&&(w=gn(e,v,y,{newInstance:!0,...m})),{...b,logger:C,dispatcher:A,chatSDK:w,cache:cn({appId:e,aiAgentId:t,storage:n})}})},[e,t,g,_,u,n]),d.useEffect(()=>()=>{f.chatSDK.connectionState==="OPEN"&&f.chatSDK.disconnectWebSocket()},[f.chatSDK]),Sr(f.chatSDK),a.createElement(Mr,{value:{...f,appId:e,aiAgentId:t,context:i,language:r,countryCode:s,queryParams:l,config:fr(c),networkStateAdapter:o}},h)}const Lr=(e,t,n)=>Ne.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0}),Lt={DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function jn(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Dr(e){const t=jn(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Pr(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Or(e,t,n){e/=255,t/=255,n/=255;const o=Math.max(e,t,n),r=Math.min(e,t,n),s=o-r;let i=0,l=0;const c=(o+r)/2;return o!==r&&(l=c>.5?s/(2-o-r):s/(o+r)),o===e?i=(t-n)/s+(t<n?6:0):o===t?i=(n-e)/s+2:o===n&&(i=(e-t)/s+4),i/=6,[i,l,c]}function Nr(e,t,n){let o,r,s;if(t===0)o=r=s=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;o=i(c,l,e+1/3),r=i(c,l,e),s=i(c,l,e-1/3)}return[Math.round(o*255),Math.round(r*255),Math.round(s*255)]}function je(e,t,n){const[o,r,s]=Dr(e),[i,l,c]=Or(o,r,s),u=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,g,_]=Nr(i,m,u);return Pr([Math.round(h),Math.round(g),Math.round(_)])}function Br(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 hn(e){const t=jn(e),n=149,o=+`0x${t[1]}${t[2]}`,r=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return o*.299+r*.587+s*.114>n?Lt.BLACK:Lt.WHITE}function Hr(e,t,n,o,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:o},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const zr=(e,t,n,o,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:o},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)"}},gt={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 fn(e){const t=Fr(e),{colors:n,aiAgentColorVariables:o}=Ur(e,t),r=jr(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:o,typography:r}}function Fr({selectedTheme:e,palette:t,primary:n}){const o=t!=null&&t.primary?t.primary:n?n===Ge.primary.main?Ge.primary:Br(n,e):Ge.primary;return{...Ge,primary:o,...t}}function Ur({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:o},r){const s=r.primary.main,i=t??hn(s),l=n??Lt.DEFAULT_BOT_MSG_BG,c=o??hn(l);return{colors:(e==="light"?Hr:zr)(r,s,i,l,c),aiAgentColorVariables:{primary_color:s,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function $r(e,t,n){const o={...e};return n.forEach(r=>{const s=t[r];s!=null&&(o[r]=s)}),o}function jr({typography:e}){if(!e)return gt;const t={...gt};return Object.keys(e).forEach(n=>{const o=e[n];if(o&&typeof o=="object"){const r=gt[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=$r(r,o,s)}}),t}const{Provider:Gr,useContext:Vr}=Z("AIAgentTheme");function qr({logger:e,palette:t,typography:n,appearance:o,children:r}){const s=d.useRef(null),[i,l]=d.useState(()=>fn({selectedTheme:(o==null?void 0:o.theme)??"light",palette:t,typography:n,primary:o==null?void 0:o.primaryColor,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor})),c=d.useCallback((u,m)=>{m&&(s.current=m);const h=(o==null?void 0:o.theme)??u,g=s.current?s.current.themes[h]:null,_={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!_.primary&&(g!=null&&g.primary_color)&&(_.primary=g.primary_color,_.primaryContrast=g.primary_contrast_color),!_.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(_.botMessageBackground=g.bot_message_bg_color,_.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const y=fn({selectedTheme:h,palette:t,typography:n,..._});l(y),e==null||e.info("theme.update:",h)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor,t,n,e]);return d.useEffect(()=>{(o!=null&&o.theme||o!=null&&o.primaryColor||o!=null&&o.botMessageBackgroundColor)&&c(i.selectedTheme)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor]),a.createElement(Gr,{value:{theme:i,updateTheme:c}},r)}const ht=25*1024*1024,pn=1,_n=new Set(["image/png","image/jpeg","image/jpg"]),yn=new Set(["application/pdf"]),Wr={off:"off",always:"always",handed_off_only:"handed_off_only"},Kr=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:pn,attachmentMode:"handed_off_only",defaultUploadSizeLimit:ht,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:_n,supportedFileMimeTypes:yn})),n=d.useCallback(({active_channel:r,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??pn,attachmentMode:Wr[r.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??ht,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??_n),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??yn)})},[]),o=d.useCallback(r=>{const{channel:s,uploadSizeLimit:i=ht}=r,l=(u=!0)=>s!=null&&s.isAIAgent?u?we(s):!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 we(s);default:return!0}},get supportedMimeTypes(){return l()?[Nn]:[...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:o}};function Gn(){const{chatSDK:e,logger:t}=X();return d.useCallback(async n=>{if(n.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw t.error("requestMessengerSettings: invalid userId",o),o}return await e.aiAgent.requestMessengerSettings({...n,shouldSendFirstMessage:!1})},[e,t])}function Yr(){const{chatSDK:e,logger:t}=X(),n=d.useCallback(async(r,s,i)=>{if(t.debug("useChatConnection.connect: start, session",r.userId),s){const l=new G.SessionHandler({...s,onSessionTokenRequired:Xr(s.onSessionTokenRequired,i)});e.setSessionHandler(l),e.aiAgent.addEventHandler(Rt.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),c=>{var m;t.debug("useChatConnection: EXTERNAL_AUTH_TOKEN_EXPIRED event received",c);const u=vr(c);(u==null?void 0:u.category)===Rt.EXTERNAL_AUTH_TOKEN_EXPIRED&&(t.debug("useChatConnection: calling onExternalAuthTokenExpired handler",u.data),(m=s==null?void 0:s.onExternalAuthTokenExpired)==null||m.call(s,u.data))})}try{return await e.connect(r.userId,r.authToken),t.debug("useChatConnection.connect: end, currentUser",e.currentUser),e.currentUser}catch(l){const c=l;if(e.isCacheEnabled){if(Jr(c))t.warn("useChatConnection.connect","offline connect restricted",c.message,c.code),t.warn("useChatConnection.connect","clear cached-data"),await e.clearCachedData().catch(u=>t.warn("useChatConnection.connect","clear cached-data failure",u));else if(e.currentUser)return t.debug("useChatConnection.connect: end (offline), currentUser",e.currentUser),e.currentUser}throw t.warn("useChatConnection.connect","connect failure",c.message,c.code),c}},[e,t]),o=d.useCallback(async()=>{t.debug("useChatConnection.disconnect: start"),e.aiAgent.removeAllEventHandlers(),await e.disconnect(),t.debug("useChatConnection.disconnect: end")},[e,t]);return{connect:n,disconnect:o}}function Xr(e,t){if(e)return async(n,o)=>{new Promise((r,s)=>e==null?void 0:e(r,s)).then(r=>{r&&(t==null||t(r)),n(r)}).catch(r=>{o(r)})}}const Zr=[400300,400301,400302,400310];function Jr(e){return Zr.some(t=>e.code===t)}const Qr=1440*60*1e3,es=e=>{const{logger:t,cache:n}=X(),o=()=>{const s=n.messenger.getAnonUser();return s?s.expireAt-Qr<=Date.now()?(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session expired, clear cache"),n.messenger.clear(s.userId),null):(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session info detected"),s):null},r=()=>{if(!e||e instanceof Qe)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof e.userId!="string")throw new Error("userSessionInfo.userId must be a string");const s=["userId","authToken","sessionHandler"].filter(i=>!(i in e));return s.length>0&&t.error(`useUserSessionCandidate.getManualSessionInfo: missing required keys in userSessionInfo: ${s.join(", ")}`),t.debug("useUserSessionCandidate.getManualSessionInfo: manual session info detected"),e};return d.useMemo(()=>e instanceof Kt?{type:"manual",userSessionCandidate:r()}:e instanceof Qe?{type:"anonymous",userSessionCandidate:o()}:e&&typeof e=="object"?(t.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:r()}):e===void 0?(t.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:o()}):{type:"anonymous",userSessionCandidate:null},[t,e==null?void 0:e.userId,e==null?void 0:e.authToken,e==null?void 0:e.sessionHandler,n.messenger.getAnonUser,n.messenger.clear])};function ts({userSessionInfo:e,onUpdateMessengerSettings:t,onPreAuth:n,onPostAuth:o,onErrorAuth:r,onAuthTokenRefreshed:s,onPostDeauth:i,forceCreateChannel:l}){const{aiAgentId:c,language:u,context:m,countryCode:h,logger:g,cache:_,dispatcher:y}=X(),{connect:v,disconnect:f}=Yr(),{type:S,userSessionCandidate:b}=es(e),C=Gn(),A=d.useCallback(async()=>{var q;g.debug("useAuthentication.authenticate: start");const x=b!=null&&b.userId?_.messenger.getSettings(b.userId):null;x!=null&&x.bot&&(t(x),g.debug("useAuthentication.authenticate: cached messenger settings",x));const L=await C({aiAgentId:c,userId:b==null?void 0:b.userId,language:u,country:h,context:m,forceCreateChannel:l,knownActiveChannelUrl:(q=x==null?void 0:x.active_channel)==null?void 0:q.channel_url});g.debug("useAuthentication.authenticate: messenger settings response",L);let V=null;if(L.auto_created_user)if(S==="manual")g.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),V={userId:b.userId,authToken:b.authToken};else{const{user_id:$,session_token:R,expire_at:F}=L.auto_created_user;_.messenger.setAnonUser({userId:$,authToken:R,expireAt:F}),V={userId:$,authToken:R}}else V={userId:(b==null?void 0:b.userId)??"",authToken:(b==null?void 0:b.authToken)??""};_.messenger.setSettings(V.userId,L),t(L);try{await n(L,V);const $=S==="anonymous"?lr(y):b==null?void 0:b.sessionHandler;await v(V,$,s),await o(L,V)}catch($){throw $ instanceof Error&&(r($),g.error("useAuthentication.authenticate: failed to connect",$)),$}return L},[C,v,S,b==null?void 0:b.userId,b==null?void 0:b.sessionHandler,b==null?void 0:b.authToken,c,u,m,h,l,_.messenger.setAnonUser,_.messenger.getSettings,_.messenger.setSettings,t,n,o,r,s]),w=d.useCallback(async()=>{g.debug("useAuthentication.deauthenticate: start"),await f(),i(),g.debug("useAuthentication.deauthenticate: completed")},[f,g,i]);return{authenticate:A,deauthenticate:w,userSessionCandidate:b}}const ns=()=>{const{chatSDK:e,logger:t,cache:n}=X(),o=d.useCallback(()=>{var l,c;const s=(c=(l=e.appInfo)==null?void 0:l.aiAgentInfo)==null?void 0:c.templateListToken;if(!s)return!1;const i=n.template.getCachedToken();return i?s!==i:!0},[e,n.template.getCachedToken]),r=d.useCallback(async()=>{try{const{templates:s,token:i}=await e.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=br(l);n.template.set(c,l)}n.template.setCachedToken(i)}catch(s){t==null||t.error("messageTemplateContext.syncCachedTemplates: error:",s)}},[e,t,n.template.set,n.template.setCachedToken]);return{shouldSyncCachedTemplate:o,syncCachedTemplates:r}},bn=(...e)=>{const[t,n,o]=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 o=="object"&&o!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:o};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},Le=e=>({...e,context:e.context??{}}),{Provider:os,useContext:Fe}=Z("AIAgentMessengerSession"),rs=d.forwardRef(function({userSessionInfo:e,forceCreateChannel:t,children:n},o){const{appId:r,aiAgentId:s,chatSDK:i,language:l,countryCode:c,context:u,cache:m,logger:h}=X(),{updateTheme:g}=Vr(),[_,y]=d.useState(void 0),[v,f]=d.useState(void 0),[S,b]=d.useState(null),[C,A]=d.useState(null),[w,x]=d.useState(null),[L,V]=d.useState(null),[q]=d.useState(()=>({initialRender:new hr((I,B)=>i.aiAgent.appendStat(I,B))})),{updateBaseAttachmentRules:$,createAttachmentRules:R}=Kr(),{shouldSyncCachedTemplate:F,syncCachedTemplates:T}=ns(),N=Gn(),{authenticate:W,deauthenticate:J}=ts({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(I=>{const{appearance:B,bot:z,launcher:re}=I;g(B.selected_theme,B),x({userId:z.bot_userid,profileUrl:z.bot_profile_url,nickname:z.bot_nickname,replyToFile:z.reply_to_file,specialNotice:z.special_notice,specialNoticeEnabled:z.is_special_notice_enabled,showHandoffButton:z.show_handoff_button??!0,isMultipleActiveConversationsEnabled:z.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:I.bot.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:I.bot.is_user_feedback_comment_option_enabled??!1}),V({type:re.image_type||"default_icon",imageUrl:re.image_url}),$(I)},[g]),onPreAuth:d.useCallback((I,B)=>{y(void 0),A(B),q.initialRender.onAuthStart()},[q]),onPostAuth:d.useCallback(async I=>{q.initialRender.onAuthComplete(),b(i.currentUser),F()&&await T(),f({url:I.active_channel.channel_url,status:"open"})},[i,F,T,q]),onErrorAuth:d.useCallback(I=>{q.initialRender.onAuthError(I),y(I)},[q]),onAuthTokenRefreshed:d.useCallback(I=>{A(B=>B?{...B,authToken:I}:null)},[]),onPostDeauth:d.useCallback(()=>{m.template.clear(),m.messenger.clear(C==null?void 0:C.userId),q.initialRender.clear(),b(null),f(void 0),A(null),x(null),V(null)},[m.template.clear,m.messenger.clear,C,q])}),Ce=d.useCallback(async()=>{var I;if(C){h.debug("agentMessengerSession.refreshActiveChannel: try to refresh active channel"),f(void 0);const B=await N({aiAgentId:s,userId:C.userId,language:l,country:c,context:u,forceCreateChannel:t,knownActiveChannelUrl:(I=m.messenger.getSettings(C.userId))==null?void 0:I.active_channel.channel_url});return m.messenger.setSettings(C.userId,B),f({url:B.active_channel.channel_url,status:"open"}),h.info("agentMessengerSession.refreshActiveChannel: refreshed active channel",B.active_channel.channel_url),B.active_channel.channel_url}else throw h.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")},[N,r,s,C==null?void 0:C.userId,l,c,u,t,m.messenger.getSettings,m.messenger.setSettings]),Me=d.useCallback(async I=>{if(!(C!=null&&C.userId))throw new Error("Current user is not authenticated. Please authenticate first.");const B=await N({...I,userId:C.userId,knownActiveChannelUrl:void 0}),z=B.active_channel.channel_url;return m.messenger.setSettings(C.userId,B),z},[C==null?void 0:C.userId,N]),he=d.useCallback(async I=>{if(!i.currentUser)throw new Error("Current user is not authenticated. Please authenticate first.");if(Object.entries(I.context).length===0)return[];const B=i.aiAgent.createConversationListQuery({aiAgentId:I.aiAgentId,status:te.ConversationStatus.OPEN,limit:100}),z=[];for(;B.hasNext;){const re=await B.next();for(const Q of re)ss(Q.context??{},I.context)&&z.push(Q.channelInfo.url)}return z},[i]),[pe]=d.useState(()=>Hn(I=>{var B;h.info("agentMessengerSession.channelChanged: channel.conversation",I.conversation),f({url:I.url,status:le(I)?"closed":"open",conversationStatus:(B=I.conversation)==null?void 0:B.status})},250,{trailing:!1,leading:!0}));return Ne.useGroupChannelHandler(i,{onChannelChanged:I=>{I.isGroupChannel()&&I.url===(v==null?void 0:v.url)&&pe(I)}}),d.useEffect(()=>()=>{pe.cancel()},[pe]),d.useImperativeHandle(o,()=>{const I=async()=>{if(!v)throw new Error("No active conversation. Please start a conversation first.");return await i.groupChannel.getChannel(v.url)};return{activeChannel:v,chatSDK:i,authenticate:W,deauthenticate:J,updateContext:async(...B)=>{const z=bn(...B);if(z.type==="active"){const se=await(await I()).updateContext(s,z.context);return Le(se)}const re=await i.aiAgent.updateContext(z.aiAgentId,z.channelUrl,z.context);return Le(re)},patchContext:async(...B)=>{const z=bn(...B);if(z.type==="active"){const se=await(await I()).patchContext(s,z.context);return Le(se)}const re=await i.aiAgent.patchContext(z.aiAgentId,z.channelUrl,z.context);return Le(re)},getContextObject:async()=>{const z=await(await I()).getContextObject(s);return Le(z)}}},[W,J,v,i,s,h]),a.createElement(os,{value:{sdkUser:S,userSessionInfo:e,userSession:C,activeChannel:v,setActiveChannel:f,refreshActiveChannel:Ce,createConversation:Me,searchConversation:he,connectionError:_,aiAgentInfo:w,launcherInfo:L,authenticate:W,deauthenticate:J,createAttachmentRules:R,statsTrackers:q}},n)}),ss=(e,t)=>Object.entries(t).every(([n,o])=>e[n]===o),Yt=(e,t)=>{const n=d.useId(),o=d.useRef(t);d.useLayoutEffect(()=>{o.current=t}),d.useEffect(()=>{const r=new G.ConnectionHandler({onDisconnected:s=>{var i,l;return(l=(i=o.current).onDisconnected)==null?void 0:l.call(i,s)},onConnected:s=>{var i,l;return(l=(i=o.current).onConnected)==null?void 0:l.call(i,s)},onReconnectStarted:()=>{var s,i;return(i=(s=o.current).onReconnectStarted)==null?void 0:i.call(s)},onReconnectSucceeded:()=>{var s,i;return(i=(s=o.current).onReconnectSucceeded)==null?void 0:i.call(s)},onReconnectFailed:()=>{var s,i;return(i=(s=o.current).onReconnectFailed)==null?void 0:i.call(s)},onConnectionLost:()=>{var s,i;return(i=(s=o.current).onConnectionLost)==null?void 0:i.call(s)},onConnectionDelayed:s=>{var i,l;return(l=(i=o.current).onConnectionDelayed)==null?void 0:l.call(i,s)}});return e.addConnectionHandler(n,r),()=>{e.removeConnectionHandler(n)}},[e,n])};function as(e){const{chatSDK:t,logger:n,aiAgentId:o}=X(),{sdkUser:r,activeChannel:s,setActiveChannel:i,statsTrackers:l}=Fe(),c=Ne.useForceUpdate(),[u,m]=d.useState(void 0),[h,g]=d.useState(void 0),[_,y]=d.useState(!1);function v(S){if(S.isAIAgent&&!S.conversation){y(!0);const b=S.initConversation({aiAgentId:o});b.catch(C=>n.warn("useChannel.initConversation: initialization failed",C)),b.finally(()=>y(!1))}}async function f(){var S,b;if(!r){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),m(void 0),g(void 0),y(!1),e){l.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const C=await t.groupChannel.getChannel(e);v(C),m(C),l.initialRender.onGetChannelComplete((S=C.conversation)==null?void 0:S.id),C.url===(s==null?void 0:s.url)&&i({url:C.url,status:le(C)?"closed":"open",conversationStatus:(b=C.conversation)==null?void 0:b.status}),n.debug("useChannel.getChannel: fetched channel",C)}catch(C){l.initialRender.onGetChannelError(C),C instanceof G.SendbirdError&&g(C),n.error("useChannel.getChannel: error",C)}}}return d.useEffect(()=>{f()},[t,r,e,o]),Yt(t,{async onReconnectSucceeded(){var b;if(!u)return;const S=await u.refresh();v(S),m(S),S.url===(s==null?void 0:s.url)&&i({url:S.url,status:le(S)?"closed":"open",conversationStatus:(b=S.conversation)==null?void 0:b.status})}}),Ne.useGroupChannelHandler(t,{onChannelChanged:S=>{S.isGroupChannel()&&S.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",S.url),m(S),c())}}),{channel:u,channelFetchError:h,getChannel:f,isInitializingConversation:_}}const is=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},ls=e=>{var i;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,o=n==null?void 0:n.form,r=!!o&&!o.submitted_at&&!o.canceled_at,s=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return r&&!s},cs=()=>{const{chatSDK:e,networkStateAdapter:t}=X(),[n,o]=d.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Yt(e,{onConnected:()=>o("connected"),onDisconnected:()=>o("disconnected"),onReconnectStarted:()=>o("reconnecting"),onReconnectSucceeded:()=>o("connected"),onReconnectFailed:()=>o("disconnected"),onConnectionLost:()=>o("reconnecting")}),d.useEffect(()=>{if(t)return t.subscribe(()=>{o("reconnecting")})},[t]),n},us=3e4,ds=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:o})=>{const[r,s]=d.useState(!1),i=d.useRef(null),l=t&&ze(t,o)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),s(!1)},u=g=>{i.current&&clearTimeout(i.current),s(!0),i.current=setTimeout(()=>{s(!1),i.current=null},g)},m=Date.now()-l,h=us-m;return n||h<=0?c():u(h),()=>{i.current&&clearTimeout(i.current)}},[n,l]),r&&e},Vn=e=>{const{chatSDK:t}=X(),[n,o]=d.useState([]);return Ne.useGroupChannelHandler(t,{onTypingStatusUpdated(r){if(r.url===(e==null?void 0:e.url)){const s=r.getTypingUsers();o(s)}}}),n},ms=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:o})=>{const[r,s]=d.useState(!1),i=Vn(e);return d.useEffect(()=>{if(!t)return;const l=i.some(u=>u.userId===n),c=ze(t,n)&&(Xe.isStreaming(t)||o);s(c||l)},[i,t,n,o]),r},gs=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:o})=>{const{aiAgentInfo:r,userSession:s}=Fe(),i=cs(),l=ms({channel:e,lastMessage:an(t,[Ae.SendingStatus.SUCCEEDED]),aiAgentUserId:(r==null?void 0:r.userId)??"",isStreamAnimating:n}),c=ds({shouldApply:!!(e!=null&&e.isAIAgent)&&!we(e),isBlockedWhileAIResponding:l,lastMessage:an(t,[Ae.SendingStatus.PENDING,Ae.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""});if(!e||i==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(i==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(le(e))return{disabled:!0,disabledBy:"conversation_closed"};if(ls(e))return{disabled:!0,disabledBy:"form_active"};const u=is(e);return u?{disabled:!0,disabledBy:u}:l||c||o?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},hs=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(r=>{t(s=>{if(s.has(r))return s;const i=new Set(s);return i.add(r),i})},[]),o=d.useCallback(r=>{t(s=>{if(!s.has(r))return s;const i=new Set(s);return i.delete(r),i})},[]);return{isAnimating:e.size>0,start:n,stop:o}},{Provider:fs}=Z("AIAgentConversation");function ps({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:o,onMessagesUpdated:r,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=kt,shouldMarkAsRead:u=!0,shouldCountNewMessages:m=()=>!1,sortComparator:h}){var $;const g=()=>u&&(f==null?void 0:f.markAsRead()),{chatSDK:_,logger:y,dispatcher:v}=X(),{channel:f,channelFetchError:S,getChannel:b,isInitializingConversation:C}=as(t),{statsTrackers:A}=Fe();d.useEffect(()=>{if(t)return A.initialRender.setChannelUrl(t),()=>{A.initialRender.cleanup()}},[t,A]);const w=Lr(_,f,{replyType:Ae.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:R=>o==null?void 0:o(R),onMessagesUpdated:R=>r==null?void 0:r(R),onCacheResult:R=>A.initialRender.onCacheResult(R),onApiResult:R=>A.initialRender.onApiResult(R),logger:y,markAsRead:g,sortComparator:h}),x=hs(),L=gs({channel:f,messages:w.messages,isStreamAnimating:x.isAnimating,isInitializingConversation:C});d.useEffect(()=>{g()},[u]);const V=le(f);d.useEffect(()=>{s==null||s(V)},[V,s]),d.useEffect(()=>{const R=async F=>{const T=typeof(F==null?void 0:F.channelUrl)=="string";f&&T&&F.channelUrl!==f.url||(y.debug("conversation.dispatcher: try to close conversation",f),f!=null&&f.conversation&&f.conversation.status===te.ConversationStatus.OPEN&&(await f.closeConversation(),i==null||i()))};return v.subscribe(Be.ConversationClose,R),()=>{v.unsubscribe(Be.ConversationClose,R)}},[v,($=f==null?void 0:f.conversation)==null?void 0:$.status,i]);const q={conversation:(f==null?void 0:f.conversation)??void 0,channelSource:{channel:f,error:S,refetch:()=>b(),closeConversation:async()=>{le(f)||await(f==null?void 0:f.closeConversation())}},messageSource:{messages:w.messages,newMessages:w.newMessages,initialized:w.initialized,loadPrevious:()=>w.loadPrevious(),loadNext:()=>w.loadNext(),deleteMessage:R=>w.deleteMessage(R),resendMessage:R=>w.resendMessage(R),resetNewMessages:()=>w.resetNewMessages(),sendUserMessage:async R=>{var T;if(((T=f==null?void 0:f.conversation)==null?void 0:T.status)===te.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(R=await l(R));const F=await w.sendUserMessage(R,c);return c==null||c(F),F},sendFileMessage:async R=>{var T;if(((T=f==null?void 0:f.conversation)==null?void 0:T.status)===te.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(R=await l(R));const F=await w.sendFileMessage(R,c);return c==null||c(F),F},sendMultipleFilesMessage:async R=>{var T;if(((T=f==null?void 0:f.conversation)==null?void 0:T.status)===te.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(R=await l(R));const F=await w.sendMultipleFilesMessage(R,c);return c==null||c(F),F}},state:{streamAnimation:x,input:L}};return a.createElement(fs,{value:q},e)}function _s(e,t){var _,y,v,f,S,b,C,A,w,x;const[n,o]=d.useState(!1),[r,s]=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,o(!1),s(null),l([]);try{c==null||c.dispose();const L=new Qo(e,t);L.setConversationListCollectionHandler({onChannelsAdded:()=>{l(L.channels)},onChannelsUpdated:()=>{l(L.channels)},onChannelsDeleted:()=>{l(L.channels)}}),await L.loadMore(),u(L),s(null)}catch(L){u(null),s(L)}finally{o(!0),m.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(v=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:v.join(),(S=(f=t.filter)==null?void 0:f.aiAgentIds)==null?void 0:S.join(),(b=t.filter)==null?void 0:b.deskChannelFilter,(A=(C=t.filter)==null?void 0:C.pinnedChannelUrls)==null?void 0:A.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(x=t.filter)==null?void 0:x.copilotSupportChannelUrl,t.limit]),g=d.useCallback(async()=>{if(c)try{await c.loadMore()}catch(L){s(L)}},[c]);return Yt(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:ys}=Z("AIAgentConversationList");function bs({conversationListLimit:e,conversationListFilter:t,children:n}){var h,g;const{chatSDK:o,aiAgentId:r,queryParams:s}=X(),i={aiAgentIds:[r],aiAgentConversationStatusFilter:[te.ConversationStatus.CLOSED,te.ConversationStatus.OPEN]},l=e??((h=s==null?void 0:s.conversationListParams)==null?void 0:h.limit),c={...i,...(g=s==null?void 0:s.conversationListParams)==null?void 0:g.filter,...t},u=_s(o,{limit:l,filter:c}),m={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return a.createElement(ys,{value:m},n)}function Es(e){let t="pending",n=e.then(o=>{t="resolved",n=o}).catch(o=>{t="rejected",n=o});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:Cs}=Z("MessageTemplateFetching");function vs({children:e,internalVariables:t}){const n=d.useRef({}),o=d.useRef({}),[r,s]=d.useState({}),i=d.useCallback((u,m)=>{s(h=>({...h,[u]:{fetching:!1,error:!1,...h[u],...m}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const _=m(h);if(_)return _;const y=o.current[h];if(y)return y;g||i(h,{fetching:!0});const v=u(h).catch(f=>{throw g||i(h,{error:!0}),f}).finally(()=>{g||i(h,{fetching:!1}),delete o.current[h]});return o.current[h]=v,v},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(u,m)=>{if(n.current[u])return n.current[u];const h=Es(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(Cs,{value:c},e)}const Ss="remove_powered_by",Xt=(e,t)=>{var r,s;const{chatSDK:n}=X(),{aiAgentInfo:o}=Fe();if(e==="handoff-button"){const i=!!((r=t==null?void 0:t.conversation)!=null&&r.handoff);return!!(t!=null&&t.isAIAgent)&&!!(o!=null&&o.showHandoffButton)&&i&&Un(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(o!=null&&o.specialNoticeEnabled)&&!!(o!=null&&o.specialNotice);if(e==="powered-by"){const i=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return d.useMemo(()=>!(Array.isArray(i)&&i.includes(Ss)),[i])}throw new Error("Unsupported feature")},As=e=>{const{aiAgentInfo:t}=Fe(),o=Vn(e)[0];if(!o)return null;const r=o.userId===(t==null?void 0:t.userId);return{user:r?t:o,isBot:r}},qn=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const o=(()=>{const[s]=e.members.filter(i=>i.userId!==t.userId);return s})(),r={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:o==null?void 0:o.profileUrl,title:(o==null?void 0:o.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?we(e)?r.human("agent"):r.ai("delight"):e.isDesk?r.human("agent"):r.channel("user")},Dt=e=>d.useReducer((t,n)=>({...t,...n}),e);var me=(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))(me||{});const Ts=new Set(["free_text","single_choice"]),ws=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:o,initialIsResolved:r})=>{const[s,i]=Dt({csatType:t,csat:n,csatReason:o,isResolved:r}),[l,c]=Dt({followUpItem:!1}),u=d.useMemo(()=>{var f;const _=s.csat,y=typeof _=="number",v=(f=e.follow_up)==null?void 0:f.find(S=>y?S.scores.includes(_):S.always_visible??!1);if(Ts.has(v==null?void 0:v.response_type))return v},[s.csat,e.follow_up]),m=(()=>{var _;if(typeof n=="number")return"submitted";if((t===me.AI_AGENT_CSAT_5||t===me.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===me.AI_AGENT_CSAT_5_WITH_CRE){const y=typeof s.csat=="number",v=!((_=e.cre)!=null&&_.required)||typeof s.isResolved=="boolean";if(y&&v)return"submittable"}return"unsubmittable"})(),h=d.useCallback(()=>typeof s.csat>"u"?!1:u!=null&&u.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,u,c]);return d.useEffect(()=>{o||(i({csatReason:""}),c({followUpItem:!1}))},[o,u,i,c]),{params:s,setParams:i,error:l,setError:c,followUpItem:u,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},ft=5,xs=250,Is=50,En=e=>Math.max(0,e-Is),ks=e=>e<1e3?{speed:ft*.5,chunkSize:2}:e<2e3?{speed:ft*.8,chunkSize:2}:{speed:ft*.6,chunkSize:3},Ms=e=>{const{text:t,enabled:n=!1,onAnimationStart:o,onAnimationProgress:r,onAnimationComplete:s}=e,[i,l]=d.useState(()=>En(t.length)),c=d.useRef(null),u=d.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,m=d.useRef({onStart:o,onProgress:r,onComplete:s}).current,h=d.useRef({startCalled:!1,completeCalled:!1}).current,g=d.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,_=n,y=i<t.length,v=g.initialEnabled&&(_||y);return d.useLayoutEffect(()=>{m.onStart=o,m.onProgress=r,m.onComplete=s,g.textLength=t.length,g.enabled=n}),d.useLayoutEffect(()=>{var f;g.initialEnabled&&(h.startCalled||(h.startCalled=!0,(f=m.onStart)==null||f.call(m)),l(S=>t.length<S?t.length:S))},[t]),d.useEffect(()=>{if(!g.initialEnabled)return;let f=En(t.length);u.lastUpdate=0,u.startTime=0,u.lastProgressCall=0;const S=b=>{var $;u.lastUpdate===0&&(u.lastUpdate=b,u.startTime=b,u.lastProgressCall=b);const C=g.textLength,A=b-u.lastUpdate,w=b-u.startTime,{speed:x,chunkSize:L}=ks(w),V=x*L;A>=V&&f<C&&(f=Math.min(f+L,C),l(f),u.lastUpdate=b),b-u.lastProgressCall>=xs&&(u.lastProgressCall=b,($=m.onProgress)==null||$.call(m)),(f<C||g.enabled)&&(c.current=requestAnimationFrame(S))};return c.current=requestAnimationFrame(S),()=>{c.current&&cancelAnimationFrame(c.current)}},[]),d.useEffect(()=>{var C;const f=g.initialEnabled&&h.startCalled,S=!n,b=i>=t.length&&t.length>0;f&&S&&b&&!h.completeCalled&&(h.completeCalled=!0,(C=m.onComplete)==null||C.call(m))},[n,i,t.length]),{streamText:g.initialEnabled?t.slice(0,i):t,isAnimating:v}},Rs="1.8.0",Wn=Rs,Ls={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"}},Pt={language:"en",strings:Ls,dateLocale:To.enUS},Ds={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:"피드백 삭제"}},Ot={language:"ko",strings:Ds,dateLocale:Ro.ko},Ps={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:"フィードバックを削除"}},Nt={language:"ja",strings:Ps,dateLocale:Mo.ja},Os={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"}},Bt={language:"es",strings:Os,dateLocale:wo.es},Ns={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"}},Ht={language:"pt",strings:Ns,dateLocale:Lo.pt},Bs={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"}},zt={language:"fr",strings:Bs,dateLocale:xo.fr},Hs={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:"प्रतिक्रिया हटाएं"}},Ft={language:"hi",strings:Hs,dateLocale:Io.hi},zs={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"}},Ut={language:"it",strings:zs,dateLocale:ko.it},Fs={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"}},$t={language:"de",strings:Fs,dateLocale:Ao.de},Us={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"}},jt={language:"tr",strings:Us,dateLocale:Do.tr},ce=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}),Cn=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??nt},nt="en",Zt={borderColor:"red",borderWidth:p.StyleSheet.hairlineWidth},E=({debug:e=!1,style:t,children:n,...o})=>a.createElement(p.View,{style:[t,o,e&&Zt],...o},n);E.Animated=({debug:e=!1,style:t,children:n,...o})=>a.createElement(p.Animated.View,{style:[t,o,e&&Zt],...o},n);const{Provider:$s,useContext:oe}=Z("MessengerSession"),js=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof Qe||t.userSessionInfo instanceof Kt))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return a.createElement(rs,{ref:n,...t},o=>a.createElement(Gs,{...o},e))}),Gs=({children:e,...t})=>{const{dispatcher:n}=X(),{userSession:o,aiAgentInfo:r,launcherInfo:s,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(Be.AnonymousSessionTokenExpired,l),()=>n.unsubscribe(Be.AnonymousSessionTokenExpired,l)},[n,i]),a.createElement($s,{value:{...t,userSession:o,aiAgentInfo:r,launcherInfo:s}},e)},Ve=50,{Provider:Vs,useContext:qs}=Z("ConversationScroll"),Ws=({children:e})=>{var T;const{config:t}=X(),n=((T=t==null?void 0:t.conversation)==null?void 0:T.scrollMode)??"auto",o=d.useRef(null),r=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),s=d.useRef(0),[i,l]=d.useState(0),[c,u]=d.useState(0),[m,h]=d.useState(!1),[g,_]=d.useState(!1),y=d.useMemo(()=>g?"auto":n,[g,n]),v=d.useCallback(()=>{const{shouldUpdate:N,shouldRecalc:W,contentHeight:J,contentSnapshotHeight:Ce,viewport:Me}=r.current;N&&Ce<J&&l(he=>{r.current.shouldUpdate=!1;const pe=J-he-Ce,I=Math.max(0,Me-pe);return he===0||I<he||W?(r.current.shouldRecalc=!1,I):he})},[]),f=d.useCallback(N=>{r.current.viewport=N.nativeEvent.layout.height},[]),S=d.useCallback((N,W)=>{r.current.contentHeight=W;const J=r.current.viewport;h(W>J),v()},[v]),b=d.useCallback(N=>{const W=N.nativeEvent.contentOffset.y;s.current=W,u(W)},[]),C=d.useMemo(()=>({minIndexForVisible:0,autoscrollToTopThreshold:Ve}),[]),A=d.useCallback((N=!0)=>{var W;(W=o.current)==null||W.scrollToOffset({offset:0,animated:N})},[]),w=d.useCallback((N,W=!0)=>{var J;(J=o.current)==null||J.scrollToIndex({index:N,animated:W,viewPosition:1})},[]),x=d.useCallback(()=>{y==="fixed"&&(r.current.contentSnapshotHeight=r.current.contentHeight-i,r.current.shouldUpdate=!0,r.current.shouldRecalc=!0)},[y,i]),L=d.useCallback(()=>{y==="fixed"?w(0):A()},[y,A,w]),V=d.useCallback(()=>{y==="fixed"?r.current.shouldUpdate=!0:s.current<=Ve&&A()},[y,A]),q=d.useCallback(N=>{_(N)},[]),$=c<=Ve,R=m&&!$,F=d.useCallback(()=>s.current>Ve,[]);return a.createElement(Vs,{value:{ref:o,state:{bottomSpace:i,isAwayFromBottom:R,shouldCountNewMessages:F},props:{maintainVisibleContentPosition:C,onLayout:f,onContentSizeChange:S,onScroll:b},actions:{scrollToBottom:A,scrollToIndex:w,onBeforeMessageSend:x,onAfterMessageSend:L,onStreamingUpdate:V,onConversationClosed:q}}},e)};function Kn(e){return new Promise((t,n)=>{p.Image.getSize(e,(o,r)=>{t({width:String(o),height:String(r)})},o=>{n(o)})})}async function Ks(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:o,height:r}=await Kn(n.uri);return new Ae.MessageMetaArray({key:On,value:[o,r]})}catch{return}}}function Ys(e,t){let n=0,o=0;return ie(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),ie(t)&&t.sendingStatus!=="succeeded"&&(o=Number.MAX_SAFE_INTEGER),t.createdAt+o-(e.createdAt+n)}const{Provider:Xs,Context:Zs,useContext:ue}=Z("Conversation"),Yn=e=>a.createElement(Ws,null,a.createElement(Js,{...e})),Js=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:o,shouldMarkAsRead:r,children:s})=>{const i=qs(),{activeChannel:l,refreshActiveChannel:c,sdkUser:u,authenticate:m}=oe();d.useEffect(()=>{u||m()},[]);const h=d.useCallback(async v=>{i.actions.onBeforeMessageSend();const f=await Ks(v);return{...v,metaArrays:f?[f]:void 0}},[i.actions.onBeforeMessageSend]),g=d.useCallback(()=>{i.actions.onAfterMessageSend()},[i.actions.onAfterMessageSend]),_=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]),y=e??(l==null?void 0:l.url);return a.createElement(ps,{key:y,channelUrl:y,onBeforeSendMessage:h,onAfterSendMessage:g,onMessagesUpdated:i.actions.onStreamingUpdate,onMessagesReceived:i.actions.onStreamingUpdate,onChannelDeleted:_,onConversationClosedStatusChanged:i.actions.onConversationClosed,sortComparator:Ys,shouldMarkAsRead:r,shouldCountNewMessages:i.state.shouldCountNewMessages},v=>a.createElement(Xs,{value:{...v,scrollSource:i,onClose:n,onNavigateToConversationList:o,updateActiveChannel:_}},s))},pt=ce($t.strings),Qs={...pt,conversation:{...pt.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:{...pt.conversation_list}},ea={language:$t.language,dateLocale:$t.dateLocale,strings:Qs},_t=ce(Pt.strings),ta={..._t,conversation:{..._t.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:{..._t.conversation_list}},na={language:Pt.language,dateLocale:Pt.dateLocale,strings:ta},yt=ce(Bt.strings),oa={...yt,conversation:{...yt.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:{...yt.conversation_list}},ra={language:Bt.language,dateLocale:Bt.dateLocale,strings:oa},bt=ce(zt.strings),sa={...bt,conversation:{...bt.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:{...bt.conversation_list}},aa={language:zt.language,dateLocale:zt.dateLocale,strings:sa},Et=ce(Ft.strings),ia={...Et,conversation:{...Et.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:{...Et.conversation_list}},la={language:Ft.language,dateLocale:Ft.dateLocale,strings:ia},Ct=ce(Ut.strings),ca={...Ct,conversation:{...Ct.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:{...Ct.conversation_list}},ua={language:Ut.language,dateLocale:Ut.dateLocale,strings:ca},vt=ce(Nt.strings),da={...vt,conversation:{...vt.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:{...vt.conversation_list}},ma={language:Nt.language,dateLocale:Nt.dateLocale,strings:da},St=ce(Ot.strings),ga={...St,conversation:{...St.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:{...St.conversation_list}},ha={language:Ot.language,dateLocale:Ot.dateLocale,strings:ga},At=ce(Ht.strings),fa={...At,conversation:{...At.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:{...At.conversation_list}},pa={language:Ht.language,dateLocale:Ht.dateLocale,strings:fa},Tt=ce(jt.strings),_a={...Tt,conversation:{...Tt.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:{...Tt.conversation_list}},ya={language:jt.language,dateLocale:jt.dateLocale,strings:_a},vn=new Map([["en",na],["ko",ha],["ja",ma],["es",ra],["pt",pa],["fr",aa],["hi",la],["it",ua],["de",ea],["tr",ya]]),Sn=e=>vn.get(e)??vn.get(nt),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:Ea,useContext:U}=Z("Localization"),Ca=({language:e=nt,logger:t,strings:n,children:o})=>{const[r,s]=d.useState(()=>{const i=Cn(e);return Sn(i)});return d.useEffect(()=>{var l;const i=Cn(e);if(r.language!==i){const c=Sn(i);s(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:r.language,to:c.language})}},[e,t]),a.createElement(Ea,{value:{language:r.language,strings:ba(r.strings,n),dateLocale:r.dateLocale,format:(i,l,c)=>Se.format(i,l,{locale:r.dateLocale,...c})}},o)},{Provider:va,useContext:ot}=Z("Modal");function Xn({children:e}){const[t,n]=d.useState([]),[o,r]=d.useState(null),s=d.useRef(0);d.useEffect(()=>{if(!o&&t.length>0){const[u,...m]=t;u&&(r(u),n(m))}},[o,t]);const i=d.useCallback(u=>new Promise(m=>{const g={id:`modal-${++s.current}`,render:u,resolve:m};n(_=>[..._,g])}),[]),l=d.useCallback((u,m)=>{r(h=>(h==null?void 0:h.id)===u?(h.resolve(m),null):h)},[]),c={openModal:i,currentModal:o};return a.createElement(va,{value:c},e,o&&a.createElement(p.Modal,{visible:!0,supportedOrientations:["landscape","portrait"],transparent:!0,animationType:"fade",onRequestClose:()=>l(o.id,null),style:{height:0}},o.render(u=>l(o.id,u??null))))}const{Provider:Sa,useContext:j}=Z("MessengerTheme"),Aa=({children:e,...t})=>a.createElement(qr,{...t,appearance:{theme:t.mode??"light"}},n=>{const o=Ta(n.theme);return a.createElement(Sa,{value:{...n,themedColor:o}},e)});function Ta(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=o=>{const r=t.get(o.theme);if(r)return r;const s=e(o),i={},l={};for(const m in s)typeof s[m]=="function"?l[m]=s[m]:i[m]=s[m];const u={...p.StyleSheet.create(i),...l};return t.set(o.theme,u),u};return{use:()=>{const o=j(),r=be.useSafeAreaInsets();return n({...o,edgeInsets:r,select:s=>s[o.theme.selectedTheme]})}}}},wa={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},Ie=(e,t=p.I18nManager.isRTL?"rtl":"ltr")=>{const n=be.useSafeAreaInsets();return e.reduce((o,r)=>{const s=wa[t][r];return o[s]=n[r],o},{})},xa={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")},Ia={send:!0,chat:!0,message:!0,good:!0,bad:!0,"good-filled":!0,"bad-filled":!0},H=({customSource:e,type:t,color:n,size:o=24,style:r})=>{const s=ka.use(),i=p.I18nManager.isRTL&&!!Ia[t];return a.createElement(E,{alignItems:"center",justifyContent:"center"},a.createElement(p.Image,{resizeMode:"contain",source:e??xa[t],style:[s.icon({color:n,size:o,mirror:i}),r]}))},ka=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})})),Jt=(e,t)=>{if(!t||t.length===0)return!1;const n=t.trimStart();if(n.length===0)return!1;const o=e==="start"?Array.from(n)[0]:Array.from(n).pop(),r=o==null?void 0:o.codePointAt(0);return r===void 0?!1:La(r)},Zn=e=>Jt("start",e),Ma=e=>Jt("end",e),Ra=e=>{const{text:t,style:n,isTextInput:o}=e;return n!=null&&n.textAlign&&n.textAlign!=="left"&&n.textAlign!=="right"?n.textAlign:p.I18nManager.isRTL&&typeof t=="string"&&Zn(t)?o?"right":p.I18nManager.doLeftAndRightSwapInRTL?"left":"right":n==null?void 0:n.textAlign},La=e=>{for(const[t,n]of Da)if(e>=t&&e<=n)return!0;return!1},Da=[[1424,1535],[1536,1791],[1872,1919],[2208,2303],[64285,64335],[65136,65279],[126464,126719]],Qt={isStartsWithRTL:Zn,isEndsWithRTL:Ma,isRTLString:Jt,useTextAlign:Ra},M=({variant:e="body1",color:t,style:n,...o})=>{const{theme:r,themedColor:s}=j(),i=d.useMemo(()=>{if(typeof t=="function")return t({theme:r,themedColor:s});if(typeof t=="string")return t;const u=p.StyleSheet.flatten(n);return u&&u.color?u.color:t??s.textHighEmphasis},[n,t,s.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,s.textHighEmphasis]),c=Qt.useTextAlign({text:o.children,style:l});return a.createElement(p.Text,{style:[l,{textAlign:c}],...o})},Jn=350,Pa=({children:e,...t})=>a.createElement(p.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:Jn,...t},n=>typeof e=="function"?e(n):e),Oa=({children:e,style:t,...n})=>{const[o,r]=d.useState(!1),s={pressed:o};return a.createElement(p.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:Jn,style:typeof t=="function"?t(s):t,onPressIn:()=>r(!0),onPressOut:()=>r(!1),...n},typeof e=="function"?e(s):e)},O=e=>e.activeOpacity&&e.activeOpacity<1?a.createElement(Oa,{...e}):a.createElement(Pa,{...e}),{Provider:Na,useContext:Qn}=Z("BottomSheetAnimation");function Ba({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 o=d.useCallback(s=>async()=>{p.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(async()=>{try{await(s==null?void 0:s())}catch{e==null||e()}})},[n]),r=d.useRef(p.PanResponder.create({onMoveShouldSetPanResponder:(s,i)=>i.dy>5,onPanResponderMove:(s,i)=>{i.dy>0&&n.setValue(i.dy)},onPanResponderRelease:(s,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(Na,{value:{wrapWithAnimation:o,translateY:n,panHandlers:r.panHandlers}},t)}const Ha=({icon:e,label:t="",destructive:n=!1,onPress:o})=>{const r=eo.use(),{themedColor:s}=j();return a.createElement(O,{onPress:o,style:r.actionItem,activeOpacity:.75},e&&a.createElement(H,{type:e,size:24,color:s.primary}),a.createElement(M,{variant:"body3",color:n?s.error:s.textHighEmphasis,numberOfLines:1},t))},za=({onClose:e,children:t})=>{const n=eo.use(),{translateY:o,panHandlers:r,wrapWithAnimation:s}=Qn(),i=Ie(["left","right"]);return a.createElement(O,{onPress:s(e),style:n.overlay},a.createElement(E.Animated,{style:[n.container,i,{transform:[{translateY:o}]}],...r},t))},rt=ae({template:za,components:{ActionItem:Ha}}),ne=e=>{const{Template:t}=rt.useContext();return a.createElement(Ba,{onClose:e.onClose},a.createElement(t,{...e}))};ne.ActionItem=e=>{const{components:t}=rt.useContext(),{wrapWithAnimation:n}=Qn();return a.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const eo=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}})),Fa=({style:e,label:t,accessibilityLabel:n,onPress:o})=>{const r=Ua.use(),{theme:s}=j();return a.createElement(O,{style:[r.button,e],onPress:o,accessibilityLabel:n,accessibilityRole:"button"},a.createElement(E,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(M,{variant:"button",color:s.colors.base.primaryContrastContent},t),a.createElement(H,{size:16,type:"chevron-down",color:s.colors.base.primaryContrastContent})))},Ua=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}]}})),en=({iconSize:e=64,icon:t,style:n,label:o,children:r})=>{const{themedColor:s}=j();return a.createElement(E,{style:[to.body,n]},t&&a.createElement(H,{type:t,size:e,color:s.textLowEmphasis}),o&&a.createElement(M,{variant:"body1",color:s.textMidEmphasis},o),r)},$a=({children:e})=>{const{theme:t}=j();return a.createElement(E,{backgroundColor:t.colors.base.background,style:to.container},e)},to=p.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),ja=({label:e,icon:t="error",action:n,...o})=>{const{strings:r}=U();return a.createElement(en,{icon:t,label:e??r.common.placeholder_something_went_wrong,...o},n&&a.createElement(Ga,{onPress:n.onPress,label:n.label??r.common.placeholder_something_went_wrong_retry_label}))},Ga=({label:e,onPress:t})=>{const{themedColor:n}=j();return a.createElement(O,{onPress:t},a.createElement(E,{style:Va.button},a.createElement(H,{type:"refresh",size:20}),a.createElement(M,{variant:"button",color:n.primary},e)))},Va=p.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),qa=({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 o=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(E.Animated,{style:[{transform:[{rotate:o}]},t]},a.createElement(H,{type:"spinner",size:e}))},Wa=({label:e,icon:t="chat",...n})=>{const{strings:o}=U();return a.createElement(en,{icon:t,label:e??o.common.placeholder_no_conversations,...n})},Ka=({label:e,icon:t="message",...n})=>{const{strings:o}=U();return a.createElement(en,{icon:t,label:e??o.common.placeholder_no_messages,...n})},Ya=e=>{const{components:t}=st.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($a,null,n)},st=ae({template:Ya,components:{Loading:qa,Error:ja,NoChannels:Wa,NoMessages:Ka}}),Te=e=>{const{Template:t}=st.useContext();return a.createElement(t,{...e})},Xa=({loading:e,error:t,empty:n,stackDirection:o,data:r=[],LoadingComponent:s,ErrorComponent:i,EmptyComponent:l,...c},u)=>{if(t)return i;if(e)return s;const{contentContainerStyle:m,...h}=c,g=o==="top"&&!n;return a.createElement(p.FlatList,{ref:u,data:r,ListEmptyComponent:n?l:null,contentContainerStyle:[m,g&&An.stackTop,n&&An.emptyContainer],...h})},An=p.StyleSheet.create({stackTop:{flexGrow:1,justifyContent:"flex-end"},emptyContainer:{flex:1}}),no=d.memo(d.forwardRef(Xa)),tn=({name:e,type:t="FILE",onPress:n})=>{const o=Za.use();return a.createElement(O,{onPress:n,style:o.container,activeOpacity:.75},a.createElement(E,{style:o.iconWrapper},a.createElement(H,{type:"file-document",size:24,color:o.icon.tintColor})),a.createElement(E,{flex:1,flexDirection:"column",gap:4,style:o.info},a.createElement(M,{variant:"button",color:({themedColor:r})=>r.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),a.createElement(M,{variant:"caption3",color:({themedColor:r})=>r.textMidEmphasis},t)))},Za=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}})),Ja=({file:e,children:t,onClickFile:n=({url:o})=>p.Linking.openURL(o)})=>a.createElement(E,{gap:D.GAP_GROUPED,width:D.BODY_MAX_WIDTH,maxWidth:D.BODY_MAX_WIDTH},a.createElement(tn,{name:e.name,type:qt(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),xe=({style:e,...t})=>a.createElement(p.Image,{style:[e,t],...t}),Qa=({file:e,onClickMedia:t=({url:o})=>p.Linking.openURL(o),children:n})=>{const o=ei.use();return a.createElement(E,{gap:D.GAP_GROUPED},a.createElement(O,{style:o.mediaContainer,onPress:()=>t==null?void 0:t(e)},a.createElement(xe,{source:{uri:e.url},style:o.media,resizeMode:"cover"})),n)},ei=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%"}})),oo=({code:e,language:t})=>{const[n,o]=d.useState(!1),r=async()=>{zo.default.setString(e),o(!0),setTimeout(()=>o(!1),2e3)};return a.createElement(E,{style:qe.container,flexDirection:"row"},a.createElement(p.Pressable,{style:qe.copyButton,onPress:r},a.createElement(H,{type:n?"done":"copy",size:16,color:"#fff"})),a.createElement(E,null,a.createElement(Fo.default,{hljsStyle:ti,scrollViewProps:{contentContainerStyle:qe.codeContainer,bounces:!1},textStyle:qe.codeText,language:t},e)))},qe=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}}),ti={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"}},ro=d.memo(({src:e,onPress:t})=>{const[n,o]=d.useState("1/1"),[r,s]=d.useState(!1),i=ni.use();return d.useLayoutEffect(()=>{e&&Kn(e).then(({width:l,height:c})=>o(`${l}/${c}`))},[e]),a.createElement(p.Pressable,{style:{marginTop:8},onPress:t},a.createElement(E,{style:[i.container,{aspectRatio:n}]},r?a.createElement(H,{size:28,type:"thumbnail-none",color:({themedColor:l})=>l.textHighEmphasisInverse}):a.createElement(p.Image,{source:{uri:e},style:p.StyleSheet.absoluteFillObject,onError:()=>s(!0)})))}),ni=P.create(({themedColor:e})=>({container:{width:"100%",backgroundColor:e.textDisabled,borderRadius:4,overflow:"hidden",justifyContent:"center",alignItems:"center"}}));ro.displayName="MarkdownImage";const De=e=>d.isValidElement(e)&&"children"in e.props,Gt=(e=.75)=>`rgba(0, 0, 0, ${e})`,oi=({children:e})=>{var i;const t=p.useWindowDimensions(),n=Gt(.3),o=d.useMemo(()=>{try{if(!Array.isArray(e)||e.length<2)return null;const l=e[0],c=e[1],u=De(c)?c.props.children:void 0;if(!u||!Array.isArray(u)||u.length===0)return null;const m=u,h=m[0],g=De(h)?h.props.children:void 0;if(!g||!Array.isArray(g)||g.length===0)return null;const _=m.length,y=g.length,v=Array(y).fill(null).map(()=>[]);for(let C=0;C<_;C++){const A=m[C],w=De(A)?A.props.children:void 0;if(!(!w||!Array.isArray(w)))for(let x=0;x<y;x++){const L=v[x];L&&x<w.length&&(L[C]=w[x])}}const f=De(l)?l.props.children:void 0,S=Array.isArray(f)?f[0]:void 0,b=De(S)?S.props.children:void 0;if(b&&Array.isArray(b))for(let C=0;C<y;C++){const A=v[C];A&&C<b.length&&A.unshift(b[C])}return v}catch{return null}},[e]),[r,s]=d.useState(Array(((i=o==null?void 0:o[0])==null?void 0:i.length)??0).fill(0));return o?a.createElement(p.View,{style:{flexDirection:"row"}},o.map((l,c)=>{const u=c===0,m=c===o.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 _=g===0,y=g===l.length-1;return a.createElement(p.View,{key:g,onLayout:({nativeEvent:{layout:v}})=>{const f=v.height;(r[g]??0)<f&&(r[g]=f,s([...r]))},style:{borderBottomWidth:y?0:1,borderColor:n,backgroundColor:_?Gt(.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)},nn=d.memo(({children:e,textStyle:t,linkStyle:n,onPressImage:o})=>{const{themedColor:r}=j(),s=p.StyleSheet.compose({fontSize:14,color:r.textHighEmphasis,textAlign:"left"},t),i=p.StyleSheet.flatten(s),l=i.fontSize||14,c=i.lineHeight||l*1.286,u=Gt(.3),m={color:i.color,textAlign:Qt.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 y,v;const _=((y=g.attributes)==null?void 0:y.src)||((v=g.attributes)==null?void 0:v.href);return _?a.createElement(ro,{key:g.key,src:_,onPress:()=>o==null?void 0:o(_)}):null},code_block:g=>a.createElement(oo,{code:g.content,language:"text"}),table:(g,_)=>a.createElement(p.View,{key:g.key,style:{marginTop:8}},a.createElement(p.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},a.createElement(oi,null,_)))}),[o]);return a.createElement(E,{flexDirection:"row",marginTop:-8},a.createElement(Uo.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},Yo(e)))});nn.displayName="MarkdownText";const Tn=({maxBodyWidth:e,customStyle:t,message:n,children:o})=>{const r=ri.use(),s=e??D.BODY_MAX_WIDTH,i=d.useMemo(()=>Vo(n),[n]),l=d.useCallback(c=>p.Linking.openURL(c),[]);return i.length===0&&!o?null:a.createElement(E,{alignSelf:"flex-start",maxWidth:s,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(E,{key:u,paddingHorizontal:12},a.createElement(nn,{onPressImage:l,textStyle:r.text},c.value)):c.type==="code"?a.createElement(oo,{key:u,code:c.value,language:c.language}):null),o)},ri=P.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),si=e=>{const{strings:t}=U(),n=()=>{const o=Bn(e)?a.createElement(Tn,{...e}):null;return e.messageType==="user"?o:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(Qa,{...e},o):a.createElement(Ja,{...e},o):a.createElement(Tn,{...e,message:t.conversation.unknown_message_type})};return a.createElement(E,{style:e.containerStyle},n())};function so({id:e,src:t,size:n=56,onClick:o,style:r}){const s=ai.use(),i=a.createElement(p.View,{style:[s.container(n),r],testID:e},t?a.createElement(p.Image,{source:{uri:t},style:s.image}):a.createElement(H,{type:"user",size:n}));return o?a.createElement(O,{onPress:o,activeOpacity:.75},i):i}const ai=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"}})),ii=({sender:e,isBotMessage:t})=>{const n=li.use();return t&&!e.profileUrl?a.createElement(E,{style:n.botContainer},a.createElement(H,{type:"delight",color:({theme:o})=>o.colors.base.primaryContrastContent,size:D.AVATAR_SIZE-8})):a.createElement(so,{src:e.profileUrl,size:D.AVATAR_SIZE})},li=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}})),ci=({sender:e})=>a.createElement(E,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7,alignItems:"flex-start"},a.createElement(M,{variant:"caption1",color:({themedColor:t})=>t.textMidEmphasis,numberOfLines:1},e.nickname)),ui=({createdAt:e,containerStyle:t})=>{const{strings:n,format:o}=U();return e?a.createElement(E,{alignItems:"flex-start",style:t},a.createElement(M,{variant:"caption4",color:({themedColor:r})=>r.textLowEmphasis},o(e,n.date_format.message_timestamp))):null},di=({customStyle:e,containerStyle:t})=>{const{theme:n}=j(),o=d.useRef(new p.Animated.Value(0)).current,r=mi.map(([s,i,l])=>[o.interpolate({inputRange:s,outputRange:i,extrapolate:"clamp"}),o.interpolate({inputRange:s,outputRange:l,extrapolate:"clamp"})]);return d.useEffect(()=>{const s=p.Animated.loop(p.Animated.timing(o,{toValue:1.4,duration:1400,easing:p.Easing.linear,useNativeDriver:!0}));return s.start(),()=>s.reset()},[]),a.createElement(E,{style:t},a.createElement(E,{width:60,flexDirection:"row",alignItems:"center",justifyContent:"center",borderRadius:16,paddingHorizontal:12,height:34,backgroundColor:(e==null?void 0:e.bubbleBackgroundColor)??n.colors.messageIncoming.background},r.map(([s,i],l)=>a.createElement(E.Animated,{key:l,style:[gi.dot,{marginEnd:l===r.length-1?0:6,opacity:i,transform:[{scale:s}],backgroundColor:(e==null?void 0:e.bubbleContentColor)??n.colors.messageIncoming.text}]}))))},mi=[[[.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]]],gi=p.StyleSheet.create({dot:{width:8,height:8,borderRadius:4}}),hi=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>p.Linking.openURL(n)})=>{const n=fi.use(),o=e==null?void 0:e.cta_button;return o?a.createElement(O,{onPress:()=>t(o),activeOpacity:.75,style:n.button},a.createElement(M,{variant:"button",color:({themedColor:r})=>r.textHighEmphasis,numberOfLines:1},o.label)):null},fi=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})}})),pi=({extendedMessagePayload:e,onClickCitation:t=n=>p.Linking.openURL(n.link)})=>{const{strings:n}=U(),{theme:o}=j(),r=e==null?void 0:e.citations;return!r||r.length===0?null:a.createElement(E,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},a.createElement(M,{variant:"caption1",color:o.colors.messageIncoming.text,style:wn.sourceLabel},n.conversation.citation_title),a.createElement(E,{gap:8},r.map(s=>a.createElement(O,{key:s.embedding_id,onPress:()=>t(s),activeOpacity:.5},a.createElement(E,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(H,{type:"source",size:16,color:o.colors.messageIncoming.text}),a.createElement(E,{flex:1},a.createElement(M,{variant:"body3",color:o.colors.messageIncoming.text,numberOfLines:1,style:wn.citationText},s.title)))))))},wn=p.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),_i=e=>a.createElement(a.Fragment,null),Vt=e=>`${e}-filled`,yi=e=>e==="good"?te.AIAgentMessageFeedbackRating.GOOD:te.AIAgentMessageFeedbackRating.BAD,xn=({onClose:e,isEdit:t,initialRating:n,initialComment:o="",isCommentEnabled:r=!1})=>{const{strings:s}=U(),{themedColor:i,theme:l}=j(),c=bi.use(),[u,m]=d.useState(o),[h,g]=d.useState(n),_=()=>{h&&e({rating:h,comment:u.trim()||void 0})},y=()=>{e()},v={good:i.secondary,bad:i.error};return a.createElement(p.KeyboardAvoidingView,{style:{flex:1},behavior:"padding"},a.createElement(O,{onPress:y,style:c.overlay},a.createElement(E,{width:280,backgroundColor:l.colors.base.modalContentBackground,borderRadius:12,overflow:"hidden",onStartShouldSetResponder:()=>!0},a.createElement(E,{padding:24},a.createElement(M,{variant:"h2",color:i.textHighEmphasis},s.feedback.title)),a.createElement(E,{paddingHorizontal:24,gap:24},a.createElement(E,{flexDirection:"row",gap:4},["good","bad"].map(f=>{const S=h===f,b=f==="good"?s.feedback.good:s.feedback.bad;return a.createElement(O,{key:f,onPress:()=>g(f),activeOpacity:.6,style:c.ratingButton(S)},a.createElement(H,{type:S?Vt(f):f,size:24,color:S?v[f]:i.textLowEmphasis}),a.createElement(M,{variant:"caption1",color:S?v[f]:i.textLowEmphasis},b))})),r&&a.createElement(E,{gap:6},a.createElement(M,{variant:"caption3",color:i.textHighEmphasis},s.feedback.comment_label),a.createElement(p.TextInput,{value:u,onChangeText:f=>m(f),placeholder:s.feedback.comment_placeholder,placeholderTextColor:i.textLowEmphasis,multiline:!0,maxLength:100,style:c.commentInput}))),a.createElement(E,{paddingHorizontal:24,paddingVertical:16,flexDirection:"row",justifyContent:"flex-end",gap:4},a.createElement(O,{onPress:y,activeOpacity:.6,style:c.cancelButton},a.createElement(M,{variant:"button",color:i.textHighEmphasis},s.feedback.cancel)),a.createElement(O,{onPress:_,disabled:!h,activeOpacity:.6,style:c.submitButton(!h)},a.createElement(M,{variant:"button",color:l.colors.base.primaryContrastContent},t?s.feedback.save:s.feedback.submit))))))},bi=P.create(({select:e,theme:t,themedColor:n})=>({overlay:{flex:1,backgroundColor:t.palette.overlay.dark,alignItems:"center",justifyContent:"center"},ratingButton:o=>({width:114,height:64,borderRadius:12,borderWidth:1,borderColor:n.textDisabled,alignItems:"center",justifyContent:"center",gap:0,backgroundColor:o?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:o=>({width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center",backgroundColor:t.colors.base.primary,opacity:o?.4:1})})),Ei=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:o,isFeedbackCommentEnabled:r,extendedMessagePayload:s,onFeedbackUpdate:i,containerStyle:l})=>{const{strings:c}=U(),{themedColor:u}=j(),{openModal:m}=ot(),h=Ci.use(),g=s==null?void 0:s.feedback,_=(g==null?void 0:g.rating)??"none";if(_!=="none"?!1:!!(n||!e||!o||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const v={good:u.secondary,bad:u.error},f=async C=>{const A=await m(w=>a.createElement(xn,{onClose:w,isEdit:!1,initialRating:C,initialComment:"",isCommentEnabled:r}));A&&(i==null||i(A))},S=async()=>{const C=await m(A=>a.createElement(ne,{onClose:()=>A()},a.createElement(ne.ActionItem,{onPress:()=>A("edit"),label:c.feedback.edit}),a.createElement(ne.ActionItem,{onPress:()=>A("remove"),label:c.feedback.remove,destructive:!0})));if(C==="edit"){const A=await m(w=>a.createElement(xn,{onClose:w,isEdit:!0,initialRating:g==null?void 0:g.rating,initialComment:g==null?void 0:g.comment,isCommentEnabled:r}));A&&(i==null||i(A))}else C==="remove"&&(i==null||i(null))},b=()=>t&&_!=="none"?a.createElement(E,{flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:D.BODY_MAX_WIDTH},a.createElement(E,{padding:2,flexShrink:0,alignItems:"center"},a.createElement(H,{type:Vt(_),size:12,color:v[_]})),(g==null?void 0:g.comment)&&a.createElement(M,{variant:"caption2",style:h.commentText},g.comment)):a.createElement(E,{gap:4,maxWidth:D.BODY_MAX_WIDTH},a.createElement(E,{flexDirection:"row",gap:2},["good","bad"].map(C=>{const A=_===C;return a.createElement(O,{key:C,onPress:()=>{_==="none"?f(C):S()},activeOpacity:.6,style:h.feedbackButton(A)},a.createElement(H,{type:A?Vt(C):C,size:14,color:A?v[C]:u.textMidEmphasis}))})),_!=="none"&&(g==null?void 0:g.comment)&&a.createElement(M,{variant:"caption2",style:h.commentText},g.comment));return a.createElement(E,{style:l},b())},Ci=P.create(({select:e,theme:t,themedColor:n})=>({feedbackButton:o=>({width:38,height:20,borderRadius:18,alignItems:"center",justifyContent:"center",borderWidth:1,borderColor:e({light:t.palette.background200,dark:t.palette.background400}),backgroundColor:o?e({light:t.palette.background100,dark:t.palette.background500}):"transparent"}),commentText:{lineHeight:16,color:e({light:n.textMidEmphasis,dark:n.textHighEmphasis})}})),vi=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},Si=e=>null,ao=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:o,...r})=>a.createElement(p.ScrollView,{style:[t,r,e&&Zt],showsHorizontalScrollIndicator:n,...r},o),Ai=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const o=Ti.use(),[r,s]=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}),s(!0)},u=()=>i.map((m,h)=>a.createElement(O,{key:h,style:o.itemContainer,onPress:()=>c(m)},a.createElement(M,{variant:"body3",color:({themedColor:g})=>g.primary},m)));return l?a.createElement(E,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:D.HORIZONTAL_PADDING},u()):a.createElement(ao,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:o.horizontalContainer},u())},Ti=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}})),wi=e=>{var f,S,b,C,A,w,x;const{components:t}=at.useContext(),{streamText:n,isAnimating:o}=Ms({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),r={...e,message:n,extendedMessagePayload:o?{}:e.extendedMessagePayload},s=!!r.isTyping,i=!!r.isSenderAvatarVisible,l=!!((f=r.extendedMessagePayload)!=null&&f.form)&&!((S=r.extendedMessagePayload)!=null&&S.form.canceled_at),c=!!((b=r.extendedMessagePayload)!=null&&b.message_template),u=!!((C=r.extendedMessagePayload)!=null&&C.cta_button),m=!!((A=r.extendedMessagePayload)!=null&&A.citations)&&r.extendedMessagePayload.citations.length>0,h=!!r.createdAt,g=r.groupType==="top"||r.groupType==="single",_=r.groupType==="bottom"||r.groupType==="single",y=i?D.AVATAR_SIZE:0,v=xi.use();return a.createElement(E,{marginBottom:s?0:Wt(r.groupType)},g&&a.createElement(E,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:D.HORIZONTAL_PADDING},i&&a.createElement(t.SenderAvatar,{...r}),a.createElement(t.SenderName,{...r})),a.createElement(E,{gap:D.GAP_GROUPED},s?a.createElement(t.TypingIndicator,{...r,containerStyle:v.middleArea(y)}):a.createElement(t.MessageBody,{...r,containerStyle:v.middleArea(y)},u&&a.createElement(E,{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:((x=(w=r.extendedMessagePayload)==null?void 0:w.message_template)==null?void 0:x.fallback_message)??"Cannot read this template.",containerStyle:v.middleArea(y)}),messageTemplateLoadingFallback:r.messageTemplateLoadingFallback??a.createElement(t.TypingIndicator,{...r,containerStyle:v.middleArea(y)})}),a.createElement(t.CustomMessageTemplate,{...r}),l&&a.createElement(t.Form,{...r,containerStyle:v.middleArea(y)})),_&&h&&a.createElement(t.SentTime,{...r,containerStyle:v.bottomArea(y)}),a.createElement(d.Fragment,null,!s&&a.createElement(t.Feedback,{...r,containerStyle:v.feedbackArea(y)}),r.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...r})))},at=ae({template:wi,components:{SenderName:ci,SenderAvatar:ii,SentTime:ui,MessageBody:si,TypingIndicator:di,SuggestedReplies:Ai,MessageTemplate:Si,CustomMessageTemplate:_i,CTAButton:hi,Citation:pi,Form:vi,Feedback:Ei}}),xi=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})})),Ii=({file:e,children:t,sendingStatus:n,onClickFile:o=({url:r})=>p.Linking.openURL(r)})=>{const r=(()=>{if(!(!o||n!=="succeeded"))return()=>o(e)})();return a.createElement(E,{flexDirection:"column",alignItems:"flex-end",gap:D.GAP_GROUPED,width:D.BODY_MAX_WIDTH,maxWidth:D.BODY_MAX_WIDTH},a.createElement(tn,{name:e.name,type:qt(e.name,e.type),onPress:r}),t)},io=({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 o=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(E.Animated,{style:{transform:[{rotate:o}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??a.createElement(H,{type:"spinner",size:e}))};function ki(e){return typeof e=="object"&&e!==null&&"uri"in e}const Mi=({file:e,metadata:t,sendingStatus:n,onClickMedia:o=({url:s})=>p.Linking.openURL(s),children:r})=>{const s=Ri.use(),{aspectRatio:i,localFile:l}=t,[c]=d.useState(()=>ki(l)?l.uri:e.url),[u,m]=d.useState(!1),h=(()=>{if(!(!o||n!=="succeeded"))return()=>o(e)})();return a.createElement(E,{flexDirection:"column",alignItems:"flex-end",gap:D.GAP_GROUPED},a.createElement(O,{onPress:h,style:[s.imageContainer,{aspectRatio:i}],activeOpacity:.75},!u&&a.createElement(E,{alignItems:"center",justifyContent:"center"},a.createElement(io,{size:26},a.createElement(H,{type:"spinner",color:({themedColor:g})=>g.textLowEmphasis,size:26}))),a.createElement(xe,{source:{uri:c},style:[s.image,{opacity:u?1:0}],resizeMode:"cover",onLoad:()=>m(!0)})),r)},Ri=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}})),In=e=>{var n,o;const t=Li.use();return a.createElement(E,{style:[t.container({maxWidth:e.maxBodyWidth??D.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},a.createElement(M,{variant:"body3",style:[t.text,((o=e.customStyle)==null?void 0:o.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},Li=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}})),Di=e=>{const{strings:t}=U(),n=()=>{const o=Bn(e)?a.createElement(In,{...e}):null;return e.messageType==="user"?o:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(Mi,{...e},o):a.createElement(Ii,{...e},o):a.createElement(In,{...e,message:t.unknown_message_type})};return a.createElement(O,{onPress:e.sendingStatus==="failed"?e.onClickFailedMessage:void 0,activeOpacity:.75},a.createElement(E,{style:e.containerStyle},n()))},Pi=({sendingStatus:e,containerStyle:t})=>{const{themedColor:n}=j(),o=()=>{switch(e){case"pending":return a.createElement(E,{marginBottom:2},a.createElement(io,{size:16},a.createElement(H,{type:"spinner",color:n.primary,size:16})));case"failed":return a.createElement(E,{marginBottom:2},a.createElement(H,{type:"error",color:n.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement(E,{marginBottom:2},a.createElement(H,{type:"done",color:n.secondary,size:16}))}};return a.createElement(E,{style:t},o())},Oi=({createdAt:e,containerStyle:t})=>{const{format:n,strings:o}=U();return e?a.createElement(E,{style:t},a.createElement(M,{variant:"caption4",color:({themedColor:r})=>r.textLowEmphasis},n(e,o.date_format.message_timestamp))):null},Ni=e=>{const{components:t}=it.useContext(),n=e.sendingStatus==="succeeded",o=e.groupType==="bottom"||e.groupType==="single";return a.createElement(E,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:Wt(e.groupType)},a.createElement(t.MessageBody,{...e,containerStyle:wt.middleArea}),o&&(n?a.createElement(t.SentTime,{...e,containerStyle:wt.bottomArea}):a.createElement(t.SendingStatus,{...e,containerStyle:wt.bottomArea})))},it=ae({template:Ni,components:{SendingStatus:Pi,SentTime:Oi,MessageBody:Di}}),wt=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}}),Bi=e=>e.messageType!=="admin"?null:a.createElement(M,{variant:"caption2",color:({themedColor:t})=>t.textMidEmphasis,style:{textAlign:"center"}},Hi(e.message)),Hi=e=>{try{const t=[];let n=e,o=0;for(;n;){const r=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),s=n.match(/\*\*([^*]+)\*\*/),i=[r&&{match:r,type:"link"},s&&{match:s,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:o++,onPress:()=>p.Linking.openURL((c==null?void 0:c[2])??""),style:{textDecorationLine:"underline"}},c[1])):u==="bold"&&t.push(a.createElement(p.Text,{key:o++,style:{fontWeight:"bold"}},c[1])),n=n.slice(m+c[0].length)}return t.filter(r=>r!=="")}catch{return[e]}},zi=({children:e,style:t})=>a.createElement(M,{variant:"caption4",color:({themedColor:n})=>n.error,style:t},e),Fi=({children:e,style:t,required:n})=>{const{strings:o}=U();return a.createElement(M,{variant:"caption3",color:({themedColor:r})=>r.textMidEmphasis,style:t},e,!n&&a.createElement(M,{variant:"caption3",color:({themedColor:r})=>r.textLowEmphasis},` (${o.form.optional_label})`))},Ui=({style:e})=>{const t=$i.use();return a.createElement(E,{style:[t.separator,e]})},$i=P.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),ji=({value:e="",onChange:t,placeholder:n,variant:o="single-line",error:r=!1,submitted:s=!1,style:i,disabled:l=!1,maxLength:c})=>{const[u,m]=d.useState(!1),h=Gi.use(),{themedColor:g}=j(),_=y=>{c&&y.length>c||t==null||t(y)};return a.createElement(p.TextInput,{value:e,onChangeText:_,placeholder:n,editable:!l&&!s,maxLength:c,multiline:o==="multi-line",style:[h.input(o,r,s,u),i],placeholderTextColor:g.textLowEmphasis,onFocus:()=>m(!0),onBlur:()=>m(!1)})},Gi=P.create(({select:e,theme:t,themedColor:n})=>({input:(o,r,s,i)=>{let l,c;s?(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:s?n.textLowEmphasis:n.textHighEmphasis};return o==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),Oe={Label:Fi,ErrorLabel:zi,TextInput:ji,Separator:Ui},lo=({onClick:e,checked:t,label:n,disabled:o,labelVariant:r="caption2"})=>{const{themedColor:s}=j(),i=Vi.use(),l=t?s.primary:o?s.textDisabled:s.textLowEmphasis;return a.createElement(O,{disabled:o||!e,onPress:e},a.createElement(E,{style:i.container},a.createElement(E,{style:i.iconContainer},a.createElement(H,{size:20,type:t?"radio-on":"radio-off",color:l})),a.createElement(M,{variant:r,style:i.label(t,o)},n)))},Vi=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 o;return t?o=e.textHighEmphasis:n?o=e.textLowEmphasis:o=e.textHighEmphasis,{flex:1,color:o,lineHeight:20}}})),qi=({csatPayload:e,submitted:t,defaultValue:n,value:o,onChange:r})=>(d.useEffect(()=>{typeof o>"u"&&typeof n=="boolean"&&(r==null||r(n))},[o,n,r]),e.cre?a.createElement(E,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(Oe.Label,{required:e.cre.required},e.cre.question),a.createElement(E,{flexDirection:"column",gap:8,width:"100%"},[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(s=>a.createElement(lo,{key:s.label,checked:o===s.value,label:s.label,disabled:t,onClick:()=>r==null?void 0:r(s.value)})))):null),Wi=({followUpItem:e,submitted:t,value:n="",onChange:o,hasError:r})=>{const{strings:s}=U();return a.createElement(E,{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=>o(i),error:r}),e.response_type==="single_choice"&&a.createElement(E,{flexDirection:"column",gap:8,width:"100%"},e.options.map(i=>a.createElement(lo,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>o==null?void 0:o(i),labelVariant:"body3"}))),r&&a.createElement(Oe.ErrorLabel,null,s.form.validation_required))},Ki=e=>null,Yi=({csatPayload:e,submitted:t,value:n,onChange:o})=>{const r=typeof n>"u",s=co.use(),[i,l]=d.useState(16);return a.createElement(E,{onLayout:c=>{c.nativeEvent.layout.width<300&&l(0)},flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(M,{variant:"caption3",color:({themedColor:c})=>c.textMidEmphasis},e.csat_question),a.createElement(E,{style:[s.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:()=>o(h),style:s.scoreButton},a.createElement(Xi,{value:h,selected:r||g,label:c,src:u}),!!c&&a.createElement(M,{style:{textAlign:"center"},variant:"caption3",color:({themedColor:_})=>g?_.textHighEmphasis:_.textLowEmphasis,lineBreakStrategyIOS:"standard",textBreakStrategy:"simple"},c))})))},Xi=({value:e,src:t,label:n,selected:o})=>{const[r,s]=d.useState(!1),i=co.use();return r?a.createElement(Ki,{value:e,selected:o,label:n}):a.createElement(xe,{source:{uri:t},style:i.emojiImage(o),onError:()=>s(!0),accessibilityLabel:n})},co=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})})),Zi=({csatPayload:e})=>a.createElement(M,{style:{textAlign:"left"},variant:"button",color:({themedColor:t})=>t.textHighEmphasis},e.title),xt=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:o,initialCsatReason:r,initialIsResolved:s})=>{const{params:i,setParams:l,error:c,setError:u,followUpItem:m,state:h,validateParams:g,itemProps:_}=ws({csatPayload:e,type:t,initialCsat:o,initialCsatReason:r,initialIsResolved:s});return a.createElement(a.Fragment,null,a.createElement(E,{flexDirection:"column",gap:12},a.createElement(Zi,{..._}),t===me.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(qi,{..._,defaultValue:s,value:i.isResolved,onChange:y=>l({isResolved:y})}),a.createElement(Yi,{..._,value:i.csat,onChange:y=>l({csat:y})}),m&&a.createElement(Wi,{..._,followUpItem:m,value:i.csatReason,onChange:y=>{l({csatReason:y}),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})))},Ji=e=>{const{strings:t}=U();return yr(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})},Qi=()=>{const{strings:e}=U();return a.createElement(M,{variant:"body2",color:({themedColor:t})=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},el=({onMount:e,children:t})=>(d.useEffect(()=>{e==null||e()},[]),a.createElement(a.Fragment,null,t)),tl=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n,onScrollToBottom:o}=e,{csat:r,csatReason:s,csatExpireAt:i,isResolvedWhenDeterminedByUser:l}=e,[,c]=d.useState(0),u=Ji(t==null?void 0:t.csat),m=d.useRef(!1),h=nl.use();if(!u||!u.visibility||!me[u.type])return null;const g=u.type===me.AI_AGENT_CSAT_5||u.type===me.AI_AGENT_CSAT_5_WITH_CRE||u.type===me.HELPDESK_CSAT_5?xt:()=>null;return a.createElement(E,{style:h.container},!r&&dn(i)?a.createElement(Qi,null):a.createElement(g,{csatPayload:u,type:u.type,initialCsat:r,initialCsatReason:s,initialIsResolved:l,renderSubmitButton:({state:_,params:y,validateParams:v})=>a.createElement(el,{onMount:o},a.createElement(O,{activeOpacity:.75,disabled:_==="submitted",onPress:async()=>{m.current||(!dn(i)&&v()?(m.current=!0,await n(y).finally(()=>{m.current=!1})):c(f=>f+1))},style:h.submitButton(_)},a.createElement(M,{variant:"button",style:h.submitButtonText(_)},_==="submitted"?u.csat_submitted_label:u.csat_submit_label)))}))},nl=P.create(({theme:e,themedColor:t})=>({container:{flexDirection:"column",backgroundColor:e.colors.csat.background,borderRadius:16,gap:16,padding:16},submitButton:n=>{let o;return n==="submitted"||n==="unsubmittable"?o=t.textDisabled:o=e.colors.base.primary,{backgroundColor:o,borderRadius:6,padding:10,paddingHorizontal:20,alignItems:"center",justifyContent:"center"}},submitButtonText:n=>{let o;return n==="submitted"?o=t.textHighEmphasis:n==="unsubmittable"?o=t.textLowEmphasis:o=e.colors.base.primaryContrastContent,{color:o}}})),ol=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(E,{paddingHorizontal:D.HORIZONTAL_PADDING,marginBottom:Wt(e.groupType)},n)},lt=ae({template:ol,components:{AdminMessage:Bi,CSATMessage:tl}}),rl=({style:e,...t})=>{const{strings:n}=U();if(!Xt("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(E,{style:[sl.container,e],...t},a.createElement(M,{variant:"caption2",color:({themedColor:s})=>s.textLowEmphasis},n.conversation.powered_by+" "),a.createElement(O,{onPress:r},a.createElement(M,{variant:"caption2",color:({themedColor:s})=>s.textLowEmphasis},"Sendbird")))},sl=p.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),al=()=>{var l;const{strings:e}=U(),{channelSource:t,scrollSource:n,updateActiveChannel:o}=ue(),r=il.use(),s=le(t.channel),i=d.useRef(s);return d.useEffect(()=>{const c=i.current;i.current=s,!c&&s&&n.actions.scrollToBottom()},[s,n]),!((l=t.channel)!=null&&l.isAIAgent)||!s?null:a.createElement(E,{justifyContent:"center",flexDirection:"row",style:r.wrapper},a.createElement(O,{activeOpacity:.75,onPress:()=>o(),style:r.button},a.createElement(M,{variant:"button",role:"button",color:({themedColor:c})=>c.textHighEmphasis},e.conversation.start_new_conversation_label)))},il=P.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),ll=({date:e=Date.now(),style:t,...n})=>{const{format:o,strings:r}=U();return a.createElement(E,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},a.createElement(M,{variant:"caption4",color:({themedColor:s})=>s.textMidEmphasis},o(e,r.date_format.date_separator)))},cl=({style:e,onPress:t})=>{const n=ul.use(),{theme:o}=j();return a.createElement(O,{style:[n.button,e],onPress:t},a.createElement(E,{alignItems:"center",justifyContent:"center"},a.createElement(H,{size:24,type:"chevron-down",color:o.colors.base.primary})))},ul=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}]}})),dl=()=>null,on=ae({template:dl,components:{DateSeparator:ll,ScrollToBottomButton:cl}}),ml=(e,t)=>!So.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),gl=({messageStackDirection:e="top"})=>{var R,F;const{Template:t}=at.useContext(),{Template:n}=it.useContext(),{Template:o}=lt.useContext(),{components:r}=on.useContext(),{openModal:s}=ot(),{strings:i}=U(),{config:l,cache:c,chatSDK:u}=X(),{aiAgentInfo:m,userSession:h,connectionError:g}=oe(),{conversation:_,messageSource:y,channelSource:v,scrollSource:f,state:{input:S,streamAnimation:b}}=ue(),C=hl.use(),A=Ie(["left","right"]),w=As(v.channel);d.useEffect(()=>{f.state.isAwayFromBottom||y.resetNewMessages()},[f.state.isAwayFromBottom]);const x=(T,N=!1)=>{var W;return N?m??{nickname:"",profileUrl:""}:((W=v.channel)==null?void 0:W.members.find(J=>J.userId===T.sender.userId))??T.sender},L=T=>{if(T.sendingStatus==="failed"&&!S.disabled)return()=>{s(N=>a.createElement(ne,{onClose:()=>N()},a.createElement(ne.ActionItem,{label:i.conversation.failed_message_resend,onPress:async()=>{y.resendMessage(T),N()}}),a.createElement(ne.ActionItem,{destructive:!0,label:i.conversation.failed_message_remove,onPress:async()=>{y.deleteMessage(T),N()}})))}},V=({item:T,index:N})=>{const W=y.messages[N+1],J=y.messages[N-1],Ce=(()=>{var B,z,re;const he=!(m!=null&&m.isUserFeedbackEnabled&&ze(T,m==null?void 0:m.userId)&&!Xe.isWelcomeMessage(T)),pe=jo(T,W,J,he),I={data:T.data,extendedMessagePayload:T.extendedMessagePayload,message:T.message,createdAt:T.createdAt,groupType:pe};if(Ue.isAdmin(T))return Ue.isCSAT(T)?_?a.createElement(o,{...I,..._,messageType:"admin.csat",isResolvedWhenDeterminedByUser:pr(_),onSubmitCSAT:async Q=>{var se;await((se=v.channel)==null?void 0:se.submitCSAT(Q))},onScrollToBottom:()=>f.actions.scrollToBottom()}):null:a.createElement(o,{...I,messageType:"admin"});if(Ue.isOutgoing(T,(h==null?void 0:h.userId)??"")){const Q={...I,sender:x(T),sendingStatus:T.sendingStatus,onClickFailedMessage:L(T)};if(T.isUserMessage())return a.createElement(n,{...Q,messageType:"user"});if(T.isFileMessage()){const[se,Re]=((B=T.metaArrays.find(K=>K.key===On))==null?void 0:B.value)??[];return a.createElement(n,{...Q,messageType:"file",file:T,metadata:{aspectRatio:se&&Re?`${se}/${Re}`:"1/1",localFile:(z=T.messageParams)==null?void 0:z.file}})}}if(Ue.isIncoming(T,(h==null?void 0:h.userId)??"")){const Q=T.sender.userId===(m==null?void 0:m.userId),se=N===0,Re={...I,sender:x(T,Q),suggestedRepliesVisible:se,isBotMessage:Q,isStreaming:Xe.isStreaming(T),isHandedOff:we(v.channel),isConversationClosed:le(v.channel),isFeedbackEnabled:m==null?void 0:m.isUserFeedbackEnabled,isFeedbackCommentEnabled:m==null?void 0:m.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(re=l==null?void 0:l.conversation)==null?void 0:re.senderAvatarEnabled,onClickSuggestedReply:async({reply:K})=>{y.sendUserMessage({message:K})},onRequestMessageTemplate:async K=>{const{template:de}=await u.aiAgent.getMessageTemplate(K);return c.template.set(K,de),de},onGetCachedMessageTemplate:K=>c.template.get(K),onHandleTemplateInternalAction:K=>{if(K.type==="internal"&&K.internalData){const{method:de,payload:_e}=K.internalData;de==="message.send"&&(_e!=null&&_e.message)&&y.sendUserMessage({message:_e.message})}},onFeedbackUpdate:K=>{const de={messageId:T.messageId,channelUrl:T.channelUrl};if(!K)return u.aiAgent.deleteMessageFeedback(de);const _e={...de,rating:yi(K.rating),comment:K.comment};return Xe.hasFeedback(T)?u.aiAgent.updateMessageFeedback(_e):u.aiAgent.createMessageFeedback(_e)},onSubmitForm:({key:K,data:de})=>u.aiAgent.submitForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:K,formData:de}),onCancelForm:({key:K})=>u.aiAgent.cancelForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:K}),onStreamAnimationStart:()=>{b.start(T.messageId)},onStreamAnimationProgress:()=>{f.actions.onStreamingUpdate()},onStreamAnimationComplete:()=>{b.stop(T.messageId),f.actions.onStreamingUpdate()}};if(T.isUserMessage())return a.createElement(t,{...Re,messageType:"user"});if(T.isFileMessage())return a.createElement(t,{...Re,messageType:"file",file:T})}return null})(),Me=ml(T,W)&&a.createElement(r.DateSeparator,{date:T.createdAt,style:C.dateSeparator});return a.createElement(E,null,Me,Ce)},q=()=>a.createElement(rl,{style:C.poweredBy}),$=()=>{var T,N;return a.createElement(a.Fragment,null,w&&a.createElement(E,{marginTop:y.messages.length===0?8:0},a.createElement(t,{isTyping:!0,isBotMessage:w.isBot,sender:w.user,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(T=l==null?void 0:l.conversation)==null?void 0:T.senderAvatarEnabled})),((N=l==null?void 0:l.conversation)==null?void 0:N.isTalkToAgentViewEnabled)&&a.createElement(al,null),f.state.bottomSpace?a.createElement(E,{height:f.state.bottomSpace}):null)};return a.createElement(E,{flex:1},a.createElement(no,{ref:f.ref,style:C.list,contentContainerStyle:[C.listContent,A],stackDirection:e,data:y.messages,onEndReached:y.loadPrevious,keyExtractor:$o,renderItem:V,loading:!y.initialized||!v.channel,empty:y.messages.length===0&&!w,error:!!(g||v.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)??((R=v.error)==null?void 0:R.message),action:v.error?{label:i.common.placeholder_something_went_wrong_retry_label,onPress:()=>v.refetch()}:void 0}),ListFooterComponent:q(),ListHeaderComponent:$(),inverted:!0,...f.props}),((F=l==null?void 0:l.conversation)==null?void 0:F.newMessageIndicatorEnabled)&&f.state.isAwayFromBottom&&y.newMessages.length>0&&a.createElement(E,{style:C.newMessagesButtonContainer},a.createElement(Fa,{label:i.conversation.scroll_to_new_messages_label(y.newMessages),accessibilityLabel:i.conversation.a11y_scroll_to_new_messages,onPress:()=>f.actions.scrollToBottom()})),f.state.isAwayFromBottom&&y.newMessages.length===0&&a.createElement(r.ScrollToBottomButton,{style:C.scrollButtonContainer,onPress:()=>f.actions.scrollToBottom()}))},hl=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"}})),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 fl(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(kn)},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(kn)}}}function pl(e,t){const n=async()=>{const r=p.Platform.select({ios:t.PERMISSIONS.IOS.CAMERA,android:t.PERMISSIONS.ANDROID.CAMERA});if(!r)return;const s=await t.request(r);if(s!=="granted"&&s!=="limited")throw new Error(ge.CAMERA_PERMISSION_DENIED)},o=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 s=await t.requestMultiple(r);if(!Object.values(s).every(l=>l==="granted"||l==="limited"))throw new Error(ge.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(ge.CAMERA_PERMISSION_DENIED):new Error(r.errorMessage||`Camera error: ${r.errorCode}`);return!r.assets||r.assets.length===0?null:r.assets.map(Mn)},selectFromGallery:async r=>{await o();const s=await e.launchImageLibrary({mediaType:"photo",selectionLimit:(r==null?void 0:r.selectionLimit)??1,assetRepresentationMode:"compatible"});if(s.didCancel)return null;if(s.errorCode)throw s.errorCode==="permission"?new Error(ge.GALLERY_PERMISSION_DENIED):new Error(s.errorMessage||`Gallery error: ${s.errorCode}`);return!s.assets||s.assets.length===0?null:s.assets.map(Mn)}}}function _l(e){return{selectFile:async t=>{const n=(t==null?void 0:t.mimeTypes)??["*/*"],o=await e.getDocumentAsync({multiple:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:n});return o.canceled||!o.assets||o.assets.length===0?null:o.assets.map(bl)}}}function yl(e){return{selectFile:async t=>{try{const n=(t==null?void 0:t.mimeTypes)??["*/*"],o=p.Platform.select({android:n,ios:void 0}),r=await e.pick({mode:"open",allowMultiSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:o});return(Array.isArray(r)?r:[r]).map(El)}catch(n){if(n&&typeof n=="object"&&"message"in n){const o=String(n.message).toLowerCase();if(o.includes("cancel")||o.includes("user cancelled"))return null;throw new Error(String(n.message))}throw new Error("File selection failed")}}}}function kn(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 bl(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function Mn(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 El(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function Cl(){return{captureCamera:async()=>{throw new Error(ge.IMAGE_PICKER_NOT_CONFIGURED)},selectFromGallery:async()=>{throw new Error(ge.IMAGE_PICKER_NOT_CONFIGURED)}}}function vl(){return{selectFile:async()=>{throw new Error(ge.DOCUMENT_PICKER_NOT_CONFIGURED)}}}const{Provider:Sl,useContext:uo}=Z("NativeAdapter"),mo=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:o,documentPicker:r,mmkv:s}=e,i=o?(Al(e),"launchCameraAsync"in o?fl(o):pl(o,e.permissions)):Cl(),l=r?"getDocumentAsync"in r?_l(r):yl(r):vl();return{...i,...l,keyValueStorage:wr(s)}},[e.imagePicker,e.documentPicker,e.mmkv,e.permissions]);return a.createElement(Sl,{value:n},t)};function Al(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 Tl=({onPressAddAttachment:e,disabled:t})=>a.createElement(O,{disabled:t,style:wl.container,activeOpacity:.75,onPress:e},a.createElement(H,{type:"add",size:24,color:({themedColor:n})=>t?n.textDisabled:n.primary})),wl=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),xl=({name:e,type:t,url:n,onRemove:o})=>{const r=Il.use();return a.createElement(E,{style:r.wrapper},Go(t)?a.createElement(xe,{source:{uri:n},style:r.image,resizeMode:"cover"}):a.createElement(tn,{name:e,type:qt(e,t)}),o&&a.createElement(O,{onPress:o,style:r.removeButton},a.createElement(H,{type:"remove",size:20,color:r.removeIcon.tintColor})))},We=7,Il=P.create(({themedColor:e})=>({wrapper:{marginTop:We,marginRight:We,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-We,right:-We,width:22,height:22,borderRadius:11,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),kl=e=>{const{theme:t,themedColor:n}=j(),o=Ml.use(),r=Qt.useTextAlign({text:e.value??e.placeholder,style:o.input,isTextInput:!0});return a.createElement(E,{style:o.container},e.attachments&&a.createElement(ao,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),a.createElement(E,null,a.createElement(p.TextInput,{multiline:!0,style:[o.input,{textAlign:r}],placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},Ml=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:{...Rl(e.typography.body3),color:e.colors.messageInput.text,includeFontPadding:!1,padding:0,margin:0,textAlignVertical:"center"}}));function Rl(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 Ll=({onPressSend:e})=>a.createElement(O,{style:Dl.container,activeOpacity:.75,onPress:e},a.createElement(H,{type:"send",size:24})),Dl=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Pl=()=>{const e=Ol.use(),{aiAgentInfo:t,userSession:n}=oe(),{messageSource:o,channelSource:r}=ue(),[s,i]=d.useState(null),l=Xt("special-notice",r.channel),c=d.useCallback(()=>r.channel?l?o.messages.some(u=>ze(u,(n==null?void 0:n.userId)??"")):!0:null,[r.channel,l,o.messages,n==null?void 0:n.userId]);return d.useEffect(()=>{s||i(c())},[c,s]),s||!(t!=null&&t.specialNotice)?null:a.createElement(E,{style:e.container},a.createElement(nn,{textStyle:e.text,linkStyle:e.link},(t==null?void 0:t.specialNotice)??""))},Ol=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})}})),Nl=()=>{var v;const{chatSDK:e}=X(),{strings:t}=U(),{createAttachmentRules:n}=oe(),{channelSource:o,state:r}=ue(),[s,i]=d.useState(""),[l,c]=d.useState([]),u=n({channel:o.channel,uploadSizeLimit:(v=e.appInfo)==null?void 0:v.uploadSizeLimit}),m=(f,S)=>{const b=S.filter(x=>u.isSupportedMimeType(x.type));if(b.length===0&&S.length>0)return p.Alert.alert("",t.conversation.file_upload_not_supported_file),f;const C=x=>{const L=u.getUploadSizeLimit(x.type);return x.size&&x.size>L},A=b.find(x=>C(x));if(A){const x=u.getUploadSizeLimitInMB(A.type);return p.Alert.alert("",t.conversation.file_upload_notification_size_limit(x)),f}return f.length+b.length>u.maxAttachmentCount?(p.Alert.alert("",t.conversation.file_upload_notification_count_limit(u.maxAttachmentCount)),f):[...f,...b]},h=f=>{c(S=>m(S,f))},g=f=>{c(S=>S.filter((b,C)=>C!==f))},_=()=>{c([])},y=(()=>{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(""),_())},[r.input.disabled]),{files:l,addFiles:h,removeFile:g,clearFiles:_,value:s,onChangeText:i,editable:!r.input.disabled,placeholder:y,sendButtonVisible:!r.input.disabled&&(!!s.trim()||l.length>0),addAttachmentButtonVisible:u.isEnabled(),addAttachmentButtonDisabled:r.input.disabled||l.length>=u.maxAttachmentCount,hasImageMimeTypes:()=>u.supportedMimeTypes.filter(S=>S.startsWith("image/")||S===Nn).length>0,hasFileMimeTypes:()=>u.supportedMimeTypes.length>0,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount}},Bl=()=>{const{config:e}=X(),t=uo(),{strings:n}=U(),{messageSource:o}=ue(),{openModal:r}=ot(),s=Ie(["left","right","bottom"]),i=Hl.use(),{maxAttachmentCount:l,sendButtonVisible:c,addAttachmentButtonVisible:u,addAttachmentButtonDisabled:m,acceptableMimeTypes:h,hasImageMimeTypes:g,hasFileMimeTypes:_,...y}=Nl(),S={...y,onPressAddAttachment:async()=>{const b=await r(C=>{var A,w,x,L,V,q,$,R;return a.createElement(ne,{onClose:()=>C()},((x=(w=(A=e==null?void 0:e.conversation)==null?void 0:A.input)==null?void 0:w.camera)==null?void 0:x.photoEnabled)&&a.createElement(ne.ActionItem,{icon:"camera",label:n.conversation.attachment_camera,onPress:async()=>{if(!g())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const F=await t.captureCamera();C(F)}}),((q=(V=(L=e==null?void 0:e.conversation)==null?void 0:L.input)==null?void 0:V.gallery)==null?void 0:q.photoEnabled)&&a.createElement(ne.ActionItem,{icon:"photo",label:n.conversation.attachment_photo,onPress:async()=>{if(!g())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const F=await t.selectFromGallery({selectionLimit:l-y.files.length});C(F)}}),((R=($=e==null?void 0:e.conversation)==null?void 0:$.input)==null?void 0:R.fileEnabled)&&a.createElement(ne.ActionItem,{icon:"document",label:n.conversation.attachment_document,onPress:async()=>{if(!_())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const F=await t.selectFile({selectionLimit:l-y.files.length,mimeTypes:h});C(F)}}))});b&&y.addFiles(b)},onPressSend:()=>{y.files.length>0?o.sendFileMessage({message:y.value.trim(),file:y.files[0]}):o.sendUserMessage({message:y.value}),y.clearFiles(),y.onChangeText("")}};return a.createElement(p.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-s.paddingBottom},a.createElement(Pl,null),a.createElement(E,{style:i.container(s)},u&&a.createElement(Tl,{...S,disabled:m}),a.createElement(kl,{...S,value:S.editable?S.value:"",attachments:S.files.length===0?null:S.files.map((b,C)=>a.createElement(xl,{key:C,name:b.name,type:b.type,url:b.uri,onRemove:()=>S.removeFile(C)}))}),c&&a.createElement(Ll,{...S})))},Hl=P.create(({theme:e})=>({container:({paddingStart:t,paddingEnd:n,paddingBottom:o})=>({alignItems:"center",flexDirection:"row",gap:8,paddingTop:10,paddingBottom:10+o,paddingStart:12+t,paddingEnd:12+n,backgroundColor:e.colors.base.background})})),go=({start:e,title:t,titleAlign:n="start",end:o})=>{const r=Ie(["left","right","top"]),[s,i]=d.useState(0),[l,c]=d.useState(0),u=g=>{i(g.nativeEvent.layout.width)},m=g=>{c(g.nativeEvent.layout.width)},h=zl.use();return a.createElement(E,{style:h.container},a.createElement(E,{height:r.paddingTop}),a.createElement(E,{style:h.contentContainer(r)},n==="center"&&t&&a.createElement(E,{style:h.centerTitleContainer(Math.max(s,l))},a.createElement(E,{style:h.centerTitle},t)),a.createElement(E,{style:h.rowContainer},a.createElement(E,{style:h.startSide,onLayout:u},e),(n==="start"||n==="end")&&t&&a.createElement(E,{style:h.titleSide(n,e,o)},t),a.createElement(E,{style:h.endSide,onLayout:m},o))))},zl=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,o,r)=>({flex:1,overflow:"hidden",alignItems:`flex-${n}`,marginStart:o?8:0,marginEnd:r?8:0})})),Fl=()=>{const{themedColor:e}=j(),{onClose:t}=ue();return t?a.createElement(O,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(H,{color:e.textHighEmphasis,type:"close",size:24})):null},Ul=()=>{const{themedColor:e}=j(),{channelSource:{channel:t}}=ue(),n=Xt("handoff-button",t),o=!Un(t)||we(t);return n?a.createElement(O,{hitSlop:4,disabled:o,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},a.createElement(H,{color:o?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},$l=()=>{const{strings:e}=U(),{themedColor:t}=j(),{onNavigateToConversationList:n}=ue();return n?a.createElement(O,{hitSlop:4,onPress:n,activeOpacity:.75,"aria-label":e.conversation.a11y_open_conversation_list},a.createElement(H,{color:t.textHighEmphasis,type:"menu",size:24})):null},ho=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:o}=oe(),{fallbackIcon:r,url:s}=qn({channel:e,aiAgentInfo:o,userSession:n}),{theme:i}=j();return s?a.createElement(so,{src:s,size:t}):a.createElement(E,{width:t,height:t,borderRadius:t/2,alignItems:"center",justifyContent:"center",flexShrink:0,style:{backgroundColor:i.colors.base.primary}},a.createElement(H,{type:r,size:t*.55,color:i.colors.base.primaryContrastContent}))},jl=()=>{var i,l;const{channelSource:{channel:e}}=ue(),{userSession:t,aiAgentInfo:n}=oe(),{config:o}=X(),r=qn({channel:e,userSession:t,aiAgentInfo:n}),s=(l=(i=o==null?void 0:o.conversation)==null?void 0:i.header)==null?void 0:l.avatarEnabled;return a.createElement(E,{gap:6,flexDirection:"row",alignItems:"center",maxWidth:"100%"},s&&a.createElement(ho,{channel:e,size:34}),a.createElement(E,{flexShrink:1},a.createElement(M,{numberOfLines:1,variant:"h1"},r.title)))},Gl=e=>{const{components:t}=Ee.useContext();return a.createElement(go,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},Vl=()=>{const{components:e}=Ee.useContext();return a.createElement(e.MenuButton,null)},ql=()=>{const{components:e}=Ee.useContext();return a.createElement(e.Title,null)},Wl=()=>{const{components:e}=Ee.useContext();return a.createElement(E,{flexDirection:"row",alignItems:"center",gap:10},a.createElement(e.HandoffButton,null),a.createElement(e.CloseButton,null))},Ee=ae({template:Gl,components:{StartArea:Vl,TitleArea:ql,EndArea:Wl,MenuButton:$l,Title:jl,HandoffButton:Ul,CloseButton:Fl}}),Kl=()=>{const{Template:e}=Ee.useContext();return a.createElement(e,{titleAlign:"start"})},Yl=e=>{const{components:t}=ct.useContext();return a.createElement(E,{flex:1},a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},ct=ae({template:Yl,components:{Header:Kl,Body:gl,Footer:Bl}}),fo=({children:e,...t})=>{const{Template:n}=ct.useContext();return a.createElement(Yn,{...t},a.createElement(n,null),e)},{Provider:Xl,Context:Zl,useContext:ut}=Z("ConversationList"),po=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:o,children:r})=>{const{sdkUser:s,authenticate:i}=oe();return d.useEffect(()=>{s||i()},[]),a.createElement(bs,{conversationListLimit:e,conversationListFilter:t},l=>a.createElement(Xl,{value:{...l,onClose:o,onNavigateToConversation:n}},r))},It=99,Jl=d.memo(function(t){const{channel:n,onClick:o}=t,{strings:r,format:s}=U(),{themedColor:i}=j(),l=ec.use(),c=Ir(n,{formatMultipleFilesCount:r.conversation_list.multiple_files_count}),u=kr(n,s,{justNow:r.date_format.just_now,minutesAgo:r.date_format.minutes_ago,hoursAgo:r.date_format.hours_ago,dateShortFormat:r.date_format.date_short}),m=n.unreadMessageCount;return a.createElement(O,{onPress:o,activeOpacity:.75},a.createElement(E,{flexDirection:"row",alignItems:"center",width:"100%",height:72,gap:16},a.createElement(E,{marginStart:16,alignItems:"center",justifyContent:"center"},a.createElement(ho,{channel:n})),a.createElement(E,{flexDirection:"row",alignItems:"center",flex:1,paddingEnd:16,height:"100%",gap:8,style:l.rightContainer},a.createElement(E,{flexDirection:"column",justifyContent:"center",flex:1,gap:4},a.createElement(M,{variant:"subtitle1",color:i.textHighEmphasis,numberOfLines:1},c),a.createElement(E,{flexDirection:"row",alignItems:"center",gap:6},le(n)&&a.createElement(a.Fragment,null,a.createElement(M,{variant:"caption1",color:i.textMidEmphasis,numberOfLines:1},r.conversation_list.ended),a.createElement(E,{width:2,height:2,borderRadius:1,backgroundColor:i.textLowEmphasis})),a.createElement(M,{variant:"caption2",color:i.textLowEmphasis,numberOfLines:1},u))),m>0&&a.createElement(E,{alignItems:"center",justifyContent:"center",height:20,width:m<=It?20:void 0,padding:4,borderRadius:10,backgroundColor:i.error},a.createElement(M,{variant:"caption3",color:i.textHighEmphasisInverse,style:{lineHeight:12}},m<=It?m:`${It}+`)))))}),Ql=ae({template:Jl,components:{}}),ec=P.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),tc=()=>{var l;const{Template:e}=Ql.useContext(),{strings:t}=U(),{connectionError:n}=oe(),{listSource:o,onNavigateToConversation:r}=ut(),s=Ie(["left","right"]),i=nc.use();return a.createElement(no,{style:i.list,contentContainerStyle:[i.listContent,s],data:o.channels,onEndReached:o.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,le(c)?"closed":"open")}),[e,r]),loading:!o.initialized,error:!!(n||o.error),empty:o.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=o.error)==null?void 0:l.message)})})},nc=P.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),oc=()=>{const{strings:e}=U(),{language:t,countryCode:n,context:o}=X(),{aiAgentInfo:r,refreshActiveChannel:s,createConversation:i,setActiveChannel:l,sdkUser:c}=oe(),{onNavigateToConversation:u}=ut(),m=Ie(["left","right","bottom"]),h=rc.use();return a.createElement(O,{activeOpacity:.75,disabled:!c,onPress:async()=>{if(r!=null&&r.isMultipleActiveConversationsEnabled){const g=await i({aiAgentId:r.userId,language:t,country:n,context:o});l({url:g,status:"open"}),u==null||u(g,"open")}else{const g=await s();u==null||u(g,"open")}}},a.createElement(E,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+m.paddingBottom,style:[h.container,m]},a.createElement(M,{variant:"h1",color:({themedColor:g})=>g.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},rc=P.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),sc=()=>{const{aiAgentInfo:e}=oe();return e?a.createElement(oc,null):null},ac=()=>{const{themedColor:e}=j(),{onClose:t}=ut();return t?a.createElement(O,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(H,{color:e.textHighEmphasis,type:"close",size:24})):null},ic=()=>{const{strings:e}=U();return a.createElement(M,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},lc=e=>{const{components:t}=ke.useContext();return a.createElement(go,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},cc=()=>null,uc=()=>{const{components:e}=ke.useContext();return a.createElement(e.Title,null)},dc=()=>{const{components:e}=ke.useContext();return a.createElement(e.CloseButton,null)},ke=ae({template:lc,components:{StartArea:cc,TitleArea:uc,EndArea:dc,Title:ic,CloseButton:ac}}),mc=()=>{const{Template:e}=ke.useContext();return a.createElement(e,{titleAlign:"start"})},gc=()=>{const{components:e}=dt.useContext();return a.createElement(E,{flex:1},a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},dt=ae({template:gc,components:{Header:mc,Body:tc,Footer:sc}}),_o=({children:e,...t})=>{const{Template:n}=dt.useContext();return a.createElement(po,{...t},a.createElement(n,null),e)},hc=d.forwardRef(function({logLevel:t=G.LogLevel.WARN,language:n=nt,userSessionInfo:o,children:r,strings:s,...i},l){const[c]=d.useState(()=>new Fn(t));c.level!==t&&(c.level=t);const{nativeModules:u,chatParams:m={},...h}=i;return a.createElement(mo,{config:u},({keyValueStorage:g})=>{var _,y;return a.createElement(pc,{logger:c,theme:h.theme,language:n,strings:s},a.createElement(Rr,{language:n,logger:c,chatSDK:h.customChatSDK,keyValueStorage:g,chatParams:{...m,useMMKVStorageStore:u.mmkv},messengerVersion:Wn,extensions:{platform:G.SendbirdPlatform.REACT_NATIVE,deviceOSPlatform:(_=p.Platform)==null?void 0:_.select({web:G.DeviceOsPlatform.WEB,ios:G.DeviceOsPlatform.IOS,default:G.DeviceOsPlatform.ANDROID}),deviceOSVersion:(y=p.Platform)!=null&&y.Version?String(p.Platform.Version):void 0},...h},a.createElement(js,{ref:l,userSessionInfo:o},r)))})}),fc=xr(ct,Ee,on,dt,ke,st,rt,at,it,lt),pc=({children:e,logger:t,theme:n,language:o,strings:r})=>a.createElement(be.SafeAreaProvider,null,a.createElement(Aa,{logger:t,...n},a.createElement(Ca,{language:o,logger:t,strings:r},a.createElement(Xn,null,a.createElement(vs,null,a.createElement(fc,null,e)))))),{Provider:_c,useContext:rn}=Z("FixedMessengerStyle"),yc={useNativeDriver:!0},Ke={OPEN_START:"0deg",OPEN_END:"-180deg",CLOSE_START:"180deg",CLOSE_END:"0deg"},Ye={VISIBLE:1,HIDDEN:0},bc=({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,...yc}).start()},[e,t]);const n={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[Ke.OPEN_START,Ke.OPEN_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Ye.VISIBLE,Ye.HIDDEN]})}]},o={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[Ke.CLOSE_START,Ke.CLOSE_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Ye.HIDDEN,Ye.VISIBLE]})}]};return{openIconStyle:n,closeIconStyle:o}},Ec=2/3,Cc=({isOpened:e,onPress:t})=>{const n=Ac.use(),{launcherInfo:o,statsTrackers:r}=oe();d.useLayoutEffect(()=>{r.initialRender.setPresentMethod("launcher_toggle")},[r]);const{theme:s}=j(),{launcherSize:i,horizontal:l}=rn(),c=Math.round(i*Ec),u=s.colors.base.primary,m=s.colors.base.primaryContrastContent,{openIconStyle:h,closeIconStyle:g}=bc({isOpened:e});return a.createElement(E,{alignSelf:l==="start"?"flex-start":"flex-end"},a.createElement(O,{onPress:t,activeOpacity:.8},({pressed:_})=>a.createElement(E,{style:[n.container({backgroundColor:u,size:i}),_&&n.pressed]},a.createElement(E.Animated,{style:[n.iconWrapper,h]},a.createElement(vc,{url:(o==null?void 0:o.imageUrl)??"",isDefaultIcon:(o==null?void 0:o.type)==="default_icon",size:c,fillColor:m})),a.createElement(E.Animated,{style:[n.iconWrapper,g]},a.createElement(Sc,{size:c,fillColor:m})))))},vc=({url:e,isDefaultIcon:t,size:n,fillColor:o})=>e?t?a.createElement(xe,{source:{uri:e},width:n,height:n,tintColor:o,resizeMode:"contain"}):a.createElement(xe,{source:{uri:e},width:n,height:n,resizeMode:"cover"}):a.createElement(H,{type:"delight",size:n,color:o}),Sc=({size:e,fillColor:t})=>a.createElement(H,{type:"chevron-down",size:e,color:t}),Ac=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"}})),ee={TRANSLATE_OFFSET:40,DURATION:300,OPACITY_DURATION:83,EASING:p.Easing.out(p.Easing.ease)},Tc=e=>e==="entered"?0:ee.TRANSLATE_OFFSET,wc=e=>e==="entered"?1:0,xc=({transitionState:e,isActive:t})=>{const[n,o]=d.useState(!1),r=d.useRef(new p.Animated.Value(Tc(e))).current,s=d.useRef(new p.Animated.Value(wc(e))).current;return d.useEffect(()=>{if(!n){e==="entered"?(r.setValue(0),s.setValue(1)):e==="exited"&&(r.setValue(ee.TRANSLATE_OFFSET),s.setValue(0)),o(!0);return}e==="entering"?(r.setValue(ee.TRANSLATE_OFFSET),s.setValue(0),p.Animated.parallel([p.Animated.timing(r,{toValue:0,duration:ee.DURATION,easing:ee.EASING,useNativeDriver:!0}),p.Animated.timing(s,{toValue:1,duration:ee.OPACITY_DURATION,easing:ee.EASING,useNativeDriver:!0})]).start()):e==="exiting"&&p.Animated.parallel([p.Animated.timing(r,{toValue:ee.TRANSLATE_OFFSET,duration:ee.DURATION,easing:ee.EASING,useNativeDriver:!0}),p.Animated.timing(s,{toValue:0,duration:ee.OPACITY_DURATION,easing:ee.EASING,useNativeDriver:!0})]).start()},[e,r,s,n]),d.useMemo(()=>({position:"absolute",top:0,left:0,width:"100%",height:"100%",transform:[{translateY:r}],opacity:s,zIndex:t?999:1,pointerEvents:t?"auto":"none",display:e==="exited"?"none":"flex"}),[r,s,t,e])},yo=d.createContext(null),Ic=()=>{const e=d.useContext(yo);if(!e)throw new Error("useNavigatorContext() must be used within <Navigator />");return e},bo=({children:e})=>{const t=Ic();return typeof e=="function"?a.createElement(a.Fragment,null,e(t)):a.createElement(a.Fragment,null,e)},kc=d.memo(({transitionState:e,isActive:t,children:n})=>{const o=xc({transitionState:e,isActive:t});return a.createElement(p.Animated.View,{style:o},n)}),Rn=300,Ze=({initialId:e,children:t})=>{const[n,o]=d.useState([e]),r=n[n.length-1],s=d.useCallback((f,S)=>{o(b=>[...b,f]),h(b=>({...b,[f]:!0})),S!=null&&S.reset&&v(b=>({...b,[f]:(b[f]||0)+1})),_(b=>({...b,[f]:"entering"})),setTimeout(()=>{_(b=>({...b,[f]:"entered"}))},Rn)},[]),i=d.useCallback(()=>{o(f=>{if(f.length<=1)return f;const S=f[f.length-1];return _(b=>({...b,[S]:"exiting"})),setTimeout(()=>{_(b=>({...b,[S]:"exited"})),o(b=>b.slice(0,-1))},Rn),f})},[]),l=d.useMemo(()=>({navigation:{navigate:s,pop:i},activeScreenId:r}),[s,i,r]),c=d.useMemo(()=>d.Children.toArray(t).filter(f=>f.type===bo),[t]),u=d.useMemo(()=>{const f={};return c.forEach(S=>{const{id:b,lazy:C,children:A}=S.props;f[b]={lazy:C,element:typeof A=="function"?A(l):A}}),f},[c,l]),[m,h]=d.useState(()=>{const f={};return Object.entries(u).forEach(([S,{lazy:b}])=>{b===!1&&(f[S]=!0)}),f[e]=!0,f}),[g,_]=d.useState(()=>{const f={};return Object.keys(u).forEach(S=>{f[S]=S===e?"entered":"exited"}),f}),[y,v]=d.useState({});return a.createElement(yo.Provider,{value:l},a.createElement(E,{style:{position:"relative",width:"100%",height:"100%"}},Object.keys(u).map(f=>{var A;if(!m[f])return null;const S=g[f]||"exited",b=f===r,C=`${f}-${y[f]||0}`;return a.createElement(kc,{key:C,transitionState:S,isActive:b},(A=u[f])==null?void 0:A.element)})))};Ze.Screen=bo;const{Provider:Mc,useContext:sn}=Z("PageChildren"),Rc=({children:e})=>{const[t,n]=d.useState(null),[o,r]=d.useState(null);return a.createElement(Mc,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:o,setConversationListChildren:r}},e)},ye={conv:"conv",convList:"conv-list"},Lc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:o,onClose:r})=>{const{conversationChildren:s,conversationListChildren:i}=sn(),l=t==="ConversationList"?ye.convList:ye.conv;return a.createElement(Ze,{initialId:l},a.createElement(Ze.Screen,{id:ye.conv},({navigation:c,activeScreenId:u})=>a.createElement(fo,{channelUrl:n,onClearChannelUrl:()=>o(void 0),onNavigateToConversationList:()=>c.navigate(ye.convList),onClose:r,shouldMarkAsRead:e&&u===ye.conv},s)),a.createElement(Ze.Screen,{id:ye.convList,lazy:!0},({navigation:c})=>a.createElement(_o,{onNavigateToConversation:u=>{o(u),c.navigate(ye.conv,{reset:!0})},onClose:r},i)))},He=.15,Dc=150,Ln=(e,t)=>e.interpolate({inputRange:[He,1],outputRange:[t,0],extrapolate:"clamp"}),Pc=(e,t)=>{if(e<=0)return 0;const n=(1-He)*e/2,o=t==="start"?-1:1,r=p.I18nManager.isRTL?-1:1;return n*o*r},Oc=(e,t)=>e<=0?0:(1-He)*e/2*(t==="top"?-1:1),Nc=({isOpened:e,horizontal:t,vertical:n})=>{const[o,r]=d.useState({width:0,height:0}),s=d.useRef(new p.Animated.Value(e?1:He)).current,i=d.useRef(new p.Animated.Value(e?1:0)).current,l=d.useMemo(()=>Pc(o.width,t),[o.width,t]),c=d.useMemo(()=>Oc(o.height,n),[o.height,n]),{translateXInterpolation:u,translateYInterpolation:m}=d.useMemo(()=>({translateXInterpolation:Ln(s,l),translateYInterpolation:Ln(s,c)}),[s,l,c]);d.useEffect(()=>{const _=e?"open":"close",y=_==="open"?1:He,v=_==="open"?1:0,f=_==="open"?p.Easing.out(p.Easing.quad):p.Easing.in(p.Easing.quad),S={duration:Dc,useNativeDriver:!0,easing:f};_==="close"&&p.Keyboard.dismiss(),p.Animated.parallel([p.Animated.timing(s,{toValue:y,...S}),p.Animated.timing(i,{toValue:v,...S})]).start()},[e,s,i]);const h=d.useMemo(()=>({opacity:i,transform:[{translateX:u},{translateY:m},{scale:s}]}),[i,u,m,s]),g=d.useMemo(()=>_=>{const{width:y,height:v}=_.nativeEvent.layout;r(f=>f.width===y&&f.height===v?f:{width:y,height:v})},[]);return{animatedStyle:h,handleLayout:g,pointerEvents:e?"auto":"none"}},Bc={top:0,left:0,right:0,bottom:0},Hc=({children:e,isOpened:t})=>{const n=zc.use(),{horizontal:o,vertical:r}=rn(),{animatedStyle:s,handleLayout:i,pointerEvents:l}=Nc({isOpened:t,horizontal:o,vertical:r});return a.createElement(be.SafeAreaInsetsContext.Provider,{value:Bc},a.createElement(E,{flex:1},a.createElement(E.Animated,{pointerEvents:l,onLayout:i,style:s},a.createElement(E,{style:n.windowContainer},e))))},zc=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)"}})),Eo=()=>{const[e,t]=d.useState(0);return d.useEffect(()=>{const n=p.Platform.OS==="ios"?"keyboardWillShow":"keyboardDidShow",o=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)}),s=p.Keyboard.addListener(o,()=>{t(0)});return()=>{r.remove(),s.remove()}},[]),e},Fc=e=>{const t=d.useRef(new p.Animated.Value(0)).current,[n,o]=d.useState(!1);return d.useEffect(()=>{const s=e?"open":"close",i={toValue:s==="open"?1:0,useNativeDriver:!0,duration:300};s==="open"&&o(!0),p.Animated.timing(t,i).start(()=>{s==="close"&&(o(!1),p.Keyboard.dismiss())})},[e,t]),{windowAnimatedStyle:{opacity:t,display:n?"flex":"none"},pointerEvents:e?"auto":"none"}},Uc=({children:e,insets:t,isOpened:n})=>{const o=$c.use(),s={...be.useSafeAreaInsets(),...t},i=Eo(),{windowAnimatedStyle:l,pointerEvents:c}=Fc(n);return a.createElement(be.SafeAreaInsetsContext.Provider,{value:s},a.createElement(E.Animated,{flex:1,style:[o.bg,l],pointerEvents:c},a.createElement(E,{flex:1},e),a.createElement(E,{height:Math.max(0,i-p.Platform.select({android:0,default:s.bottom})),style:o.bg})))},$c=P.create(({theme:e})=>({bg:{backgroundColor:e.colors.base.background}})),jc="end-bottom",Pe={top:24,bottom:24,start:24,end:24},Gc=({mode:e,edgeToEdgeEnabled:t})=>{const n=e==="floating"?Hc:Uc,[o,r]=Dt({position:jc,margin:Pe,launcherSize:48,spacing:12}),{bottom:s}=be.useSafeAreaInsets(),i=Eo(),[l,c]=o.position.split("-"),u=(()=>{const g=p.Platform.select({android:t?s:0,default:0}),_=c==="top"?o.spacing:-o.launcherSize,y=i>0?i+_+g:0;return y>0?y:o.margin.bottom})(),m={position:"absolute",zIndex:1e3,...c==="top"?{top:o.margin.top}:{bottom:o.margin.bottom},...l==="start"?{left:o.margin.start}:{right:o.margin.end}},h=(()=>{if(e==="floating"){const g=o.launcherSize+o.spacing;return{position:"absolute",top:o.margin.top+(c==="top"?g:0),bottom:u+(c==="bottom"?g:0),left:o.margin.start,right:o.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:{...o,horizontal:l,vertical:c,setPosition:g=>r({position:g}),setMargin:({top:g=Pe.top,bottom:_=Pe.bottom,start:y=Pe.start,end:v=Pe.end})=>r({margin:{top:g,bottom:_,start:y,end:v}}),setLauncherSize:g=>r({launcherSize:g}),setSpacing:g=>r({spacing:g})}}},Vc=e=>{var s,i,l,c;const{setPosition:t,setMargin:n,setLauncherSize:o,setSpacing:r}=rn();return d.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n(e.margin),e.launcherSize!==void 0&&o(e.launcherSize),e.spacing!==void 0&&r(e.spacing)},[e.position,(s=e.margin)==null?void 0:s.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},qc=({children:e})=>{const{setConversationChildren:t}=sn();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Wc=({children:e})=>{const{setConversationListChildren:t}=sn();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},Kc=({entryPoint:e="Conversation",edgeToEdgeEnabled:t=!0,windowMode:n="floating",fullscreenInsets:o,initialChannelUrl:r,windowContainerProps:s,children:i})=>{const[l,c]=d.useState(!1),[u,m]=d.useState(r),{Window:h,windowContainerStyle:g,launcherContainerStyle:_,styleContext:y}=Gc({mode:n,edgeToEdgeEnabled:t});return d.useEffect(()=>{const v=p.BackHandler.addEventListener("hardwareBackPress",()=>l?(c(!1),!0):!1);return()=>v.remove()},[l]),a.createElement(_c,{value:y},a.createElement(Rc,null,a.createElement(E,{style:g,backgroundColor:"transparent",pointerEvents:l?"auto":"box-none",...s},a.createElement(h,{isOpened:l,insets:o},a.createElement(Lc,{isOpened:l,entryPoint:e,selectedChannelUrl:u,setSelectedChannelUrl:m,onClose:()=>c(!1)}))),a.createElement(E,{style:_,backgroundColor:"transparent",pointerEvents:"box-none"},a.createElement(Cc,{isOpened:l,onPress:()=>c(!l)})),i))},Yc=Object.assign(Kc,{Style:Vc,ConversationChildren:qc,ConversationListChildren:Wc});var Dn,Pn;Ar.set(G.SendbirdPlatform.REACT_NATIVE,{deviceOSPlatform:(Dn=p.Platform)==null?void 0:Dn.select({ios:G.DeviceOsPlatform.IOS,android:G.DeviceOsPlatform.ANDROID,default:G.DeviceOsPlatform.ANDROID}),deviceOSVersion:(Pn=p.Platform)!=null&&Pn.Version?String(p.Platform.Version):void 0,messengerVersion:Wn,keyValueStorage:Tr()});exports.AIAgentProviderContainer=hc;exports.AnonymousSessionInfo=Qe;exports.BottomSheet=ne;exports.BottomSheetLayout=rt;exports.Conversation=fo;exports.ConversationContext=Zs;exports.ConversationContextProvider=Yn;exports.ConversationHeaderLayout=Ee;exports.ConversationLayout=ct;exports.ConversationList=_o;exports.ConversationListContext=Zl;exports.ConversationListContextProvider=po;exports.ConversationListHeaderLayout=ke;exports.ConversationListLayout=dt;exports.FixedMessenger=Yc;exports.IncomingMessageLayout=at;exports.ManualSessionInfo=Kt;exports.MessageListUILayout=on;exports.ModalProvider=Xn;exports.NativeAdapterProvider=mo;exports.OutgoingMessageLayout=it;exports.PlaceholderLayout=st;exports.SystemMessageLayout=lt;exports.useConversationContext=ue;exports.useConversationListContext=ut;exports.useMessengerSessionContext=oe;exports.useModalContext=ot;exports.useNativeAdapterContext=uo;
|