@sendbird/ai-agent-messenger-react-native 1.3.0 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +93 -91
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var so=Object.defineProperty;var ao=(e,t,n)=>t in e?so(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var z=(e,t,n)=>ao(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react"),p=require("react-native"),_e=require("react-native-safe-area-context"),K=require("@sendbird/chat"),Y=require("@sendbird/chat/aiAgent"),Nt=require("@sendbird/uikit-tools"),Ce=require("date-fns"),Se=require("@sendbird/chat/message"),We=require("@sendbird/chat/groupChannel"),io=require("date-fns/isSameDay"),lo=require("date-fns/locale/de"),co=require("date-fns/locale/en-US"),uo=require("date-fns/locale/es"),mo=require("date-fns/locale/fr"),go=require("date-fns/locale/hi"),ho=require("date-fns/locale/it"),fo=require("date-fns/locale/ja"),po=require("date-fns/locale/ko"),_o=require("date-fns/locale/pt"),yo=require("date-fns/locale/tr"),bo=require("@react-native-clipboard/clipboard"),Eo=require("react-native-code-highlighter"),vo=require("react-syntax-highlighter/dist/esm/styles/hljs"),Co=require("react-native-markdown-display"),je=e=>e&&e.__esModule?e:{default:e};function So(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 s=So(d),Ao=je(K),wo=je(bo),xo=je(Eo),Io=je(Co),X=(e,t)=>{const n=d.createContext(null),o=({children:i,value:l})=>s.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),r=({children:i})=>s.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),a=()=>{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`,a.displayName=`use${e}Context`,{Context:n,Provider:o,Consumer:r,useContext:a}};function ae(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:a}){const[i,l]=d.useState(()=>e.template),[c,u]=d.useState(e.components),g={Template:i,updateTemplate:h=>l(()=>h),components:c,updateComponent:(h,m)=>u(_=>({..._,[h]:m}))};return s.createElement(t.Provider,{value:g},a)}function o({template:a,children:i}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{a&&l(a)},[a]),s.createElement(s.Fragment,null,i)}function r({children:a}){return s.createElement(n,null,a)}return r.defaults=e,r.useContext=()=>d.useContext(t),r.Context=t,r.Template=o,Object.keys(e.components).forEach(a=>{r[a]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(a,l)},[l]),null}}),r}function To(...e){return function({children:n}){return e.reduce((o,r)=>s.createElement(r,null,o),n)}}const ye=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Y.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Cn=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Y.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 ko(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function en(e){return!!e&&e<Date.now()}function Mo(e){return!e.title}function Lo(e,t){var n;if(e)return Mo(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}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}function Po(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 Ro(e,t,n){var i;const o=new Date,r=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),a=Ce.differenceInMinutes(o,r);return a<1?n.justNow:a<60?n.minutesAgo(a):Ce.isToday(r)?n.hoursAgo(Ce.differenceInHours(o,r)):t(r,n.dateShortFormat)}const ve="sb-agent",Sn="KEY_IMG_ASPECT_RATIO",An="*/*",k={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},se=e=>!!e&&"sender"in e,Do=e=>se(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Oo=(e,t,n,o=!0)=>{if(!o||!se(e))return"single";const r=()=>{if(!t||!se(t))return!1;const c=t.sender.userId===e.sender.userId,u=Ce.isSameMinute(t.createdAt,e.createdAt);return c&&u},a=()=>{if(!n||!se(n))return!1;const c=n.sender.userId===e.sender.userId,u=Ce.isSameMinute(n.createdAt,e.createdAt);return c&&u},i=r(),l=a();return i&&l?"middle":i?"bottom":l?"top":"single"},Re=(e,t)=>(()=>{var o;return se(e)?e.sender.userId:((o=e==null?void 0:e.sender)==null?void 0:o.userId)??void 0})()===t,Oe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>se(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>se(e)&&(e.sender.userId===t||e.sendingStatus===Se.SendingStatus.PENDING)},Bo=e=>e.startsWith("image/"),Ht=(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"},wn=e=>e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.message.length>0,zt=e=>{switch(e){case"top":case"middle":return k.GAP_GROUPED;default:return k.GAP_UNGROUPED}},No=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,o=[];let r=0;return e.replace(n,(a,...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+a.length,a}),r<e.length&&o.push({type:"text",value:e.slice(r).trim()}),o},Ho=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),zo=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Fo=e=>e.replace(/~~/g,"\\~\\~"),$o=e=>{let t=e;return t=Ho(t),t=zo(t),t=Fo(t),t},Uo=typeof navigator<"u"&&navigator.product==="ReactNative",tn=(e,t)=>{const n=o=>!t||t.length===0?!0:se(o)&&t.includes(o.sendingStatus);return Uo?e.find(n):e.findLast(n)};function Et(){}function qo(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Vo(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 nn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},qe={isStreaming(e){const t=nn(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(Re(e,t)){const o=nn(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)}},rt=`@${ve}`,on=({appId:e,aiAgentId:t,storage:n})=>{const o={templateBase:`${rt}-template`,template:r=>`${o.templateBase}/templates/${r}`,templateToken:()=>`${o.templateBase}-template/message-template/tokens`,messengerSession:r=>{const a=Vo(`${e}/${t}/${r}`);return`${rt}-udata/${a}`},anonUserSession:()=>`${rt}-session/${e}/${t}`};return{template:{set:(r,a)=>n.set(o.template(r),a),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 a=n.get(o.messengerSession(r));return a?JSON.parse(a):null}catch{return null}},setSettings:(r,a)=>{try{delete a.auto_created_user;const i=JSON.stringify(a);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 a=JSON.stringify(r);n.set(o.anonUserSession(),a)}catch{return}},clear:r=>{try{r&&n.delete(o.messengerSession(r)),n.delete(o.anonUserSession())}catch{return}}}}};class Wo{constructor(t){z(this,"subscribers",{});this.logger=t}async send(t){const n=Go(),o=this.subscribers[t.type];if(o){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const r=o.map(a=>a(t.payload));await Promise.all(r).catch(a=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,a)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(o=>o!==n))}}const Go=()=>{let e=Et,t=Et;return{promise:new Promise((o,r)=>{e=o,t=r}),resolve:e,reject:t}};var xn=(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))(xn||{});class In{constructor(t){z(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)}}function rn(e,t,n,o){const r=Ao.default.init({appId:e,modules:[new We.GroupChannelModule,new Y.AIAgentModule],localCacheEnabled:!0,options:new K.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...o});return r.addSendbirdExtensions([{version:n,product:K.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),r}function jo(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 he={conversation:{isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0,header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Ko=e=>{var t,n,o,r,a,i,l,c,u,g,h,m,_,b;return e?{...he,...e,conversation:{...he.conversation,...e==null?void 0:e.conversation,header:{...(t=he.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(o=he.conversation)==null?void 0:o.input,...(r=e==null?void 0:e.conversation)==null?void 0:r.input,camera:{...(i=(a=he.conversation)==null?void 0:a.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:{...(g=(u=he.conversation)==null?void 0:u.input)==null?void 0:g.gallery,...(m=(h=e==null?void 0:e.conversation)==null?void 0:h.input)==null?void 0:m.gallery}},fileViewer:{...(_=he.conversation)==null?void 0:_.fileViewer,...(b=e==null?void 0:e.conversation)==null?void 0:b.fileViewer}}}:he},{Provider:Yo,useContext:j}=X("AIAgent");function Xo({appId:e,aiAgentId:t,keyValueStorage:n,networkStateAdapter:o,language:r,countryCode:a,context:i,queryParams:l,config:c,chatSDK:u,chatParams:g,children:h,logger:m,dispatcher:_,messengerVersion:b,extensions:S={platform:K.SendbirdPlatform.JS,deviceOSPlatform:qo()?K.DeviceOsPlatform.MOBILE_WEB:K.DeviceOsPlatform.WEB}}){const[f,E]=d.useState(()=>{const C=m??new In(xn.WARN),v=_??new Wo(C);return{logger:C,dispatcher:v,chatSDK:u??rn(e,S,b,g),cache:on({appId:e,aiAgentId:t,storage:n})}});return d.useEffect(()=>{E(C=>{let v=C.logger,A=C.dispatcher,I=C.chatSDK;return m&&m!==C.logger&&(v=m),_&&_!==C.dispatcher&&(A=_),u&&u!==C.chatSDK?I=u:!u&&C.chatSDK.appId!==e&&(I=rn(e,S,b,{newInstance:!0,...g})),{...C,logger:v,dispatcher:A,chatSDK:I,cache:on({appId:e,aiAgentId:t,storage:n})}})},[e,t,m,_,u,n]),d.useEffect(()=>()=>{f.chatSDK.disconnectWebSocket()},[f.chatSDK]),jo(f.chatSDK),s.createElement(Yo,{value:{...f,appId:e,aiAgentId:t,context:i,language:r,countryCode:a,queryParams:l,config:Ko(c),networkStateAdapter:o}},h)}const Zo=(e,t,n)=>Nt.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0});var vt=(e=>(e.ConversationClose="conv.close",e))(vt||{});const Tn=(e,t,n={})=>{let o=null,r=null,a=null;const{leading:i=!0,trailing:l=!0}=n,c=(...u)=>{const g=Date.now();if(a===null||g-a>=t)i?(e(...u),a=g):(r=u,a=g);else if(r=u,l&&!o){const h=t-(g-a);o=setTimeout(()=>{r&&l&&(e(...r),a=Date.now()),o=null,r=null},h)}};return c.cancel=()=>{o&&(clearTimeout(o),o=null),r=null,a=null},c},Ct={DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function kn(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Jo(e){const t=kn(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Qo(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function er(e,t,n){e/=255,t/=255,n/=255;const o=Math.max(e,t,n),r=Math.min(e,t,n),a=o-r;let i=0,l=0;const c=(o+r)/2;return o!==r&&(l=c>.5?a/(2-o-r):a/(o+r)),o===e?i=(t-n)/a+(t<n?6:0):o===t?i=(n-e)/a+2:o===n&&(i=(e-t)/a+4),i/=6,[i,l,c]}function tr(e,t,n){let o,r,a;if(t===0)o=r=a=n;else{const i=function(g,h,m){return m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?g+(h-g)*6*m:m<.5?h:m<.6666666666666666?g+(h-g)*(.6666666666666666-m)*6:g},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),a=i(c,l,e-1/3)}return[Math.round(o*255),Math.round(r*255),Math.round(a*255)]}function Be(e,t,n){const[o,r,a]=Jo(e),[i,l,c]=er(o,r,a),u=Math.max(0,Math.min(1,c*t)),g=Math.max(0,Math.min(1,l*n)),[h,m,_]=tr(i,g,u);return Qo([Math.round(h),Math.round(m),Math.round(_)])}function nr(e,t="light"){return{extraDark:Be(e,.6,1.2),dark:Be(e,.85,1.1),main:e,light:Be(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Be(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function sn(e){const t=kn(e),n=149,o=+`0x${t[1]}${t[2]}`,r=+`0x${t[3]}${t[4]}`,a=+`0x${t[5]}${t[6]}`;return o*.299+r*.587+a*.114>n?Ct.BLACK:Ct.WHITE}function or(e,t,n,o,r){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},metadata:{errorContent:e.ondark.textHighEmphasis},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 rr=(e,t,n,o,r)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},metadata:{errorContent:e.ondark.textHighEmphasis},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}}),Ne={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)"}},st={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 an(e){const t=sr(e),{colors:n,aiAgentColorVariables:o}=ar(e,t),r=lr(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:o,typography:r}}function sr({selectedTheme:e,palette:t,primary:n}){const o=t!=null&&t.primary?t.primary:n?n===Ne.primary.main?Ne.primary:nr(n,e):Ne.primary;return{...Ne,primary:o,...t}}function ar({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:o},r){const a=r.primary.main,i=t??sn(a),l=n??Ct.DEFAULT_BOT_MSG_BG,c=o??sn(l);return{colors:(e==="light"?or:rr)(r,a,i,l,c),aiAgentColorVariables:{primary_color:a,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function ir(e,t,n){const o={...e};return n.forEach(r=>{const a=t[r];a!=null&&(o[r]=a)}),o}function lr({typography:e}){if(!e)return st;const t={...st};return Object.keys(e).forEach(n=>{const o=e[n];if(o&&typeof o=="object"){const r=st[n],a=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=ir(r,o,a)}}),t}const{Provider:cr,useContext:ur}=X("AIAgentTheme");function dr({logger:e,palette:t,typography:n,appearance:o,children:r}){const a=d.useRef(null),[i,l]=d.useState(()=>an({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,g)=>{g&&(a.current=g);const h=(o==null?void 0:o.theme)??u,m=a.current?a.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&&(m!=null&&m.primary_color)&&(_.primary=m.primary_color,_.primaryContrast=m.primary_contrast_color),!_.botMessageBackground&&(m!=null&&m.bot_message_bg_color)&&(_.botMessageBackground=m.bot_message_bg_color,_.botMessageBackgroundContrast=m.bot_message_bg_contrast_color);const b=an({selectedTheme:h,palette:t,typography:n,..._});l(b),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]),s.createElement(cr,{value:{theme:i,updateTheme:c}},r)}const ln=25*1024*1024,mr={off:"off",always:"always",handed_off_only:"handed_off_only"},gr=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:1,attachmentMode:"handed_off_only",defaultUploadSizeLimit:ln,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:a})=>{const{maxAttachmentCount:i,attachmentMode:l,defaultUploadSizeLimit:c,supportedImageMimeTypes:u,supportedFileMimeTypes:g}=e;t({maxAttachmentCount:i,attachmentMode:mr[r.attachment_mode]??l,defaultUploadSizeLimit:(a==null?void 0:a.default_upload_size_limit)??c,uploadSizeLimitPerType:new Map(Object.entries((a==null?void 0:a.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((a==null?void 0:a.supported_image_mime_types)??u),supportedFileMimeTypes:new Set((a==null?void 0:a.supported_file_mime_types)??g)})},[]),o=d.useCallback(r=>{const{channel:a,uploadSizeLimit:i=ln}=r,l=(u=!0)=>a!=null&&a.isAIAgent?u?we(a):!1:!0,c=u=>{if(l())return e.defaultUploadSizeLimit??i;const g=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(u)??g;return Math.min(g,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(a);default:return!0}},get supportedMimeTypes(){return l()?[An]:[...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 Mn(){const{chatSDK:e,logger:t}=j();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)},[e,t])}function hr(){const{chatSDK:e,logger:t}=j(),n=d.useCallback(async(r,a,i)=>{if(t.debug("useChatConnection.connect: start, session",r.userId),a){const l=new K.SessionHandler({...a,onSessionTokenRequired:fr(a.onSessionTokenRequired,i)});e.setSessionHandler(l)}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(_r(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"),await e.disconnect(),t.debug("useChatConnection.disconnect: end")},[e,t]);return{connect:n,disconnect:o}}function fr(e,t){if(e)return async(n,o)=>{new Promise((r,a)=>e==null?void 0:e(r,a)).then(r=>{r&&(t==null||t(r)),n(r)}).catch(r=>{o(r)})}}const pr=[400300,400301,400302,400310];function _r(e){return pr.some(t=>e.code===t)}class Ft{constructor({userId:t,authToken:n,sessionHandler:o}){z(this,"userId");z(this,"authToken");z(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=o}}class Ge{constructor(){z(this,"userId");z(this,"authToken");z(this,"sessionHandler")}}const yr=1440*60*1e3,br=e=>{const{logger:t,cache:n}=j(),o=()=>{const a=n.messenger.getAnonUser();return a?a.expireAt-yr<=Date.now()?(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session expired, clear cache"),n.messenger.clear(a.userId),null):(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session info detected"),a):null},r=()=>{if(!e||e instanceof Ge)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 a=["userId","authToken","sessionHandler"].filter(i=>!(i in e));return a.length>0&&t.error(`useUserSessionCandidate.getManualSessionInfo: missing required keys in userSessionInfo: ${a.join(", ")}`),t.debug("useUserSessionCandidate.getManualSessionInfo: manual session info detected"),e};return d.useMemo(()=>e instanceof Ft?{type:"manual",userSessionCandidate:r()}:e instanceof Ge?{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 Er({userSessionInfo:e,onUpdateMessengerSettings:t,onPreAuth:n,onPostAuth:o,onErrorAuth:r,onAuthTokenRefreshed:a,onPostDeauth:i,forceCreateChannel:l}){const{aiAgentId:c,language:u,context:g,countryCode:h,logger:m,cache:_}=j(),{connect:b,disconnect:S}=hr(),{type:f,userSessionCandidate:E}=br(e),C=Mn(),v=d.useCallback(async()=>{var B;m.debug("useAuthentication.authenticate: start");const I=E!=null&&E.userId?_.messenger.getSettings(E.userId):null;I!=null&&I.bot&&(t(I),m.debug("useAuthentication.authenticate: cached messenger settings",I));const x=await C({aiAgentId:c,userId:E==null?void 0:E.userId,language:u,country:h,context:g,forceCreateChannel:l,knownActiveChannelUrl:(B=I==null?void 0:I.active_channel)==null?void 0:B.channel_url});m.debug("useAuthentication.authenticate: messenger settings response",x);let O=null;if(x.auto_created_user)if(f==="manual")m.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),O={userId:E.userId,authToken:E.authToken};else{const{user_id:M,session_token:H,expire_at:G}=x.auto_created_user;_.messenger.setAnonUser({userId:M,authToken:H,expireAt:G}),O={userId:M,authToken:H}}else O={userId:(E==null?void 0:E.userId)??"",authToken:(E==null?void 0:E.authToken)??""};_.messenger.setSettings(O.userId,x),t(x);try{await n(x,O),await b(O,E==null?void 0:E.sessionHandler,a),await o(x,O)}catch(M){throw M instanceof Error&&(r(M),m.error("useAuthentication.authenticate: failed to connect",M)),M}return x},[C,b,f,E==null?void 0:E.userId,E==null?void 0:E.sessionHandler,E==null?void 0:E.authToken,c,u,g,h,l,_.messenger.setAnonUser,_.messenger.getSettings,_.messenger.setSettings,t,n,o,r,a]),A=d.useCallback(async()=>{m.debug("useAuthentication.deauthenticate: start"),await S(),i(),m.debug("useAuthentication.deauthenticate: completed")},[S,m,i]);return{authenticate:v,deauthenticate:A,userSessionCandidate:E}}const vr=e=>JSON.parse(e),Cr=()=>{const{chatSDK:e,logger:t,cache:n}=j(),o=d.useCallback(()=>{var l,c;const a=(c=(l=e.appInfo)==null?void 0:l.aiAgentInfo)==null?void 0:c.templateListToken;if(!a)return!1;const i=n.template.getCachedToken();return i?a!==i:!0},[e,n.template.getCachedToken]),r=d.useCallback(async()=>{try{const{templates:a,token:i}=await e.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of a){const{key:c}=vr(l);n.template.set(c,l)}n.template.setCachedToken(i)}catch(a){t==null||t.error("messageTemplateContext.syncCachedTemplates: error:",a)}},[e,t,n.template.set,n.template.setCachedToken]);return{shouldSyncCachedTemplate:o,syncCachedTemplates:r}},{Provider:Sr,useContext:Ke}=X("AIAgentMessengerSession"),Ar=d.forwardRef(function({userSessionInfo:e,forceCreateChannel:t,children:n},o){const{appId:r,aiAgentId:a,chatSDK:i,language:l,countryCode:c,context:u,cache:g,logger:h}=j(),{updateTheme:m}=ur(),[_,b]=d.useState(void 0),[S,f]=d.useState(void 0),[E,C]=d.useState(null),[v,A]=d.useState(null),[I,x]=d.useState(null),[O,B]=d.useState(null),{updateBaseAttachmentRules:M,createAttachmentRules:H}=gr(),{shouldSyncCachedTemplate:G,syncCachedTemplates:Z}=Cr(),ne=Mn(),{authenticate:q,deauthenticate:w}=Er({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(L=>{const{appearance:N,bot:V,launcher:re}=L;m(N.selected_theme,N),x({userId:V.bot_userid,profileUrl:V.bot_profile_url,nickname:V.bot_nickname,replyToFile:V.reply_to_file,specialNotice:V.special_notice,specialNoticeEnabled:V.is_special_notice_enabled,showHandoffButton:V.show_handoff_button??!0,isMultipleActiveConversationsEnabled:V.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:L.bot.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:L.bot.is_user_feedback_comment_option_enabled??!1}),B({type:re.image_type||"default_icon",imageUrl:re.image_url}),M(L)},[m]),onPreAuth:d.useCallback((L,N)=>{b(void 0),A(N)},[]),onPostAuth:d.useCallback(async L=>{C(i.currentUser),G()&&await Z(),f({url:L.active_channel.channel_url,status:Y.ConversationStatus.OPEN})},[i,G,Z]),onErrorAuth:d.useCallback(L=>{b(L)},[]),onAuthTokenRefreshed:d.useCallback(L=>{A(N=>N?{...N,authToken:L}:null)},[]),onPostDeauth:d.useCallback(()=>{g.template.clear(),g.messenger.clear(v==null?void 0:v.userId),C(null),f(void 0),A(null),x(null),B(null)},[g.template.clear,g.messenger.clear,v])}),U=d.useCallback(async()=>{var L;if(v){h.debug("agentMessengerSession.refreshActiveChannel: try to refresh active channel"),f(void 0);const N=await ne({aiAgentId:a,userId:v.userId,language:l,country:c,context:u,forceCreateChannel:t,knownActiveChannelUrl:(L=g.messenger.getSettings(v.userId))==null?void 0:L.active_channel.channel_url});return g.messenger.setSettings(v.userId,N),f({url:N.active_channel.channel_url,status:Y.ConversationStatus.OPEN}),h.info("agentMessengerSession.refreshActiveChannel: refreshed active channel",N.active_channel.channel_url),N.active_channel.channel_url}else throw h.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")},[ne,r,a,v==null?void 0:v.userId,l,c,u,t,g.messenger.getSettings,g.messenger.setSettings]),oe=d.useCallback(async L=>{if(!(v!=null&&v.userId))throw new Error("Current user is not authenticated. Please authenticate first.");const N=await ne({...L,userId:v.userId,knownActiveChannelUrl:void 0}),V=N.active_channel.channel_url;return g.messenger.setSettings(v.userId,N),V},[v==null?void 0:v.userId,ne]),[le]=d.useState(()=>Tn(L=>{var N;h.info("agentMessengerSession.channelChanged: channel.conversation",L.conversation),f({url:L.url,status:((N=L.conversation)==null?void 0:N.status)??Y.ConversationStatus.OPEN})},250,{trailing:!1,leading:!0}));return Nt.useGroupChannelHandler(i,{onChannelChanged:L=>{L.isGroupChannel()&&L.url===(S==null?void 0:S.url)&&le(L)}}),d.useEffect(()=>()=>{le.cancel()},[le]),d.useImperativeHandle(o,()=>{const L=async()=>{if(!S)throw new Error("No active conversation. Please start a conversation first.");return await i.groupChannel.getChannel(S.url)};return{activeChannel:S,chatSDK:i,authenticate:q,deauthenticate:w,updateContext:async N=>{const re=await(await L()).updateContext(a,N);return{...re,context:re.context??{}}},patchContext:async N=>{const re=await(await L()).patchContext(a,N);return{...re,context:re.context??{}}},getContextObject:async()=>{const V=await(await L()).getContextObject(a);return{...V,context:V.context??{}}}}},[q,w,S,i,a,h]),s.createElement(Sr,{value:{sdkUser:E,userSessionInfo:e,userSession:v,activeChannel:S,setActiveChannel:f,refreshActiveChannel:U,createConversation:oe,connectionError:_,aiAgentInfo:I,launcherInfo:O,authenticate:q,deauthenticate:w,createAttachmentRules:H}},n)}),wr=()=>{const e=d.useId(),{chatSDK:t,networkStateAdapter:n}=j(),[o,r]=d.useState(()=>n?n.isOnline()?"connected":"reconnecting":"connected");return d.useEffect(()=>{const a=new K.ConnectionHandler({onDisconnected:()=>r("disconnected"),onConnected:()=>r("connected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")});return t.addConnectionHandler(e,a),()=>{t.removeConnectionHandler(e)}},[t,e]),d.useEffect(()=>{if(n)return n.subscribe(()=>{r("reconnecting")})},[n]),o},Ln=e=>{const{chatSDK:t}=j(),[n,o]=d.useState([]);return Nt.useGroupChannelHandler(t,{onTypingStatusUpdated(r){if(r.url===(e==null?void 0:e.url)){const a=r.getTypingUsers();o(a)}}}),n},xr=({channel:e,messages:t,isStreamAnimating:n})=>{const{aiAgentInfo:o,userSession:r}=Ke(),a=wr(),i=Ir({channel:e,lastMessage:tn(t,[Se.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),l=Lr({shouldApply:!!(e!=null&&e.isAIAgent)&&!we(e),isDisabledWhileAIResponding:i,lastMessage:tn(t,[Se.SendingStatus.PENDING,Se.SendingStatus.SUCCEEDED]),currentUserId:(r==null?void 0:r.userId)??""});if(!e||a==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(a==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(ye(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Tr(e))return{disabled:!0,disabledBy:"form_active"};const c=kr(e);return c?{disabled:!0,disabledBy:c}:i||l?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},Ir=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:o})=>{const[r,a]=d.useState(!1),i=Ln(e);return d.useEffect(()=>{if(!t)return;const l=i.some(u=>u.userId===n),c=Re(t,n)&&(qe.isStreaming(t)||o);a(!!(c||l))},[i,t,n,o]),r},Tr=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,a=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return r&&!a},kr=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},Mr=3e4,Lr=({shouldApply:e,lastMessage:t,isDisabledWhileAIResponding:n,currentUserId:o})=>{const[r,a]=d.useState(!1),i=d.useRef(null),l=t&&Re(t,o)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),a(!1)},u=m=>{i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},m)},g=Date.now()-l,h=Mr-g;return n||h<=0?c():u(h),()=>{i.current&&clearTimeout(i.current)}},[n,l]),r&&e},Pr=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(r=>{t(a=>{if(a.has(r))return a;const i=new Set(a);return i.add(r),i})},[]),o=d.useCallback(r=>{t(a=>{if(!a.has(r))return a;const i=new Set(a);return i.delete(r),i})},[]);return{isAnimating:e.size>0,start:n,stop:o}},{Provider:Rr}=X("AIAgentConversation");function Dr({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:o,onMessagesUpdated:r,onConversationClosedStatusChanged:a,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Et,shouldMarkAsRead:u=!0,shouldCountNewMessages:g=()=>!1,sortComparator:h}){var B;const m=()=>u&&(f==null?void 0:f.markAsRead()),{chatSDK:_,logger:b,dispatcher:S}=j(),{channel:f,channelFetchError:E,fetchChannel:C}=Or(t),v=Zo(_,f,{replyType:Se.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:g,onChannelDeleted:n,onMessagesReceived:M=>o==null?void 0:o(M),onMessagesUpdated:M=>r==null?void 0:r(M),logger:b,markAsRead:m,sortComparator:h}),A=Pr(),I=xr({channel:f,messages:v.messages,isStreamAnimating:A.isAnimating});d.useEffect(()=>{m()},[u]);const x=ye(f);d.useEffect(()=>{a==null||a(x)},[x,a]),d.useEffect(()=>{const M=async H=>{const G=typeof(H==null?void 0:H.channelUrl)=="string";f&&G&&H.channelUrl!==f.url||(b.debug("conversation.dispatcher: try to close conversation",f),f!=null&&f.conversation&&f.conversation.status===Y.ConversationStatus.OPEN&&(await f.closeConversation(),i==null||i()))};return S.subscribe(vt.ConversationClose,M),()=>{S.unsubscribe(vt.ConversationClose,M)}},[S,(B=f==null?void 0:f.conversation)==null?void 0:B.status,i]);const O={conversation:(f==null?void 0:f.conversation)??void 0,channelSource:{channel:f,error:E,refetch:()=>C(),closeConversation:async()=>{ye(f)||await(f==null?void 0:f.closeConversation())}},messageSource:{messages:v.messages,newMessages:v.newMessages,initialized:v.initialized,loadPrevious:()=>v.loadPrevious(),loadNext:()=>v.loadNext(),deleteMessage:M=>v.deleteMessage(M),resendMessage:M=>v.resendMessage(M),resetNewMessages:()=>v.resetNewMessages(),sendUserMessage:async M=>{var G;if(((G=f==null?void 0:f.conversation)==null?void 0:G.status)===Y.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(M=await l(M));const H=await v.sendUserMessage(M,c);return c==null||c(H),H},sendFileMessage:async M=>{var G;if(((G=f==null?void 0:f.conversation)==null?void 0:G.status)===Y.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(M=await l(M));const H=await v.sendFileMessage(M,c);return c==null||c(H),H}},state:{streamAnimation:A,input:I}};return s.createElement(Rr,{value:O},e)}function Or(e){const{chatSDK:t,logger:n}=j(),{sdkUser:o}=Ke(),[r,a]=d.useState(void 0),[i,l]=d.useState(void 0);async function c(){if(!o){n.debug("conversation.fetchChannel: no sdk user, skip fetching channel");return}if(n.debug("conversation.fetchChannel: start"),a(void 0),l(void 0),e)try{n.debug("conversation.fetchChannel: get channel",e);const u=await t.groupChannel.getChannel(e);a(u),n.debug("conversation.fetchChannel: fetched channel",u)}catch(u){u instanceof K.SendbirdError&&l(u),n.error("conversation.fetchChannel: error",u)}}return Br(r),d.useEffect(()=>{c()},[t,o,e]),{channel:r,channelFetchError:i,fetchChannel:c}}function Br(e){const{chatSDK:t}=j(),{activeChannel:n,setActiveChannel:o}=Ke(),r=d.useId();d.useEffect(()=>{if(!e||!n)return;const a=new K.ConnectionHandler({onReconnectSucceeded:async()=>{var l;const i=await e.refresh();i.url===n.url&&o({url:i.url,status:((l=i.conversation)==null?void 0:l.status)??Y.ConversationStatus.OPEN})}});return t.addConnectionHandler(r,a),()=>{t.removeConnectionHandler(r)}},[t,e,n])}class Nr{constructor(t,{filter:n,limit:o=20}){z(this,"filter");z(this,"_sdk");z(this,"_pinnedChannels");z(this,"_channels");z(this,"_isDisposed",!1);z(this,"_handlerId",`handler-id-${Date.now()}`);z(this,"_order",We.GroupChannelListOrder.LATEST_LAST_MESSAGE);z(this,"_limit");z(this,"_query");z(this,"_token");z(this,"_timestamp");z(this,"_isSyncing");z(this,"_channelHandler");z(this,"_connectionHandler");z(this,"_collectionEventHandler");z(this,"_throttledOnChannelChanged");var r,a,i,l,c,u,g;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:(a=this.filter)==null?void 0:a.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:(g=this.filter)==null?void 0:g.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=Tn(h=>{h.isGroupChannel()&&(this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url]))},250,{trailing:!1,leading:!0}),this._channelHandler=new We.GroupChannelHandler({onChannelChanged:this._throttledOnChannelChanged,onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new K.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 a,i;const n=new Set(((a=this.filter)==null?void 0:a.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=[],a=[],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 g=St(this._pinnedChannels,c);g>=0?(this._pinnedChannels.splice(g,1),a.push(c)):r.push(c);const m=this._pinnedChannels.findIndex(b=>(o.get(b.url)??1/0)>u),_=m===-1?this._pinnedChannels.length:m;this._pinnedChannels.splice(_,0,c)}return{addedChannels:r,updatedChannels:a,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const o=[],r=[],a=[];for(const i of t){if(!this._query.belongsTo(i)){o.push(i.url);continue}const l=St(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const g=Hr(this._channels,i,this._order).place,h=g===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(i),r.push(i)):(this._channels.splice(g,0,i),r.push(i)):(this._channels.splice(g,0,i),a.push(i))}return{addedChannels:r,updatedChannels:a,unmatchedChannelUrls:o}}_addChannelsToView(t,n=!1){var h,m,_,b,S;const o=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),r=[],a=[];for(const f of t)o.has(f.url)?r.push(f):a.push(f);const i=this._upsertPinnedChannelsToArray(r),l=this._upsertRegularChannelsToArray(a,n),c=i.addedChannels.concat(l.addedChannels),u=i.updatedChannels.concat(l.updatedChannels),g=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((_=(m=this._collectionEventHandler)==null?void 0:m.onChannelsAdded)==null||_.call(m,{},c)),u.length>0&&((S=(b=this._collectionEventHandler)==null?void 0:b.onChannelsUpdated)==null||S.call(b,{},u)),g.length>0&&this._removeChannelsFromView(g)}_removeChannelsFromView(t){var r,a,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=(a=this._collectionEventHandler)==null?void 0:a.onChannelsDeleted)==null||i.call(a,{},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 St=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Hr=(e,t,n)=>{if(e.length>0){const o=St(e,t);let r=0,a=e.length-1,i=Math.floor((r+a)/2);for(;r<a;){const c=cn(e[i],t,n);if(c>0)a=i,i=Math.floor((r+a)/2);else if(c<0)r=i+1,i=Math.floor((r+a)/2);else return{place:i,oldPosition:o}}return{place:cn(e[i],t,n)>=0?i:i+1,oldPosition:o}}return{place:e.length,oldPosition:-1}},cn=(e,t,n)=>{switch(n){case We.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}};function zr(e,t){var b,S,f,E,C,v,A,I,x,O;const n=d.useId(),[o,r]=d.useState(!1),[a,i]=d.useState(null),[l,c]=d.useState([]),[u,g]=d.useState(null),h=d.useRef(!1),m=d.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,r(!1),i(null),c([]);try{u==null||u.dispose();const B=new Nr(e,t);B.setConversationListCollectionHandler({onChannelsAdded:()=>{c(B.channels)},onChannelsUpdated:()=>{c(B.channels)},onChannelsDeleted:()=>{c(B.channels)}}),await B.loadMore(),g(B),i(null)}catch(B){g(null),i(B)}finally{r(!0),h.current=!1}}},[e,e.currentUser,(b=t.filter)==null?void 0:b.aiAgentChannelFilter,(f=(S=t.filter)==null?void 0:S.aiAgentConversationStatusFilter)==null?void 0:f.join(),(C=(E=t.filter)==null?void 0:E.aiAgentIds)==null?void 0:C.join(),(v=t.filter)==null?void 0:v.deskChannelFilter,(I=(A=t.filter)==null?void 0:A.pinnedChannelUrls)==null?void 0:I.join(),(x=t.filter)==null?void 0:x.copilotConversationOnly,(O=t.filter)==null?void 0:O.copilotSupportChannelUrl,t.limit]),_=d.useCallback(async()=>{if(u)try{await u.loadMore()}catch(B){i(B)}},[u]);return d.useEffect(()=>(e.addConnectionHandler(n,new K.ConnectionHandler({onConnected:()=>m()})),()=>e.removeConnectionHandler(n)),[e,n,m]),d.useEffect(()=>{m()},[m]),d.useEffect(()=>()=>{h.current=!1,u==null||u.dispose()},[u]),{initialized:o,error:a,channels:l,loadMore:_}}const{Provider:Fr}=X("AIAgentConversationList");function $r({conversationListLimit:e,conversationListFilter:t,children:n}){var h,m;const{chatSDK:o,aiAgentId:r,queryParams:a}=j(),i={aiAgentIds:[r],aiAgentConversationStatusFilter:[Y.ConversationStatus.CLOSED,Y.ConversationStatus.OPEN]},l=e??((h=a==null?void 0:a.conversationListParams)==null?void 0:h.limit),c={...i,...(m=a==null?void 0:a.conversationListParams)==null?void 0:m.filter,...t},u=zr(o,{limit:l,filter:c}),g={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return s.createElement(Fr,{value:g},n)}function Ur(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:qr}=X("MessageTemplateFetching");function Vr({children:e,internalVariables:t}){const n=d.useRef({}),o=d.useRef({}),[r,a]=d.useState({}),i=d.useCallback((u,g)=>{a(h=>({...h,[u]:{fetching:!1,error:!1,...h[u],...g}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:g,templateKey:h,suspense:m=!1})=>{const _=g(h);if(_)return _;const b=o.current[h];if(b)return b;m||i(h,{fetching:!0});const S=u(h).catch(f=>{throw m||i(h,{error:!0}),f}).finally(()=>{m||i(h,{fetching:!1}),delete o.current[h]});return o.current[h]=S,S},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(u,g)=>{if(n.current[u])return n.current[u];const h=Ur(g());return n.current[u]=h,h},getIsFetching:u=>{var g;return((g=r[u])==null?void 0:g.fetching)??!1},getHasError:u=>{var g;return((g=r[u])==null?void 0:g.error)??!1}};return s.createElement(qr,{value:c},e)}const Wr="remove_powered_by",$t=(e,t)=>{var r,a;const{chatSDK:n}=j(),{aiAgentInfo:o}=Ke();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&&Cn(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(o!=null&&o.specialNoticeEnabled)&&!!(o!=null&&o.specialNotice);if(e==="powered-by"){const i=(a=n==null?void 0:n.appInfo)==null?void 0:a.applicationAttributes;return d.useMemo(()=>!(Array.isArray(i)&&i.includes(Wr)),[i])}throw new Error("Unsupported feature")},Pn=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const o=(()=>{const[a]=e.members.filter(i=>i.userId!==t.userId);return a})(),r={ai(a){return{fallbackIcon:a,url:n.profileUrl,title:n.nickname}},human(a){return{fallbackIcon:a,url:o==null?void 0:o.profileUrl,title:(o==null?void 0:o.nickname)||n.nickname}},channel(a){return{fallbackIcon:a,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")},At=e=>d.useReducer((t,n)=>({...t,...n}),e);var ue=(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))(ue||{});const Gr=new Set(["free_text","single_choice"]),jr=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:o,initialIsResolved:r})=>{const[a,i]=At({csatType:t,csat:n,csatReason:o,isResolved:r}),[l,c]=At({followUpItem:!1}),u=d.useMemo(()=>{var S;const _=a.csat;if(typeof _!="number")return;const b=(S=e.follow_up)==null?void 0:S.find(f=>f.scores.includes(_));if(Gr.has(b==null?void 0:b.response_type))return b},[a.csat,e.follow_up]),g=(()=>{var _;if(typeof n=="number")return"submitted";if((t===ue.AI_AGENT_CSAT_5||t===ue.HELPDESK_CSAT_5)&&typeof a.csat=="number")return"submittable";if(t===ue.AI_AGENT_CSAT_5_WITH_CRE){const b=typeof a.csat=="number",S=!((_=e.cre)!=null&&_.required)||typeof a.isResolved=="boolean";if(b&&S)return"submittable"}return"unsubmittable"})(),h=d.useCallback(()=>typeof a.csat>"u"?!1:u!=null&&u.required&&!a.csatReason?(c({followUpItem:!0}),!1):!0,[a,u,c]);return d.useEffect(()=>{o||(i({csatReason:""}),c({followUpItem:!1}))},[o,u,i,c]),{params:a,setParams:i,error:l,setError:c,followUpItem:u,state:g,validateParams:h,itemProps:{csatPayload:e,state:g,submitted:g==="submitted"}}},at=5,Kr=250,Yr=50,un=e=>Math.max(0,e-Yr),Xr=e=>e<1e3?{speed:at*.5,chunkSize:2}:e<2e3?{speed:at*.8,chunkSize:2}:{speed:at*.6,chunkSize:3},Zr=e=>{const{text:t,enabled:n=!1,onAnimationStart:o,onAnimationProgress:r,onAnimationComplete:a}=e,[i,l]=d.useState(()=>un(t.length)),c=d.useRef(null),u=d.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,g=d.useRef({onStart:o,onProgress:r,onComplete:a}).current,h=d.useRef({startCalled:!1,completeCalled:!1}).current,m=d.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,_=n,b=i<t.length,S=m.initialEnabled&&(_||b);return d.useLayoutEffect(()=>{g.onStart=o,g.onProgress=r,g.onComplete=a,m.textLength=t.length,m.enabled=n}),d.useLayoutEffect(()=>{var f;m.initialEnabled&&(h.startCalled||(h.startCalled=!0,(f=g.onStart)==null||f.call(g)),l(E=>t.length<E?t.length:E))},[t]),d.useEffect(()=>{if(!m.initialEnabled)return;let f=un(t.length);u.lastUpdate=0,u.startTime=0,u.lastProgressCall=0;const E=C=>{var H;u.lastUpdate===0&&(u.lastUpdate=C,u.startTime=C,u.lastProgressCall=C);const v=m.textLength,A=C-u.lastUpdate,I=C-u.startTime,{speed:x,chunkSize:O}=Xr(I),B=x*O;A>=B&&f<v&&(f=Math.min(f+O,v),l(f),u.lastUpdate=C),C-u.lastProgressCall>=Kr&&(u.lastProgressCall=C,(H=g.onProgress)==null||H.call(g)),(f<v||m.enabled)&&(c.current=requestAnimationFrame(E))};return c.current=requestAnimationFrame(E),()=>{c.current&&cancelAnimationFrame(c.current)}},[]),d.useEffect(()=>{var v;const f=m.initialEnabled&&h.startCalled,E=!n,C=i>=t.length&&t.length>0;f&&E&&C&&!h.completeCalled&&(h.completeCalled=!0,(v=g.onComplete)==null||v.call(g))},[n,i,t.length]),{streamText:m.initialEnabled?t.slice(0,i):t,isAnimating:S}},Jr={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"}},wt={language:"en",strings:Jr,dateLocale:co.enUS},Qr={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:"피드백 삭제"}},xt={language:"ko",strings:Qr,dateLocale:po.ko},es={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:"フィードバックを削除"}},It={language:"ja",strings:es,dateLocale:fo.ja},ts={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"}},Tt={language:"es",strings:ts,dateLocale:uo.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"},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"}},kt={language:"pt",strings:ns,dateLocale:_o.pt},os={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"}},Mt={language:"fr",strings:os,dateLocale:mo.fr},rs={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:"प्रतिक्रिया हटाएं"}},Lt={language:"hi",strings:rs,dateLocale:go.hi},ss={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"}},Pt={language:"it",strings:ss,dateLocale:ho.it},as={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"}},Rt={language:"de",strings:as,dateLocale:lo.de},is={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"}},Dt={language:"tr",strings:is,dateLocale:yo.tr},ie=e=>({conversation:e.conversation,conversation_list:e.conversation_list,date_format:e.date_format,csat:e.csat,form:e.form,common:e.common,feedback:e.feedback}),dn=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Ye},Ye="en",Ut={borderColor:"red",borderWidth:p.StyleSheet.hairlineWidth},y=({debug:e=!1,style:t,children:n,...o})=>s.createElement(p.View,{style:[t,o,e&&Ut],...o},n);y.Animated=({debug:e=!1,style:t,children:n,...o})=>s.createElement(p.Animated.View,{style:[t,o,e&&Ut],...o},n);const{Provider:ls,useContext:J}=X("MessengerSession"),cs=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof Ge||t.userSessionInfo instanceof Ft))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return s.createElement(Ar,{ref:n,...t},o=>s.createElement(us,{...o},e))}),us=({children:e,...t})=>{const{userSession:n,aiAgentInfo:o,launcherInfo:r}=t;return s.createElement(ls,{value:{...t,userSession:n,aiAgentInfo:o,launcherInfo:r}},e)},He=50,{Provider:ds,useContext:ms}=X("ConversationScroll"),gs=({children:e})=>{var ne;const{config:t}=j(),n=((ne=t==null?void 0:t.conversation)==null?void 0:ne.scrollMode)??"auto",o=d.useRef(null),r=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),a=d.useRef(0),[i,l]=d.useState(0),[c,u]=d.useState(0),[g,h]=d.useState(!1),[m,_]=d.useState(!1),b=d.useMemo(()=>m?"auto":n,[m,n]),S=d.useCallback(()=>{const{shouldUpdate:q,shouldRecalc:w,contentHeight:U,contentSnapshotHeight:oe,viewport:le}=r.current;q&&oe<U&&l(L=>{r.current.shouldUpdate=!1;const N=U-L-oe,V=Math.max(0,le-N);return L===0||V<L||w?(r.current.shouldRecalc=!1,V):L})},[]),f=d.useCallback(q=>{r.current.viewport=q.nativeEvent.layout.height},[]),E=d.useCallback((q,w)=>{r.current.contentHeight=w;const U=r.current.viewport;h(w>U),S()},[S]),C=d.useCallback(q=>{const w=q.nativeEvent.contentOffset.y;a.current=w,u(w)},[]),v=d.useMemo(()=>({minIndexForVisible:0,autoscrollToTopThreshold:He}),[]),A=d.useCallback((q=!0)=>{var w;(w=o.current)==null||w.scrollToOffset({offset:0,animated:q})},[]),I=d.useCallback((q,w=!0)=>{var U;(U=o.current)==null||U.scrollToIndex({index:q,animated:w,viewPosition:1})},[]),x=d.useCallback(()=>{b==="fixed"&&(r.current.contentSnapshotHeight=r.current.contentHeight-i,r.current.shouldUpdate=!0,r.current.shouldRecalc=!0)},[b,i]),O=d.useCallback(()=>{b==="fixed"?I(0):A()},[b,A,I]),B=d.useCallback(()=>{b==="fixed"?r.current.shouldUpdate=!0:a.current<=He&&A()},[b,A]),M=d.useCallback(q=>{_(q)},[]),H=c<=He,G=g&&!H,Z=d.useCallback(()=>a.current>He,[]);return s.createElement(ds,{value:{ref:o,state:{bottomSpace:i,isAwayFromBottom:G,shouldCountNewMessages:Z},props:{maintainVisibleContentPosition:v,onLayout:f,onContentSizeChange:E,onScroll:C},actions:{scrollToBottom:A,scrollToIndex:I,onBeforeMessageSend:x,onAfterMessageSend:O,onStreamingUpdate:B,onConversationClosed:M}}},e)};function Rn(e){return new Promise((t,n)=>{p.Image.getSize(e,(o,r)=>{t({width:String(o),height:String(r)})},o=>{n(o)})})}async function hs(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 Rn(n.uri);return new Se.MessageMetaArray({key:Sn,value:[o,r]})}catch{return}}}function fs(e,t){let n=0,o=0;return se(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),se(t)&&t.sendingStatus!=="succeeded"&&(o=Number.MAX_SAFE_INTEGER),t.createdAt+o-(e.createdAt+n)}const{Provider:ps,Context:_s,useContext:te}=X("Conversation"),Dn=e=>s.createElement(gs,null,s.createElement(ys,{...e})),ys=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:o,shouldMarkAsRead:r,children:a})=>{const i=ms(),{activeChannel:l,refreshActiveChannel:c,sdkUser:u,authenticate:g}=J();d.useEffect(()=>{u||g()},[]);const h=d.useCallback(async S=>{i.actions.onBeforeMessageSend();const f=await hs(S);return{...S,metaArrays:f?[f]:void 0}},[i.actions.onBeforeMessageSend]),m=d.useCallback(()=>{i.actions.onAfterMessageSend()},[i.actions.onAfterMessageSend]),_=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]),b=e??(l==null?void 0:l.url);return s.createElement(Dr,{key:b,channelUrl:b,onBeforeSendMessage:h,onAfterSendMessage:m,onMessagesUpdated:i.actions.onStreamingUpdate,onMessagesReceived:i.actions.onStreamingUpdate,onChannelDeleted:_,onConversationClosedStatusChanged:i.actions.onConversationClosed,sortComparator:fs,shouldMarkAsRead:r,shouldCountNewMessages:i.state.shouldCountNewMessages},S=>s.createElement(ps,{value:{...S,scrollSource:i,onClose:n,onNavigateToConversationList:o,updateActiveChannel:_}},a))},it=ie(Rt.strings),bs={...it,conversation:{...it.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:{...it.conversation_list}},Es={language:Rt.language,dateLocale:Rt.dateLocale,strings:bs},lt=ie(wt.strings),vs={...lt,conversation:{...lt.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:{...lt.conversation_list}},Cs={language:wt.language,dateLocale:wt.dateLocale,strings:vs},ct=ie(Tt.strings),Ss={...ct,conversation:{...ct.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:{...ct.conversation_list}},As={language:Tt.language,dateLocale:Tt.dateLocale,strings:Ss},ut=ie(Mt.strings),ws={...ut,conversation:{...ut.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:{...ut.conversation_list}},xs={language:Mt.language,dateLocale:Mt.dateLocale,strings:ws},dt=ie(Lt.strings),Is={...dt,conversation:{...dt.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:{...dt.conversation_list}},Ts={language:Lt.language,dateLocale:Lt.dateLocale,strings:Is},mt=ie(Pt.strings),ks={...mt,conversation:{...mt.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:{...mt.conversation_list}},Ms={language:Pt.language,dateLocale:Pt.dateLocale,strings:ks},gt=ie(It.strings),Ls={...gt,conversation:{...gt.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:{...gt.conversation_list}},Ps={language:It.language,dateLocale:It.dateLocale,strings:Ls},ht=ie(xt.strings),Rs={...ht,conversation:{...ht.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:{...ht.conversation_list}},Ds={language:xt.language,dateLocale:xt.dateLocale,strings:Rs},ft=ie(kt.strings),Os={...ft,conversation:{...ft.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:{...ft.conversation_list}},Bs={language:kt.language,dateLocale:kt.dateLocale,strings:Os},pt=ie(Dt.strings),Ns={...pt,conversation:{...pt.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:{...pt.conversation_list}},Hs={language:Dt.language,dateLocale:Dt.dateLocale,strings:Ns},mn=new Map([["en",Cs],["ko",Ds],["ja",Ps],["es",As],["pt",Bs],["fr",xs],["hi",Ts],["it",Ms],["de",Es],["tr",Hs]]),gn=e=>mn.get(e)??mn.get(Ye),zs=(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:Fs,useContext:F}=X("Localization"),$s=({language:e=Ye,logger:t,strings:n,children:o})=>{const[r,a]=d.useState(()=>{const i=dn(e);return gn(i)});return d.useEffect(()=>{var l;const i=dn(e);if(r.language!==i){const c=gn(i);a(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:r.language,to:c.language})}},[e,t]),s.createElement(Fs,{value:{language:r.language,strings:zs(r.strings,n),dateLocale:r.dateLocale,format:(i,l,c)=>Ce.format(i,l,{locale:r.dateLocale,...c})}},o)},{Provider:Us,useContext:Xe}=X("Modal");function On({children:e}){const[t,n]=d.useState([]),[o,r]=d.useState(null),a=d.useRef(0);d.useEffect(()=>{if(!o&&t.length>0){const[u,...g]=t;u&&(r(u),n(g))}},[o,t]);const i=d.useCallback(u=>new Promise(g=>{const m={id:`modal-${++a.current}`,render:u,resolve:g};n(_=>[..._,m])}),[]),l=d.useCallback((u,g)=>{r(h=>(h==null?void 0:h.id)===u?(h.resolve(g),null):h)},[]),c={openModal:i,currentModal:o};return s.createElement(Us,{value:c},e,o&&s.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:qs,useContext:$}=X("MessengerTheme"),Vs=({children:e,...t})=>s.createElement(dr,{...t,appearance:{theme:t.mode??"light"}},n=>{const o=Ws(n.theme);return s.createElement(qs,{value:{...n,themedColor:o}},e)});function Ws(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 a=e(o),i={},l={};for(const g in a)typeof a[g]=="function"?l[g]=a[g]:i[g]=a[g];const u={...p.StyleSheet.create(i),...l};return t.set(o.theme,u),u};return{use:()=>{const o=$(),r=_e.useSafeAreaInsets();return n({...o,edgeInsets:r,select:a=>a[o.theme.selectedTheme]})}}}},Gs={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=_e.useSafeAreaInsets();return e.reduce((o,r)=>{const a=Gs[t][r];return o[a]=n[r],o},{})},js={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")},Ks={send:!0,chat:!0,message:!0,good:!0,bad:!0,"good-filled":!0,"bad-filled":!0},D=({customSource:e,type:t,color:n,size:o=24,style:r})=>{const a=Ys.use(),i=p.I18nManager.isRTL&&!!Ks[t];return s.createElement(y,{alignItems:"center",justifyContent:"center"},s.createElement(p.Image,{resizeMode:"contain",source:e??js[t],style:[a.icon({color:n,size:o,mirror:i}),r]}))},Ys=P.create(({theme:e,themedColor:t})=>({icon:n=>({tintColor:typeof n.color=="function"?n.color(t):n.color??e.colors.base.primary,width:n.size,height:n.size,transform:n.mirror?[{scaleX:-1}]:void 0})})),qt=(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:Js(r)},Bn=e=>qt("start",e),Xs=e=>qt("end",e),Zs=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"&&Bn(t)?o?"right":p.I18nManager.doLeftAndRightSwapInRTL?"left":"right":n==null?void 0:n.textAlign},Js=e=>{for(const[t,n]of Qs)if(e>=t&&e<=n)return!0;return!1},Qs=[[1424,1535],[1536,1791],[1872,1919],[2208,2303],[64285,64335],[65136,65279],[126464,126719]],Vt={isStartsWithRTL:Bn,isEndsWithRTL:Xs,isRTLString:qt,useTextAlign:Zs},T=({variant:e="body1",color:t,style:n,...o})=>{const{theme:r,themedColor:a}=$(),i=d.useMemo(()=>{if(typeof t=="function")return t(a);if(typeof t=="string")return t;const u=p.StyleSheet.flatten(n);return u&&u.color?u.color:t??a.textHighEmphasis},[n,t,a.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,a.textHighEmphasis]),c=Vt.useTextAlign({text:o.children,style:l});return s.createElement(p.Text,{style:[l,{textAlign:c}],...o})},Nn=350,ea=({children:e,...t})=>s.createElement(p.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:Nn,...t},n=>typeof e=="function"?e(n):e),ta=({children:e,style:t,...n})=>{const[o,r]=d.useState(!1),a={pressed:o};return s.createElement(p.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:Nn,style:typeof t=="function"?t(a):t,onPressIn:()=>r(!0),onPressOut:()=>r(!1),...n},typeof e=="function"?e(a):e)},R=e=>e.activeOpacity&&e.activeOpacity<1?s.createElement(ta,{...e}):s.createElement(ea,{...e}),{Provider:na,useContext:Hn}=X("BottomSheetAnimation");function oa({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(a=>async()=>{p.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(async()=>{try{await(a==null?void 0:a())}catch{e==null||e()}})},[n]),r=d.useRef(p.PanResponder.create({onMoveShouldSetPanResponder:(a,i)=>i.dy>5,onPanResponderMove:(a,i)=>{i.dy>0&&n.setValue(i.dy)},onPanResponderRelease:(a,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 s.createElement(na,{value:{wrapWithAnimation:o,translateY:n,panHandlers:r.panHandlers}},t)}const ra=({icon:e,label:t="",destructive:n=!1,onPress:o})=>{const r=zn.use(),{themedColor:a}=$();return s.createElement(R,{onPress:o,style:r.actionItem,activeOpacity:.75},e&&s.createElement(D,{type:e,size:24,color:a.primary}),s.createElement(T,{variant:"body3",color:n?a.error:a.textHighEmphasis,numberOfLines:1},t))},sa=({onClose:e,children:t})=>{const n=zn.use(),{translateY:o,panHandlers:r,wrapWithAnimation:a}=Hn(),i=Ie(["left","right"]);return s.createElement(R,{onPress:a(e),style:n.overlay},s.createElement(y.Animated,{style:[n.container,i,{transform:[{translateY:o}]}],...r},t))},Ze=ae({template:sa,components:{ActionItem:ra}}),ee=e=>{const{Template:t}=Ze.useContext();return s.createElement(oa,{onClose:e.onClose},s.createElement(t,{...e}))};ee.ActionItem=e=>{const{components:t}=Ze.useContext(),{wrapWithAnimation:n}=Hn();return s.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const zn=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}})),aa=({date:e=Date.now(),style:t,...n})=>{const{format:o,strings:r}=F();return s.createElement(y,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},s.createElement(T,{variant:"caption4",color:a=>a.textMidEmphasis},o(e,r.date_format.date_separator)))},ia=({style:e,label:t,accessibilityLabel:n,onPress:o})=>{const r=la.use(),{theme:a}=$();return s.createElement(R,{style:[r.button,e],onPress:o,accessibilityLabel:n,accessibilityRole:"button"},s.createElement(y,{flexDirection:"row",alignItems:"center",gap:4},s.createElement(T,{variant:"button",color:a.colors.base.primaryContrastContent},t),s.createElement(D,{size:16,type:"chevron-down",color:a.colors.base.primaryContrastContent})))},la=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}]}})),Wt=({iconSize:e=64,icon:t,style:n,label:o,children:r})=>{const{themedColor:a}=$();return s.createElement(y,{style:[Fn.body,n]},t&&s.createElement(D,{type:t,size:e,color:a.textLowEmphasis}),o&&s.createElement(T,{variant:"body1",color:a.textMidEmphasis},o),r)},ca=({children:e})=>{const{theme:t}=$();return s.createElement(y,{backgroundColor:t.colors.base.background,style:Fn.container},e)},Fn=p.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),ua=({label:e,icon:t="error",action:n,...o})=>{const{strings:r}=F();return s.createElement(Wt,{icon:t,label:e??r.common.placeholder_something_went_wrong,...o},n&&s.createElement(da,{onPress:n.onPress,label:n.label??r.common.placeholder_something_went_wrong_retry_label}))},da=({label:e,onPress:t})=>{const{themedColor:n}=$();return s.createElement(R,{onPress:t},s.createElement(y,{style:ma.button},s.createElement(D,{type:"refresh",size:20}),s.createElement(T,{variant:"button",color:n.primary},e)))},ma=p.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),ga=({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 s.createElement(y.Animated,{style:[{transform:[{rotate:o}]},t]},s.createElement(D,{type:"spinner",size:e}))},ha=({label:e,icon:t="chat",...n})=>{const{strings:o}=F();return s.createElement(Wt,{icon:t,label:e??o.common.placeholder_no_conversations,...n})},fa=({label:e,icon:t="message",...n})=>{const{strings:o}=F();return s.createElement(Wt,{icon:t,label:e??o.common.placeholder_no_messages,...n})},pa=e=>{const{components:t}=Gt.useContext(),n=e.type==="loading"?s.createElement(t.Loading,{...e}):e.type==="error"?s.createElement(t.Error,{...e}):e.type==="noChannels"?s.createElement(t.NoChannels,{...e}):e.type==="noMessages"?s.createElement(t.NoMessages,{...e}):null;return n&&s.createElement(ca,null,n)},Gt=ae({template:pa,components:{Loading:ga,Error:ua,NoChannels:ha,NoMessages:fa}}),Ae=e=>{const{Template:t}=Gt.useContext();return s.createElement(t,{...e})},_a=({style:e,onPress:t})=>{const n=ya.use(),{theme:o}=$();return s.createElement(R,{style:[n.button,e],onPress:t},s.createElement(y,{alignItems:"center",justifyContent:"center"},s.createElement(D,{size:24,type:"chevron-down",color:o.colors.base.primary})))},ya=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}]}})),ba=({loading:e,error:t,data:n,LoadingComponent:o,ErrorComponent:r,EmptyComponent:a,...i},l)=>t?r:e?o:!n||n.length===0?a:s.createElement(p.FlatList,{ref:l,data:n,...i}),$n=d.memo(d.forwardRef(ba)),jt=({name:e,type:t="FILE",onPress:n})=>{const o=Ea.use();return s.createElement(R,{onPress:n,style:o.container,activeOpacity:.75},s.createElement(y,{style:o.iconWrapper},s.createElement(D,{type:"file-document",size:24,color:o.icon.tintColor})),s.createElement(y,{flex:1,flexDirection:"column",gap:4,style:o.info},s.createElement(T,{variant:"button",color:r=>r.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),s.createElement(T,{variant:"caption3",color:r=>r.textMidEmphasis},t)))},Ea=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}})),va=({file:e,children:t,onClickFile:n=({url:o})=>p.Linking.openURL(o)})=>s.createElement(y,{gap:k.GAP_GROUPED,width:k.BODY_MAX_WIDTH,maxWidth:k.BODY_MAX_WIDTH},s.createElement(jt,{name:e.name,type:Ht(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),xe=({style:e,...t})=>s.createElement(p.Image,{style:[e,t],...t}),Ca=({file:e,onClickMedia:t=({url:o})=>p.Linking.openURL(o),children:n})=>{const o=Sa.use();return s.createElement(y,{gap:k.GAP_GROUPED},s.createElement(R,{style:o.mediaContainer,onPress:()=>t==null?void 0:t(e)},s.createElement(xe,{source:{uri:e.url},style:o.media,resizeMode:"cover"})),n)},Sa=P.create(({select:e,theme:t})=>({mediaContainer:{width:k.BODY_MAX_WIDTH,height:160,borderRadius:12,overflow:"hidden",backgroundColor:e({light:t.palette.background100,dark:t.palette.background400})},media:{width:"100%",height:"100%"}})),Un=({code:e,language:t})=>{const[n,o]=d.useState(!1),r=async()=>{wo.default.setString(e),o(!0),setTimeout(()=>o(!1),2e3)};return s.createElement(y,{style:ze.container,flexDirection:"row"},s.createElement(p.Pressable,{style:ze.copyButton,onPress:r},s.createElement(D,{type:n?"done":"copy",size:16,color:"#fff"})),s.createElement(y,null,s.createElement(xo.default,{hljsStyle:vo.atomOneDarkReasonable,scrollViewProps:{contentContainerStyle:ze.codeContainer,bounces:!1},textStyle:ze.codeText,language:t},e)))},ze=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}}),qn=d.memo(({src:e,onPress:t})=>{const[n,o]=d.useState("1/1"),[r,a]=d.useState(!1),i=Aa.use();return d.useLayoutEffect(()=>{e&&Rn(e).then(({width:l,height:c})=>o(`${l}/${c}`))},[e]),s.createElement(p.Pressable,{style:{marginTop:8},onPress:t},s.createElement(y,{style:[i.container,{aspectRatio:n}]},r?s.createElement(D,{size:28,type:"thumbnail-none",color:l=>l.textHighEmphasisInverse}):s.createElement(p.Image,{source:{uri:e},style:p.StyleSheet.absoluteFillObject,onError:()=>a(!0)})))}),Aa=P.create(({themedColor:e})=>({container:{width:"100%",backgroundColor:e.textDisabled,borderRadius:4,overflow:"hidden",justifyContent:"center",alignItems:"center"}}));qn.displayName="MarkdownImage";const ke=e=>d.isValidElement(e)&&"children"in e.props,Ot=(e=.75)=>`rgba(0, 0, 0, ${e})`,wa=({children:e})=>{var i;const t=p.useWindowDimensions(),n=Ot(.3),o=d.useMemo(()=>{try{if(!Array.isArray(e)||e.length<2)return null;const l=e[0],c=e[1],u=ke(c)?c.props.children:void 0;if(!u||!Array.isArray(u)||u.length===0)return null;const g=u,h=g[0],m=ke(h)?h.props.children:void 0;if(!m||!Array.isArray(m)||m.length===0)return null;const _=g.length,b=m.length,S=Array(b).fill(null).map(()=>[]);for(let v=0;v<_;v++){const A=g[v],I=ke(A)?A.props.children:void 0;if(!(!I||!Array.isArray(I)))for(let x=0;x<b;x++){const O=S[x];O&&x<I.length&&(O[v]=I[x])}}const f=ke(l)?l.props.children:void 0,E=Array.isArray(f)?f[0]:void 0,C=ke(E)?E.props.children:void 0;if(C&&Array.isArray(C))for(let v=0;v<b;v++){const A=S[v];A&&v<C.length&&A.unshift(C[v])}return S}catch{return null}},[e]),[r,a]=d.useState(Array(((i=o==null?void 0:o[0])==null?void 0:i.length)??0).fill(0));return o?s.createElement(p.View,{style:{flexDirection:"row"}},o.map((l,c)=>{const u=c===0,g=c===o.length-1;return s.createElement(p.View,{key:c,style:{flexDirection:"column",borderStartWidth:1,borderEndWidth:g?1:0,borderTopWidth:1,borderBottomWidth:1,borderColor:n,borderTopStartRadius:u?6:0,borderBottomStartRadius:u?6:0,borderTopEndRadius:g?6:0,borderBottomEndRadius:g?6:0}},l.map((h,m)=>{const _=m===0,b=m===l.length-1;return s.createElement(p.View,{key:m,onLayout:({nativeEvent:{layout:S}})=>{const f=S.height;(r[m]??0)<f&&(r[m]=f,a([...r]))},style:{borderBottomWidth:b?0:1,borderColor:n,backgroundColor:_?Ot(.15):"transparent",maxWidth:t.width*2/3,minHeight:(r[m]??0)>0?r[m]:void 0,padding:8}},h)}))})):s.createElement(p.View,null,e)},Kt=d.memo(({children:e,textStyle:t,linkStyle:n,onPressImage:o})=>{const{themedColor:r}=$(),a=p.StyleSheet.compose({fontSize:14,color:r.textHighEmphasis,textAlign:"left"},t),i=p.StyleSheet.flatten(a),l=i.fontSize||14,c=i.lineHeight||l*1.286,u=Ot(.3),g={color:i.color,textAlign:Vt.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:m=>{var b,S;const _=((b=m.attributes)==null?void 0:b.src)||((S=m.attributes)==null?void 0:S.href);return _?s.createElement(qn,{key:m.key,src:_,onPress:()=>o==null?void 0:o(_)}):null},code_block:m=>s.createElement(Un,{code:m.content,language:"text"}),table:(m,_)=>s.createElement(p.View,{key:m.key,style:{marginTop:8}},s.createElement(p.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},s.createElement(wa,null,_)))}),[o]);return s.createElement(y,{flexDirection:"row",marginTop:-8},s.createElement(Io.default,{style:{body:{...g,width:e.length>50?"100%":void 0,marginBottom:0},paragraph:{...g,marginTop:8,marginBottom:0},heading1:{...g,marginTop:8,marginBottom:0,fontSize:l*1.429,lineHeight:l*1.429*1.4,fontWeight:"700"},heading2:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.286,lineHeight:l*1.286*1.333},heading3:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading4:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading5:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading6:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},link:p.StyleSheet.flatten(p.StyleSheet.compose({...g,fontWeight:"700",textDecorationLine:"underline"},n)),code_inline:{...g,fontSize:l*.929,lineHeight:l*.929*1.538,fontWeight:"600",backgroundColor:u},code_block:{...g,borderWidth:0,backgroundColor:u,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538},fence:{...g,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:{...g,marginTop:4,marginBottom:0},blockquote:{...g,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:{...g,padding:4,fontSize:l,lineHeight:l*1.143,fontWeight:"700"},td:{...g,padding:2,fontSize:l,lineHeight:l*1.429},image:{maxHeight:300,maxWidth:"100%"}},rules:h},$o(e)))});Kt.displayName="MarkdownText";const hn=({maxBodyWidth:e,customStyle:t,message:n,children:o})=>{const r=xa.use(),a=e??k.BODY_MAX_WIDTH,i=d.useMemo(()=>No(n),[n]),l=d.useCallback(c=>p.Linking.openURL(c),[]);return i.length===0&&!o?null:s.createElement(y,{alignSelf:"flex-start",maxWidth:a,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"?s.createElement(y,{key:u,paddingHorizontal:12},s.createElement(Kt,{onPressImage:l,textStyle:r.text},c.value)):c.type==="code"?s.createElement(Un,{key:u,code:c.value,language:c.language}):null),o)},xa=P.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),Ia=e=>{const{strings:t}=F(),n=()=>{const o=wn(e)?s.createElement(hn,{...e}):null;return e.messageType==="user"?o:e.messageType==="file"?e.file.type.startsWith("image")?s.createElement(Ca,{...e},o):s.createElement(va,{...e},o):s.createElement(hn,{...e,message:t.conversation.unknown_message_type})};return s.createElement(y,{style:e.containerStyle},n())};function Vn({id:e,src:t,size:n=56,onClick:o,style:r}){const a=Ta.use(),i=s.createElement(p.View,{style:[a.container(n),r],testID:e},t?s.createElement(p.Image,{source:{uri:t},style:a.image}):s.createElement(D,{type:"user",size:n}));return o?s.createElement(R,{onPress:o,activeOpacity:.75},i):i}const Ta=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"}})),ka=({sender:e,isBotMessage:t})=>{const n=Ma.use();return t&&!e.profileUrl?s.createElement(y,{style:n.botContainer},s.createElement(D,{type:"delight",size:k.AVATAR_SIZE-8})):s.createElement(Vn,{src:e.profileUrl,size:k.AVATAR_SIZE})},Ma=P.create(({theme:e})=>({botContainer:{width:k.AVATAR_SIZE,height:k.AVATAR_SIZE,borderRadius:k.AVATAR_SIZE/2,padding:4,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary}})),La=({sender:e})=>s.createElement(y,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7,alignItems:"flex-start"},s.createElement(T,{variant:"caption1",color:t=>t.textMidEmphasis,numberOfLines:1},e.nickname)),Pa=({createdAt:e,containerStyle:t})=>{const{strings:n,format:o}=F();return e?s.createElement(y,{alignItems:"flex-start",style:t},s.createElement(T,{variant:"caption4",color:r=>r.textLowEmphasis},o(e,n.date_format.message_timestamp))):null},Ra=({customStyle:e,containerStyle:t})=>{const{theme:n}=$(),o=d.useRef(new p.Animated.Value(0)).current,r=Da.map(([a,i,l])=>[o.interpolate({inputRange:a,outputRange:i,extrapolate:"clamp"}),o.interpolate({inputRange:a,outputRange:l,extrapolate:"clamp"})]);return d.useEffect(()=>{const a=p.Animated.loop(p.Animated.timing(o,{toValue:1.4,duration:1400,easing:p.Easing.linear,useNativeDriver:!0}));return a.start(),()=>a.reset()},[]),s.createElement(y,{style:t},s.createElement(y,{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(([a,i],l)=>s.createElement(y.Animated,{key:l,style:[Oa.dot,{marginEnd:l===r.length-1?0:6,opacity:i,transform:[{scale:a}],backgroundColor:(e==null?void 0:e.bubbleContentColor)??n.colors.messageIncoming.text}]}))))},Da=[[[.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]]],Oa=p.StyleSheet.create({dot:{width:8,height:8,borderRadius:4}}),Ba=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>p.Linking.openURL(n)})=>{const n=Na.use(),o=e==null?void 0:e.cta_button;return o?s.createElement(R,{onPress:()=>t(o),activeOpacity:.75,style:n.button},s.createElement(T,{variant:"button",color:r=>r.textHighEmphasis,numberOfLines:1},o.label)):null},Na=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})}})),Ha=({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:s.createElement(y,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},s.createElement(T,{variant:"caption1",color:o.colors.messageIncoming.text,style:fn.sourceLabel},n.conversation.citation_title),s.createElement(y,{gap:8},r.map(a=>s.createElement(R,{key:a.embedding_id,onPress:()=>t(a),activeOpacity:.5},s.createElement(y,{flexDirection:"row",alignItems:"center",gap:4},s.createElement(D,{type:"source",size:16,color:o.colors.messageIncoming.text}),s.createElement(y,{flex:1},s.createElement(T,{variant:"body3",color:o.colors.messageIncoming.text,numberOfLines:1,style:fn.citationText},a.title)))))))},fn=p.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),za=e=>s.createElement(s.Fragment,null),Bt=e=>`${e}-filled`,Fa=e=>e==="good"?Y.AIAgentMessageFeedbackRating.GOOD:Y.AIAgentMessageFeedbackRating.BAD,pn=({onClose:e,isEdit:t,initialRating:n,initialComment:o="",isCommentEnabled:r=!1})=>{const{strings:a}=F(),{themedColor:i,theme:l}=$(),c=$a.use(),[u,g]=d.useState(o),[h,m]=d.useState(n),_=()=>{h&&e({rating:h,comment:u.trim()||void 0})},b=()=>{e()},S={good:i.secondary,bad:i.error};return s.createElement(p.KeyboardAvoidingView,{style:{flex:1},behavior:"padding"},s.createElement(R,{onPress:b,style:c.overlay},s.createElement(y,{width:280,backgroundColor:l.colors.base.modalContentBackground,borderRadius:12,overflow:"hidden",onStartShouldSetResponder:()=>!0},s.createElement(y,{padding:24},s.createElement(T,{variant:"h2",color:i.textHighEmphasis},a.feedback.title)),s.createElement(y,{paddingHorizontal:24,gap:24},s.createElement(y,{flexDirection:"row",gap:4},["good","bad"].map(f=>{const E=h===f,C=f==="good"?a.feedback.good:a.feedback.bad;return s.createElement(R,{key:f,onPress:()=>m(f),activeOpacity:.6,style:c.ratingButton(E)},s.createElement(D,{type:E?Bt(f):f,size:24,color:E?S[f]:i.textLowEmphasis}),s.createElement(T,{variant:"caption1",color:E?S[f]:i.textLowEmphasis},C))})),r&&s.createElement(y,{gap:6},s.createElement(T,{variant:"caption3",color:i.textHighEmphasis},a.feedback.comment_label),s.createElement(p.TextInput,{value:u,onChangeText:f=>g(f),placeholder:a.feedback.comment_placeholder,placeholderTextColor:i.textLowEmphasis,multiline:!0,maxLength:100,style:c.commentInput}))),s.createElement(y,{paddingHorizontal:24,paddingVertical:16,flexDirection:"row",justifyContent:"flex-end",gap:4},s.createElement(R,{onPress:b,activeOpacity:.6,style:c.cancelButton},s.createElement(T,{variant:"button",color:i.textHighEmphasis},a.feedback.cancel)),s.createElement(R,{onPress:_,disabled:!h,activeOpacity:.6,style:c.submitButton(!h)},s.createElement(T,{variant:"button",color:l.colors.base.primaryContrastContent},t?a.feedback.save:a.feedback.submit))))))},$a=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})})),Ua=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:o,isFeedbackCommentEnabled:r,extendedMessagePayload:a,onFeedbackUpdate:i,containerStyle:l})=>{const{strings:c}=F(),{themedColor:u}=$(),{openModal:g}=Xe(),h=qa.use(),m=a==null?void 0:a.feedback,_=(m==null?void 0:m.rating)??"none";if(_!=="none"?!1:!!(n||!e||!o||(a==null?void 0:a.bot_message_type)!=="generated"||t))return null;const S={good:u.secondary,bad:u.error},f=async v=>{const A=await g(I=>s.createElement(pn,{onClose:I,isEdit:!1,initialRating:v,initialComment:"",isCommentEnabled:r}));A&&(i==null||i(A))},E=async()=>{const v=await g(A=>s.createElement(ee,{onClose:()=>A()},s.createElement(ee.ActionItem,{onPress:()=>A("edit"),label:c.feedback.edit}),s.createElement(ee.ActionItem,{onPress:()=>A("remove"),label:c.feedback.remove,destructive:!0})));if(v==="edit"){const A=await g(I=>s.createElement(pn,{onClose:I,isEdit:!0,initialRating:m==null?void 0:m.rating,initialComment:m==null?void 0:m.comment,isCommentEnabled:r}));A&&(i==null||i(A))}else v==="remove"&&(i==null||i(null))},C=()=>t&&_!=="none"?s.createElement(y,{flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:k.BODY_MAX_WIDTH},s.createElement(y,{padding:2,flexShrink:0,alignItems:"center"},s.createElement(D,{type:Bt(_),size:12,color:S[_]})),(m==null?void 0:m.comment)&&s.createElement(T,{variant:"caption2",style:h.commentText},m.comment)):s.createElement(y,{gap:4,maxWidth:k.BODY_MAX_WIDTH},s.createElement(y,{flexDirection:"row",gap:2},["good","bad"].map(v=>{const A=_===v;return s.createElement(R,{key:v,onPress:()=>{_==="none"?f(v):E()},activeOpacity:.6,style:h.feedbackButton(A)},s.createElement(D,{type:A?Bt(v):v,size:14,color:A?S[v]:u.textMidEmphasis}))})),_!=="none"&&(m==null?void 0:m.comment)&&s.createElement(T,{variant:"caption2",style:h.commentText},m.comment));return s.createElement(y,{style:l},C())},qa=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})}})),Va=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},Wa=e=>null,Wn=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:o,...r})=>s.createElement(p.ScrollView,{style:[t,r,e&&Ut],showsHorizontalScrollIndicator:n,...r},o),Ga=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const o=ja.use(),[r,a]=d.useState(!1),i=(e==null?void 0:e.suggested_replies)??[];if(i.length===0||r)return null;const l=n==="vertical",c=g=>{t==null||t({reply:g}),a(!0)},u=()=>i.map((g,h)=>s.createElement(R,{key:h,style:o.itemContainer,onPress:()=>c(g)},s.createElement(T,{variant:"body3",color:m=>m.primary},g)));return l?s.createElement(y,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:k.HORIZONTAL_PADDING},u()):s.createElement(Wn,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:o.horizontalContainer},u())},ja=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:k.HORIZONTAL_PADDING,paddingVertical:16}})),Ka=e=>{var f,E,C,v,A,I,x;const{components:t}=Je.useContext(),{streamText:n,isAnimating:o}=Zr({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),r={...e,message:n,extendedMessagePayload:o?{}:e.extendedMessagePayload},a=!!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=!!((v=r.extendedMessagePayload)!=null&&v.cta_button),g=!!((A=r.extendedMessagePayload)!=null&&A.citations)&&r.extendedMessagePayload.citations.length>0,h=!!r.createdAt,m=r.groupType==="top"||r.groupType==="single",_=r.groupType==="bottom"||r.groupType==="single",b=i?k.AVATAR_SIZE:0,S=Ya.use();return s.createElement(y,{marginBottom:a?0:zt(r.groupType)},m&&s.createElement(y,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:k.HORIZONTAL_PADDING},i&&s.createElement(t.SenderAvatar,{...r}),s.createElement(t.SenderName,{...r})),s.createElement(y,{gap:k.GAP_GROUPED},a?s.createElement(t.TypingIndicator,{...r,containerStyle:S.middleArea(b)}):s.createElement(t.MessageBody,{...r,containerStyle:S.middleArea(b)},u&&s.createElement(y,{marginTop:12,marginHorizontal:12},s.createElement(t.CTAButton,{...r})),g&&s.createElement(t.Citation,{...r})),c&&s.createElement(t.MessageTemplate,{...r,messageTemplateErrorFallback:r.messageTemplateErrorFallback??s.createElement(t.MessageBody,{...r,messageType:"user",message:((x=(I=r.extendedMessagePayload)==null?void 0:I.message_template)==null?void 0:x.fallback_message)??"Cannot read this template.",containerStyle:S.middleArea(b)}),messageTemplateLoadingFallback:r.messageTemplateLoadingFallback??s.createElement(t.TypingIndicator,{...r,containerStyle:S.middleArea(b)})}),s.createElement(t.CustomMessageTemplate,{...r}),l&&s.createElement(t.Form,{...r,containerStyle:S.middleArea(b)})),_&&h&&s.createElement(t.SentTime,{...r,containerStyle:S.bottomArea(b)}),s.createElement(d.Fragment,null,!a&&s.createElement(t.Feedback,{...r,containerStyle:S.feedbackArea(b)}),r.suggestedRepliesVisible&&s.createElement(t.SuggestedReplies,{...r})))},Je=ae({template:Ka,components:{SenderName:La,SenderAvatar:ka,SentTime:Pa,MessageBody:Ia,TypingIndicator:Ra,SuggestedReplies:Ga,MessageTemplate:Wa,CustomMessageTemplate:za,CTAButton:Ba,Citation:Ha,Form:Va,Feedback:Ua}}),Ya=P.create(()=>({middleArea:e=>({paddingStart:k.HORIZONTAL_PADDING+e,paddingEnd:k.HORIZONTAL_PADDING}),bottomArea:e=>({marginTop:k.BODY_TIME_GAP,paddingStart:k.HORIZONTAL_PADDING+e+8,paddingEnd:k.HORIZONTAL_PADDING}),feedbackArea:e=>({marginTop:8,paddingStart:k.HORIZONTAL_PADDING+e+8,paddingEnd:k.HORIZONTAL_PADDING})})),Xa=({file:e,children:t,sendingStatus:n,onClickFile:o=({url:r})=>p.Linking.openURL(r)})=>{const r=(()=>{if(!(!o||n!=="succeeded"))return()=>o(e)})();return s.createElement(y,{flexDirection:"column",alignItems:"flex-end",gap:k.GAP_GROUPED,width:k.BODY_MAX_WIDTH,maxWidth:k.BODY_MAX_WIDTH},s.createElement(jt,{name:e.name,type:Ht(e.name,e.type),onPress:r}),t)},Gn=({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 s.createElement(y.Animated,{style:{transform:[{rotate:o}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??s.createElement(D,{type:"spinner",size:e}))};function Za(e){return typeof e=="object"&&e!==null&&"uri"in e}const Ja=({file:e,metadata:t,sendingStatus:n,onClickMedia:o=({url:a})=>p.Linking.openURL(a),children:r})=>{const a=Qa.use(),{aspectRatio:i,localFile:l}=t,[c]=d.useState(()=>Za(l)?l.uri:e.url),[u,g]=d.useState(!1),h=(()=>{if(!(!o||n!=="succeeded"))return()=>o(e)})();return s.createElement(y,{flexDirection:"column",alignItems:"flex-end",gap:k.GAP_GROUPED},s.createElement(R,{onPress:h,style:[a.imageContainer,{aspectRatio:i}],activeOpacity:.75},!u&&s.createElement(y,{alignItems:"center",justifyContent:"center"},s.createElement(Gn,{size:26},s.createElement(D,{type:"spinner",color:m=>m.textLowEmphasis,size:26}))),s.createElement(xe,{source:{uri:c},style:[a.image,{opacity:u?1:0}],resizeMode:"cover",onLoad:()=>g(!0)})),r)},Qa=P.create(({themedColor:e})=>({imageContainer:{width:k.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}})),_n=e=>{var n,o;const t=ei.use();return s.createElement(y,{style:[t.container({maxWidth:e.maxBodyWidth??k.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},s.createElement(T,{variant:"body3",style:[t.text,((o=e.customStyle)==null?void 0:o.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},ei=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}})),ti=e=>{const{strings:t}=F(),n=()=>{const o=wn(e)?s.createElement(_n,{...e}):null;return e.messageType==="user"?o:e.messageType==="file"?e.file.type.startsWith("image")?s.createElement(Ja,{...e},o):s.createElement(Xa,{...e},o):s.createElement(_n,{...e,message:t.unknown_message_type})};return s.createElement(R,{onPress:e.sendingStatus==="failed"?e.onClickFailedMessage:void 0,activeOpacity:.75},s.createElement(y,{style:e.containerStyle},n()))},ni=({sendingStatus:e,containerStyle:t})=>{const{themedColor:n}=$(),o=()=>{switch(e){case"pending":return s.createElement(y,{marginBottom:2},s.createElement(Gn,{size:16},s.createElement(D,{type:"spinner",color:n.primary,size:16})));case"failed":return s.createElement(y,{marginBottom:2},s.createElement(D,{type:"error",color:n.error,size:16}));case"scheduled":case"canceled":return null;default:return s.createElement(y,{marginBottom:2},s.createElement(D,{type:"done",color:n.secondary,size:16}))}};return s.createElement(y,{style:t},o())},oi=({createdAt:e,containerStyle:t})=>{const{format:n,strings:o}=F();return e?s.createElement(y,{style:t},s.createElement(T,{variant:"caption4",color:r=>r.textLowEmphasis},n(e,o.date_format.message_timestamp))):null},ri=e=>{const{components:t}=Qe.useContext(),n=e.sendingStatus==="succeeded",o=e.groupType==="bottom"||e.groupType==="single";return s.createElement(y,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:zt(e.groupType)},s.createElement(t.MessageBody,{...e,containerStyle:_t.middleArea}),o&&(n?s.createElement(t.SentTime,{...e,containerStyle:_t.bottomArea}):s.createElement(t.SendingStatus,{...e,containerStyle:_t.bottomArea})))},Qe=ae({template:ri,components:{SendingStatus:ni,SentTime:oi,MessageBody:ti}}),_t=p.StyleSheet.create({middleArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:k.HORIZONTAL_PADDING},bottomArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingStart:k.HORIZONTAL_PADDING,paddingEnd:k.HORIZONTAL_PADDING+8,marginTop:k.BODY_TIME_GAP}}),si=e=>e.messageType!=="admin"?null:s.createElement(T,{variant:"caption2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},ai(e.message)),ai=e=>{try{const t=[];let n=e,o=0;for(;n;){const r=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=n.match(/\*\*([^*]+)\*\*/),i=[r&&{match:r,type:"link"},a&&{match:a,type:"bold"}].filter(h=>!!h);if(!i.length){t.push(n);break}const l=i.reduce((h,m)=>m.match.index<h.match.index?m:h),{match:c,type:u}=l,g=c.index;g>0&&t.push(n.slice(0,g)),u==="link"?t.push(s.createElement(p.Text,{key:o++,onPress:()=>p.Linking.openURL((c==null?void 0:c[2])??""),style:{textDecorationLine:"underline"}},c[1])):u==="bold"&&t.push(s.createElement(p.Text,{key:o++,style:{fontWeight:"bold"}},c[1])),n=n.slice(g+c[0].length)}return t.filter(r=>r!=="")}catch{return[e]}},ii=({children:e,style:t})=>s.createElement(T,{variant:"caption4",color:n=>n.error,style:t},e),li=({children:e,style:t,required:n})=>{const{strings:o}=F();return s.createElement(T,{variant:"caption3",color:r=>r.textMidEmphasis,style:t},e,!n&&s.createElement(T,{variant:"caption3",color:r=>r.textLowEmphasis},` (${o.form.optional_label})`))},ci=({style:e})=>{const t=ui.use();return s.createElement(y,{style:[t.separator,e]})},ui=P.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),di=({value:e="",onChange:t,placeholder:n,variant:o="single-line",error:r=!1,submitted:a=!1,style:i,disabled:l=!1,maxLength:c})=>{const[u,g]=d.useState(!1),h=mi.use(),{themedColor:m}=$(),_=b=>{c&&b.length>c||t==null||t(b)};return s.createElement(p.TextInput,{value:e,onChangeText:_,placeholder:n,editable:!l&&!a,maxLength:c,multiline:o==="multi-line",style:[h.input(o,r,a,u),i],placeholderTextColor:m.textLowEmphasis,onFocus:()=>g(!0),onBlur:()=>g(!1)})},mi=P.create(({select:e,theme:t,themedColor:n})=>({input:(o,r,a,i)=>{let l,c;a?(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:a?n.textLowEmphasis:n.textHighEmphasis};return o==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),Le={Label:li,ErrorLabel:ii,TextInput:di,Separator:ci},jn=({onClick:e,checked:t,label:n,disabled:o,labelVariant:r="caption2"})=>{const{themedColor:a}=$(),i=gi.use(),l=t?a.primary:o?a.textDisabled:a.textLowEmphasis;return s.createElement(R,{disabled:o||!e,onPress:e},s.createElement(y,{style:i.container},s.createElement(y,{style:i.iconContainer},s.createElement(D,{size:20,type:t?"radio-on":"radio-off",color:l})),s.createElement(T,{variant:r,style:i.label(t,o)},n)))},gi=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}}})),hi=({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?s.createElement(y,{flexDirection:"column",gap:8,alignItems:"flex-start"},s.createElement(Le.Label,{required:e.cre.required},e.cre.question),s.createElement(y,{flexDirection:"column",gap:8,width:"100%"},[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(a=>s.createElement(jn,{key:a.label,checked:o===a.value,label:a.label,disabled:t,onClick:()=>r==null?void 0:r(a.value)})))):null),fi=({followUpItem:e,submitted:t,value:n="",onChange:o,hasError:r})=>{const{strings:a}=F();return s.createElement(y,{flexDirection:"column",gap:8,alignItems:"flex-start"},s.createElement(Le.Label,{required:e.required},e.question),e.response_type==="free_text"&&s.createElement(Le.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>o(i),error:r}),e.response_type==="single_choice"&&s.createElement(y,{flexDirection:"column",gap:8,width:"100%"},e.options.map(i=>s.createElement(jn,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>o==null?void 0:o(i),labelVariant:"body3"}))),r&&s.createElement(Le.ErrorLabel,null,a.form.validation_required))},pi=e=>null,_i=({csatPayload:e,submitted:t,value:n,onChange:o})=>{const r=typeof n>"u",a=Kn.use(),[i,l]=d.useState(16);return s.createElement(y,{onLayout:c=>{c.nativeEvent.layout.width<300&&l(0)},flexDirection:"column",gap:8,alignItems:"flex-start"},s.createElement(T,{variant:"caption3",color:c=>c.textMidEmphasis},e.csat_question),s.createElement(y,{style:[a.scoresContainer,{gap:i}]},e.csat_scores.map(({label:c,image_url:u},g)=>{const h=g+1,m=n===h;return s.createElement(R,{key:g,disabled:t,onPress:()=>o(h),style:a.scoreButton},s.createElement(yi,{value:h,selected:r||m,label:c,src:u}),!!c&&s.createElement(T,{style:{textAlign:"center"},variant:"caption3",color:_=>m?_.textHighEmphasis:_.textLowEmphasis,lineBreakStrategyIOS:"standard",textBreakStrategy:"simple"},c))})))},yi=({value:e,src:t,label:n,selected:o})=>{const[r,a]=d.useState(!1),i=Kn.use();return r?s.createElement(pi,{value:e,selected:o,label:n}):s.createElement(xe,{source:{uri:t},style:i.emojiImage(o),onError:()=>a(!0),accessibilityLabel:n})},Kn=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})})),bi=({csatPayload:e})=>s.createElement(T,{style:{textAlign:"left"},variant:"button",color:t=>t.textHighEmphasis},e.title),yt=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:o,initialCsatReason:r,initialIsResolved:a})=>{const{params:i,setParams:l,error:c,setError:u,followUpItem:g,state:h,validateParams:m,itemProps:_}=jr({csatPayload:e,type:t,initialCsat:o,initialCsatReason:r,initialIsResolved:a});return s.createElement(s.Fragment,null,s.createElement(y,{flexDirection:"column",gap:12},s.createElement(bi,{..._}),t===ue.AI_AGENT_CSAT_5_WITH_CRE&&s.createElement(hi,{..._,defaultValue:a,value:i.isResolved,onChange:b=>l({isResolved:b})}),s.createElement(_i,{..._,value:i.csat,onChange:b=>l({csat:b})}),g&&s.createElement(fi,{..._,followUpItem:g,value:i.csatReason,onChange:b=>{l({csatReason:b}),u({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&s.createElement(s.Fragment,null,s.createElement(Le.Separator,null),n({state:h,params:i,validateParams:m})))},Ei=e=>{const{strings:t}=F();return Lo(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})},vi=()=>{const{strings:e}=F();return s.createElement(T,{variant:"body2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},Ci=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n}=e,{csat:o,csatReason:r,csatExpireAt:a,isResolvedWhenDeterminedByUser:i}=e,[,l]=d.useState(0),c=Ei(t==null?void 0:t.csat),u=Si.use();if(!c||!c.visibility||!ue[c.type])return null;const g=c.type===ue.AI_AGENT_CSAT_5||c.type===ue.AI_AGENT_CSAT_5_WITH_CRE||c.type===ue.HELPDESK_CSAT_5?yt:()=>null;return s.createElement(y,{style:u.container},!o&&en(a)?s.createElement(vi,null):s.createElement(g,{csatPayload:c,type:c.type,initialCsat:o,initialCsatReason:r,initialIsResolved:i,renderSubmitButton:({state:h,params:m,validateParams:_})=>s.createElement(R,{activeOpacity:.75,disabled:h==="submitted",onPress:async()=>{!en(a)&&_()?await n(m):l(b=>b+1)},style:u.submitButton(h)},s.createElement(T,{variant:"button",style:u.submitButtonText(h)},h==="submitted"?c.csat_submitted_label:c.csat_submit_label))}))},Si=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}}})),Ai=e=>{const{components:t}=et.useContext(),n=e.messageType==="admin"?s.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?s.createElement(t.CSATMessage,{...e}):null;return s.createElement(y,{paddingHorizontal:k.HORIZONTAL_PADDING,marginBottom:zt(e.groupType)},n)},et=ae({template:Ai,components:{AdminMessage:si,CSATMessage:Ci}}),wi=({style:e,...t})=>{const{strings:n}=F();if(!$t("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 s.createElement(y,{style:[xi.container,e],...t},s.createElement(T,{variant:"caption2",color:a=>a.textLowEmphasis},n.conversation.powered_by+" "),s.createElement(R,{onPress:r},s.createElement(T,{variant:"caption2",color:a=>a.textLowEmphasis},"Sendbird")))},xi=p.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),Ii=()=>{var l;const{strings:e}=F(),{channelSource:t,scrollSource:n,updateActiveChannel:o}=te(),r=Ti.use(),a=ye(t.channel),i=d.useRef(a);return d.useEffect(()=>{const c=i.current;i.current=a,!c&&a&&n.actions.scrollToBottom()},[a,n]),!((l=t.channel)!=null&&l.isAIAgent)||!a?null:s.createElement(y,{justifyContent:"center",flexDirection:"row",style:r.wrapper},s.createElement(R,{activeOpacity:.75,onPress:()=>o(),style:r.button},s.createElement(T,{variant:"button",role:"button",color:c=>c.textHighEmphasis},e.conversation.start_new_conversation_label)))},Ti=P.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),ki=()=>{const{aiAgentInfo:e}=J(),{channelSource:t}=te(),n=Ln(t.channel);return(()=>{const o=n[0];if(!o)return null;const r=o.userId===(e==null?void 0:e.userId);return{user:r?e:o,isBot:r}})()},Mi=(e,t)=>!io.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Li=({messageStackDirection:e="top"})=>{var Z,ne,q;const{Template:t}=Je.useContext(),{Template:n}=Qe.useContext(),{Template:o}=et.useContext(),{openModal:r}=Xe(),{strings:a}=F(),{config:i,cache:l,chatSDK:c}=j(),{aiAgentInfo:u,userSession:g,connectionError:h}=J(),{messageSource:m,channelSource:_,scrollSource:b,state:{input:S,streamAnimation:f}}=te(),E=ki(),C=Pi.use(),v=Ie(["left","right"]),{state:A,props:I}=b;d.useEffect(()=>{A.isAwayFromBottom||m.resetNewMessages()},[A.isAwayFromBottom]);const x=(Z=_.channel)==null?void 0:Z.conversation,O=(w,U=!1)=>{var oe;return U?u??{nickname:"",profileUrl:""}:((oe=_.channel)==null?void 0:oe.members.find(le=>le.userId===w.sender.userId))??w.sender},B=w=>{if(w.sendingStatus==="failed"&&!S.disabled)return()=>{r(U=>s.createElement(ee,{onClose:()=>U()},s.createElement(ee.ActionItem,{label:a.conversation.failed_message_resend,onPress:async()=>{m.resendMessage(w),U()}}),s.createElement(ee.ActionItem,{destructive:!0,label:a.conversation.failed_message_remove,onPress:async()=>{m.deleteMessage(w),U()}})))}},M=({item:w,index:U})=>{const oe=m.messages[U+1],le=m.messages[U-1],L=(()=>{var Zt,Jt,Qt;const V=!(u!=null&&u.isUserFeedbackEnabled&&Re(w,u==null?void 0:u.userId)&&!qe.isWelcomeMessage(w)),re=Oo(w,oe,le,V),De={data:w.data,extendedMessagePayload:w.extendedMessagePayload,message:w.message,createdAt:w.createdAt,groupType:re};if(Oe.isAdmin(w))return Oe.isCSAT(w)?x?s.createElement(o,{...De,...x,messageType:"admin.csat",isResolvedWhenDeterminedByUser:ko(x),onSubmitCSAT:async({csat:me,...Ee})=>{var ge;me&&await((ge=_.channel)==null?void 0:ge.submitCSAT({csat:me,...Ee}))}}):null:s.createElement(o,{...De,messageType:"admin"});if(Oe.isOutgoing(w,(g==null?void 0:g.userId)??"")){const me={...De,sender:O(w),sendingStatus:w.sendingStatus,onClickFailedMessage:B(w)};if(w.isUserMessage())return s.createElement(n,{...me,messageType:"user"});if(w.isFileMessage()){const[Ee,ge]=((Zt=w.metaArrays.find(W=>W.key===Sn))==null?void 0:Zt.value)??[];return s.createElement(n,{...me,messageType:"file",file:w,metadata:{aspectRatio:Ee&&ge?`${Ee}/${ge}`:"1/1",localFile:(Jt=w.messageParams)==null?void 0:Jt.file}})}}if(Oe.isIncoming(w,(g==null?void 0:g.userId)??"")){const me=w.sender.userId===(u==null?void 0:u.userId),Ee=U===0,ge={...De,sender:O(w,me),suggestedRepliesVisible:Ee,isBotMessage:me,isStreaming:qe.isStreaming(w),isHandedOff:we(_.channel),isConversationClosed:ye(_.channel),isFeedbackEnabled:u==null?void 0:u.isUserFeedbackEnabled,isFeedbackCommentEnabled:u==null?void 0:u.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(Qt=i==null?void 0:i.conversation)==null?void 0:Qt.senderAvatarEnabled,onClickSuggestedReply:async({reply:W})=>{m.sendUserMessage({message:W})},onRequestMessageTemplate:async W=>{const{template:ce}=await c.aiAgent.getMessageTemplate(W);return l.template.set(W,ce),ce},onGetCachedMessageTemplate:W=>l.template.get(W),onHandleTemplateInternalAction:W=>{if(W.type==="internal"&&W.internalData){const{method:ce,payload:fe}=W.internalData;ce==="message.send"&&(fe!=null&&fe.message)&&m.sendUserMessage({message:fe.message})}},onFeedbackUpdate:W=>{const ce={messageId:w.messageId,channelUrl:w.channelUrl};if(!W)return c.aiAgent.deleteMessageFeedback(ce);const fe={...ce,rating:Fa(W.rating),comment:W.comment};return qe.hasFeedback(w)?c.aiAgent.updateMessageFeedback(fe):c.aiAgent.createMessageFeedback(fe)},onSubmitForm:({key:W,data:ce})=>c.aiAgent.submitForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:W,formData:ce}),onCancelForm:({key:W})=>c.aiAgent.cancelForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:W}),onStreamAnimationStart:()=>{f.start(w.messageId)},onStreamAnimationProgress:()=>{b.actions.onStreamingUpdate()},onStreamAnimationComplete:()=>{f.stop(w.messageId),b.actions.onStreamingUpdate()}};if(w.isUserMessage())return s.createElement(t,{...ge,messageType:"user"});if(w.isFileMessage())return s.createElement(t,{...ge,messageType:"file",file:w})}return null})(),N=Mi(w,oe)&&s.createElement(aa,{date:w.createdAt,style:C.dateSeparator});return s.createElement(y,null,N,L)},H=()=>s.createElement(wi,{style:C.poweredBy}),G=()=>{var w,U;return s.createElement(s.Fragment,null,E&&s.createElement(t,{isTyping:!0,isBotMessage:E.isBot,sender:E.user,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(w=i==null?void 0:i.conversation)==null?void 0:w.senderAvatarEnabled}),((U=i==null?void 0:i.conversation)==null?void 0:U.isTalkToAgentViewEnabled)&&s.createElement(Ii,null),A.bottomSpace?s.createElement(y,{height:A.bottomSpace}):null)};return s.createElement(y,{flex:1},s.createElement($n,{ref:b.ref,style:C.list,contentContainerStyle:[C.listContent,v,e==="top"&&C.stackTop],data:m.messages,onEndReached:m.loadPrevious,keyExtractor:Do,renderItem:M,loading:!m.initialized,error:!!(h||_.error),LoadingComponent:s.createElement(Ae,{type:"loading"}),EmptyComponent:s.createElement(Ae,{type:"noMessages",label:a.common.placeholder_no_messages}),ErrorComponent:s.createElement(Ae,{type:"error",label:(h==null?void 0:h.message)??((ne=_.error)==null?void 0:ne.message),action:_.error?{label:a.common.placeholder_something_went_wrong_retry_label,onPress:()=>_.refetch()}:void 0}),ListFooterComponent:H(),ListHeaderComponent:G(),inverted:!0,...I}),((q=i==null?void 0:i.conversation)==null?void 0:q.newMessageIndicatorEnabled)&&A.isAwayFromBottom&&m.newMessages.length>0&&s.createElement(y,{style:C.newMessagesButtonContainer},s.createElement(ia,{label:a.conversation.scroll_to_new_messages_label(m.newMessages),accessibilityLabel:a.conversation.a11y_scroll_to_new_messages,onPress:()=>b.actions.scrollToBottom()})),A.isAwayFromBottom&&m.newMessages.length===0&&s.createElement(y,{style:C.scrollButtonContainer},s.createElement(_a,{onPress:()=>b.actions.scrollToBottom()})))},Pi=P.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background},stackTop:{flexGrow:1,justifyContent:"flex-end"},dateSeparator:{marginVertical:16},poweredBy:{marginTop:16},scrollButtonContainer:{position:"absolute",bottom:12,end:16},newMessagesButtonContainer:{position:"absolute",bottom:12,alignSelf:"center"}})),de={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 Ri(e){return{captureCamera:async()=>{if(e.requestCameraPermissionsAsync&&!(await e.requestCameraPermissionsAsync()).granted)throw new Error(de.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(yn)},selectFromGallery:async t=>{if(e.requestMediaLibraryPermissionsAsync&&!(await e.requestMediaLibraryPermissionsAsync()).granted)throw new Error(de.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(yn)}}}function Di(e,t){const n=async()=>{const r=p.Platform.select({ios:t.PERMISSIONS.IOS.CAMERA,android:t.PERMISSIONS.ANDROID.CAMERA});if(!r)return;const a=await t.request(r);if(a!=="granted"&&a!=="limited")throw new Error(de.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 a=await t.requestMultiple(r);if(!Object.values(a).every(l=>l==="granted"||l==="limited"))throw new Error(de.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(de.CAMERA_PERMISSION_DENIED):new Error(r.errorMessage||`Camera error: ${r.errorCode}`);return!r.assets||r.assets.length===0?null:r.assets.map(bn)},selectFromGallery:async r=>{await o();const a=await e.launchImageLibrary({mediaType:"photo",selectionLimit:(r==null?void 0:r.selectionLimit)??1,assetRepresentationMode:"compatible"});if(a.didCancel)return null;if(a.errorCode)throw a.errorCode==="permission"?new Error(de.GALLERY_PERMISSION_DENIED):new Error(a.errorMessage||`Gallery error: ${a.errorCode}`);return!a.assets||a.assets.length===0?null:a.assets.map(bn)}}}function Oi(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(Ni)}}}function Bi(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(Hi)}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 yn(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 Ni(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function bn(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 Hi(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function zi(e){return{keyValueStorage:{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))}}}function Fi(){return{captureCamera:async()=>{throw new Error(de.IMAGE_PICKER_NOT_CONFIGURED)},selectFromGallery:async()=>{throw new Error(de.IMAGE_PICKER_NOT_CONFIGURED)}}}function $i(){return{selectFile:async()=>{throw new Error(de.DOCUMENT_PICKER_NOT_CONFIGURED)}}}const{Provider:Ui,useContext:Yn}=X("NativeAdapter"),Xn=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:o,documentPicker:r,mmkv:a}=e,i=o?(qi(e),"launchCameraAsync"in o?Ri(o):Di(o,e.permissions)):Fi(),l=r?"getDocumentAsync"in r?Oi(r):Bi(r):$i(),c=zi(a);return{...i,...l,...c}},[e.imagePicker,e.documentPicker,e.mmkv,e.permissions]);return s.createElement(Ui,{value:n},t)};function qi(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 Vi=({onPressAddAttachment:e,disabled:t})=>s.createElement(R,{disabled:t,style:Wi.container,activeOpacity:.75,onPress:e},s.createElement(D,{type:"add",size:24,color:n=>t?n.textDisabled:n.primary})),Wi=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Gi=({name:e,type:t,url:n,onRemove:o})=>{const r=ji.use();return s.createElement(y,{style:r.wrapper},Bo(t)?s.createElement(xe,{source:{uri:n},style:r.image,resizeMode:"cover"}):s.createElement(jt,{name:e,type:Ht(e,t)}),o&&s.createElement(R,{onPress:o,style:r.removeButton},s.createElement(D,{type:"remove",size:20,color:r.removeIcon.tintColor})))},Fe=7,ji=P.create(({themedColor:e})=>({wrapper:{marginTop:Fe,marginRight:Fe,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-Fe,right:-Fe,width:22,height:22,borderRadius:11,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),Ki=e=>{const{theme:t,themedColor:n}=$(),o=Yi.use(),r=Vt.useTextAlign({text:e.value??e.placeholder,style:o.input,isTextInput:!0});return s.createElement(y,{style:o.container},e.attachments&&s.createElement(Wn,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),s.createElement(y,null,s.createElement(p.TextInput,{multiline:!0,style:[o.input,{textAlign:r}],placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},Yi=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:{...Xi(e.typography.body3),color:e.colors.messageInput.text,includeFontPadding:!1,padding:0,margin:0,textAlignVertical:"center"}}));function Xi(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 Zi=({onPressSend:e})=>s.createElement(R,{style:Ji.container,activeOpacity:.75,onPress:e},s.createElement(D,{type:"send",size:24})),Ji=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Qi=()=>{const e=el.use(),{aiAgentInfo:t,userSession:n}=J(),{messageSource:o,channelSource:r}=te(),[a,i]=d.useState(null),l=$t("special-notice",r.channel),c=d.useCallback(()=>r.channel?l?o.messages.some(u=>Re(u,(n==null?void 0:n.userId)??"")):!0:null,[r.channel,l,o.messages,n==null?void 0:n.userId]);return d.useEffect(()=>{a||i(c())},[c,a]),a||!(t!=null&&t.specialNotice)?null:s.createElement(y,{style:e.container},s.createElement(Kt,{textStyle:e.text,linkStyle:e.link},(t==null?void 0:t.specialNotice)??""))},el=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})}})),tl=()=>{var S;const{chatSDK:e}=j(),{strings:t}=F(),{createAttachmentRules:n}=J(),{channelSource:o,state:r}=te(),[a,i]=d.useState(""),[l,c]=d.useState([]),u=n({channel:o.channel,uploadSizeLimit:(S=e.appInfo)==null?void 0:S.uploadSizeLimit}),g=(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 v=x=>{const O=u.getUploadSizeLimit(x.type);return x.size&&x.size>O},A=C.find(x=>v(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+C.length>u.maxAttachmentCount?(p.Alert.alert("",t.conversation.file_upload_notification_count_limit(u.maxAttachmentCount)),f):[...f,...C]},h=f=>{c(E=>g(E,f))},m=f=>{c(E=>E.filter((C,v)=>v!==f))},_=()=>{c([])},b=(()=>{if(!r.input.disabled)return t.conversation.input_placeholder;switch(r.input.disabledBy){case"form_active":return t.conversation.input_placeholder_active_form;case"ai_responding":return t.conversation.input_placeholder_wait_ai_agent_response;case"reconnecting":return t.conversation.input_placeholder_reconnecting;case"unavailable":case"conversation_closed":default:return t.conversation.input_placeholder_disabled}})();return d.useEffect(()=>{r.input.disabled&&(i(""),_())},[r.input.disabled]),{files:l,addFiles:h,removeFile:m,clearFiles:_,value:a,onChangeText:i,editable:!r.input.disabled,placeholder:b,sendButtonVisible:!r.input.disabled&&(!!a.trim()||l.length>0),addAttachmentButtonVisible:u.isEnabled(),addAttachmentButtonDisabled:r.input.disabled||l.length>=u.maxAttachmentCount,hasImageMimeTypes:()=>u.supportedMimeTypes.filter(E=>E.startsWith("image/")||E===An).length>0,hasFileMimeTypes:()=>u.supportedMimeTypes.length>0,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount}},nl=()=>{const{config:e}=j(),t=Yn(),{strings:n}=F(),{messageSource:o}=te(),{openModal:r}=Xe(),a=Ie(["left","right","bottom"]),i=ol.use(),{maxAttachmentCount:l,sendButtonVisible:c,addAttachmentButtonVisible:u,addAttachmentButtonDisabled:g,acceptableMimeTypes:h,hasImageMimeTypes:m,hasFileMimeTypes:_,...b}=tl(),E={...b,onPressAddAttachment:async()=>{const C=await r(v=>{var A,I,x,O,B,M,H,G;return s.createElement(ee,{onClose:()=>v()},((x=(I=(A=e==null?void 0:e.conversation)==null?void 0:A.input)==null?void 0:I.camera)==null?void 0:x.photoEnabled)&&s.createElement(ee.ActionItem,{icon:"camera",label:n.conversation.attachment_camera,onPress:async()=>{if(!m())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),v(null);const Z=await t.captureCamera();v(Z)}}),((M=(B=(O=e==null?void 0:e.conversation)==null?void 0:O.input)==null?void 0:B.gallery)==null?void 0:M.photoEnabled)&&s.createElement(ee.ActionItem,{icon:"photo",label:n.conversation.attachment_photo,onPress:async()=>{if(!m())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),v(null);const Z=await t.selectFromGallery({selectionLimit:l-b.files.length});v(Z)}}),((G=(H=e==null?void 0:e.conversation)==null?void 0:H.input)==null?void 0:G.fileEnabled)&&s.createElement(ee.ActionItem,{icon:"document",label:n.conversation.attachment_document,onPress:async()=>{if(!_())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),v(null);const Z=await t.selectFile({selectionLimit:l-b.files.length,mimeTypes:h});v(Z)}}))});C&&b.addFiles(C)},onPressSend:()=>{b.files.length>0?o.sendFileMessage({message:b.value.trim(),file:b.files[0]}):o.sendUserMessage({message:b.value}),b.clearFiles(),b.onChangeText("")}};return s.createElement(p.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-a.paddingBottom},s.createElement(Qi,null),s.createElement(y,{style:i.container(a)},u&&s.createElement(Vi,{...E,disabled:g}),s.createElement(Ki,{...E,value:E.editable?E.value:"",attachments:E.files.length===0?null:E.files.map((C,v)=>s.createElement(Gi,{key:v,name:C.name,type:C.type,url:C.uri,onRemove:()=>E.removeFile(v)}))}),c&&s.createElement(Zi,{...E})))},ol=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})})),Zn=({start:e,title:t,titleAlign:n="start",end:o})=>{const r=Ie(["left","right","top"]),[a,i]=d.useState(0),[l,c]=d.useState(0),u=m=>{i(m.nativeEvent.layout.width)},g=m=>{c(m.nativeEvent.layout.width)},h=rl.use();return s.createElement(y,{style:h.container},s.createElement(y,{height:r.paddingTop}),s.createElement(y,{style:h.contentContainer(r)},n==="center"&&t&&s.createElement(y,{style:h.centerTitleContainer(Math.max(a,l))},s.createElement(y,{style:h.centerTitle},t)),s.createElement(y,{style:h.rowContainer},s.createElement(y,{style:h.startSide,onLayout:u},e),(n==="start"||n==="end")&&t&&s.createElement(y,{style:h.titleSide(n,e,o)},t),s.createElement(y,{style:h.endSide,onLayout:g},o))))},rl=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})})),sl=()=>{const{themedColor:e}=$(),{onClose:t}=te();return t?s.createElement(R,{hitSlop:4,onPress:t,activeOpacity:.75},s.createElement(D,{color:e.textHighEmphasis,type:"close",size:24})):null},al=()=>{const{themedColor:e}=$(),{channelSource:{channel:t}}=te(),n=$t("handoff-button",t),o=!Cn(t)||we(t);return n?s.createElement(R,{hitSlop:4,disabled:o,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},s.createElement(D,{color:o?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},il=()=>{const{strings:e}=F(),{themedColor:t}=$(),{onNavigateToConversationList:n}=te();return n?s.createElement(R,{hitSlop:4,onPress:n,activeOpacity:.75,"aria-label":e.conversation.a11y_open_conversation_list},s.createElement(D,{color:t.textHighEmphasis,type:"menu",size:24})):null},Jn=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:o}=J(),{fallbackIcon:r,url:a}=Pn({channel:e,aiAgentInfo:o,userSession:n}),{theme:i}=$();return a?s.createElement(Vn,{src:a,size:t}):s.createElement(y,{width:t,height:t,borderRadius:t/2,alignItems:"center",justifyContent:"center",flexShrink:0,style:{backgroundColor:i.colors.base.primary}},s.createElement(D,{type:r,size:t*.55,color:i.colors.base.primaryContrastContent}))},ll=()=>{var i,l;const{channelSource:{channel:e}}=te(),{userSession:t,aiAgentInfo:n}=J(),{config:o}=j(),r=Pn({channel:e,userSession:t,aiAgentInfo:n}),a=(l=(i=o==null?void 0:o.conversation)==null?void 0:i.header)==null?void 0:l.avatarEnabled;return s.createElement(y,{gap:6,flexDirection:"row",alignItems:"center",maxWidth:"100%"},a&&s.createElement(Jn,{channel:e,size:34}),s.createElement(y,{flexShrink:1},s.createElement(T,{numberOfLines:1,variant:"h1"},r.title)))},cl=e=>{const{components:t}=be.useContext();return s.createElement(Zn,{start:s.createElement(t.StartArea,null),title:s.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:s.createElement(t.EndArea,null)})},ul=()=>{const{components:e}=be.useContext();return s.createElement(e.MenuButton,null)},dl=()=>{const{components:e}=be.useContext();return s.createElement(e.Title,null)},ml=()=>{const{components:e}=be.useContext();return s.createElement(y,{flexDirection:"row",alignItems:"center",gap:10},s.createElement(e.HandoffButton,null),s.createElement(e.CloseButton,null))},be=ae({template:cl,components:{StartArea:ul,TitleArea:dl,EndArea:ml,MenuButton:il,Title:ll,HandoffButton:al,CloseButton:sl}}),gl=()=>{const{Template:e}=be.useContext();return s.createElement(e,{titleAlign:"start"})},hl=e=>{const{components:t}=tt.useContext();return s.createElement(y,{flex:1},s.createElement(t.Header,null),s.createElement(t.Body,null),s.createElement(t.Footer,null))},tt=ae({template:hl,components:{Header:gl,Body:Li,Footer:nl}}),Qn=({children:e,...t})=>{const{Template:n}=tt.useContext();return s.createElement(Dn,{...t},s.createElement(n,null),e)},{Provider:fl,Context:pl,useContext:nt}=X("ConversationList"),eo=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:o,children:r})=>{const{sdkUser:a,authenticate:i}=J();return d.useEffect(()=>{a||i()},[]),s.createElement($r,{conversationListLimit:e,conversationListFilter:t},l=>s.createElement(fl,{value:{...l,onClose:o,onNavigateToConversation:n}},r))},bt=99,_l=d.memo(function(t){const{channel:n,onClick:o}=t,{strings:r,format:a}=F(),{themedColor:i}=$(),l=bl.use(),c=Po(n),u=Ro(n,a,{justNow:r.date_format.just_now,minutesAgo:r.date_format.minutes_ago,hoursAgo:r.date_format.hours_ago,dateShortFormat:r.date_format.date_short}),g=n.unreadMessageCount;return s.createElement(R,{onPress:o,activeOpacity:.75},s.createElement(y,{flexDirection:"row",alignItems:"center",width:"100%",height:72,gap:16},s.createElement(y,{marginStart:16,alignItems:"center",justifyContent:"center"},s.createElement(Jn,{channel:n})),s.createElement(y,{flexDirection:"row",alignItems:"center",flex:1,paddingEnd:16,height:"100%",gap:8,style:l.rightContainer},s.createElement(y,{flexDirection:"column",justifyContent:"center",flex:1,gap:4},s.createElement(T,{variant:"subtitle1",color:i.textHighEmphasis,numberOfLines:1},c),s.createElement(y,{flexDirection:"row",alignItems:"center",gap:6},ye(n)&&s.createElement(s.Fragment,null,s.createElement(T,{variant:"caption1",color:i.textMidEmphasis,numberOfLines:1},r.conversation_list.ended),s.createElement(y,{width:2,height:2,borderRadius:1,backgroundColor:i.textLowEmphasis})),s.createElement(T,{variant:"caption2",color:i.textLowEmphasis,numberOfLines:1},u))),g>0&&s.createElement(y,{alignItems:"center",justifyContent:"center",height:20,width:g<=bt?20:void 0,padding:4,borderRadius:10,backgroundColor:i.error},s.createElement(T,{variant:"caption3",color:i.textHighEmphasisInverse,style:{lineHeight:12}},g<=bt?g:`${bt}+`)))))}),yl=ae({template:_l,components:{}}),bl=P.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),El=()=>{var l;const{Template:e}=yl.useContext(),{strings:t}=F(),{connectionError:n}=J(),{listSource:o,onNavigateToConversation:r}=nt(),a=Ie(["left","right"]),i=vl.use();return s.createElement($n,{style:i.list,contentContainerStyle:[i.listContent,a],data:o.channels,onEndReached:o.loadMore,keyExtractor:d.useCallback(c=>c.url,[]),renderItem:d.useCallback(({item:c})=>s.createElement(e,{channel:c,onClick:()=>r==null?void 0:r(c.url,ye(c)?"closed":"open")}),[e,r]),loading:!o.initialized,error:!!(n||o.error),LoadingComponent:s.createElement(Ae,{type:"loading"}),EmptyComponent:s.createElement(Ae,{type:"noChannels",label:t.common.placeholder_no_conversations}),ErrorComponent:s.createElement(Ae,{type:"error",label:(n==null?void 0:n.message)??((l=o.error)==null?void 0:l.message)})})},vl=P.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),Cl=()=>{const{strings:e}=F(),{language:t,countryCode:n,context:o}=j(),{aiAgentInfo:r,refreshActiveChannel:a,createConversation:i,setActiveChannel:l,sdkUser:c}=J(),{onNavigateToConversation:u}=nt(),g=Ie(["left","right","bottom"]),h=Sl.use();return s.createElement(R,{activeOpacity:.75,disabled:!c,onPress:async()=>{if(r!=null&&r.isMultipleActiveConversationsEnabled){const m=await i({aiAgentId:r.userId,language:t,country:n,context:o});l({url:m,status:Y.ConversationStatus.OPEN}),u==null||u(m,Y.ConversationStatus.OPEN)}else{const m=await a();u==null||u(m,Y.ConversationStatus.OPEN)}}},s.createElement(y,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+g.paddingBottom,style:[h.container,g]},s.createElement(T,{variant:"h1",color:m=>m.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},Sl=P.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),Al=()=>{const{aiAgentInfo:e}=J();return e?s.createElement(Cl,null):null},wl=()=>{const{themedColor:e}=$(),{onClose:t}=nt();return t?s.createElement(R,{hitSlop:4,onPress:t,activeOpacity:.75},s.createElement(D,{color:e.textHighEmphasis,type:"close",size:24})):null},xl=()=>{const{strings:e}=F();return s.createElement(T,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},Il=e=>{const{components:t}=Te.useContext();return s.createElement(Zn,{start:s.createElement(t.StartArea,null),title:s.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:s.createElement(t.EndArea,null)})},Tl=()=>null,kl=()=>{const{components:e}=Te.useContext();return s.createElement(e.Title,null)},Ml=()=>{const{components:e}=Te.useContext();return s.createElement(e.CloseButton,null)},Te=ae({template:Il,components:{StartArea:Tl,TitleArea:kl,EndArea:Ml,Title:xl,CloseButton:wl}}),Ll=()=>{const{Template:e}=Te.useContext();return s.createElement(e,{titleAlign:"start"})},Pl=()=>{const{components:e}=ot.useContext();return s.createElement(y,{flex:1},s.createElement(e.Header,null),s.createElement(e.Body,null),s.createElement(e.Footer,null))},ot=ae({template:Pl,components:{Header:Ll,Body:El,Footer:Al}}),to=({children:e,...t})=>{const{Template:n}=ot.useContext();return s.createElement(eo,{...t},s.createElement(n,null),e)},Rl="1.3.0",Dl=Rl,Ol=d.forwardRef(function({logLevel:t=K.LogLevel.WARN,language:n=Ye,userSessionInfo:o,children:r,strings:a,...i},l){const[c]=d.useState(()=>new In(t));c.level!==t&&(c.level=t);const{nativeModules:u,chatParams:g={},...h}=i;return s.createElement(Xn,{config:u},({keyValueStorage:m})=>s.createElement(Nl,{logger:c,theme:h.theme,language:n,strings:a},s.createElement(Xo,{language:n,logger:c,chatSDK:h.customChatSDK,keyValueStorage:m,chatParams:{...g,useMMKVStorageStore:u.mmkv},messengerVersion:Dl,extensions:{platform:K.SendbirdPlatform.REACT_NATIVE,deviceOSPlatform:p.Platform.select({web:K.DeviceOsPlatform.WEB,ios:K.DeviceOsPlatform.IOS,default:K.DeviceOsPlatform.ANDROID})},...h},s.createElement(cs,{ref:l,userSessionInfo:o},r))))}),Bl=To(tt,be,ot,Te,Gt,Ze,Je,Qe,et),Nl=({children:e,logger:t,theme:n,language:o,strings:r})=>s.createElement(_e.SafeAreaProvider,null,s.createElement(Vs,{logger:t,...n},s.createElement($s,{language:o,logger:t,strings:r},s.createElement(On,null,s.createElement(Vr,null,s.createElement(Bl,null,e)))))),{Provider:Hl,useContext:Yt}=X("FixedMessengerStyle"),zl={useNativeDriver:!0},$e={OPEN_START:"0deg",OPEN_END:"-180deg",CLOSE_START:"180deg",CLOSE_END:"0deg"},Ue={VISIBLE:1,HIDDEN:0},Fl=({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,...zl}).start()},[e,t]);const n={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[$e.OPEN_START,$e.OPEN_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Ue.VISIBLE,Ue.HIDDEN]})}]},o={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[$e.CLOSE_START,$e.CLOSE_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Ue.HIDDEN,Ue.VISIBLE]})}]};return{openIconStyle:n,closeIconStyle:o}},$l=2/3,Ul=({isOpened:e,onPress:t})=>{const n=Wl.use(),{launcherInfo:o}=J(),{theme:r}=$(),{launcherSize:a,horizontal:i}=Yt(),l=Math.round(a*$l),c=r.colors.base.primary,u=r.colors.base.primaryContrastContent,{openIconStyle:g,closeIconStyle:h}=Fl({isOpened:e});return s.createElement(y,{alignSelf:i==="start"?"flex-start":"flex-end"},s.createElement(R,{onPress:t,activeOpacity:.8},({pressed:m})=>s.createElement(y,{style:[n.container({backgroundColor:c,size:a}),m&&n.pressed]},s.createElement(y.Animated,{style:[n.iconWrapper,g]},s.createElement(ql,{url:(o==null?void 0:o.imageUrl)??"",isDefaultIcon:(o==null?void 0:o.type)==="default_icon",size:l,fillColor:u})),s.createElement(y.Animated,{style:[n.iconWrapper,h]},s.createElement(Vl,{size:l,fillColor:u})))))},ql=({url:e,isDefaultIcon:t,size:n,fillColor:o})=>e?t?s.createElement(xe,{source:{uri:e},width:n,height:n,tintColor:o,resizeMode:"contain"}):s.createElement(xe,{source:{uri:e},width:n,height:n,resizeMode:"cover"}):s.createElement(D,{type:"delight",size:n,color:o}),Vl=({size:e,fillColor:t})=>s.createElement(D,{type:"chevron-down",size:e,color:t}),Wl=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"}})),Q={TRANSLATE_OFFSET:40,DURATION:300,OPACITY_DURATION:83,EASING:p.Easing.out(p.Easing.ease)},Gl=e=>e==="entered"?0:Q.TRANSLATE_OFFSET,jl=e=>e==="entered"?1:0,Kl=({transitionState:e,isActive:t})=>{const[n,o]=d.useState(!1),r=d.useRef(new p.Animated.Value(Gl(e))).current,a=d.useRef(new p.Animated.Value(jl(e))).current;return d.useEffect(()=>{if(!n){e==="entered"?(r.setValue(0),a.setValue(1)):e==="exited"&&(r.setValue(Q.TRANSLATE_OFFSET),a.setValue(0)),o(!0);return}e==="entering"?(r.setValue(Q.TRANSLATE_OFFSET),a.setValue(0),p.Animated.parallel([p.Animated.timing(r,{toValue:0,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),p.Animated.timing(a,{toValue:1,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()):e==="exiting"&&p.Animated.parallel([p.Animated.timing(r,{toValue:Q.TRANSLATE_OFFSET,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),p.Animated.timing(a,{toValue:0,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()},[e,r,a,n]),d.useMemo(()=>({position:"absolute",top:0,left:0,width:"100%",height:"100%",transform:[{translateY:r}],opacity:a,zIndex:t?999:1,pointerEvents:t?"auto":"none",display:e==="exited"?"none":"flex"}),[r,a,t,e])},no=d.createContext(null),Yl=()=>{const e=d.useContext(no);if(!e)throw new Error("useNavigatorContext() must be used within <Navigator />");return e},oo=({children:e})=>{const t=Yl();return typeof e=="function"?s.createElement(s.Fragment,null,e(t)):s.createElement(s.Fragment,null,e)},Xl=d.memo(({transitionState:e,isActive:t,children:n})=>{const o=Kl({transitionState:e,isActive:t});return s.createElement(p.Animated.View,{style:o},n)}),En=300,Ve=({initialId:e,children:t})=>{const[n,o]=d.useState([e]),r=n[n.length-1],a=d.useCallback((f,E)=>{o(C=>[...C,f]),h(C=>({...C,[f]:!0})),E!=null&&E.reset&&S(C=>({...C,[f]:(C[f]||0)+1})),_(C=>({...C,[f]:"entering"})),setTimeout(()=>{_(C=>({...C,[f]:"entered"}))},En)},[]),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))},En),f})},[]),l=d.useMemo(()=>({navigation:{navigate:a,pop:i},activeScreenId:r}),[a,i,r]),c=d.useMemo(()=>d.Children.toArray(t).filter(f=>f.type===oo),[t]),u=d.useMemo(()=>{const f={};return c.forEach(E=>{const{id:C,lazy:v,children:A}=E.props;f[C]={lazy:v,element:typeof A=="function"?A(l):A}}),f},[c,l]),[g,h]=d.useState(()=>{const f={};return Object.entries(u).forEach(([E,{lazy:C}])=>{C===!1&&(f[E]=!0)}),f[e]=!0,f}),[m,_]=d.useState(()=>{const f={};return Object.keys(u).forEach(E=>{f[E]=E===e?"entered":"exited"}),f}),[b,S]=d.useState({});return s.createElement(no.Provider,{value:l},s.createElement(y,{style:{position:"relative",width:"100%",height:"100%"}},Object.keys(u).map(f=>{var A;if(!g[f])return null;const E=m[f]||"exited",C=f===r,v=`${f}-${b[f]||0}`;return s.createElement(Xl,{key:v,transitionState:E,isActive:C},(A=u[f])==null?void 0:A.element)})))};Ve.Screen=oo;const{Provider:Zl,useContext:Xt}=X("PageChildren"),Jl=({children:e})=>{const[t,n]=d.useState(null),[o,r]=d.useState(null);return s.createElement(Zl,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:o,setConversationListChildren:r}},e)},pe={conv:"conv",convList:"conv-list"},Ql=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:o,onClose:r})=>{const{conversationChildren:a,conversationListChildren:i}=Xt(),l=t==="ConversationList"?pe.convList:pe.conv;return s.createElement(Ve,{initialId:l},s.createElement(Ve.Screen,{id:pe.conv},({navigation:c,activeScreenId:u})=>s.createElement(Qn,{channelUrl:n,onClearChannelUrl:()=>o(void 0),onNavigateToConversationList:()=>c.navigate(pe.convList),onClose:r,shouldMarkAsRead:e&&u===pe.conv},a)),s.createElement(Ve.Screen,{id:pe.convList,lazy:!0},({navigation:c})=>s.createElement(to,{onNavigateToConversation:u=>{o(u),c.navigate(pe.conv,{reset:!0})},onClose:r},i)))},Pe=.15,ec=150,vn=(e,t)=>e.interpolate({inputRange:[Pe,1],outputRange:[t,0],extrapolate:"clamp"}),tc=(e,t)=>{if(e<=0)return 0;const n=(1-Pe)*e/2,o=t==="start"?-1:1,r=p.I18nManager.isRTL?-1:1;return n*o*r},nc=(e,t)=>e<=0?0:(1-Pe)*e/2*(t==="top"?-1:1),oc=({isOpened:e,horizontal:t,vertical:n})=>{const[o,r]=d.useState({width:0,height:0}),a=d.useRef(new p.Animated.Value(e?1:Pe)).current,i=d.useRef(new p.Animated.Value(e?1:0)).current,l=d.useMemo(()=>tc(o.width,t),[o.width,t]),c=d.useMemo(()=>nc(o.height,n),[o.height,n]),{translateXInterpolation:u,translateYInterpolation:g}=d.useMemo(()=>({translateXInterpolation:vn(a,l),translateYInterpolation:vn(a,c)}),[a,l,c]);d.useEffect(()=>{const _=e?"open":"close",b=_==="open"?1:Pe,S=_==="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(a,{toValue:b,...E}),p.Animated.timing(i,{toValue:S,...E})]).start()},[e,a,i]);const h=d.useMemo(()=>({opacity:i,transform:[{translateX:u},{translateY:g},{scale:a}]}),[i,u,g,a]),m=d.useMemo(()=>_=>{const{width:b,height:S}=_.nativeEvent.layout;r(f=>f.width===b&&f.height===S?f:{width:b,height:S})},[]);return{animatedStyle:h,handleLayout:m,pointerEvents:e?"auto":"none"}},rc={top:0,left:0,right:0,bottom:0},sc=({children:e,isOpened:t})=>{const n=ac.use(),{horizontal:o,vertical:r}=Yt(),{animatedStyle:a,handleLayout:i,pointerEvents:l}=oc({isOpened:t,horizontal:o,vertical:r});return s.createElement(_e.SafeAreaInsetsContext.Provider,{value:rc},s.createElement(y,{flex:1},s.createElement(y.Animated,{pointerEvents:l,onLayout:i,style:a},s.createElement(y,{style:n.windowContainer},e))))},ac=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)"}})),ro=()=>{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)}),a=p.Keyboard.addListener(o,()=>{t(0)});return()=>{r.remove(),a.remove()}},[]),e},ic=e=>{const t=d.useRef(new p.Animated.Value(0)).current,[n,o]=d.useState(!1);return d.useEffect(()=>{const a=e?"open":"close",i={toValue:a==="open"?1:0,useNativeDriver:!0,duration:300};a==="open"&&o(!0),p.Animated.timing(t,i).start(()=>{a==="close"&&(o(!1),p.Keyboard.dismiss())})},[e,t]),{windowAnimatedStyle:{opacity:t,display:n?"flex":"none"},pointerEvents:e?"auto":"none"}},lc=({children:e,insets:t,isOpened:n})=>{const o=cc.use(),a={..._e.useSafeAreaInsets(),...t},i=ro(),{windowAnimatedStyle:l,pointerEvents:c}=ic(n);return s.createElement(_e.SafeAreaInsetsContext.Provider,{value:a},s.createElement(y.Animated,{flex:1,style:[o.bg,l],pointerEvents:c},s.createElement(y,{flex:1},e),s.createElement(y,{height:Math.max(0,i-p.Platform.select({android:0,default:a.bottom})),style:o.bg})))},cc=P.create(({theme:e})=>({bg:{backgroundColor:e.colors.base.background}})),uc="end-bottom",Me={top:24,bottom:24,start:24,end:24},dc=({mode:e,edgeToEdgeEnabled:t})=>{const n=e==="floating"?sc:lc,[o,r]=At({position:uc,margin:Me,launcherSize:48,spacing:12}),{bottom:a}=_e.useSafeAreaInsets(),i=ro(),[l,c]=o.position.split("-"),u=(()=>{const m=p.Platform.select({android:t?a:0,default:0}),_=c==="top"?o.spacing:-o.launcherSize,b=i>0?i+_+m:0;return b>0?b:o.margin.bottom})(),g={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 m=o.launcherSize+o.spacing;return{position:"absolute",top:o.margin.top+(c==="top"?m:0),bottom:u+(c==="bottom"?m: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:g,styleContext:{...o,horizontal:l,vertical:c,setPosition:m=>r({position:m}),setMargin:({top:m=Me.top,bottom:_=Me.bottom,start:b=Me.start,end:S=Me.end})=>r({margin:{top:m,bottom:_,start:b,end:S}}),setLauncherSize:m=>r({launcherSize:m}),setSpacing:m=>r({spacing:m})}}},mc=e=>{var a,i,l,c;const{setPosition:t,setMargin:n,setLauncherSize:o,setSpacing:r}=Yt();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,(a=e.margin)==null?void 0:a.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},gc=({children:e})=>{const{setConversationChildren:t}=Xt();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},hc=({children:e})=>{const{setConversationListChildren:t}=Xt();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},fc=({entryPoint:e="Conversation",edgeToEdgeEnabled:t=!0,windowMode:n="floating",fullscreenInsets:o,initialChannelUrl:r,windowContainerProps:a,children:i})=>{const[l,c]=d.useState(!1),[u,g]=d.useState(r),{Window:h,windowContainerStyle:m,launcherContainerStyle:_,styleContext:b}=dc({mode:n,edgeToEdgeEnabled:t});return d.useEffect(()=>{const S=p.BackHandler.addEventListener("hardwareBackPress",()=>l?(c(!1),!0):!1);return()=>S.remove()},[l]),s.createElement(Hl,{value:b},s.createElement(Jl,null,s.createElement(y,{style:m,backgroundColor:"transparent",pointerEvents:l?"auto":"box-none",...a},s.createElement(h,{isOpened:l,insets:o},s.createElement(Ql,{isOpened:l,entryPoint:e,selectedChannelUrl:u,setSelectedChannelUrl:g,onClose:()=>c(!1)}))),s.createElement(y,{style:_,backgroundColor:"transparent",pointerEvents:"box-none"},s.createElement(Ul,{isOpened:l,onPress:()=>c(!l)})),i))},pc=Object.assign(fc,{Style:mc,ConversationChildren:gc,ConversationListChildren:hc});exports.AIAgentProviderContainer=Ol;exports.AnonymousSessionInfo=Ge;exports.BottomSheet=ee;exports.BottomSheetLayout=Ze;exports.Conversation=Qn;exports.ConversationContext=_s;exports.ConversationContextProvider=Dn;exports.ConversationHeaderLayout=be;exports.ConversationLayout=tt;exports.ConversationList=to;exports.ConversationListContext=pl;exports.ConversationListContextProvider=eo;exports.ConversationListHeaderLayout=Te;exports.ConversationListLayout=ot;exports.FixedMessenger=pc;exports.IncomingMessageLayout=Je;exports.ManualSessionInfo=Ft;exports.ModalProvider=On;exports.NativeAdapterProvider=Xn;exports.OutgoingMessageLayout=Qe;exports.SystemMessageLayout=et;exports.useConversationContext=te;exports.useConversationListContext=nt;exports.useMessengerSessionContext=J;exports.useModalContext=Xe;exports.useNativeAdapterContext=Yn;
|
|
1
|
+
"use strict";var so=Object.defineProperty;var ao=(e,t,n)=>t in e?so(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var z=(e,t,n)=>ao(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react"),p=require("react-native"),_e=require("react-native-safe-area-context"),K=require("@sendbird/chat"),Y=require("@sendbird/chat/aiAgent"),Nt=require("@sendbird/uikit-tools"),ve=require("date-fns"),Ce=require("@sendbird/chat/message"),We=require("@sendbird/chat/groupChannel"),io=require("date-fns/isSameDay"),lo=require("date-fns/locale/de"),co=require("date-fns/locale/en-US"),uo=require("date-fns/locale/es"),mo=require("date-fns/locale/fr"),go=require("date-fns/locale/hi"),ho=require("date-fns/locale/it"),fo=require("date-fns/locale/ja"),po=require("date-fns/locale/ko"),_o=require("date-fns/locale/pt"),yo=require("date-fns/locale/tr"),bo=require("@react-native-clipboard/clipboard"),Eo=require("react-native-code-highlighter"),vo=require("react-syntax-highlighter/dist/esm/styles/hljs"),Co=require("react-native-markdown-display"),je=e=>e&&e.__esModule?e:{default:e};function So(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 s=So(d),Ao=je(K),wo=je(bo),xo=je(Eo),Io=je(Co),X=(e,t)=>{const n=d.createContext(null),o=({children:i,value:l})=>s.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),r=({children:i})=>s.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),a=()=>{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`,a.displayName=`use${e}Context`,{Context:n,Provider:o,Consumer:r,useContext:a}};function ae(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:a}){const[i,l]=d.useState(()=>e.template),[c,u]=d.useState(e.components),g={Template:i,updateTemplate:h=>l(()=>h),components:c,updateComponent:(h,m)=>u(_=>({..._,[h]:m}))};return s.createElement(t.Provider,{value:g},a)}function o({template:a,children:i}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{a&&l(a)},[a]),s.createElement(s.Fragment,null,i)}function r({children:a}){return s.createElement(n,null,a)}return r.defaults=e,r.useContext=()=>d.useContext(t),r.Context=t,r.Template=o,Object.keys(e.components).forEach(a=>{r[a]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(a,l)},[l]),null}}),r}function To(...e){return function({children:n}){return e.reduce((o,r)=>s.createElement(r,null,o),n)}}const ye=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Y.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Cn=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Y.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function Ae(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 ko(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function en(e){return!!e&&e<Date.now()}function Mo(e){return!e.title}function Lo(e,t){var n;if(e)return Mo(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}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}function Ro(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 Po(e,t,n){var i;const o=new Date,r=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),a=ve.differenceInMinutes(o,r);return a<1?n.justNow:a<60?n.minutesAgo(a):ve.isToday(r)?n.hoursAgo(ve.differenceInHours(o,r)):t(r,n.dateShortFormat)}const Ee="sb-agent",Sn="KEY_IMG_ASPECT_RATIO",An="*/*",k={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},se=e=>!!e&&"sender"in e,Do=e=>se(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Oo=(e,t,n,o=!0)=>{if(!o||!se(e))return"single";const r=()=>{if(!t||!se(t))return!1;const c=t.sender.userId===e.sender.userId,u=ve.isSameMinute(t.createdAt,e.createdAt);return c&&u},a=()=>{if(!n||!se(n))return!1;const c=n.sender.userId===e.sender.userId,u=ve.isSameMinute(n.createdAt,e.createdAt);return c&&u},i=r(),l=a();return i&&l?"middle":i?"bottom":l?"top":"single"},Pe=(e,t)=>(()=>{var o;return se(e)?e.sender.userId:((o=e==null?void 0:e.sender)==null?void 0:o.userId)??void 0})()===t,Oe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>se(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>se(e)&&(e.sender.userId===t||e.sendingStatus===Ce.SendingStatus.PENDING)},Bo=e=>e.startsWith("image/"),Ht=(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"},wn=e=>e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.message.length>0,zt=e=>{switch(e){case"top":case"middle":return k.GAP_GROUPED;default:return k.GAP_UNGROUPED}},No=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,o=[];let r=0;return e.replace(n,(a,...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+a.length,a}),r<e.length&&o.push({type:"text",value:e.slice(r).trim()}),o},Ho=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),zo=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Fo=e=>e.replace(/~~/g,"\\~\\~"),$o=e=>{let t=e;return t=Ho(t),t=zo(t),t=Fo(t),t},Uo=typeof navigator<"u"&&navigator.product==="ReactNative",tn=(e,t)=>{const n=o=>!t||t.length===0?!0:se(o)&&t.includes(o.sendingStatus);return Uo?e.find(n):e.findLast(n)};function Et(){}function qo(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Vo(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 nn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},qe={isStreaming(e){const t=nn(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(Pe(e,t)){const o=nn(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)}},rt=`@${Ee}`,on=({appId:e,aiAgentId:t,storage:n})=>{const o={templateBase:`${rt}-template`,template:r=>`${o.templateBase}/templates/${r}`,templateToken:()=>`${o.templateBase}-template/message-template/tokens`,messengerSession:r=>{const a=Vo(`${e}/${t}/${r}`);return`${rt}-udata/${a}`},anonUserSession:()=>`${rt}-session/${e}/${t}`};return{template:{set:(r,a)=>n.set(o.template(r),a),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 a=n.get(o.messengerSession(r));return a?JSON.parse(a):null}catch{return null}},setSettings:(r,a)=>{try{delete a.auto_created_user;const i=JSON.stringify(a);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 a=JSON.stringify(r);n.set(o.anonUserSession(),a)}catch{return}},clear:r=>{try{r&&n.delete(o.messengerSession(r)),n.delete(o.anonUserSession())}catch{return}}}}};class Wo{constructor(t){z(this,"subscribers",{});this.logger=t}async send(t){const n=Go(),o=this.subscribers[t.type];if(o){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const r=o.map(a=>a(t.payload));await Promise.all(r).catch(a=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,a)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(o=>o!==n))}}const Go=()=>{let e=Et,t=Et;return{promise:new Promise((o,r)=>{e=o,t=r}),resolve:e,reject:t}};var xn=(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))(xn||{});class In{constructor(t){z(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ee}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ee}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ee}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ee}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ee}/error]`,...t)}}function rn(e,t,n,o){const r=Ao.default.init({appId:e,modules:[new We.GroupChannelModule,new Y.AIAgentModule],localCacheEnabled:!0,options:new K.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...o});return r.addSendbirdExtensions([{version:n,product:K.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),r}function jo(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 me={conversation:{isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0,header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}}},Ko=e=>{var t,n,o,r,a,i,l,c,u,g,h,m,_,b;return e?{...me,...e,conversation:{...me.conversation,...e==null?void 0:e.conversation,header:{...(t=me.conversation)==null?void 0:t.header,...(n=e==null?void 0:e.conversation)==null?void 0:n.header},input:{...(o=me.conversation)==null?void 0:o.input,...(r=e==null?void 0:e.conversation)==null?void 0:r.input,camera:{...(i=(a=me.conversation)==null?void 0:a.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:{...(g=(u=me.conversation)==null?void 0:u.input)==null?void 0:g.gallery,...(m=(h=e==null?void 0:e.conversation)==null?void 0:h.input)==null?void 0:m.gallery}},fileViewer:{...(_=me.conversation)==null?void 0:_.fileViewer,...(b=e==null?void 0:e.conversation)==null?void 0:b.fileViewer}}}:me},{Provider:Yo,useContext:j}=X("AIAgent");function Xo({appId:e,aiAgentId:t,keyValueStorage:n,networkStateAdapter:o,language:r,countryCode:a,context:i,queryParams:l,config:c,chatSDK:u,chatParams:g,children:h,logger:m,dispatcher:_,messengerVersion:b,extensions:S={platform:K.SendbirdPlatform.JS,deviceOSPlatform:qo()?K.DeviceOsPlatform.MOBILE_WEB:K.DeviceOsPlatform.WEB}}){const[f,E]=d.useState(()=>{const C=m??new In(xn.WARN),v=_??new Wo(C);return{logger:C,dispatcher:v,chatSDK:u??rn(e,S,b,g),cache:on({appId:e,aiAgentId:t,storage:n})}});return d.useEffect(()=>{E(C=>{let v=C.logger,A=C.dispatcher,I=C.chatSDK;return m&&m!==C.logger&&(v=m),_&&_!==C.dispatcher&&(A=_),u&&u!==C.chatSDK?I=u:!u&&C.chatSDK.appId!==e&&(I=rn(e,S,b,{newInstance:!0,...g})),{...C,logger:v,dispatcher:A,chatSDK:I,cache:on({appId:e,aiAgentId:t,storage:n})}})},[e,t,m,_,u,n]),d.useEffect(()=>()=>{f.chatSDK.disconnectWebSocket()},[f.chatSDK]),jo(f.chatSDK),s.createElement(Yo,{value:{...f,appId:e,aiAgentId:t,context:i,language:r,countryCode:a,queryParams:l,config:Ko(c),networkStateAdapter:o}},h)}const Zo=(e,t,n)=>Nt.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0});var vt=(e=>(e.ConversationClose="conv.close",e))(vt||{});const Tn=(e,t,n={})=>{let o=null,r=null,a=null;const{leading:i=!0,trailing:l=!0}=n,c=(...u)=>{const g=Date.now();if(a===null||g-a>=t)i?(e(...u),a=g):(r=u,a=g);else if(r=u,l&&!o){const h=t-(g-a);o=setTimeout(()=>{r&&l&&(e(...r),a=Date.now()),o=null,r=null},h)}};return c.cancel=()=>{o&&(clearTimeout(o),o=null),r=null,a=null},c},Ct={DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function kn(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Jo(e){const t=kn(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Qo(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function er(e,t,n){e/=255,t/=255,n/=255;const o=Math.max(e,t,n),r=Math.min(e,t,n),a=o-r;let i=0,l=0;const c=(o+r)/2;return o!==r&&(l=c>.5?a/(2-o-r):a/(o+r)),o===e?i=(t-n)/a+(t<n?6:0):o===t?i=(n-e)/a+2:o===n&&(i=(e-t)/a+4),i/=6,[i,l,c]}function tr(e,t,n){let o,r,a;if(t===0)o=r=a=n;else{const i=function(g,h,m){return m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?g+(h-g)*6*m:m<.5?h:m<.6666666666666666?g+(h-g)*(.6666666666666666-m)*6:g},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),a=i(c,l,e-1/3)}return[Math.round(o*255),Math.round(r*255),Math.round(a*255)]}function Be(e,t,n){const[o,r,a]=Jo(e),[i,l,c]=er(o,r,a),u=Math.max(0,Math.min(1,c*t)),g=Math.max(0,Math.min(1,l*n)),[h,m,_]=tr(i,g,u);return Qo([Math.round(h),Math.round(m),Math.round(_)])}function nr(e,t="light"){return{extraDark:Be(e,.6,1.2),dark:Be(e,.85,1.1),main:e,light:Be(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Be(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function sn(e){const t=kn(e),n=149,o=+`0x${t[1]}${t[2]}`,r=+`0x${t[3]}${t[4]}`,a=+`0x${t[5]}${t[6]}`;return o*.299+r*.587+a*.114>n?Ct.BLACK:Ct.WHITE}function or(e,t,n,o,r){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},metadata:{errorContent:e.ondark.textHighEmphasis},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 rr=(e,t,n,o,r)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},metadata:{errorContent:e.ondark.textHighEmphasis},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}}),Ne={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)"}},st={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 an(e){const t=sr(e),{colors:n,aiAgentColorVariables:o}=ar(e,t),r=lr(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:o,typography:r}}function sr({selectedTheme:e,palette:t,primary:n}){const o=t!=null&&t.primary?t.primary:n?n===Ne.primary.main?Ne.primary:nr(n,e):Ne.primary;return{...Ne,primary:o,...t}}function ar({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:o},r){const a=r.primary.main,i=t??sn(a),l=n??Ct.DEFAULT_BOT_MSG_BG,c=o??sn(l);return{colors:(e==="light"?or:rr)(r,a,i,l,c),aiAgentColorVariables:{primary_color:a,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function ir(e,t,n){const o={...e};return n.forEach(r=>{const a=t[r];a!=null&&(o[r]=a)}),o}function lr({typography:e}){if(!e)return st;const t={...st};return Object.keys(e).forEach(n=>{const o=e[n];if(o&&typeof o=="object"){const r=st[n],a=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=ir(r,o,a)}}),t}const{Provider:cr,useContext:ur}=X("AIAgentTheme");function dr({logger:e,palette:t,typography:n,appearance:o,children:r}){const a=d.useRef(null),[i,l]=d.useState(()=>an({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,g)=>{g&&(a.current=g);const h=(o==null?void 0:o.theme)??u,m=a.current?a.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&&(m!=null&&m.primary_color)&&(_.primary=m.primary_color,_.primaryContrast=m.primary_contrast_color),!_.botMessageBackground&&(m!=null&&m.bot_message_bg_color)&&(_.botMessageBackground=m.bot_message_bg_color,_.botMessageBackgroundContrast=m.bot_message_bg_contrast_color);const b=an({selectedTheme:h,palette:t,typography:n,..._});l(b),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]),s.createElement(cr,{value:{theme:i,updateTheme:c}},r)}const ln=25*1024*1024,mr={off:"off",always:"always",handed_off_only:"handed_off_only"},gr=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:1,attachmentMode:"handed_off_only",defaultUploadSizeLimit:ln,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:a})=>{const{maxAttachmentCount:i,attachmentMode:l,defaultUploadSizeLimit:c,supportedImageMimeTypes:u,supportedFileMimeTypes:g}=e;t({maxAttachmentCount:i,attachmentMode:mr[r.attachment_mode]??l,defaultUploadSizeLimit:(a==null?void 0:a.default_upload_size_limit)??c,uploadSizeLimitPerType:new Map(Object.entries((a==null?void 0:a.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((a==null?void 0:a.supported_image_mime_types)??u),supportedFileMimeTypes:new Set((a==null?void 0:a.supported_file_mime_types)??g)})},[]),o=d.useCallback(r=>{const{channel:a,uploadSizeLimit:i=ln}=r,l=(u=!0)=>a!=null&&a.isAIAgent?u?Ae(a):!1:!0,c=u=>{if(l())return e.defaultUploadSizeLimit??i;const g=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(u)??g;return Math.min(g,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 Ae(a);default:return!0}},get supportedMimeTypes(){return l()?[An]:[...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 Mn(){const{chatSDK:e,logger:t}=j();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)},[e,t])}function hr(){const{chatSDK:e,logger:t}=j(),n=d.useCallback(async(r,a,i)=>{if(t.debug("useChatConnection.connect: start, session",r.userId),a){const l=new K.SessionHandler({...a,onSessionTokenRequired:fr(a.onSessionTokenRequired,i)});e.setSessionHandler(l)}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(_r(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"),await e.disconnect(),t.debug("useChatConnection.disconnect: end")},[e,t]);return{connect:n,disconnect:o}}function fr(e,t){if(e)return async(n,o)=>{new Promise((r,a)=>e==null?void 0:e(r,a)).then(r=>{r&&(t==null||t(r)),n(r)}).catch(r=>{o(r)})}}const pr=[400300,400301,400302,400310];function _r(e){return pr.some(t=>e.code===t)}class Ft{constructor({userId:t,authToken:n,sessionHandler:o}){z(this,"userId");z(this,"authToken");z(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=o}}class Ge{constructor(){z(this,"userId");z(this,"authToken");z(this,"sessionHandler")}}const yr=1440*60*1e3,br=e=>{const{logger:t,cache:n}=j(),o=()=>{const a=n.messenger.getAnonUser();return a?a.expireAt-yr<=Date.now()?(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session expired, clear cache"),n.messenger.clear(a.userId),null):(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session info detected"),a):null},r=()=>{if(!e||e instanceof Ge)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 a=["userId","authToken","sessionHandler"].filter(i=>!(i in e));return a.length>0&&t.error(`useUserSessionCandidate.getManualSessionInfo: missing required keys in userSessionInfo: ${a.join(", ")}`),t.debug("useUserSessionCandidate.getManualSessionInfo: manual session info detected"),e};return d.useMemo(()=>e instanceof Ft?{type:"manual",userSessionCandidate:r()}:e instanceof Ge?{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 Er({userSessionInfo:e,onUpdateMessengerSettings:t,onPreAuth:n,onPostAuth:o,onErrorAuth:r,onAuthTokenRefreshed:a,onPostDeauth:i,forceCreateChannel:l}){const{aiAgentId:c,language:u,context:g,countryCode:h,logger:m,cache:_}=j(),{connect:b,disconnect:S}=hr(),{type:f,userSessionCandidate:E}=br(e),C=Mn(),v=d.useCallback(async()=>{var B;m.debug("useAuthentication.authenticate: start");const I=E!=null&&E.userId?_.messenger.getSettings(E.userId):null;I!=null&&I.bot&&(t(I),m.debug("useAuthentication.authenticate: cached messenger settings",I));const x=await C({aiAgentId:c,userId:E==null?void 0:E.userId,language:u,country:h,context:g,forceCreateChannel:l,knownActiveChannelUrl:(B=I==null?void 0:I.active_channel)==null?void 0:B.channel_url});m.debug("useAuthentication.authenticate: messenger settings response",x);let O=null;if(x.auto_created_user)if(f==="manual")m.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),O={userId:E.userId,authToken:E.authToken};else{const{user_id:M,session_token:H,expire_at:G}=x.auto_created_user;_.messenger.setAnonUser({userId:M,authToken:H,expireAt:G}),O={userId:M,authToken:H}}else O={userId:(E==null?void 0:E.userId)??"",authToken:(E==null?void 0:E.authToken)??""};_.messenger.setSettings(O.userId,x),t(x);try{await n(x,O),await b(O,E==null?void 0:E.sessionHandler,a),await o(x,O)}catch(M){throw M instanceof Error&&(r(M),m.error("useAuthentication.authenticate: failed to connect",M)),M}return x},[C,b,f,E==null?void 0:E.userId,E==null?void 0:E.sessionHandler,E==null?void 0:E.authToken,c,u,g,h,l,_.messenger.setAnonUser,_.messenger.getSettings,_.messenger.setSettings,t,n,o,r,a]),A=d.useCallback(async()=>{m.debug("useAuthentication.deauthenticate: start"),await S(),i(),m.debug("useAuthentication.deauthenticate: completed")},[S,m,i]);return{authenticate:v,deauthenticate:A,userSessionCandidate:E}}const vr=e=>JSON.parse(e),Cr=()=>{const{chatSDK:e,logger:t,cache:n}=j(),o=d.useCallback(()=>{var l,c;const a=(c=(l=e.appInfo)==null?void 0:l.aiAgentInfo)==null?void 0:c.templateListToken;if(!a)return!1;const i=n.template.getCachedToken();return i?a!==i:!0},[e,n.template.getCachedToken]),r=d.useCallback(async()=>{try{const{templates:a,token:i}=await e.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of a){const{key:c}=vr(l);n.template.set(c,l)}n.template.setCachedToken(i)}catch(a){t==null||t.error("messageTemplateContext.syncCachedTemplates: error:",a)}},[e,t,n.template.set,n.template.setCachedToken]);return{shouldSyncCachedTemplate:o,syncCachedTemplates:r}},{Provider:Sr,useContext:Ke}=X("AIAgentMessengerSession"),Ar=d.forwardRef(function({userSessionInfo:e,forceCreateChannel:t,children:n},o){const{appId:r,aiAgentId:a,chatSDK:i,language:l,countryCode:c,context:u,cache:g,logger:h}=j(),{updateTheme:m}=ur(),[_,b]=d.useState(void 0),[S,f]=d.useState(void 0),[E,C]=d.useState(null),[v,A]=d.useState(null),[I,x]=d.useState(null),[O,B]=d.useState(null),{updateBaseAttachmentRules:M,createAttachmentRules:H}=gr(),{shouldSyncCachedTemplate:G,syncCachedTemplates:Z}=Cr(),ne=Mn(),{authenticate:q,deauthenticate:w}=Er({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(L=>{const{appearance:N,bot:V,launcher:re}=L;m(N.selected_theme,N),x({userId:V.bot_userid,profileUrl:V.bot_profile_url,nickname:V.bot_nickname,replyToFile:V.reply_to_file,specialNotice:V.special_notice,specialNoticeEnabled:V.is_special_notice_enabled,showHandoffButton:V.show_handoff_button??!0,isMultipleActiveConversationsEnabled:V.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:L.bot.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:L.bot.is_user_feedback_comment_option_enabled??!1}),B({type:re.image_type||"default_icon",imageUrl:re.image_url}),M(L)},[m]),onPreAuth:d.useCallback((L,N)=>{b(void 0),A(N)},[]),onPostAuth:d.useCallback(async L=>{C(i.currentUser),G()&&await Z(),f({url:L.active_channel.channel_url,status:Y.ConversationStatus.OPEN})},[i,G,Z]),onErrorAuth:d.useCallback(L=>{b(L)},[]),onAuthTokenRefreshed:d.useCallback(L=>{A(N=>N?{...N,authToken:L}:null)},[]),onPostDeauth:d.useCallback(()=>{g.template.clear(),g.messenger.clear(v==null?void 0:v.userId),C(null),f(void 0),A(null),x(null),B(null)},[g.template.clear,g.messenger.clear,v])}),U=d.useCallback(async()=>{var L;if(v){h.debug("agentMessengerSession.refreshActiveChannel: try to refresh active channel"),f(void 0);const N=await ne({aiAgentId:a,userId:v.userId,language:l,country:c,context:u,forceCreateChannel:t,knownActiveChannelUrl:(L=g.messenger.getSettings(v.userId))==null?void 0:L.active_channel.channel_url});return g.messenger.setSettings(v.userId,N),f({url:N.active_channel.channel_url,status:Y.ConversationStatus.OPEN}),h.info("agentMessengerSession.refreshActiveChannel: refreshed active channel",N.active_channel.channel_url),N.active_channel.channel_url}else throw h.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")},[ne,r,a,v==null?void 0:v.userId,l,c,u,t,g.messenger.getSettings,g.messenger.setSettings]),oe=d.useCallback(async L=>{if(!(v!=null&&v.userId))throw new Error("Current user is not authenticated. Please authenticate first.");const N=await ne({...L,userId:v.userId,knownActiveChannelUrl:void 0}),V=N.active_channel.channel_url;return g.messenger.setSettings(v.userId,N),V},[v==null?void 0:v.userId,ne]),[le]=d.useState(()=>Tn(L=>{var N;h.info("agentMessengerSession.channelChanged: channel.conversation",L.conversation),f({url:L.url,status:((N=L.conversation)==null?void 0:N.status)??Y.ConversationStatus.OPEN})},250,{trailing:!1,leading:!0}));return Nt.useGroupChannelHandler(i,{onChannelChanged:L=>{L.isGroupChannel()&&L.url===(S==null?void 0:S.url)&&le(L)}}),d.useEffect(()=>()=>{le.cancel()},[le]),d.useImperativeHandle(o,()=>{const L=async()=>{if(!S)throw new Error("No active conversation. Please start a conversation first.");return await i.groupChannel.getChannel(S.url)};return{activeChannel:S,chatSDK:i,authenticate:q,deauthenticate:w,updateContext:async N=>{const re=await(await L()).updateContext(a,N);return{...re,context:re.context??{}}},patchContext:async N=>{const re=await(await L()).patchContext(a,N);return{...re,context:re.context??{}}},getContextObject:async()=>{const V=await(await L()).getContextObject(a);return{...V,context:V.context??{}}}}},[q,w,S,i,a,h]),s.createElement(Sr,{value:{sdkUser:E,userSessionInfo:e,userSession:v,activeChannel:S,setActiveChannel:f,refreshActiveChannel:U,createConversation:oe,connectionError:_,aiAgentInfo:I,launcherInfo:O,authenticate:q,deauthenticate:w,createAttachmentRules:H}},n)}),wr=()=>{const e=d.useId(),{chatSDK:t,networkStateAdapter:n}=j(),[o,r]=d.useState(()=>n?n.isOnline()?"connected":"reconnecting":"connected");return d.useEffect(()=>{const a=new K.ConnectionHandler({onDisconnected:()=>r("disconnected"),onConnected:()=>r("connected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")});return t.addConnectionHandler(e,a),()=>{t.removeConnectionHandler(e)}},[t,e]),d.useEffect(()=>{if(n)return n.subscribe(()=>{r("reconnecting")})},[n]),o},Ln=e=>{const{chatSDK:t}=j(),[n,o]=d.useState([]);return Nt.useGroupChannelHandler(t,{onTypingStatusUpdated(r){if(r.url===(e==null?void 0:e.url)){const a=r.getTypingUsers();o(a)}}}),n},xr=({channel:e,messages:t,isStreamAnimating:n})=>{const{aiAgentInfo:o,userSession:r}=Ke(),a=wr(),i=Ir({channel:e,lastMessage:tn(t,[Ce.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),l=Lr({shouldApply:!!(e!=null&&e.isAIAgent)&&!Ae(e),isDisabledWhileAIResponding:i,lastMessage:tn(t,[Ce.SendingStatus.PENDING,Ce.SendingStatus.SUCCEEDED]),currentUserId:(r==null?void 0:r.userId)??""});if(!e||a==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(a==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(ye(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Tr(e))return{disabled:!0,disabledBy:"form_active"};const c=kr(e);return c?{disabled:!0,disabledBy:c}:i||l?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},Ir=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:o})=>{const[r,a]=d.useState(!1),i=Ln(e);return d.useEffect(()=>{if(!t)return;const l=i.some(u=>u.userId===n),c=Pe(t,n)&&(qe.isStreaming(t)||o);a(!!(c||l))},[i,t,n,o]),r},Tr=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,a=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return r&&!a},kr=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},Mr=3e4,Lr=({shouldApply:e,lastMessage:t,isDisabledWhileAIResponding:n,currentUserId:o})=>{const[r,a]=d.useState(!1),i=d.useRef(null),l=t&&Pe(t,o)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),a(!1)},u=m=>{i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},m)},g=Date.now()-l,h=Mr-g;return n||h<=0?c():u(h),()=>{i.current&&clearTimeout(i.current)}},[n,l]),r&&e},Rr=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(r=>{t(a=>{if(a.has(r))return a;const i=new Set(a);return i.add(r),i})},[]),o=d.useCallback(r=>{t(a=>{if(!a.has(r))return a;const i=new Set(a);return i.delete(r),i})},[]);return{isAnimating:e.size>0,start:n,stop:o}},{Provider:Pr}=X("AIAgentConversation");function Dr({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:o,onMessagesUpdated:r,onConversationClosedStatusChanged:a,onConversationClosedViaDispatcher:i,onBeforeSendMessage:l,onAfterSendMessage:c=Et,shouldMarkAsRead:u=!0,shouldCountNewMessages:g=()=>!1,sortComparator:h}){var B;const m=()=>u&&(f==null?void 0:f.markAsRead()),{chatSDK:_,logger:b,dispatcher:S}=j(),{channel:f,channelFetchError:E,fetchChannel:C}=Or(t),v=Zo(_,f,{replyType:Ce.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:g,onChannelDeleted:n,onMessagesReceived:M=>o==null?void 0:o(M),onMessagesUpdated:M=>r==null?void 0:r(M),logger:b,markAsRead:m,sortComparator:h}),A=Rr(),I=xr({channel:f,messages:v.messages,isStreamAnimating:A.isAnimating});d.useEffect(()=>{m()},[u]);const x=ye(f);d.useEffect(()=>{a==null||a(x)},[x,a]),d.useEffect(()=>{const M=async H=>{const G=typeof(H==null?void 0:H.channelUrl)=="string";f&&G&&H.channelUrl!==f.url||(b.debug("conversation.dispatcher: try to close conversation",f),f!=null&&f.conversation&&f.conversation.status===Y.ConversationStatus.OPEN&&(await f.closeConversation(),i==null||i()))};return S.subscribe(vt.ConversationClose,M),()=>{S.unsubscribe(vt.ConversationClose,M)}},[S,(B=f==null?void 0:f.conversation)==null?void 0:B.status,i]);const O={conversation:(f==null?void 0:f.conversation)??void 0,channelSource:{channel:f,error:E,refetch:()=>C(),closeConversation:async()=>{ye(f)||await(f==null?void 0:f.closeConversation())}},messageSource:{messages:v.messages,newMessages:v.newMessages,initialized:v.initialized,loadPrevious:()=>v.loadPrevious(),loadNext:()=>v.loadNext(),deleteMessage:M=>v.deleteMessage(M),resendMessage:M=>v.resendMessage(M),resetNewMessages:()=>v.resetNewMessages(),sendUserMessage:async M=>{var G;if(((G=f==null?void 0:f.conversation)==null?void 0:G.status)===Y.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(M=await l(M));const H=await v.sendUserMessage(M,c);return c==null||c(H),H},sendFileMessage:async M=>{var G;if(((G=f==null?void 0:f.conversation)==null?void 0:G.status)===Y.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(M=await l(M));const H=await v.sendFileMessage(M,c);return c==null||c(H),H}},state:{streamAnimation:A,input:I}};return s.createElement(Pr,{value:O},e)}function Or(e){const{chatSDK:t,logger:n}=j(),{sdkUser:o}=Ke(),[r,a]=d.useState(void 0),[i,l]=d.useState(void 0);async function c(){if(!o){n.debug("conversation.fetchChannel: no sdk user, skip fetching channel");return}if(n.debug("conversation.fetchChannel: start"),a(void 0),l(void 0),e)try{n.debug("conversation.fetchChannel: get channel",e);const u=await t.groupChannel.getChannel(e);a(u),n.debug("conversation.fetchChannel: fetched channel",u)}catch(u){u instanceof K.SendbirdError&&l(u),n.error("conversation.fetchChannel: error",u)}}return Br(r),d.useEffect(()=>{c()},[t,o,e]),{channel:r,channelFetchError:i,fetchChannel:c}}function Br(e){const{chatSDK:t}=j(),{activeChannel:n,setActiveChannel:o}=Ke(),r=d.useId();d.useEffect(()=>{if(!e||!n)return;const a=new K.ConnectionHandler({onReconnectSucceeded:async()=>{var l;const i=await e.refresh();i.url===n.url&&o({url:i.url,status:((l=i.conversation)==null?void 0:l.status)??Y.ConversationStatus.OPEN})}});return t.addConnectionHandler(r,a),()=>{t.removeConnectionHandler(r)}},[t,e,n])}class Nr{constructor(t,{filter:n,limit:o=20}){z(this,"filter");z(this,"_sdk");z(this,"_pinnedChannels");z(this,"_channels");z(this,"_isDisposed",!1);z(this,"_handlerId",`handler-id-${Date.now()}`);z(this,"_order",We.GroupChannelListOrder.LATEST_LAST_MESSAGE);z(this,"_limit");z(this,"_query");z(this,"_token");z(this,"_timestamp");z(this,"_isSyncing");z(this,"_channelHandler");z(this,"_connectionHandler");z(this,"_collectionEventHandler");z(this,"_throttledOnChannelChanged");var r,a,i,l,c,u,g;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:(a=this.filter)==null?void 0:a.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:(g=this.filter)==null?void 0:g.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=Tn(h=>{h.isGroupChannel()&&(this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url]))},250,{trailing:!1,leading:!0}),this._channelHandler=new We.GroupChannelHandler({onChannelChanged:this._throttledOnChannelChanged,onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new K.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 a,i;const n=new Set(((a=this.filter)==null?void 0:a.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=[],a=[],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 g=St(this._pinnedChannels,c);g>=0?(this._pinnedChannels.splice(g,1),a.push(c)):r.push(c);const m=this._pinnedChannels.findIndex(b=>(o.get(b.url)??1/0)>u),_=m===-1?this._pinnedChannels.length:m;this._pinnedChannels.splice(_,0,c)}return{addedChannels:r,updatedChannels:a,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const o=[],r=[],a=[];for(const i of t){if(!this._query.belongsTo(i)){o.push(i.url);continue}const l=St(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const g=Hr(this._channels,i,this._order).place,h=g===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(i),r.push(i)):(this._channels.splice(g,0,i),r.push(i)):(this._channels.splice(g,0,i),a.push(i))}return{addedChannels:r,updatedChannels:a,unmatchedChannelUrls:o}}_addChannelsToView(t,n=!1){var h,m,_,b,S;const o=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),r=[],a=[];for(const f of t)o.has(f.url)?r.push(f):a.push(f);const i=this._upsertPinnedChannelsToArray(r),l=this._upsertRegularChannelsToArray(a,n),c=i.addedChannels.concat(l.addedChannels),u=i.updatedChannels.concat(l.updatedChannels),g=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((_=(m=this._collectionEventHandler)==null?void 0:m.onChannelsAdded)==null||_.call(m,{},c)),u.length>0&&((S=(b=this._collectionEventHandler)==null?void 0:b.onChannelsUpdated)==null||S.call(b,{},u)),g.length>0&&this._removeChannelsFromView(g)}_removeChannelsFromView(t){var r,a,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=(a=this._collectionEventHandler)==null?void 0:a.onChannelsDeleted)==null||i.call(a,{},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 St=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Hr=(e,t,n)=>{if(e.length>0){const o=St(e,t);let r=0,a=e.length-1,i=Math.floor((r+a)/2);for(;r<a;){const c=cn(e[i],t,n);if(c>0)a=i,i=Math.floor((r+a)/2);else if(c<0)r=i+1,i=Math.floor((r+a)/2);else return{place:i,oldPosition:o}}return{place:cn(e[i],t,n)>=0?i:i+1,oldPosition:o}}return{place:e.length,oldPosition:-1}},cn=(e,t,n)=>{switch(n){case We.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}};function zr(e,t){var b,S,f,E,C,v,A,I,x,O;const n=d.useId(),[o,r]=d.useState(!1),[a,i]=d.useState(null),[l,c]=d.useState([]),[u,g]=d.useState(null),h=d.useRef(!1),m=d.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,r(!1),i(null),c([]);try{u==null||u.dispose();const B=new Nr(e,t);B.setConversationListCollectionHandler({onChannelsAdded:()=>{c(B.channels)},onChannelsUpdated:()=>{c(B.channels)},onChannelsDeleted:()=>{c(B.channels)}}),await B.loadMore(),g(B),i(null)}catch(B){g(null),i(B)}finally{r(!0),h.current=!1}}},[e,e.currentUser,(b=t.filter)==null?void 0:b.aiAgentChannelFilter,(f=(S=t.filter)==null?void 0:S.aiAgentConversationStatusFilter)==null?void 0:f.join(),(C=(E=t.filter)==null?void 0:E.aiAgentIds)==null?void 0:C.join(),(v=t.filter)==null?void 0:v.deskChannelFilter,(I=(A=t.filter)==null?void 0:A.pinnedChannelUrls)==null?void 0:I.join(),(x=t.filter)==null?void 0:x.copilotConversationOnly,(O=t.filter)==null?void 0:O.copilotSupportChannelUrl,t.limit]),_=d.useCallback(async()=>{if(u)try{await u.loadMore()}catch(B){i(B)}},[u]);return d.useEffect(()=>(e.addConnectionHandler(n,new K.ConnectionHandler({onConnected:()=>m()})),()=>e.removeConnectionHandler(n)),[e,n,m]),d.useEffect(()=>{m()},[m]),d.useEffect(()=>()=>{h.current=!1,u==null||u.dispose()},[u]),{initialized:o,error:a,channels:l,loadMore:_}}const{Provider:Fr}=X("AIAgentConversationList");function $r({conversationListLimit:e,conversationListFilter:t,children:n}){var h,m;const{chatSDK:o,aiAgentId:r,queryParams:a}=j(),i={aiAgentIds:[r],aiAgentConversationStatusFilter:[Y.ConversationStatus.CLOSED,Y.ConversationStatus.OPEN]},l=e??((h=a==null?void 0:a.conversationListParams)==null?void 0:h.limit),c={...i,...(m=a==null?void 0:a.conversationListParams)==null?void 0:m.filter,...t},u=zr(o,{limit:l,filter:c}),g={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return s.createElement(Fr,{value:g},n)}function Ur(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:qr}=X("MessageTemplateFetching");function Vr({children:e,internalVariables:t}){const n=d.useRef({}),o=d.useRef({}),[r,a]=d.useState({}),i=d.useCallback((u,g)=>{a(h=>({...h,[u]:{fetching:!1,error:!1,...h[u],...g}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:g,templateKey:h,suspense:m=!1})=>{const _=g(h);if(_)return _;const b=o.current[h];if(b)return b;m||i(h,{fetching:!0});const S=u(h).catch(f=>{throw m||i(h,{error:!0}),f}).finally(()=>{m||i(h,{fetching:!1}),delete o.current[h]});return o.current[h]=S,S},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(u,g)=>{if(n.current[u])return n.current[u];const h=Ur(g());return n.current[u]=h,h},getIsFetching:u=>{var g;return((g=r[u])==null?void 0:g.fetching)??!1},getHasError:u=>{var g;return((g=r[u])==null?void 0:g.error)??!1}};return s.createElement(qr,{value:c},e)}const Wr="remove_powered_by",$t=(e,t)=>{var r,a;const{chatSDK:n}=j(),{aiAgentInfo:o}=Ke();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&&Cn(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(o!=null&&o.specialNoticeEnabled)&&!!(o!=null&&o.specialNotice);if(e==="powered-by"){const i=(a=n==null?void 0:n.appInfo)==null?void 0:a.applicationAttributes;return d.useMemo(()=>!(Array.isArray(i)&&i.includes(Wr)),[i])}throw new Error("Unsupported feature")},Rn=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const o=(()=>{const[a]=e.members.filter(i=>i.userId!==t.userId);return a})(),r={ai(a){return{fallbackIcon:a,url:n.profileUrl,title:n.nickname}},human(a){return{fallbackIcon:a,url:o==null?void 0:o.profileUrl,title:(o==null?void 0:o.nickname)||n.nickname}},channel(a){return{fallbackIcon:a,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?Ae(e)?r.human("agent"):r.ai("delight"):e.isDesk?r.human("agent"):r.channel("user")},At=e=>d.useReducer((t,n)=>({...t,...n}),e);var ue=(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))(ue||{});const Gr=new Set(["free_text","single_choice"]),jr=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:o,initialIsResolved:r})=>{const[a,i]=At({csatType:t,csat:n,csatReason:o,isResolved:r}),[l,c]=At({followUpItem:!1}),u=d.useMemo(()=>{var S;const _=a.csat;if(typeof _!="number")return;const b=(S=e.follow_up)==null?void 0:S.find(f=>f.scores.includes(_));if(Gr.has(b==null?void 0:b.response_type))return b},[a.csat,e.follow_up]),g=(()=>{var _;if(typeof n=="number")return"submitted";if((t===ue.AI_AGENT_CSAT_5||t===ue.HELPDESK_CSAT_5)&&typeof a.csat=="number")return"submittable";if(t===ue.AI_AGENT_CSAT_5_WITH_CRE){const b=typeof a.csat=="number",S=!((_=e.cre)!=null&&_.required)||typeof a.isResolved=="boolean";if(b&&S)return"submittable"}return"unsubmittable"})(),h=d.useCallback(()=>typeof a.csat>"u"?!1:u!=null&&u.required&&!a.csatReason?(c({followUpItem:!0}),!1):!0,[a,u,c]);return d.useEffect(()=>{o||(i({csatReason:""}),c({followUpItem:!1}))},[o,u,i,c]),{params:a,setParams:i,error:l,setError:c,followUpItem:u,state:g,validateParams:h,itemProps:{csatPayload:e,state:g,submitted:g==="submitted"}}},at=5,Kr=250,Yr=50,un=e=>Math.max(0,e-Yr),Xr=e=>e<1e3?{speed:at*.5,chunkSize:2}:e<2e3?{speed:at*.8,chunkSize:2}:{speed:at*.6,chunkSize:3},Zr=e=>{const{text:t,enabled:n=!1,onAnimationStart:o,onAnimationProgress:r,onAnimationComplete:a}=e,[i,l]=d.useState(()=>un(t.length)),c=d.useRef(null),u=d.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,g=d.useRef({onStart:o,onProgress:r,onComplete:a}).current,h=d.useRef({startCalled:!1,completeCalled:!1}).current,m=d.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,_=n,b=i<t.length,S=m.initialEnabled&&(_||b);return d.useLayoutEffect(()=>{g.onStart=o,g.onProgress=r,g.onComplete=a,m.textLength=t.length,m.enabled=n}),d.useLayoutEffect(()=>{var f;m.initialEnabled&&(h.startCalled||(h.startCalled=!0,(f=g.onStart)==null||f.call(g)),l(E=>t.length<E?t.length:E))},[t]),d.useEffect(()=>{if(!m.initialEnabled)return;let f=un(t.length);u.lastUpdate=0,u.startTime=0,u.lastProgressCall=0;const E=C=>{var H;u.lastUpdate===0&&(u.lastUpdate=C,u.startTime=C,u.lastProgressCall=C);const v=m.textLength,A=C-u.lastUpdate,I=C-u.startTime,{speed:x,chunkSize:O}=Xr(I),B=x*O;A>=B&&f<v&&(f=Math.min(f+O,v),l(f),u.lastUpdate=C),C-u.lastProgressCall>=Kr&&(u.lastProgressCall=C,(H=g.onProgress)==null||H.call(g)),(f<v||m.enabled)&&(c.current=requestAnimationFrame(E))};return c.current=requestAnimationFrame(E),()=>{c.current&&cancelAnimationFrame(c.current)}},[]),d.useEffect(()=>{var v;const f=m.initialEnabled&&h.startCalled,E=!n,C=i>=t.length&&t.length>0;f&&E&&C&&!h.completeCalled&&(h.completeCalled=!0,(v=g.onComplete)==null||v.call(g))},[n,i,t.length]),{streamText:m.initialEnabled?t.slice(0,i):t,isAnimating:S}},Jr={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"}},wt={language:"en",strings:Jr,dateLocale:co.enUS},Qr={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:"피드백 삭제"}},xt={language:"ko",strings:Qr,dateLocale:po.ko},es={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:"フィードバックを削除"}},It={language:"ja",strings:es,dateLocale:fo.ja},ts={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"}},Tt={language:"es",strings:ts,dateLocale:uo.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"},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"}},kt={language:"pt",strings:ns,dateLocale:_o.pt},os={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"}},Mt={language:"fr",strings:os,dateLocale:mo.fr},rs={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:"प्रतिक्रिया हटाएं"}},Lt={language:"hi",strings:rs,dateLocale:go.hi},ss={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"}},Rt={language:"it",strings:ss,dateLocale:ho.it},as={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"}},Pt={language:"de",strings:as,dateLocale:lo.de},is={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"}},Dt={language:"tr",strings:is,dateLocale:yo.tr},ie=e=>({conversation:e.conversation,conversation_list:e.conversation_list,date_format:e.date_format,csat:e.csat,form:e.form,common:e.common,feedback:e.feedback}),dn=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Ye},Ye="en",Ut={borderColor:"red",borderWidth:p.StyleSheet.hairlineWidth},y=({debug:e=!1,style:t,children:n,...o})=>s.createElement(p.View,{style:[t,o,e&&Ut],...o},n);y.Animated=({debug:e=!1,style:t,children:n,...o})=>s.createElement(p.Animated.View,{style:[t,o,e&&Ut],...o},n);const{Provider:ls,useContext:J}=X("MessengerSession"),cs=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof Ge||t.userSessionInfo instanceof Ft))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return s.createElement(Ar,{ref:n,...t},o=>s.createElement(us,{...o},e))}),us=({children:e,...t})=>{const{userSession:n,aiAgentInfo:o,launcherInfo:r}=t;return s.createElement(ls,{value:{...t,userSession:n,aiAgentInfo:o,launcherInfo:r}},e)},He=50,{Provider:ds,useContext:ms}=X("ConversationScroll"),gs=({children:e})=>{var ne;const{config:t}=j(),n=((ne=t==null?void 0:t.conversation)==null?void 0:ne.scrollMode)??"auto",o=d.useRef(null),r=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),a=d.useRef(0),[i,l]=d.useState(0),[c,u]=d.useState(0),[g,h]=d.useState(!1),[m,_]=d.useState(!1),b=d.useMemo(()=>m?"auto":n,[m,n]),S=d.useCallback(()=>{const{shouldUpdate:q,shouldRecalc:w,contentHeight:U,contentSnapshotHeight:oe,viewport:le}=r.current;q&&oe<U&&l(L=>{r.current.shouldUpdate=!1;const N=U-L-oe,V=Math.max(0,le-N);return L===0||V<L||w?(r.current.shouldRecalc=!1,V):L})},[]),f=d.useCallback(q=>{r.current.viewport=q.nativeEvent.layout.height},[]),E=d.useCallback((q,w)=>{r.current.contentHeight=w;const U=r.current.viewport;h(w>U),S()},[S]),C=d.useCallback(q=>{const w=q.nativeEvent.contentOffset.y;a.current=w,u(w)},[]),v=d.useMemo(()=>({minIndexForVisible:0,autoscrollToTopThreshold:He}),[]),A=d.useCallback((q=!0)=>{var w;(w=o.current)==null||w.scrollToOffset({offset:0,animated:q})},[]),I=d.useCallback((q,w=!0)=>{var U;(U=o.current)==null||U.scrollToIndex({index:q,animated:w,viewPosition:1})},[]),x=d.useCallback(()=>{b==="fixed"&&(r.current.contentSnapshotHeight=r.current.contentHeight-i,r.current.shouldUpdate=!0,r.current.shouldRecalc=!0)},[b,i]),O=d.useCallback(()=>{b==="fixed"?I(0):A()},[b,A,I]),B=d.useCallback(()=>{b==="fixed"?r.current.shouldUpdate=!0:a.current<=He&&A()},[b,A]),M=d.useCallback(q=>{_(q)},[]),H=c<=He,G=g&&!H,Z=d.useCallback(()=>a.current>He,[]);return s.createElement(ds,{value:{ref:o,state:{bottomSpace:i,isAwayFromBottom:G,shouldCountNewMessages:Z},props:{maintainVisibleContentPosition:v,onLayout:f,onContentSizeChange:E,onScroll:C},actions:{scrollToBottom:A,scrollToIndex:I,onBeforeMessageSend:x,onAfterMessageSend:O,onStreamingUpdate:B,onConversationClosed:M}}},e)};function Pn(e){return new Promise((t,n)=>{p.Image.getSize(e,(o,r)=>{t({width:String(o),height:String(r)})},o=>{n(o)})})}async function hs(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 Pn(n.uri);return new Ce.MessageMetaArray({key:Sn,value:[o,r]})}catch{return}}}function fs(e,t){let n=0,o=0;return se(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),se(t)&&t.sendingStatus!=="succeeded"&&(o=Number.MAX_SAFE_INTEGER),t.createdAt+o-(e.createdAt+n)}const{Provider:ps,Context:_s,useContext:te}=X("Conversation"),Dn=e=>s.createElement(gs,null,s.createElement(ys,{...e})),ys=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:o,shouldMarkAsRead:r,children:a})=>{const i=ms(),{activeChannel:l,refreshActiveChannel:c,sdkUser:u,authenticate:g}=J();d.useEffect(()=>{u||g()},[]);const h=d.useCallback(async S=>{i.actions.onBeforeMessageSend();const f=await hs(S);return{...S,metaArrays:f?[f]:void 0}},[i.actions.onBeforeMessageSend]),m=d.useCallback(()=>{i.actions.onAfterMessageSend()},[i.actions.onAfterMessageSend]),_=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]),b=e??(l==null?void 0:l.url);return s.createElement(Dr,{key:b,channelUrl:b,onBeforeSendMessage:h,onAfterSendMessage:m,onMessagesUpdated:i.actions.onStreamingUpdate,onMessagesReceived:i.actions.onStreamingUpdate,onChannelDeleted:_,onConversationClosedStatusChanged:i.actions.onConversationClosed,sortComparator:fs,shouldMarkAsRead:r,shouldCountNewMessages:i.state.shouldCountNewMessages},S=>s.createElement(ps,{value:{...S,scrollSource:i,onClose:n,onNavigateToConversationList:o,updateActiveChannel:_}},a))},it=ie(Pt.strings),bs={...it,conversation:{...it.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:{...it.conversation_list}},Es={language:Pt.language,dateLocale:Pt.dateLocale,strings:bs},lt=ie(wt.strings),vs={...lt,conversation:{...lt.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:{...lt.conversation_list}},Cs={language:wt.language,dateLocale:wt.dateLocale,strings:vs},ct=ie(Tt.strings),Ss={...ct,conversation:{...ct.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:{...ct.conversation_list}},As={language:Tt.language,dateLocale:Tt.dateLocale,strings:Ss},ut=ie(Mt.strings),ws={...ut,conversation:{...ut.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:{...ut.conversation_list}},xs={language:Mt.language,dateLocale:Mt.dateLocale,strings:ws},dt=ie(Lt.strings),Is={...dt,conversation:{...dt.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:{...dt.conversation_list}},Ts={language:Lt.language,dateLocale:Lt.dateLocale,strings:Is},mt=ie(Rt.strings),ks={...mt,conversation:{...mt.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:{...mt.conversation_list}},Ms={language:Rt.language,dateLocale:Rt.dateLocale,strings:ks},gt=ie(It.strings),Ls={...gt,conversation:{...gt.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:{...gt.conversation_list}},Rs={language:It.language,dateLocale:It.dateLocale,strings:Ls},ht=ie(xt.strings),Ps={...ht,conversation:{...ht.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:{...ht.conversation_list}},Ds={language:xt.language,dateLocale:xt.dateLocale,strings:Ps},ft=ie(kt.strings),Os={...ft,conversation:{...ft.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:{...ft.conversation_list}},Bs={language:kt.language,dateLocale:kt.dateLocale,strings:Os},pt=ie(Dt.strings),Ns={...pt,conversation:{...pt.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:{...pt.conversation_list}},Hs={language:Dt.language,dateLocale:Dt.dateLocale,strings:Ns},mn=new Map([["en",Cs],["ko",Ds],["ja",Rs],["es",As],["pt",Bs],["fr",xs],["hi",Ts],["it",Ms],["de",Es],["tr",Hs]]),gn=e=>mn.get(e)??mn.get(Ye),zs=(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:Fs,useContext:F}=X("Localization"),$s=({language:e=Ye,logger:t,strings:n,children:o})=>{const[r,a]=d.useState(()=>{const i=dn(e);return gn(i)});return d.useEffect(()=>{var l;const i=dn(e);if(r.language!==i){const c=gn(i);a(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:r.language,to:c.language})}},[e,t]),s.createElement(Fs,{value:{language:r.language,strings:zs(r.strings,n),dateLocale:r.dateLocale,format:(i,l,c)=>ve.format(i,l,{locale:r.dateLocale,...c})}},o)},{Provider:Us,useContext:Xe}=X("Modal");function On({children:e}){const[t,n]=d.useState([]),[o,r]=d.useState(null),a=d.useRef(0);d.useEffect(()=>{if(!o&&t.length>0){const[u,...g]=t;u&&(r(u),n(g))}},[o,t]);const i=d.useCallback(u=>new Promise(g=>{const m={id:`modal-${++a.current}`,render:u,resolve:g};n(_=>[..._,m])}),[]),l=d.useCallback((u,g)=>{r(h=>(h==null?void 0:h.id)===u?(h.resolve(g),null):h)},[]),c={openModal:i,currentModal:o};return s.createElement(Us,{value:c},e,o&&s.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:qs,useContext:$}=X("MessengerTheme"),Vs=({children:e,...t})=>s.createElement(dr,{...t,appearance:{theme:t.mode??"light"}},n=>{const o=Ws(n.theme);return s.createElement(qs,{value:{...n,themedColor:o}},e)});function Ws(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 R={create:e=>{const t=new WeakMap,n=o=>{const r=t.get(o.theme);if(r)return r;const a=e(o),i={},l={};for(const g in a)typeof a[g]=="function"?l[g]=a[g]:i[g]=a[g];const u={...p.StyleSheet.create(i),...l};return t.set(o.theme,u),u};return{use:()=>{const o=$(),r=_e.useSafeAreaInsets();return n({...o,edgeInsets:r,select:a=>a[o.theme.selectedTheme]})}}}},Gs={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},xe=(e,t=p.I18nManager.isRTL?"rtl":"ltr")=>{const n=_e.useSafeAreaInsets();return e.reduce((o,r)=>{const a=Gs[t][r];return o[a]=n[r],o},{})},js={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")},Ks={send:!0,chat:!0,message:!0,good:!0,bad:!0,"good-filled":!0,"bad-filled":!0},D=({customSource:e,type:t,color:n,size:o=24,style:r})=>{const a=Ys.use(),i=p.I18nManager.isRTL&&!!Ks[t];return s.createElement(y,{alignItems:"center",justifyContent:"center"},s.createElement(p.Image,{resizeMode:"contain",source:e??js[t],style:[a.icon({color:n,size:o,mirror:i}),r]}))},Ys=R.create(({theme:e,themedColor:t})=>({icon:n=>({tintColor:typeof n.color=="function"?n.color(t):n.color??e.colors.base.primary,width:n.size,height:n.size,transform:n.mirror?[{scaleX:-1}]:void 0})})),qt=(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:Js(r)},Bn=e=>qt("start",e),Xs=e=>qt("end",e),Zs=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"&&Bn(t)?o?"right":p.I18nManager.doLeftAndRightSwapInRTL?"left":"right":n==null?void 0:n.textAlign},Js=e=>{for(const[t,n]of Qs)if(e>=t&&e<=n)return!0;return!1},Qs=[[1424,1535],[1536,1791],[1872,1919],[2208,2303],[64285,64335],[65136,65279],[126464,126719]],Vt={isStartsWithRTL:Bn,isEndsWithRTL:Xs,isRTLString:qt,useTextAlign:Zs},T=({variant:e="body1",color:t,style:n,...o})=>{const{theme:r,themedColor:a}=$(),i=d.useMemo(()=>{if(typeof t=="function")return t(a);if(typeof t=="string")return t;const u=p.StyleSheet.flatten(n);return u&&u.color?u.color:t??a.textHighEmphasis},[n,t,a.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,a.textHighEmphasis]),c=Vt.useTextAlign({text:o.children,style:l});return s.createElement(p.Text,{style:[l,{textAlign:c}],...o})},Nn=350,ea=({children:e,...t})=>s.createElement(p.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:Nn,...t},n=>typeof e=="function"?e(n):e),ta=({children:e,style:t,...n})=>{const[o,r]=d.useState(!1),a={pressed:o};return s.createElement(p.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:Nn,style:typeof t=="function"?t(a):t,onPressIn:()=>r(!0),onPressOut:()=>r(!1),...n},typeof e=="function"?e(a):e)},P=e=>e.activeOpacity&&e.activeOpacity<1?s.createElement(ta,{...e}):s.createElement(ea,{...e}),{Provider:na,useContext:Hn}=X("BottomSheetAnimation");function oa({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(a=>async()=>{p.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(async()=>{try{await(a==null?void 0:a())}catch{e==null||e()}})},[n]),r=d.useRef(p.PanResponder.create({onMoveShouldSetPanResponder:(a,i)=>i.dy>5,onPanResponderMove:(a,i)=>{i.dy>0&&n.setValue(i.dy)},onPanResponderRelease:(a,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 s.createElement(na,{value:{wrapWithAnimation:o,translateY:n,panHandlers:r.panHandlers}},t)}const ra=({icon:e,label:t="",destructive:n=!1,onPress:o})=>{const r=zn.use(),{themedColor:a}=$();return s.createElement(P,{onPress:o,style:r.actionItem,activeOpacity:.75},e&&s.createElement(D,{type:e,size:24,color:a.primary}),s.createElement(T,{variant:"body3",color:n?a.error:a.textHighEmphasis,numberOfLines:1},t))},sa=({onClose:e,children:t})=>{const n=zn.use(),{translateY:o,panHandlers:r,wrapWithAnimation:a}=Hn(),i=xe(["left","right"]);return s.createElement(P,{onPress:a(e),style:n.overlay},s.createElement(y.Animated,{style:[n.container,i,{transform:[{translateY:o}]}],...r},t))},Ze=ae({template:sa,components:{ActionItem:ra}}),ee=e=>{const{Template:t}=Ze.useContext();return s.createElement(oa,{onClose:e.onClose},s.createElement(t,{...e}))};ee.ActionItem=e=>{const{components:t}=Ze.useContext(),{wrapWithAnimation:n}=Hn();return s.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const zn=R.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}})),aa=({date:e=Date.now(),style:t,...n})=>{const{format:o,strings:r}=F();return s.createElement(y,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},s.createElement(T,{variant:"caption4",color:a=>a.textMidEmphasis},o(e,r.date_format.date_separator)))},ia=({style:e,label:t,accessibilityLabel:n,onPress:o})=>{const r=la.use(),{theme:a}=$();return s.createElement(P,{style:[r.button,e],onPress:o,accessibilityLabel:n,accessibilityRole:"button"},s.createElement(y,{flexDirection:"row",alignItems:"center",gap:4},s.createElement(T,{variant:"button",color:a.colors.base.primaryContrastContent},t),s.createElement(D,{size:16,type:"chevron-down",color:a.colors.base.primaryContrastContent})))},la=R.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}]}})),Wt=({iconSize:e=64,icon:t,style:n,label:o,children:r})=>{const{themedColor:a}=$();return s.createElement(y,{style:[Fn.body,n]},t&&s.createElement(D,{type:t,size:e,color:a.textLowEmphasis}),o&&s.createElement(T,{variant:"body1",color:a.textMidEmphasis},o),r)},ca=({children:e})=>{const{theme:t}=$();return s.createElement(y,{backgroundColor:t.colors.base.background,style:Fn.container},e)},Fn=p.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),ua=({label:e,icon:t="error",action:n,...o})=>{const{strings:r}=F();return s.createElement(Wt,{icon:t,label:e??r.common.placeholder_something_went_wrong,...o},n&&s.createElement(da,{onPress:n.onPress,label:n.label??r.common.placeholder_something_went_wrong_retry_label}))},da=({label:e,onPress:t})=>{const{themedColor:n}=$();return s.createElement(P,{onPress:t},s.createElement(y,{style:ma.button},s.createElement(D,{type:"refresh",size:20}),s.createElement(T,{variant:"button",color:n.primary},e)))},ma=p.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),ga=({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 s.createElement(y.Animated,{style:[{transform:[{rotate:o}]},t]},s.createElement(D,{type:"spinner",size:e}))},ha=({label:e,icon:t="chat",...n})=>{const{strings:o}=F();return s.createElement(Wt,{icon:t,label:e??o.common.placeholder_no_conversations,...n})},fa=({label:e,icon:t="message",...n})=>{const{strings:o}=F();return s.createElement(Wt,{icon:t,label:e??o.common.placeholder_no_messages,...n})},pa=e=>{const{components:t}=Gt.useContext(),n=e.type==="loading"?s.createElement(t.Loading,{...e}):e.type==="error"?s.createElement(t.Error,{...e}):e.type==="noChannels"?s.createElement(t.NoChannels,{...e}):e.type==="noMessages"?s.createElement(t.NoMessages,{...e}):null;return n&&s.createElement(ca,null,n)},Gt=ae({template:pa,components:{Loading:ga,Error:ua,NoChannels:ha,NoMessages:fa}}),Se=e=>{const{Template:t}=Gt.useContext();return s.createElement(t,{...e})},_a=({style:e,onPress:t})=>{const n=ya.use(),{theme:o}=$();return s.createElement(P,{style:[n.button,e],onPress:t},s.createElement(y,{alignItems:"center",justifyContent:"center"},s.createElement(D,{size:24,type:"chevron-down",color:o.colors.base.primary})))},ya=R.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}]}})),ba=({loading:e,error:t,data:n,LoadingComponent:o,ErrorComponent:r,EmptyComponent:a,...i},l)=>t?r:e?o:!n||n.length===0?a:s.createElement(p.FlatList,{ref:l,data:n,...i}),$n=d.memo(d.forwardRef(ba)),jt=({name:e,type:t="FILE",onPress:n})=>{const o=Ea.use();return s.createElement(P,{onPress:n,style:o.container,activeOpacity:.75},s.createElement(y,{style:o.iconWrapper},s.createElement(D,{type:"file-document",size:24,color:o.icon.tintColor})),s.createElement(y,{flex:1,flexDirection:"column",gap:4,style:o.info},s.createElement(T,{variant:"button",color:r=>r.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),s.createElement(T,{variant:"caption3",color:r=>r.textMidEmphasis},t)))},Ea=R.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}})),va=({file:e,children:t,onClickFile:n=({url:o})=>p.Linking.openURL(o)})=>s.createElement(y,{gap:k.GAP_GROUPED,width:k.BODY_MAX_WIDTH,maxWidth:k.BODY_MAX_WIDTH},s.createElement(jt,{name:e.name,type:Ht(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),we=({style:e,...t})=>s.createElement(p.Image,{style:[e,t],...t}),Ca=({file:e,onClickMedia:t=({url:o})=>p.Linking.openURL(o),children:n})=>{const o=Sa.use();return s.createElement(y,{gap:k.GAP_GROUPED},s.createElement(P,{style:o.mediaContainer,onPress:()=>t==null?void 0:t(e)},s.createElement(we,{source:{uri:e.url},style:o.media,resizeMode:"cover"})),n)},Sa=R.create(({select:e,theme:t})=>({mediaContainer:{width:k.BODY_MAX_WIDTH,height:160,borderRadius:12,overflow:"hidden",backgroundColor:e({light:t.palette.background100,dark:t.palette.background400})},media:{width:"100%",height:"100%"}})),Un=({code:e,language:t})=>{const[n,o]=d.useState(!1),r=async()=>{wo.default.setString(e),o(!0),setTimeout(()=>o(!1),2e3)};return s.createElement(y,{style:ze.container,flexDirection:"row"},s.createElement(p.Pressable,{style:ze.copyButton,onPress:r},s.createElement(D,{type:n?"done":"copy",size:16,color:"#fff"})),s.createElement(y,null,s.createElement(xo.default,{hljsStyle:vo.atomOneDarkReasonable,scrollViewProps:{contentContainerStyle:ze.codeContainer,bounces:!1},textStyle:ze.codeText,language:t},e)))},ze=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}}),qn=d.memo(({src:e,onPress:t})=>{const[n,o]=d.useState("1/1"),[r,a]=d.useState(!1),i=Aa.use();return d.useLayoutEffect(()=>{e&&Pn(e).then(({width:l,height:c})=>o(`${l}/${c}`))},[e]),s.createElement(p.Pressable,{style:{marginTop:8},onPress:t},s.createElement(y,{style:[i.container,{aspectRatio:n}]},r?s.createElement(D,{size:28,type:"thumbnail-none",color:l=>l.textHighEmphasisInverse}):s.createElement(p.Image,{source:{uri:e},style:p.StyleSheet.absoluteFillObject,onError:()=>a(!0)})))}),Aa=R.create(({themedColor:e})=>({container:{width:"100%",backgroundColor:e.textDisabled,borderRadius:4,overflow:"hidden",justifyContent:"center",alignItems:"center"}}));qn.displayName="MarkdownImage";const ke=e=>d.isValidElement(e)&&"children"in e.props,Ot=(e=.75)=>`rgba(0, 0, 0, ${e})`,wa=({children:e})=>{var i;const t=p.useWindowDimensions(),n=Ot(.3),o=d.useMemo(()=>{try{if(!Array.isArray(e)||e.length<2)return null;const l=e[0],c=e[1],u=ke(c)?c.props.children:void 0;if(!u||!Array.isArray(u)||u.length===0)return null;const g=u,h=g[0],m=ke(h)?h.props.children:void 0;if(!m||!Array.isArray(m)||m.length===0)return null;const _=g.length,b=m.length,S=Array(b).fill(null).map(()=>[]);for(let v=0;v<_;v++){const A=g[v],I=ke(A)?A.props.children:void 0;if(!(!I||!Array.isArray(I)))for(let x=0;x<b;x++){const O=S[x];O&&x<I.length&&(O[v]=I[x])}}const f=ke(l)?l.props.children:void 0,E=Array.isArray(f)?f[0]:void 0,C=ke(E)?E.props.children:void 0;if(C&&Array.isArray(C))for(let v=0;v<b;v++){const A=S[v];A&&v<C.length&&A.unshift(C[v])}return S}catch{return null}},[e]),[r,a]=d.useState(Array(((i=o==null?void 0:o[0])==null?void 0:i.length)??0).fill(0));return o?s.createElement(p.View,{style:{flexDirection:"row"}},o.map((l,c)=>{const u=c===0,g=c===o.length-1;return s.createElement(p.View,{key:c,style:{flexDirection:"column",borderStartWidth:1,borderEndWidth:g?1:0,borderTopWidth:1,borderBottomWidth:1,borderColor:n,borderTopStartRadius:u?6:0,borderBottomStartRadius:u?6:0,borderTopEndRadius:g?6:0,borderBottomEndRadius:g?6:0}},l.map((h,m)=>{const _=m===0,b=m===l.length-1;return s.createElement(p.View,{key:m,onLayout:({nativeEvent:{layout:S}})=>{const f=S.height;(r[m]??0)<f&&(r[m]=f,a([...r]))},style:{borderBottomWidth:b?0:1,borderColor:n,backgroundColor:_?Ot(.15):"transparent",maxWidth:t.width*2/3,minHeight:(r[m]??0)>0?r[m]:void 0,padding:8}},h)}))})):s.createElement(p.View,null,e)},Kt=d.memo(({children:e,textStyle:t,linkStyle:n,onPressImage:o})=>{const{themedColor:r}=$(),a=p.StyleSheet.compose({fontSize:14,color:r.textHighEmphasis,textAlign:"left"},t),i=p.StyleSheet.flatten(a),l=i.fontSize||14,c=i.lineHeight||l*1.286,u=Ot(.3),g={color:i.color,textAlign:Vt.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:m=>{var b,S;const _=((b=m.attributes)==null?void 0:b.src)||((S=m.attributes)==null?void 0:S.href);return _?s.createElement(qn,{key:m.key,src:_,onPress:()=>o==null?void 0:o(_)}):null},code_block:m=>s.createElement(Un,{code:m.content,language:"text"}),table:(m,_)=>s.createElement(p.View,{key:m.key,style:{marginTop:8}},s.createElement(p.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},s.createElement(wa,null,_)))}),[o]);return s.createElement(y,{flexDirection:"row",marginTop:-8},s.createElement(Io.default,{style:{body:{...g,width:e.length>50?"100%":void 0,marginBottom:0},paragraph:{...g,marginTop:8,marginBottom:0},heading1:{...g,marginTop:8,marginBottom:0,fontSize:l*1.429,lineHeight:l*1.429*1.4,fontWeight:"700"},heading2:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.286,lineHeight:l*1.286*1.333},heading3:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading4:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading5:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading6:{...g,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},link:p.StyleSheet.flatten(p.StyleSheet.compose({...g,fontWeight:"700",textDecorationLine:"underline"},n)),code_inline:{...g,fontSize:l*.929,lineHeight:l*.929*1.538,fontWeight:"600",backgroundColor:u},code_block:{...g,borderWidth:0,backgroundColor:u,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538},fence:{...g,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:{...g,marginTop:4,marginBottom:0},blockquote:{...g,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:{...g,padding:4,fontSize:l,lineHeight:l*1.143,fontWeight:"700"},td:{...g,padding:2,fontSize:l,lineHeight:l*1.429},image:{maxHeight:300,maxWidth:"100%"}},rules:h},$o(e)))});Kt.displayName="MarkdownText";const hn=({maxBodyWidth:e,customStyle:t,message:n,children:o})=>{const r=xa.use(),a=e??k.BODY_MAX_WIDTH,i=d.useMemo(()=>No(n),[n]),l=d.useCallback(c=>p.Linking.openURL(c),[]);return i.length===0&&!o?null:s.createElement(y,{alignSelf:"flex-start",maxWidth:a,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"?s.createElement(y,{key:u,paddingHorizontal:12},s.createElement(Kt,{onPressImage:l,textStyle:r.text},c.value)):c.type==="code"?s.createElement(Un,{key:u,code:c.value,language:c.language}):null),o)},xa=R.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),Ia=e=>{const{strings:t}=F(),n=()=>{const o=wn(e)?s.createElement(hn,{...e}):null;return e.messageType==="user"?o:e.messageType==="file"?e.file.type.startsWith("image")?s.createElement(Ca,{...e},o):s.createElement(va,{...e},o):s.createElement(hn,{...e,message:t.conversation.unknown_message_type})};return s.createElement(y,{style:e.containerStyle},n())};function Vn({id:e,src:t,size:n=56,onClick:o,style:r}){const a=Ta.use(),i=s.createElement(p.View,{style:[a.container(n),r],testID:e},t?s.createElement(p.Image,{source:{uri:t},style:a.image}):s.createElement(D,{type:"user",size:n}));return o?s.createElement(P,{onPress:o,activeOpacity:.75},i):i}const Ta=R.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"}})),ka=({sender:e,isBotMessage:t})=>{const n=Ma.use();return t&&!e.profileUrl?s.createElement(y,{style:n.botContainer},s.createElement(D,{type:"delight",size:k.AVATAR_SIZE-8})):s.createElement(Vn,{src:e.profileUrl,size:k.AVATAR_SIZE})},Ma=R.create(({theme:e})=>({botContainer:{width:k.AVATAR_SIZE,height:k.AVATAR_SIZE,borderRadius:k.AVATAR_SIZE/2,padding:4,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary}})),La=({sender:e})=>s.createElement(y,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7,alignItems:"flex-start"},s.createElement(T,{variant:"caption1",color:t=>t.textMidEmphasis,numberOfLines:1},e.nickname)),Ra=({createdAt:e,containerStyle:t})=>{const{strings:n,format:o}=F();return e?s.createElement(y,{alignItems:"flex-start",style:t},s.createElement(T,{variant:"caption4",color:r=>r.textLowEmphasis},o(e,n.date_format.message_timestamp))):null},Pa=({customStyle:e,containerStyle:t})=>{const{theme:n}=$(),o=d.useRef(new p.Animated.Value(0)).current,r=Da.map(([a,i,l])=>[o.interpolate({inputRange:a,outputRange:i,extrapolate:"clamp"}),o.interpolate({inputRange:a,outputRange:l,extrapolate:"clamp"})]);return d.useEffect(()=>{const a=p.Animated.loop(p.Animated.timing(o,{toValue:1.4,duration:1400,easing:p.Easing.linear,useNativeDriver:!0}));return a.start(),()=>a.reset()},[]),s.createElement(y,{style:t},s.createElement(y,{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(([a,i],l)=>s.createElement(y.Animated,{key:l,style:[Oa.dot,{marginEnd:l===r.length-1?0:6,opacity:i,transform:[{scale:a}],backgroundColor:(e==null?void 0:e.bubbleContentColor)??n.colors.messageIncoming.text}]}))))},Da=[[[.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]]],Oa=p.StyleSheet.create({dot:{width:8,height:8,borderRadius:4}}),Ba=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>p.Linking.openURL(n)})=>{const n=Na.use(),o=e==null?void 0:e.cta_button;return o?s.createElement(P,{onPress:()=>t(o),activeOpacity:.75,style:n.button},s.createElement(T,{variant:"button",color:r=>r.textHighEmphasis,numberOfLines:1},o.label)):null},Na=R.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})}})),Ha=({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:s.createElement(y,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},s.createElement(T,{variant:"caption1",color:o.colors.messageIncoming.text,style:fn.sourceLabel},n.conversation.citation_title),s.createElement(y,{gap:8},r.map(a=>s.createElement(P,{key:a.embedding_id,onPress:()=>t(a),activeOpacity:.5},s.createElement(y,{flexDirection:"row",alignItems:"center",gap:4},s.createElement(D,{type:"source",size:16,color:o.colors.messageIncoming.text}),s.createElement(y,{flex:1},s.createElement(T,{variant:"body3",color:o.colors.messageIncoming.text,numberOfLines:1,style:fn.citationText},a.title)))))))},fn=p.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),za=e=>s.createElement(s.Fragment,null),Bt=e=>`${e}-filled`,Fa=e=>e==="good"?Y.AIAgentMessageFeedbackRating.GOOD:Y.AIAgentMessageFeedbackRating.BAD,pn=({onClose:e,isEdit:t,initialRating:n,initialComment:o="",isCommentEnabled:r=!1})=>{const{strings:a}=F(),{themedColor:i,theme:l}=$(),c=$a.use(),[u,g]=d.useState(o),[h,m]=d.useState(n),_=()=>{h&&e({rating:h,comment:u.trim()||void 0})},b=()=>{e()},S={good:i.secondary,bad:i.error};return s.createElement(p.KeyboardAvoidingView,{style:{flex:1},behavior:"padding"},s.createElement(P,{onPress:b,style:c.overlay},s.createElement(y,{width:280,backgroundColor:l.colors.base.modalContentBackground,borderRadius:12,overflow:"hidden",onStartShouldSetResponder:()=>!0},s.createElement(y,{padding:24},s.createElement(T,{variant:"h2",color:i.textHighEmphasis},a.feedback.title)),s.createElement(y,{paddingHorizontal:24,gap:24},s.createElement(y,{flexDirection:"row",gap:4},["good","bad"].map(f=>{const E=h===f,C=f==="good"?a.feedback.good:a.feedback.bad;return s.createElement(P,{key:f,onPress:()=>m(f),activeOpacity:.6,style:c.ratingButton(E)},s.createElement(D,{type:E?Bt(f):f,size:24,color:E?S[f]:i.textLowEmphasis}),s.createElement(T,{variant:"caption1",color:E?S[f]:i.textLowEmphasis},C))})),r&&s.createElement(y,{gap:6},s.createElement(T,{variant:"caption3",color:i.textHighEmphasis},a.feedback.comment_label),s.createElement(p.TextInput,{value:u,onChangeText:f=>g(f),placeholder:a.feedback.comment_placeholder,placeholderTextColor:i.textLowEmphasis,multiline:!0,maxLength:100,style:c.commentInput}))),s.createElement(y,{paddingHorizontal:24,paddingVertical:16,flexDirection:"row",justifyContent:"flex-end",gap:4},s.createElement(P,{onPress:b,activeOpacity:.6,style:c.cancelButton},s.createElement(T,{variant:"button",color:i.textHighEmphasis},a.feedback.cancel)),s.createElement(P,{onPress:_,disabled:!h,activeOpacity:.6,style:c.submitButton(!h)},s.createElement(T,{variant:"button",color:l.colors.base.primaryContrastContent},t?a.feedback.save:a.feedback.submit))))))},$a=R.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})})),Ua=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:o,isFeedbackCommentEnabled:r,extendedMessagePayload:a,onFeedbackUpdate:i,containerStyle:l})=>{const{strings:c}=F(),{themedColor:u}=$(),{openModal:g}=Xe(),h=qa.use(),m=a==null?void 0:a.feedback,_=(m==null?void 0:m.rating)??"none";if(_!=="none"?!1:!!(n||!e||!o||(a==null?void 0:a.bot_message_type)!=="generated"||t))return null;const S={good:u.secondary,bad:u.error},f=async v=>{const A=await g(I=>s.createElement(pn,{onClose:I,isEdit:!1,initialRating:v,initialComment:"",isCommentEnabled:r}));A&&(i==null||i(A))},E=async()=>{const v=await g(A=>s.createElement(ee,{onClose:()=>A()},s.createElement(ee.ActionItem,{onPress:()=>A("edit"),label:c.feedback.edit}),s.createElement(ee.ActionItem,{onPress:()=>A("remove"),label:c.feedback.remove,destructive:!0})));if(v==="edit"){const A=await g(I=>s.createElement(pn,{onClose:I,isEdit:!0,initialRating:m==null?void 0:m.rating,initialComment:m==null?void 0:m.comment,isCommentEnabled:r}));A&&(i==null||i(A))}else v==="remove"&&(i==null||i(null))},C=()=>t&&_!=="none"?s.createElement(y,{flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:k.BODY_MAX_WIDTH},s.createElement(y,{padding:2,flexShrink:0,alignItems:"center"},s.createElement(D,{type:Bt(_),size:12,color:S[_]})),(m==null?void 0:m.comment)&&s.createElement(T,{variant:"caption2",style:h.commentText},m.comment)):s.createElement(y,{gap:4,maxWidth:k.BODY_MAX_WIDTH},s.createElement(y,{flexDirection:"row",gap:2},["good","bad"].map(v=>{const A=_===v;return s.createElement(P,{key:v,onPress:()=>{_==="none"?f(v):E()},activeOpacity:.6,style:h.feedbackButton(A)},s.createElement(D,{type:A?Bt(v):v,size:14,color:A?S[v]:u.textMidEmphasis}))})),_!=="none"&&(m==null?void 0:m.comment)&&s.createElement(T,{variant:"caption2",style:h.commentText},m.comment));return s.createElement(y,{style:l},C())},qa=R.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})}})),Va=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},Wa=e=>null,Wn=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:o,...r})=>s.createElement(p.ScrollView,{style:[t,r,e&&Ut],showsHorizontalScrollIndicator:n,...r},o),Ga=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const o=ja.use(),[r,a]=d.useState(!1),i=(e==null?void 0:e.suggested_replies)??[];if(i.length===0||r)return null;const l=n==="vertical",c=g=>{t==null||t({reply:g}),a(!0)},u=()=>i.map((g,h)=>s.createElement(P,{key:h,style:o.itemContainer,onPress:()=>c(g)},s.createElement(T,{variant:"body3",color:m=>m.primary},g)));return l?s.createElement(y,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:k.HORIZONTAL_PADDING},u()):s.createElement(Wn,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:o.horizontalContainer},u())},ja=R.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:k.HORIZONTAL_PADDING,paddingVertical:16}})),Ka=e=>{var f,E,C,v,A,I,x;const{components:t}=Je.useContext(),{streamText:n,isAnimating:o}=Zr({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),r={...e,message:n,extendedMessagePayload:o?{}:e.extendedMessagePayload},a=!!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=!!((v=r.extendedMessagePayload)!=null&&v.cta_button),g=!!((A=r.extendedMessagePayload)!=null&&A.citations)&&r.extendedMessagePayload.citations.length>0,h=!!r.createdAt,m=r.groupType==="top"||r.groupType==="single",_=r.groupType==="bottom"||r.groupType==="single",b=i?k.AVATAR_SIZE:0,S=Ya.use();return s.createElement(y,{marginBottom:a?0:zt(r.groupType)},m&&s.createElement(y,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:k.HORIZONTAL_PADDING},i&&s.createElement(t.SenderAvatar,{...r}),s.createElement(t.SenderName,{...r})),s.createElement(y,{gap:k.GAP_GROUPED},a?s.createElement(t.TypingIndicator,{...r,containerStyle:S.middleArea(b)}):s.createElement(t.MessageBody,{...r,containerStyle:S.middleArea(b)},u&&s.createElement(y,{marginTop:12,marginHorizontal:12},s.createElement(t.CTAButton,{...r})),g&&s.createElement(t.Citation,{...r})),c&&s.createElement(t.MessageTemplate,{...r,messageTemplateErrorFallback:r.messageTemplateErrorFallback??s.createElement(t.MessageBody,{...r,messageType:"user",message:((x=(I=r.extendedMessagePayload)==null?void 0:I.message_template)==null?void 0:x.fallback_message)??"Cannot read this template.",containerStyle:S.middleArea(b)}),messageTemplateLoadingFallback:r.messageTemplateLoadingFallback??s.createElement(t.TypingIndicator,{...r,containerStyle:S.middleArea(b)})}),s.createElement(t.CustomMessageTemplate,{...r}),l&&s.createElement(t.Form,{...r,containerStyle:S.middleArea(b)})),_&&h&&s.createElement(t.SentTime,{...r,containerStyle:S.bottomArea(b)}),s.createElement(d.Fragment,null,!a&&s.createElement(t.Feedback,{...r,containerStyle:S.feedbackArea(b)}),r.suggestedRepliesVisible&&s.createElement(t.SuggestedReplies,{...r})))},Je=ae({template:Ka,components:{SenderName:La,SenderAvatar:ka,SentTime:Ra,MessageBody:Ia,TypingIndicator:Pa,SuggestedReplies:Ga,MessageTemplate:Wa,CustomMessageTemplate:za,CTAButton:Ba,Citation:Ha,Form:Va,Feedback:Ua}}),Ya=R.create(()=>({middleArea:e=>({paddingStart:k.HORIZONTAL_PADDING+e,paddingEnd:k.HORIZONTAL_PADDING}),bottomArea:e=>({marginTop:k.BODY_TIME_GAP,paddingStart:k.HORIZONTAL_PADDING+e+8,paddingEnd:k.HORIZONTAL_PADDING}),feedbackArea:e=>({marginTop:8,paddingStart:k.HORIZONTAL_PADDING+e+8,paddingEnd:k.HORIZONTAL_PADDING})})),Xa=({file:e,children:t,sendingStatus:n,onClickFile:o=({url:r})=>p.Linking.openURL(r)})=>{const r=(()=>{if(!(!o||n!=="succeeded"))return()=>o(e)})();return s.createElement(y,{flexDirection:"column",alignItems:"flex-end",gap:k.GAP_GROUPED,width:k.BODY_MAX_WIDTH,maxWidth:k.BODY_MAX_WIDTH},s.createElement(jt,{name:e.name,type:Ht(e.name,e.type),onPress:r}),t)},Gn=({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 s.createElement(y.Animated,{style:{transform:[{rotate:o}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??s.createElement(D,{type:"spinner",size:e}))};function Za(e){return typeof e=="object"&&e!==null&&"uri"in e}const Ja=({file:e,metadata:t,sendingStatus:n,onClickMedia:o=({url:a})=>p.Linking.openURL(a),children:r})=>{const a=Qa.use(),{aspectRatio:i,localFile:l}=t,[c]=d.useState(()=>Za(l)?l.uri:e.url),[u,g]=d.useState(!1),h=(()=>{if(!(!o||n!=="succeeded"))return()=>o(e)})();return s.createElement(y,{flexDirection:"column",alignItems:"flex-end",gap:k.GAP_GROUPED},s.createElement(P,{onPress:h,style:[a.imageContainer,{aspectRatio:i}],activeOpacity:.75},!u&&s.createElement(y,{alignItems:"center",justifyContent:"center"},s.createElement(Gn,{size:26},s.createElement(D,{type:"spinner",color:m=>m.textLowEmphasis,size:26}))),s.createElement(we,{source:{uri:c},style:[a.image,{opacity:u?1:0}],resizeMode:"cover",onLoad:()=>g(!0)})),r)},Qa=R.create(({themedColor:e})=>({imageContainer:{width:k.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}})),_n=e=>{var n,o;const t=ei.use();return s.createElement(y,{style:[t.container({maxWidth:e.maxBodyWidth??k.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},s.createElement(T,{variant:"body3",style:[t.text,((o=e.customStyle)==null?void 0:o.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},ei=R.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}})),ti=e=>{const{strings:t}=F(),n=()=>{const o=wn(e)?s.createElement(_n,{...e}):null;return e.messageType==="user"?o:e.messageType==="file"?e.file.type.startsWith("image")?s.createElement(Ja,{...e},o):s.createElement(Xa,{...e},o):s.createElement(_n,{...e,message:t.unknown_message_type})};return s.createElement(P,{onPress:e.sendingStatus==="failed"?e.onClickFailedMessage:void 0,activeOpacity:.75},s.createElement(y,{style:e.containerStyle},n()))},ni=({sendingStatus:e,containerStyle:t})=>{const{themedColor:n}=$(),o=()=>{switch(e){case"pending":return s.createElement(y,{marginBottom:2},s.createElement(Gn,{size:16},s.createElement(D,{type:"spinner",color:n.primary,size:16})));case"failed":return s.createElement(y,{marginBottom:2},s.createElement(D,{type:"error",color:n.error,size:16}));case"scheduled":case"canceled":return null;default:return s.createElement(y,{marginBottom:2},s.createElement(D,{type:"done",color:n.secondary,size:16}))}};return s.createElement(y,{style:t},o())},oi=({createdAt:e,containerStyle:t})=>{const{format:n,strings:o}=F();return e?s.createElement(y,{style:t},s.createElement(T,{variant:"caption4",color:r=>r.textLowEmphasis},n(e,o.date_format.message_timestamp))):null},ri=e=>{const{components:t}=Qe.useContext(),n=e.sendingStatus==="succeeded",o=e.groupType==="bottom"||e.groupType==="single";return s.createElement(y,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:zt(e.groupType)},s.createElement(t.MessageBody,{...e,containerStyle:_t.middleArea}),o&&(n?s.createElement(t.SentTime,{...e,containerStyle:_t.bottomArea}):s.createElement(t.SendingStatus,{...e,containerStyle:_t.bottomArea})))},Qe=ae({template:ri,components:{SendingStatus:ni,SentTime:oi,MessageBody:ti}}),_t=p.StyleSheet.create({middleArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:k.HORIZONTAL_PADDING},bottomArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingStart:k.HORIZONTAL_PADDING,paddingEnd:k.HORIZONTAL_PADDING+8,marginTop:k.BODY_TIME_GAP}}),si=e=>e.messageType!=="admin"?null:s.createElement(T,{variant:"caption2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},ai(e.message)),ai=e=>{try{const t=[];let n=e,o=0;for(;n;){const r=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=n.match(/\*\*([^*]+)\*\*/),i=[r&&{match:r,type:"link"},a&&{match:a,type:"bold"}].filter(h=>!!h);if(!i.length){t.push(n);break}const l=i.reduce((h,m)=>m.match.index<h.match.index?m:h),{match:c,type:u}=l,g=c.index;g>0&&t.push(n.slice(0,g)),u==="link"?t.push(s.createElement(p.Text,{key:o++,onPress:()=>p.Linking.openURL((c==null?void 0:c[2])??""),style:{textDecorationLine:"underline"}},c[1])):u==="bold"&&t.push(s.createElement(p.Text,{key:o++,style:{fontWeight:"bold"}},c[1])),n=n.slice(g+c[0].length)}return t.filter(r=>r!=="")}catch{return[e]}},ii=({children:e,style:t})=>s.createElement(T,{variant:"caption4",color:n=>n.error,style:t},e),li=({children:e,style:t,required:n})=>{const{strings:o}=F();return s.createElement(T,{variant:"caption3",color:r=>r.textMidEmphasis,style:t},e,!n&&s.createElement(T,{variant:"caption3",color:r=>r.textLowEmphasis},` (${o.form.optional_label})`))},ci=({style:e})=>{const t=ui.use();return s.createElement(y,{style:[t.separator,e]})},ui=R.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),di=({value:e="",onChange:t,placeholder:n,variant:o="single-line",error:r=!1,submitted:a=!1,style:i,disabled:l=!1,maxLength:c})=>{const[u,g]=d.useState(!1),h=mi.use(),{themedColor:m}=$(),_=b=>{c&&b.length>c||t==null||t(b)};return s.createElement(p.TextInput,{value:e,onChangeText:_,placeholder:n,editable:!l&&!a,maxLength:c,multiline:o==="multi-line",style:[h.input(o,r,a,u),i],placeholderTextColor:m.textLowEmphasis,onFocus:()=>g(!0),onBlur:()=>g(!1)})},mi=R.create(({select:e,theme:t,themedColor:n})=>({input:(o,r,a,i)=>{let l,c;a?(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:a?n.textLowEmphasis:n.textHighEmphasis};return o==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),Le={Label:li,ErrorLabel:ii,TextInput:di,Separator:ci},jn=({onClick:e,checked:t,label:n,disabled:o,labelVariant:r="caption2"})=>{const{themedColor:a}=$(),i=gi.use(),l=t?a.primary:o?a.textDisabled:a.textLowEmphasis;return s.createElement(P,{disabled:o||!e,onPress:e},s.createElement(y,{style:i.container},s.createElement(y,{style:i.iconContainer},s.createElement(D,{size:20,type:t?"radio-on":"radio-off",color:l})),s.createElement(T,{variant:r,style:i.label(t,o)},n)))},gi=R.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}}})),hi=({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?s.createElement(y,{flexDirection:"column",gap:8,alignItems:"flex-start"},s.createElement(Le.Label,{required:e.cre.required},e.cre.question),s.createElement(y,{flexDirection:"column",gap:8,width:"100%"},[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(a=>s.createElement(jn,{key:a.label,checked:o===a.value,label:a.label,disabled:t,onClick:()=>r==null?void 0:r(a.value)})))):null),fi=({followUpItem:e,submitted:t,value:n="",onChange:o,hasError:r})=>{const{strings:a}=F();return s.createElement(y,{flexDirection:"column",gap:8,alignItems:"flex-start"},s.createElement(Le.Label,{required:e.required},e.question),e.response_type==="free_text"&&s.createElement(Le.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>o(i),error:r}),e.response_type==="single_choice"&&s.createElement(y,{flexDirection:"column",gap:8,width:"100%"},e.options.map(i=>s.createElement(jn,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>o==null?void 0:o(i),labelVariant:"body3"}))),r&&s.createElement(Le.ErrorLabel,null,a.form.validation_required))},pi=e=>null,_i=({csatPayload:e,submitted:t,value:n,onChange:o})=>{const r=typeof n>"u",a=Kn.use(),[i,l]=d.useState(16);return s.createElement(y,{onLayout:c=>{c.nativeEvent.layout.width<300&&l(0)},flexDirection:"column",gap:8,alignItems:"flex-start"},s.createElement(T,{variant:"caption3",color:c=>c.textMidEmphasis},e.csat_question),s.createElement(y,{style:[a.scoresContainer,{gap:i}]},e.csat_scores.map(({label:c,image_url:u},g)=>{const h=g+1,m=n===h;return s.createElement(P,{key:g,disabled:t,onPress:()=>o(h),style:a.scoreButton},s.createElement(yi,{value:h,selected:r||m,label:c,src:u}),!!c&&s.createElement(T,{style:{textAlign:"center"},variant:"caption3",color:_=>m?_.textHighEmphasis:_.textLowEmphasis,lineBreakStrategyIOS:"standard",textBreakStrategy:"simple"},c))})))},yi=({value:e,src:t,label:n,selected:o})=>{const[r,a]=d.useState(!1),i=Kn.use();return r?s.createElement(pi,{value:e,selected:o,label:n}):s.createElement(we,{source:{uri:t},style:i.emojiImage(o),onError:()=>a(!0),accessibilityLabel:n})},Kn=R.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})})),bi=({csatPayload:e})=>s.createElement(T,{style:{textAlign:"left"},variant:"button",color:t=>t.textHighEmphasis},e.title),yt=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:o,initialCsatReason:r,initialIsResolved:a})=>{const{params:i,setParams:l,error:c,setError:u,followUpItem:g,state:h,validateParams:m,itemProps:_}=jr({csatPayload:e,type:t,initialCsat:o,initialCsatReason:r,initialIsResolved:a});return s.createElement(s.Fragment,null,s.createElement(y,{flexDirection:"column",gap:12},s.createElement(bi,{..._}),t===ue.AI_AGENT_CSAT_5_WITH_CRE&&s.createElement(hi,{..._,defaultValue:a,value:i.isResolved,onChange:b=>l({isResolved:b})}),s.createElement(_i,{..._,value:i.csat,onChange:b=>l({csat:b})}),g&&s.createElement(fi,{..._,followUpItem:g,value:i.csatReason,onChange:b=>{l({csatReason:b}),u({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&s.createElement(s.Fragment,null,s.createElement(Le.Separator,null),n({state:h,params:i,validateParams:m})))},Ei=e=>{const{strings:t}=F();return Lo(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})},vi=()=>{const{strings:e}=F();return s.createElement(T,{variant:"body2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},Ci=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n}=e,{csat:o,csatReason:r,csatExpireAt:a,isResolvedWhenDeterminedByUser:i}=e,[,l]=d.useState(0),c=Ei(t==null?void 0:t.csat),u=d.useRef(!1),g=Si.use();if(!c||!c.visibility||!ue[c.type])return null;const h=c.type===ue.AI_AGENT_CSAT_5||c.type===ue.AI_AGENT_CSAT_5_WITH_CRE||c.type===ue.HELPDESK_CSAT_5?yt:()=>null;return s.createElement(y,{style:g.container},!o&&en(a)?s.createElement(vi,null):s.createElement(h,{csatPayload:c,type:c.type,initialCsat:o,initialCsatReason:r,initialIsResolved:i,renderSubmitButton:({state:m,params:_,validateParams:b})=>s.createElement(P,{activeOpacity:.75,disabled:m==="submitted",onPress:async()=>{u.current||(!en(a)&&b()?(u.current=!0,await n(_).finally(()=>{u.current=!1})):l(S=>S+1))},style:g.submitButton(m)},s.createElement(T,{variant:"button",style:g.submitButtonText(m)},m==="submitted"?c.csat_submitted_label:c.csat_submit_label))}))},Si=R.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}}})),Ai=e=>{const{components:t}=et.useContext(),n=e.messageType==="admin"?s.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?s.createElement(t.CSATMessage,{...e}):null;return s.createElement(y,{paddingHorizontal:k.HORIZONTAL_PADDING,marginBottom:zt(e.groupType)},n)},et=ae({template:Ai,components:{AdminMessage:si,CSATMessage:Ci}}),wi=({style:e,...t})=>{const{strings:n}=F();if(!$t("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 s.createElement(y,{style:[xi.container,e],...t},s.createElement(T,{variant:"caption2",color:a=>a.textLowEmphasis},n.conversation.powered_by+" "),s.createElement(P,{onPress:r},s.createElement(T,{variant:"caption2",color:a=>a.textLowEmphasis},"Sendbird")))},xi=p.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),Ii=()=>{var l;const{strings:e}=F(),{channelSource:t,scrollSource:n,updateActiveChannel:o}=te(),r=Ti.use(),a=ye(t.channel),i=d.useRef(a);return d.useEffect(()=>{const c=i.current;i.current=a,!c&&a&&n.actions.scrollToBottom()},[a,n]),!((l=t.channel)!=null&&l.isAIAgent)||!a?null:s.createElement(y,{justifyContent:"center",flexDirection:"row",style:r.wrapper},s.createElement(P,{activeOpacity:.75,onPress:()=>o(),style:r.button},s.createElement(T,{variant:"button",role:"button",color:c=>c.textHighEmphasis},e.conversation.start_new_conversation_label)))},Ti=R.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),ki=()=>{const{aiAgentInfo:e}=J(),{channelSource:t}=te(),n=Ln(t.channel);return(()=>{const o=n[0];if(!o)return null;const r=o.userId===(e==null?void 0:e.userId);return{user:r?e:o,isBot:r}})()},Mi=(e,t)=>!io.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Li=({messageStackDirection:e="top"})=>{var Z,ne,q;const{Template:t}=Je.useContext(),{Template:n}=Qe.useContext(),{Template:o}=et.useContext(),{openModal:r}=Xe(),{strings:a}=F(),{config:i,cache:l,chatSDK:c}=j(),{aiAgentInfo:u,userSession:g,connectionError:h}=J(),{messageSource:m,channelSource:_,scrollSource:b,state:{input:S,streamAnimation:f}}=te(),E=ki(),C=Ri.use(),v=xe(["left","right"]),{state:A,props:I}=b;d.useEffect(()=>{A.isAwayFromBottom||m.resetNewMessages()},[A.isAwayFromBottom]);const x=(Z=_.channel)==null?void 0:Z.conversation,O=(w,U=!1)=>{var oe;return U?u??{nickname:"",profileUrl:""}:((oe=_.channel)==null?void 0:oe.members.find(le=>le.userId===w.sender.userId))??w.sender},B=w=>{if(w.sendingStatus==="failed"&&!S.disabled)return()=>{r(U=>s.createElement(ee,{onClose:()=>U()},s.createElement(ee.ActionItem,{label:a.conversation.failed_message_resend,onPress:async()=>{m.resendMessage(w),U()}}),s.createElement(ee.ActionItem,{destructive:!0,label:a.conversation.failed_message_remove,onPress:async()=>{m.deleteMessage(w),U()}})))}},M=({item:w,index:U})=>{const oe=m.messages[U+1],le=m.messages[U-1],L=(()=>{var Zt,Jt,Qt;const V=!(u!=null&&u.isUserFeedbackEnabled&&Pe(w,u==null?void 0:u.userId)&&!qe.isWelcomeMessage(w)),re=Oo(w,oe,le,V),De={data:w.data,extendedMessagePayload:w.extendedMessagePayload,message:w.message,createdAt:w.createdAt,groupType:re};if(Oe.isAdmin(w))return Oe.isCSAT(w)?x?s.createElement(o,{...De,...x,messageType:"admin.csat",isResolvedWhenDeterminedByUser:ko(x),onSubmitCSAT:async ge=>{var he;await((he=_.channel)==null?void 0:he.submitCSAT(ge))}}):null:s.createElement(o,{...De,messageType:"admin"});if(Oe.isOutgoing(w,(g==null?void 0:g.userId)??"")){const ge={...De,sender:O(w),sendingStatus:w.sendingStatus,onClickFailedMessage:B(w)};if(w.isUserMessage())return s.createElement(n,{...ge,messageType:"user"});if(w.isFileMessage()){const[he,Te]=((Zt=w.metaArrays.find(W=>W.key===Sn))==null?void 0:Zt.value)??[];return s.createElement(n,{...ge,messageType:"file",file:w,metadata:{aspectRatio:he&&Te?`${he}/${Te}`:"1/1",localFile:(Jt=w.messageParams)==null?void 0:Jt.file}})}}if(Oe.isIncoming(w,(g==null?void 0:g.userId)??"")){const ge=w.sender.userId===(u==null?void 0:u.userId),he=U===0,Te={...De,sender:O(w,ge),suggestedRepliesVisible:he,isBotMessage:ge,isStreaming:qe.isStreaming(w),isHandedOff:Ae(_.channel),isConversationClosed:ye(_.channel),isFeedbackEnabled:u==null?void 0:u.isUserFeedbackEnabled,isFeedbackCommentEnabled:u==null?void 0:u.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:(Qt=i==null?void 0:i.conversation)==null?void 0:Qt.senderAvatarEnabled,onClickSuggestedReply:async({reply:W})=>{m.sendUserMessage({message:W})},onRequestMessageTemplate:async W=>{const{template:ce}=await c.aiAgent.getMessageTemplate(W);return l.template.set(W,ce),ce},onGetCachedMessageTemplate:W=>l.template.get(W),onHandleTemplateInternalAction:W=>{if(W.type==="internal"&&W.internalData){const{method:ce,payload:fe}=W.internalData;ce==="message.send"&&(fe!=null&&fe.message)&&m.sendUserMessage({message:fe.message})}},onFeedbackUpdate:W=>{const ce={messageId:w.messageId,channelUrl:w.channelUrl};if(!W)return c.aiAgent.deleteMessageFeedback(ce);const fe={...ce,rating:Fa(W.rating),comment:W.comment};return qe.hasFeedback(w)?c.aiAgent.updateMessageFeedback(fe):c.aiAgent.createMessageFeedback(fe)},onSubmitForm:({key:W,data:ce})=>c.aiAgent.submitForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:W,formData:ce}),onCancelForm:({key:W})=>c.aiAgent.cancelForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:W}),onStreamAnimationStart:()=>{f.start(w.messageId)},onStreamAnimationProgress:()=>{b.actions.onStreamingUpdate()},onStreamAnimationComplete:()=>{f.stop(w.messageId),b.actions.onStreamingUpdate()}};if(w.isUserMessage())return s.createElement(t,{...Te,messageType:"user"});if(w.isFileMessage())return s.createElement(t,{...Te,messageType:"file",file:w})}return null})(),N=Mi(w,oe)&&s.createElement(aa,{date:w.createdAt,style:C.dateSeparator});return s.createElement(y,null,N,L)},H=()=>s.createElement(wi,{style:C.poweredBy}),G=()=>{var w,U;return s.createElement(s.Fragment,null,E&&s.createElement(t,{isTyping:!0,isBotMessage:E.isBot,sender:E.user,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:(w=i==null?void 0:i.conversation)==null?void 0:w.senderAvatarEnabled}),((U=i==null?void 0:i.conversation)==null?void 0:U.isTalkToAgentViewEnabled)&&s.createElement(Ii,null),A.bottomSpace?s.createElement(y,{height:A.bottomSpace}):null)};return s.createElement(y,{flex:1},s.createElement($n,{ref:b.ref,style:C.list,contentContainerStyle:[C.listContent,v,e==="top"&&C.stackTop],data:m.messages,onEndReached:m.loadPrevious,keyExtractor:Do,renderItem:M,loading:!m.initialized,error:!!(h||_.error),LoadingComponent:s.createElement(Se,{type:"loading"}),EmptyComponent:s.createElement(Se,{type:"noMessages",label:a.common.placeholder_no_messages}),ErrorComponent:s.createElement(Se,{type:"error",label:(h==null?void 0:h.message)??((ne=_.error)==null?void 0:ne.message),action:_.error?{label:a.common.placeholder_something_went_wrong_retry_label,onPress:()=>_.refetch()}:void 0}),ListFooterComponent:H(),ListHeaderComponent:G(),inverted:!0,...I}),((q=i==null?void 0:i.conversation)==null?void 0:q.newMessageIndicatorEnabled)&&A.isAwayFromBottom&&m.newMessages.length>0&&s.createElement(y,{style:C.newMessagesButtonContainer},s.createElement(ia,{label:a.conversation.scroll_to_new_messages_label(m.newMessages),accessibilityLabel:a.conversation.a11y_scroll_to_new_messages,onPress:()=>b.actions.scrollToBottom()})),A.isAwayFromBottom&&m.newMessages.length===0&&s.createElement(y,{style:C.scrollButtonContainer},s.createElement(_a,{onPress:()=>b.actions.scrollToBottom()})))},Ri=R.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background},stackTop:{flexGrow:1,justifyContent:"flex-end"},dateSeparator:{marginVertical:16},poweredBy:{marginTop:16},scrollButtonContainer:{position:"absolute",bottom:12,end:16},newMessagesButtonContainer:{position:"absolute",bottom:12,alignSelf:"center"}})),de={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 Pi(e){return{captureCamera:async()=>{if(e.requestCameraPermissionsAsync&&!(await e.requestCameraPermissionsAsync()).granted)throw new Error(de.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(yn)},selectFromGallery:async t=>{if(e.requestMediaLibraryPermissionsAsync&&!(await e.requestMediaLibraryPermissionsAsync()).granted)throw new Error(de.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(yn)}}}function Di(e,t){const n=async()=>{const r=p.Platform.select({ios:t.PERMISSIONS.IOS.CAMERA,android:t.PERMISSIONS.ANDROID.CAMERA});if(!r)return;const a=await t.request(r);if(a!=="granted"&&a!=="limited")throw new Error(de.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 a=await t.requestMultiple(r);if(!Object.values(a).every(l=>l==="granted"||l==="limited"))throw new Error(de.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(de.CAMERA_PERMISSION_DENIED):new Error(r.errorMessage||`Camera error: ${r.errorCode}`);return!r.assets||r.assets.length===0?null:r.assets.map(bn)},selectFromGallery:async r=>{await o();const a=await e.launchImageLibrary({mediaType:"photo",selectionLimit:(r==null?void 0:r.selectionLimit)??1,assetRepresentationMode:"compatible"});if(a.didCancel)return null;if(a.errorCode)throw a.errorCode==="permission"?new Error(de.GALLERY_PERMISSION_DENIED):new Error(a.errorMessage||`Gallery error: ${a.errorCode}`);return!a.assets||a.assets.length===0?null:a.assets.map(bn)}}}function Oi(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(Ni)}}}function Bi(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(Hi)}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 yn(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 Ni(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function bn(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 Hi(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function zi(e){return{keyValueStorage:{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))}}}function Fi(){return{captureCamera:async()=>{throw new Error(de.IMAGE_PICKER_NOT_CONFIGURED)},selectFromGallery:async()=>{throw new Error(de.IMAGE_PICKER_NOT_CONFIGURED)}}}function $i(){return{selectFile:async()=>{throw new Error(de.DOCUMENT_PICKER_NOT_CONFIGURED)}}}const{Provider:Ui,useContext:Yn}=X("NativeAdapter"),Xn=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:o,documentPicker:r,mmkv:a}=e,i=o?(qi(e),"launchCameraAsync"in o?Pi(o):Di(o,e.permissions)):Fi(),l=r?"getDocumentAsync"in r?Oi(r):Bi(r):$i(),c=zi(a);return{...i,...l,...c}},[e.imagePicker,e.documentPicker,e.mmkv,e.permissions]);return s.createElement(Ui,{value:n},t)};function qi(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 Vi=({onPressAddAttachment:e,disabled:t})=>s.createElement(P,{disabled:t,style:Wi.container,activeOpacity:.75,onPress:e},s.createElement(D,{type:"add",size:24,color:n=>t?n.textDisabled:n.primary})),Wi=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Gi=({name:e,type:t,url:n,onRemove:o})=>{const r=ji.use();return s.createElement(y,{style:r.wrapper},Bo(t)?s.createElement(we,{source:{uri:n},style:r.image,resizeMode:"cover"}):s.createElement(jt,{name:e,type:Ht(e,t)}),o&&s.createElement(P,{onPress:o,style:r.removeButton},s.createElement(D,{type:"remove",size:20,color:r.removeIcon.tintColor})))},Fe=7,ji=R.create(({themedColor:e})=>({wrapper:{marginTop:Fe,marginRight:Fe,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-Fe,right:-Fe,width:22,height:22,borderRadius:11,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),Ki=e=>{const{theme:t,themedColor:n}=$(),o=Yi.use(),r=Vt.useTextAlign({text:e.value??e.placeholder,style:o.input,isTextInput:!0});return s.createElement(y,{style:o.container},e.attachments&&s.createElement(Wn,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),s.createElement(y,null,s.createElement(p.TextInput,{multiline:!0,style:[o.input,{textAlign:r}],placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},Yi=R.create(({theme:e})=>({container:{backgroundColor:e.colors.messageInput.background,gap:16,flex:1,paddingHorizontal:16,paddingVertical:8,justifyContent:"center",borderRadius:20,minHeight:36},input:{...Xi(e.typography.body3),color:e.colors.messageInput.text,includeFontPadding:!1,padding:0,margin:0,textAlignVertical:"center"}}));function Xi(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 Zi=({onPressSend:e})=>s.createElement(P,{style:Ji.container,activeOpacity:.75,onPress:e},s.createElement(D,{type:"send",size:24})),Ji=p.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Qi=()=>{const e=el.use(),{aiAgentInfo:t,userSession:n}=J(),{messageSource:o,channelSource:r}=te(),[a,i]=d.useState(null),l=$t("special-notice",r.channel),c=d.useCallback(()=>r.channel?l?o.messages.some(u=>Pe(u,(n==null?void 0:n.userId)??"")):!0:null,[r.channel,l,o.messages,n==null?void 0:n.userId]);return d.useEffect(()=>{a||i(c())},[c,a]),a||!(t!=null&&t.specialNotice)?null:s.createElement(y,{style:e.container},s.createElement(Kt,{textStyle:e.text,linkStyle:e.link},(t==null?void 0:t.specialNotice)??""))},el=R.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})}})),tl=()=>{var S;const{chatSDK:e}=j(),{strings:t}=F(),{createAttachmentRules:n}=J(),{channelSource:o,state:r}=te(),[a,i]=d.useState(""),[l,c]=d.useState([]),u=n({channel:o.channel,uploadSizeLimit:(S=e.appInfo)==null?void 0:S.uploadSizeLimit}),g=(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 v=x=>{const O=u.getUploadSizeLimit(x.type);return x.size&&x.size>O},A=C.find(x=>v(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+C.length>u.maxAttachmentCount?(p.Alert.alert("",t.conversation.file_upload_notification_count_limit(u.maxAttachmentCount)),f):[...f,...C]},h=f=>{c(E=>g(E,f))},m=f=>{c(E=>E.filter((C,v)=>v!==f))},_=()=>{c([])},b=(()=>{if(!r.input.disabled)return t.conversation.input_placeholder;switch(r.input.disabledBy){case"form_active":return t.conversation.input_placeholder_active_form;case"ai_responding":return t.conversation.input_placeholder_wait_ai_agent_response;case"reconnecting":return t.conversation.input_placeholder_reconnecting;case"unavailable":case"conversation_closed":default:return t.conversation.input_placeholder_disabled}})();return d.useEffect(()=>{r.input.disabled&&(i(""),_())},[r.input.disabled]),{files:l,addFiles:h,removeFile:m,clearFiles:_,value:a,onChangeText:i,editable:!r.input.disabled,placeholder:b,sendButtonVisible:!r.input.disabled&&(!!a.trim()||l.length>0),addAttachmentButtonVisible:u.isEnabled(),addAttachmentButtonDisabled:r.input.disabled||l.length>=u.maxAttachmentCount,hasImageMimeTypes:()=>u.supportedMimeTypes.filter(E=>E.startsWith("image/")||E===An).length>0,hasFileMimeTypes:()=>u.supportedMimeTypes.length>0,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount}},nl=()=>{const{config:e}=j(),t=Yn(),{strings:n}=F(),{messageSource:o}=te(),{openModal:r}=Xe(),a=xe(["left","right","bottom"]),i=ol.use(),{maxAttachmentCount:l,sendButtonVisible:c,addAttachmentButtonVisible:u,addAttachmentButtonDisabled:g,acceptableMimeTypes:h,hasImageMimeTypes:m,hasFileMimeTypes:_,...b}=tl(),E={...b,onPressAddAttachment:async()=>{const C=await r(v=>{var A,I,x,O,B,M,H,G;return s.createElement(ee,{onClose:()=>v()},((x=(I=(A=e==null?void 0:e.conversation)==null?void 0:A.input)==null?void 0:I.camera)==null?void 0:x.photoEnabled)&&s.createElement(ee.ActionItem,{icon:"camera",label:n.conversation.attachment_camera,onPress:async()=>{if(!m())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),v(null);const Z=await t.captureCamera();v(Z)}}),((M=(B=(O=e==null?void 0:e.conversation)==null?void 0:O.input)==null?void 0:B.gallery)==null?void 0:M.photoEnabled)&&s.createElement(ee.ActionItem,{icon:"photo",label:n.conversation.attachment_photo,onPress:async()=>{if(!m())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),v(null);const Z=await t.selectFromGallery({selectionLimit:l-b.files.length});v(Z)}}),((G=(H=e==null?void 0:e.conversation)==null?void 0:H.input)==null?void 0:G.fileEnabled)&&s.createElement(ee.ActionItem,{icon:"document",label:n.conversation.attachment_document,onPress:async()=>{if(!_())return p.Alert.alert("",n.conversation.file_upload_no_supported_files),v(null);const Z=await t.selectFile({selectionLimit:l-b.files.length,mimeTypes:h});v(Z)}}))});C&&b.addFiles(C)},onPressSend:()=>{b.files.length>0?o.sendFileMessage({message:b.value.trim(),file:b.files[0]}):o.sendUserMessage({message:b.value}),b.clearFiles(),b.onChangeText("")}};return s.createElement(p.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-a.paddingBottom},s.createElement(Qi,null),s.createElement(y,{style:i.container(a)},u&&s.createElement(Vi,{...E,disabled:g}),s.createElement(Ki,{...E,value:E.editable?E.value:"",attachments:E.files.length===0?null:E.files.map((C,v)=>s.createElement(Gi,{key:v,name:C.name,type:C.type,url:C.uri,onRemove:()=>E.removeFile(v)}))}),c&&s.createElement(Zi,{...E})))},ol=R.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})})),Zn=({start:e,title:t,titleAlign:n="start",end:o})=>{const r=xe(["left","right","top"]),[a,i]=d.useState(0),[l,c]=d.useState(0),u=m=>{i(m.nativeEvent.layout.width)},g=m=>{c(m.nativeEvent.layout.width)},h=rl.use();return s.createElement(y,{style:h.container},s.createElement(y,{height:r.paddingTop}),s.createElement(y,{style:h.contentContainer(r)},n==="center"&&t&&s.createElement(y,{style:h.centerTitleContainer(Math.max(a,l))},s.createElement(y,{style:h.centerTitle},t)),s.createElement(y,{style:h.rowContainer},s.createElement(y,{style:h.startSide,onLayout:u},e),(n==="start"||n==="end")&&t&&s.createElement(y,{style:h.titleSide(n,e,o)},t),s.createElement(y,{style:h.endSide,onLayout:g},o))))},rl=R.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})})),sl=()=>{const{themedColor:e}=$(),{onClose:t}=te();return t?s.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},s.createElement(D,{color:e.textHighEmphasis,type:"close",size:24})):null},al=()=>{const{themedColor:e}=$(),{channelSource:{channel:t}}=te(),n=$t("handoff-button",t),o=!Cn(t)||Ae(t);return n?s.createElement(P,{hitSlop:4,disabled:o,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},s.createElement(D,{color:o?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},il=()=>{const{strings:e}=F(),{themedColor:t}=$(),{onNavigateToConversationList:n}=te();return n?s.createElement(P,{hitSlop:4,onPress:n,activeOpacity:.75,"aria-label":e.conversation.a11y_open_conversation_list},s.createElement(D,{color:t.textHighEmphasis,type:"menu",size:24})):null},Jn=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:o}=J(),{fallbackIcon:r,url:a}=Rn({channel:e,aiAgentInfo:o,userSession:n}),{theme:i}=$();return a?s.createElement(Vn,{src:a,size:t}):s.createElement(y,{width:t,height:t,borderRadius:t/2,alignItems:"center",justifyContent:"center",flexShrink:0,style:{backgroundColor:i.colors.base.primary}},s.createElement(D,{type:r,size:t*.55,color:i.colors.base.primaryContrastContent}))},ll=()=>{var i,l;const{channelSource:{channel:e}}=te(),{userSession:t,aiAgentInfo:n}=J(),{config:o}=j(),r=Rn({channel:e,userSession:t,aiAgentInfo:n}),a=(l=(i=o==null?void 0:o.conversation)==null?void 0:i.header)==null?void 0:l.avatarEnabled;return s.createElement(y,{gap:6,flexDirection:"row",alignItems:"center",maxWidth:"100%"},a&&s.createElement(Jn,{channel:e,size:34}),s.createElement(y,{flexShrink:1},s.createElement(T,{numberOfLines:1,variant:"h1"},r.title)))},cl=e=>{const{components:t}=be.useContext();return s.createElement(Zn,{start:s.createElement(t.StartArea,null),title:s.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:s.createElement(t.EndArea,null)})},ul=()=>{const{components:e}=be.useContext();return s.createElement(e.MenuButton,null)},dl=()=>{const{components:e}=be.useContext();return s.createElement(e.Title,null)},ml=()=>{const{components:e}=be.useContext();return s.createElement(y,{flexDirection:"row",alignItems:"center",gap:10},s.createElement(e.HandoffButton,null),s.createElement(e.CloseButton,null))},be=ae({template:cl,components:{StartArea:ul,TitleArea:dl,EndArea:ml,MenuButton:il,Title:ll,HandoffButton:al,CloseButton:sl}}),gl=()=>{const{Template:e}=be.useContext();return s.createElement(e,{titleAlign:"start"})},hl=e=>{const{components:t}=tt.useContext();return s.createElement(y,{flex:1},s.createElement(t.Header,null),s.createElement(t.Body,null),s.createElement(t.Footer,null))},tt=ae({template:hl,components:{Header:gl,Body:Li,Footer:nl}}),Qn=({children:e,...t})=>{const{Template:n}=tt.useContext();return s.createElement(Dn,{...t},s.createElement(n,null),e)},{Provider:fl,Context:pl,useContext:nt}=X("ConversationList"),eo=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:o,children:r})=>{const{sdkUser:a,authenticate:i}=J();return d.useEffect(()=>{a||i()},[]),s.createElement($r,{conversationListLimit:e,conversationListFilter:t},l=>s.createElement(fl,{value:{...l,onClose:o,onNavigateToConversation:n}},r))},bt=99,_l=d.memo(function(t){const{channel:n,onClick:o}=t,{strings:r,format:a}=F(),{themedColor:i}=$(),l=bl.use(),c=Ro(n),u=Po(n,a,{justNow:r.date_format.just_now,minutesAgo:r.date_format.minutes_ago,hoursAgo:r.date_format.hours_ago,dateShortFormat:r.date_format.date_short}),g=n.unreadMessageCount;return s.createElement(P,{onPress:o,activeOpacity:.75},s.createElement(y,{flexDirection:"row",alignItems:"center",width:"100%",height:72,gap:16},s.createElement(y,{marginStart:16,alignItems:"center",justifyContent:"center"},s.createElement(Jn,{channel:n})),s.createElement(y,{flexDirection:"row",alignItems:"center",flex:1,paddingEnd:16,height:"100%",gap:8,style:l.rightContainer},s.createElement(y,{flexDirection:"column",justifyContent:"center",flex:1,gap:4},s.createElement(T,{variant:"subtitle1",color:i.textHighEmphasis,numberOfLines:1},c),s.createElement(y,{flexDirection:"row",alignItems:"center",gap:6},ye(n)&&s.createElement(s.Fragment,null,s.createElement(T,{variant:"caption1",color:i.textMidEmphasis,numberOfLines:1},r.conversation_list.ended),s.createElement(y,{width:2,height:2,borderRadius:1,backgroundColor:i.textLowEmphasis})),s.createElement(T,{variant:"caption2",color:i.textLowEmphasis,numberOfLines:1},u))),g>0&&s.createElement(y,{alignItems:"center",justifyContent:"center",height:20,width:g<=bt?20:void 0,padding:4,borderRadius:10,backgroundColor:i.error},s.createElement(T,{variant:"caption3",color:i.textHighEmphasisInverse,style:{lineHeight:12}},g<=bt?g:`${bt}+`)))))}),yl=ae({template:_l,components:{}}),bl=R.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),El=()=>{var l;const{Template:e}=yl.useContext(),{strings:t}=F(),{connectionError:n}=J(),{listSource:o,onNavigateToConversation:r}=nt(),a=xe(["left","right"]),i=vl.use();return s.createElement($n,{style:i.list,contentContainerStyle:[i.listContent,a],data:o.channels,onEndReached:o.loadMore,keyExtractor:d.useCallback(c=>c.url,[]),renderItem:d.useCallback(({item:c})=>s.createElement(e,{channel:c,onClick:()=>r==null?void 0:r(c.url,ye(c)?"closed":"open")}),[e,r]),loading:!o.initialized,error:!!(n||o.error),LoadingComponent:s.createElement(Se,{type:"loading"}),EmptyComponent:s.createElement(Se,{type:"noChannels",label:t.common.placeholder_no_conversations}),ErrorComponent:s.createElement(Se,{type:"error",label:(n==null?void 0:n.message)??((l=o.error)==null?void 0:l.message)})})},vl=R.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),Cl=()=>{const{strings:e}=F(),{language:t,countryCode:n,context:o}=j(),{aiAgentInfo:r,refreshActiveChannel:a,createConversation:i,setActiveChannel:l,sdkUser:c}=J(),{onNavigateToConversation:u}=nt(),g=xe(["left","right","bottom"]),h=Sl.use();return s.createElement(P,{activeOpacity:.75,disabled:!c,onPress:async()=>{if(r!=null&&r.isMultipleActiveConversationsEnabled){const m=await i({aiAgentId:r.userId,language:t,country:n,context:o});l({url:m,status:Y.ConversationStatus.OPEN}),u==null||u(m,Y.ConversationStatus.OPEN)}else{const m=await a();u==null||u(m,Y.ConversationStatus.OPEN)}}},s.createElement(y,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+g.paddingBottom,style:[h.container,g]},s.createElement(T,{variant:"h1",color:m=>m.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},Sl=R.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),Al=()=>{const{aiAgentInfo:e}=J();return e?s.createElement(Cl,null):null},wl=()=>{const{themedColor:e}=$(),{onClose:t}=nt();return t?s.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},s.createElement(D,{color:e.textHighEmphasis,type:"close",size:24})):null},xl=()=>{const{strings:e}=F();return s.createElement(T,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},Il=e=>{const{components:t}=Ie.useContext();return s.createElement(Zn,{start:s.createElement(t.StartArea,null),title:s.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:s.createElement(t.EndArea,null)})},Tl=()=>null,kl=()=>{const{components:e}=Ie.useContext();return s.createElement(e.Title,null)},Ml=()=>{const{components:e}=Ie.useContext();return s.createElement(e.CloseButton,null)},Ie=ae({template:Il,components:{StartArea:Tl,TitleArea:kl,EndArea:Ml,Title:xl,CloseButton:wl}}),Ll=()=>{const{Template:e}=Ie.useContext();return s.createElement(e,{titleAlign:"start"})},Rl=()=>{const{components:e}=ot.useContext();return s.createElement(y,{flex:1},s.createElement(e.Header,null),s.createElement(e.Body,null),s.createElement(e.Footer,null))},ot=ae({template:Rl,components:{Header:Ll,Body:El,Footer:Al}}),to=({children:e,...t})=>{const{Template:n}=ot.useContext();return s.createElement(eo,{...t},s.createElement(n,null),e)},Pl="1.3.1",Dl=Pl,Ol=d.forwardRef(function({logLevel:t=K.LogLevel.WARN,language:n=Ye,userSessionInfo:o,children:r,strings:a,...i},l){const[c]=d.useState(()=>new In(t));c.level!==t&&(c.level=t);const{nativeModules:u,chatParams:g={},...h}=i;return s.createElement(Xn,{config:u},({keyValueStorage:m})=>s.createElement(Nl,{logger:c,theme:h.theme,language:n,strings:a},s.createElement(Xo,{language:n,logger:c,chatSDK:h.customChatSDK,keyValueStorage:m,chatParams:{...g,useMMKVStorageStore:u.mmkv},messengerVersion:Dl,extensions:{platform:K.SendbirdPlatform.REACT_NATIVE,deviceOSPlatform:p.Platform.select({web:K.DeviceOsPlatform.WEB,ios:K.DeviceOsPlatform.IOS,default:K.DeviceOsPlatform.ANDROID})},...h},s.createElement(cs,{ref:l,userSessionInfo:o},r))))}),Bl=To(tt,be,ot,Ie,Gt,Ze,Je,Qe,et),Nl=({children:e,logger:t,theme:n,language:o,strings:r})=>s.createElement(_e.SafeAreaProvider,null,s.createElement(Vs,{logger:t,...n},s.createElement($s,{language:o,logger:t,strings:r},s.createElement(On,null,s.createElement(Vr,null,s.createElement(Bl,null,e)))))),{Provider:Hl,useContext:Yt}=X("FixedMessengerStyle"),zl={useNativeDriver:!0},$e={OPEN_START:"0deg",OPEN_END:"-180deg",CLOSE_START:"180deg",CLOSE_END:"0deg"},Ue={VISIBLE:1,HIDDEN:0},Fl=({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,...zl}).start()},[e,t]);const n={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[$e.OPEN_START,$e.OPEN_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Ue.VISIBLE,Ue.HIDDEN]})}]},o={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[$e.CLOSE_START,$e.CLOSE_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[Ue.HIDDEN,Ue.VISIBLE]})}]};return{openIconStyle:n,closeIconStyle:o}},$l=2/3,Ul=({isOpened:e,onPress:t})=>{const n=Wl.use(),{launcherInfo:o}=J(),{theme:r}=$(),{launcherSize:a,horizontal:i}=Yt(),l=Math.round(a*$l),c=r.colors.base.primary,u=r.colors.base.primaryContrastContent,{openIconStyle:g,closeIconStyle:h}=Fl({isOpened:e});return s.createElement(y,{alignSelf:i==="start"?"flex-start":"flex-end"},s.createElement(P,{onPress:t,activeOpacity:.8},({pressed:m})=>s.createElement(y,{style:[n.container({backgroundColor:c,size:a}),m&&n.pressed]},s.createElement(y.Animated,{style:[n.iconWrapper,g]},s.createElement(ql,{url:(o==null?void 0:o.imageUrl)??"",isDefaultIcon:(o==null?void 0:o.type)==="default_icon",size:l,fillColor:u})),s.createElement(y.Animated,{style:[n.iconWrapper,h]},s.createElement(Vl,{size:l,fillColor:u})))))},ql=({url:e,isDefaultIcon:t,size:n,fillColor:o})=>e?t?s.createElement(we,{source:{uri:e},width:n,height:n,tintColor:o,resizeMode:"contain"}):s.createElement(we,{source:{uri:e},width:n,height:n,resizeMode:"cover"}):s.createElement(D,{type:"delight",size:n,color:o}),Vl=({size:e,fillColor:t})=>s.createElement(D,{type:"chevron-down",size:e,color:t}),Wl=R.create(()=>({container:e=>({position:"relative",width:e.size,height:e.size,backgroundColor:e.backgroundColor,borderRadius:e.size/2,justifyContent:"center",alignItems:"center",boxShadow:"0px 8px 16px 0px rgba(33, 33, 33, 0.3)"}),pressed:{transform:[{scale:.9}]},iconWrapper:{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"}})),Q={TRANSLATE_OFFSET:40,DURATION:300,OPACITY_DURATION:83,EASING:p.Easing.out(p.Easing.ease)},Gl=e=>e==="entered"?0:Q.TRANSLATE_OFFSET,jl=e=>e==="entered"?1:0,Kl=({transitionState:e,isActive:t})=>{const[n,o]=d.useState(!1),r=d.useRef(new p.Animated.Value(Gl(e))).current,a=d.useRef(new p.Animated.Value(jl(e))).current;return d.useEffect(()=>{if(!n){e==="entered"?(r.setValue(0),a.setValue(1)):e==="exited"&&(r.setValue(Q.TRANSLATE_OFFSET),a.setValue(0)),o(!0);return}e==="entering"?(r.setValue(Q.TRANSLATE_OFFSET),a.setValue(0),p.Animated.parallel([p.Animated.timing(r,{toValue:0,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),p.Animated.timing(a,{toValue:1,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()):e==="exiting"&&p.Animated.parallel([p.Animated.timing(r,{toValue:Q.TRANSLATE_OFFSET,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),p.Animated.timing(a,{toValue:0,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()},[e,r,a,n]),d.useMemo(()=>({position:"absolute",top:0,left:0,width:"100%",height:"100%",transform:[{translateY:r}],opacity:a,zIndex:t?999:1,pointerEvents:t?"auto":"none",display:e==="exited"?"none":"flex"}),[r,a,t,e])},no=d.createContext(null),Yl=()=>{const e=d.useContext(no);if(!e)throw new Error("useNavigatorContext() must be used within <Navigator />");return e},oo=({children:e})=>{const t=Yl();return typeof e=="function"?s.createElement(s.Fragment,null,e(t)):s.createElement(s.Fragment,null,e)},Xl=d.memo(({transitionState:e,isActive:t,children:n})=>{const o=Kl({transitionState:e,isActive:t});return s.createElement(p.Animated.View,{style:o},n)}),En=300,Ve=({initialId:e,children:t})=>{const[n,o]=d.useState([e]),r=n[n.length-1],a=d.useCallback((f,E)=>{o(C=>[...C,f]),h(C=>({...C,[f]:!0})),E!=null&&E.reset&&S(C=>({...C,[f]:(C[f]||0)+1})),_(C=>({...C,[f]:"entering"})),setTimeout(()=>{_(C=>({...C,[f]:"entered"}))},En)},[]),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))},En),f})},[]),l=d.useMemo(()=>({navigation:{navigate:a,pop:i},activeScreenId:r}),[a,i,r]),c=d.useMemo(()=>d.Children.toArray(t).filter(f=>f.type===oo),[t]),u=d.useMemo(()=>{const f={};return c.forEach(E=>{const{id:C,lazy:v,children:A}=E.props;f[C]={lazy:v,element:typeof A=="function"?A(l):A}}),f},[c,l]),[g,h]=d.useState(()=>{const f={};return Object.entries(u).forEach(([E,{lazy:C}])=>{C===!1&&(f[E]=!0)}),f[e]=!0,f}),[m,_]=d.useState(()=>{const f={};return Object.keys(u).forEach(E=>{f[E]=E===e?"entered":"exited"}),f}),[b,S]=d.useState({});return s.createElement(no.Provider,{value:l},s.createElement(y,{style:{position:"relative",width:"100%",height:"100%"}},Object.keys(u).map(f=>{var A;if(!g[f])return null;const E=m[f]||"exited",C=f===r,v=`${f}-${b[f]||0}`;return s.createElement(Xl,{key:v,transitionState:E,isActive:C},(A=u[f])==null?void 0:A.element)})))};Ve.Screen=oo;const{Provider:Zl,useContext:Xt}=X("PageChildren"),Jl=({children:e})=>{const[t,n]=d.useState(null),[o,r]=d.useState(null);return s.createElement(Zl,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:o,setConversationListChildren:r}},e)},pe={conv:"conv",convList:"conv-list"},Ql=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:o,onClose:r})=>{const{conversationChildren:a,conversationListChildren:i}=Xt(),l=t==="ConversationList"?pe.convList:pe.conv;return s.createElement(Ve,{initialId:l},s.createElement(Ve.Screen,{id:pe.conv},({navigation:c,activeScreenId:u})=>s.createElement(Qn,{channelUrl:n,onClearChannelUrl:()=>o(void 0),onNavigateToConversationList:()=>c.navigate(pe.convList),onClose:r,shouldMarkAsRead:e&&u===pe.conv},a)),s.createElement(Ve.Screen,{id:pe.convList,lazy:!0},({navigation:c})=>s.createElement(to,{onNavigateToConversation:u=>{o(u),c.navigate(pe.conv,{reset:!0})},onClose:r},i)))},Re=.15,ec=150,vn=(e,t)=>e.interpolate({inputRange:[Re,1],outputRange:[t,0],extrapolate:"clamp"}),tc=(e,t)=>{if(e<=0)return 0;const n=(1-Re)*e/2,o=t==="start"?-1:1,r=p.I18nManager.isRTL?-1:1;return n*o*r},nc=(e,t)=>e<=0?0:(1-Re)*e/2*(t==="top"?-1:1),oc=({isOpened:e,horizontal:t,vertical:n})=>{const[o,r]=d.useState({width:0,height:0}),a=d.useRef(new p.Animated.Value(e?1:Re)).current,i=d.useRef(new p.Animated.Value(e?1:0)).current,l=d.useMemo(()=>tc(o.width,t),[o.width,t]),c=d.useMemo(()=>nc(o.height,n),[o.height,n]),{translateXInterpolation:u,translateYInterpolation:g}=d.useMemo(()=>({translateXInterpolation:vn(a,l),translateYInterpolation:vn(a,c)}),[a,l,c]);d.useEffect(()=>{const _=e?"open":"close",b=_==="open"?1:Re,S=_==="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(a,{toValue:b,...E}),p.Animated.timing(i,{toValue:S,...E})]).start()},[e,a,i]);const h=d.useMemo(()=>({opacity:i,transform:[{translateX:u},{translateY:g},{scale:a}]}),[i,u,g,a]),m=d.useMemo(()=>_=>{const{width:b,height:S}=_.nativeEvent.layout;r(f=>f.width===b&&f.height===S?f:{width:b,height:S})},[]);return{animatedStyle:h,handleLayout:m,pointerEvents:e?"auto":"none"}},rc={top:0,left:0,right:0,bottom:0},sc=({children:e,isOpened:t})=>{const n=ac.use(),{horizontal:o,vertical:r}=Yt(),{animatedStyle:a,handleLayout:i,pointerEvents:l}=oc({isOpened:t,horizontal:o,vertical:r});return s.createElement(_e.SafeAreaInsetsContext.Provider,{value:rc},s.createElement(y,{flex:1},s.createElement(y.Animated,{pointerEvents:l,onLayout:i,style:a},s.createElement(y,{style:n.windowContainer},e))))},ac=R.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)"}})),ro=()=>{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)}),a=p.Keyboard.addListener(o,()=>{t(0)});return()=>{r.remove(),a.remove()}},[]),e},ic=e=>{const t=d.useRef(new p.Animated.Value(0)).current,[n,o]=d.useState(!1);return d.useEffect(()=>{const a=e?"open":"close",i={toValue:a==="open"?1:0,useNativeDriver:!0,duration:300};a==="open"&&o(!0),p.Animated.timing(t,i).start(()=>{a==="close"&&(o(!1),p.Keyboard.dismiss())})},[e,t]),{windowAnimatedStyle:{opacity:t,display:n?"flex":"none"},pointerEvents:e?"auto":"none"}},lc=({children:e,insets:t,isOpened:n})=>{const o=cc.use(),a={..._e.useSafeAreaInsets(),...t},i=ro(),{windowAnimatedStyle:l,pointerEvents:c}=ic(n);return s.createElement(_e.SafeAreaInsetsContext.Provider,{value:a},s.createElement(y.Animated,{flex:1,style:[o.bg,l],pointerEvents:c},s.createElement(y,{flex:1},e),s.createElement(y,{height:Math.max(0,i-p.Platform.select({android:0,default:a.bottom})),style:o.bg})))},cc=R.create(({theme:e})=>({bg:{backgroundColor:e.colors.base.background}})),uc="end-bottom",Me={top:24,bottom:24,start:24,end:24},dc=({mode:e,edgeToEdgeEnabled:t})=>{const n=e==="floating"?sc:lc,[o,r]=At({position:uc,margin:Me,launcherSize:48,spacing:12}),{bottom:a}=_e.useSafeAreaInsets(),i=ro(),[l,c]=o.position.split("-"),u=(()=>{const m=p.Platform.select({android:t?a:0,default:0}),_=c==="top"?o.spacing:-o.launcherSize,b=i>0?i+_+m:0;return b>0?b:o.margin.bottom})(),g={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 m=o.launcherSize+o.spacing;return{position:"absolute",top:o.margin.top+(c==="top"?m:0),bottom:u+(c==="bottom"?m: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:g,styleContext:{...o,horizontal:l,vertical:c,setPosition:m=>r({position:m}),setMargin:({top:m=Me.top,bottom:_=Me.bottom,start:b=Me.start,end:S=Me.end})=>r({margin:{top:m,bottom:_,start:b,end:S}}),setLauncherSize:m=>r({launcherSize:m}),setSpacing:m=>r({spacing:m})}}},mc=e=>{var a,i,l,c;const{setPosition:t,setMargin:n,setLauncherSize:o,setSpacing:r}=Yt();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,(a=e.margin)==null?void 0:a.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},gc=({children:e})=>{const{setConversationChildren:t}=Xt();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},hc=({children:e})=>{const{setConversationListChildren:t}=Xt();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},fc=({entryPoint:e="Conversation",edgeToEdgeEnabled:t=!0,windowMode:n="floating",fullscreenInsets:o,initialChannelUrl:r,windowContainerProps:a,children:i})=>{const[l,c]=d.useState(!1),[u,g]=d.useState(r),{Window:h,windowContainerStyle:m,launcherContainerStyle:_,styleContext:b}=dc({mode:n,edgeToEdgeEnabled:t});return d.useEffect(()=>{const S=p.BackHandler.addEventListener("hardwareBackPress",()=>l?(c(!1),!0):!1);return()=>S.remove()},[l]),s.createElement(Hl,{value:b},s.createElement(Jl,null,s.createElement(y,{style:m,backgroundColor:"transparent",pointerEvents:l?"auto":"box-none",...a},s.createElement(h,{isOpened:l,insets:o},s.createElement(Ql,{isOpened:l,entryPoint:e,selectedChannelUrl:u,setSelectedChannelUrl:g,onClose:()=>c(!1)}))),s.createElement(y,{style:_,backgroundColor:"transparent",pointerEvents:"box-none"},s.createElement(Ul,{isOpened:l,onPress:()=>c(!l)})),i))},pc=Object.assign(fc,{Style:mc,ConversationChildren:gc,ConversationListChildren:hc});exports.AIAgentProviderContainer=Ol;exports.AnonymousSessionInfo=Ge;exports.BottomSheet=ee;exports.BottomSheetLayout=Ze;exports.Conversation=Qn;exports.ConversationContext=_s;exports.ConversationContextProvider=Dn;exports.ConversationHeaderLayout=be;exports.ConversationLayout=tt;exports.ConversationList=to;exports.ConversationListContext=pl;exports.ConversationListContextProvider=eo;exports.ConversationListHeaderLayout=Ie;exports.ConversationListLayout=ot;exports.FixedMessenger=pc;exports.IncomingMessageLayout=Je;exports.ManualSessionInfo=Ft;exports.ModalProvider=On;exports.NativeAdapterProvider=Xn;exports.OutgoingMessageLayout=Qe;exports.SystemMessageLayout=et;exports.useConversationContext=te;exports.useConversationListContext=nt;exports.useMessengerSessionContext=J;exports.useModalContext=Xe;exports.useNativeAdapterContext=Yn;
|