@sendbird/ai-agent-messenger-react-native 0.0.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +35 -0
- package/README.md +3 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +952 -0
- package/dist/index.js +5029 -0
- package/package.json +112 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Sendbird SDK LICENSE
|
|
2
|
+
|
|
3
|
+
This is an agreement between You ("You") and Sendbird, Inc., the developer of Sendbird, located at 400 1st Ave, San Mateo, CA 94401, ("Sendbird") regarding Your use of the Sendbird SDK and any associated documentation or other materials made available by Sendbird (collectively the "SDK"). This agreement applies to any updates or supplements for the SDK, unless other terms accompany those items. If so, those other terms apply.
|
|
4
|
+
|
|
5
|
+
By installing, accessing or otherwise using the SDK, You accept the terms of this agreement. If You do not agree to the terms of this agreement, do not install, access or use the SDK.
|
|
6
|
+
|
|
7
|
+
If You comply with this agreement, You have the rights below.
|
|
8
|
+
|
|
9
|
+
(1) USE OF THE SDK. Subject to Your compliance with this agreement, Sendbird hereby authorizes You to use the SDK solely for the purpose of creating applications designed to operate with the Services (referred to as "Authorized Applications"). You may not rent, lease or lend any of Your rights in the SDK or access to the Services. You may make a reasonable number of copies of the SDK for the purposes set forth herein, provided that You reproduce only complete copies, including without limitation all "read me" files, copyright notices, and other legal notices and terms that Sendbird has included in the SDK.
|
|
10
|
+
|
|
11
|
+
(2) SCOPE OF LICENSE. The SDK is licensed, not sold. This agreement only gives You some rights to use the SDK. Sendbird specifically does not grant any express or implied rights under its patents with respect to your Authorized Applications. In doing so, You must comply with any technical limitations in the SDK that only allow You to use it in certain ways. You may not: (a) reverse engineer, decompile, distribute or disassemble the SDK, except and only to the extent that applicable law expressly permits; or (b) make more copies of the SDK than specified in this agreement, except and only to the extent applicable law expressly permits; or (c) publish the SDK for others to copy; or (d) rent, lease or lend the SDK.
|
|
12
|
+
|
|
13
|
+
(3) USE OF THE SERVICES. Your use of the Services, and the use of the Services by anyone hosting or using your Authorized Application, is governed by the then-current Terms of Services ("TOS") which can be found at: https://sendbird.com/terms.
|
|
14
|
+
|
|
15
|
+
(4) EXPORT RESTRICTIONS. THE SDK IS SUBJECT TO UNITED STATES EXPORT LAWS AND REGULATIONS. YOU MUST COMPLY WITH ALL DOMESTIC AND INTERNATIONAL EXPORT LAWS AND REGULATIONS THAT APPLY TO THE SDK.
|
|
16
|
+
|
|
17
|
+
(5) FEEDBACK. By submitting feedback to Sendbird, either via email at support@sendbird.com or by any other means: You automatically grant to Sendbird a perpetual, irrevocable, transferable, royalty-free license to use Your feedback for any and all purposes without any compensation to You.
|
|
18
|
+
|
|
19
|
+
(6) TERMINATION. Sendbird reserves the right to discontinue offering the SDK or Services or to modify the SDK or Services at any time in its sole discretion. This Section and Sections 3, 4, 5, 8, 9, 10, 11, and 12 will survive termination of this agreement or any discontinuation of the offering of the SDK or Services along with any other provisions that would reasonably be deemed to survive such events.
|
|
20
|
+
|
|
21
|
+
(7) RESERVATION OF RIGHTS. You are not authorized to alter, modify, copy, edit, format, create derivative works of or otherwise use any materials, content or technology provided under this agreement except as explicitly provided in this agreement or approved in advance in writing by Sendbird.
|
|
22
|
+
|
|
23
|
+
(8) MODIFICATIONS; NOTICES. If we change this contract, then we will give you notice before the change is in force. If you do not agree to these changes, then you must cancel and stop using the SDK and Services before the changes are in force. If you do not stop using the SDK or Services, then your use of the SDK or Services will continue under the changed contract. Sendbird may give notices to You, at Sendbird's option, by posting on any portion of sendbird.com or by electronic mail to any e-mail address provided by You to Sendbird.
|
|
24
|
+
|
|
25
|
+
(9) ENTIRE AGREEMENT. This agreement, and any applicable TOS or contract for Services, are the entire agreement with respect to the SDK or Services.
|
|
26
|
+
|
|
27
|
+
(10) APPLICABLE LAW AND VENUE. California state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where You live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort. You agree that any action brought under this agreement will be subject to exclusive jurisdiction and venue in the state and federal courts located in San Francisco, California.
|
|
28
|
+
|
|
29
|
+
(11) DISCLAIMER OF WARRANTY. The SDK is licensed "as-is." You bear the risk of using it. Sendbird gives no express or implied warranties, guarantees or conditions. You may have additional consumer rights under Your local laws which this agreement cannot change. To the extent permitted under Your local laws, Sendbird excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement. Sendbird does not represent or warrant that the SDK or the Services will always be available, uninterrupted, secure, or error free.
|
|
30
|
+
|
|
31
|
+
(12) LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. You can recover from Sendbird and its suppliers only direct damages up to U.S. $5.00. You cannot recover any other damages, including consequential, lost profits, special, indirect or incidental damages. This limitation applies to:
|
|
32
|
+
|
|
33
|
+
a. anything related to the SDK, services, or content (including code) on third party Internet sites, or third party programs; and
|
|
34
|
+
|
|
35
|
+
b. claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.
|
package/README.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
# Sendbird AI Agent Messenger for React-Native
|
|
2
|
+
|
|
3
|
+
A React-Native component library for integrating Sendbird's AI Agent chatbot functionality into your React-Native applications. This package provides pre-built UI components and hooks to quickly add intelligent conversational AI to your mobile app.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react"),y=require("react-native"),lt=require("react-native-safe-area-context"),F=require("@sendbird/chat"),z=require("@sendbird/chat/aiAgent"),ct=require("@sendbird/uikit-tools"),ce=require("date-fns"),Nt=require("@sendbird/chat/message"),Ce=require("@sendbird/chat/groupChannel"),bn=require("date-fns/locale/de"),En=require("date-fns/locale/en-US"),Cn=require("date-fns/locale/es"),vn=require("date-fns/locale/fr"),Sn=require("date-fns/locale/hi"),An=require("date-fns/locale/it"),wn=require("date-fns/locale/ja"),xn=require("date-fns/locale/ko"),Tn=require("date-fns/locale/pt"),In=require("date-fns/locale/tr"),kn=require("date-fns/isSameDay"),Mn=require("@react-native-clipboard/clipboard"),Pn=require("react-native-code-highlighter"),Ln=require("react-syntax-highlighter/dist/esm/styles/hljs"),Dn=require("react-native-markdown-display"),Ae=e=>e&&e.__esModule?e:{default:e};function Rn(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const s=Rn(d),Bn=Ae(F),Hn=Ae(Mn),On=Ae(Pn),Nn=Ae(Dn),q=(e,t)=>{const n=d.createContext(null),r=({children:i,value:c})=>s.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),o=({children:i})=>s.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):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`,r.displayName=`${e}Provider`,o.displayName=`${e}Consumer`,a.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:a}};function oe(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:a}){const[i,c]=d.useState(()=>e.template),[l,u]=d.useState(e.components),g={Template:i,updateTemplate:m=>c(()=>m),components:l,updateComponent:(m,h)=>u(p=>({...p,[m]:h}))};return s.createElement(t.Provider,{value:g},a)}function r({template:a,children:i}){const{updateTemplate:c}=d.useContext(t);return d.useLayoutEffect(()=>{a&&c(a)},[a]),s.createElement(s.Fragment,null,i)}function o({children:a}){return s.createElement(n,null,a)}return o.defaults=e,o.useContext=()=>d.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(a=>{o[a]=function({component:c}){const{updateComponent:l}=d.useContext(t);return d.useLayoutEffect(()=>{c&&l(a,c)},[c]),null}}),o}function $n(...e){return function({children:n}){return e.reduce((r,o)=>s.createElement(o,null,r),n)}}const me=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===z.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},$t=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===z.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function ge(e){var n,r,o;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((o=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:o.timestamp))=="number"}function Fn(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Ct(e){return!!e&&e<Date.now()}function Un(e){return!e.title}function zn(e,t){if(e)return Un(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:{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 qn(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 Wn(e,t,n){var i;const r=new Date,o=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),a=ce.differenceInMinutes(r,o);return a<1?t.justNow:a<60?t.minutesAgo(a):ce.isToday(o)?t.hoursAgo(ce.differenceInHours(r,o)):n(o,t.dateShortFormat)}const Gn="1.6.4",ie="sb-agent",jn=Gn,Ft="KEY_IMG_ASPECT_RATIO",w={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},ee=e=>!!e&&"sender"in e,Vn=e=>ee(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Kn=(e,t,n,r=!0)=>{if(!r||!ee(e))return"single";const o=()=>{if(!t||!ee(t))return!1;const l=t.sender.userId===e.sender.userId,u=ce.isSameMinute(t.createdAt,e.createdAt);return l&&u},a=()=>{if(!n||!ee(n))return!1;const l=n.sender.userId===e.sender.userId,u=ce.isSameMinute(n.createdAt,e.createdAt);return l&&u},i=o(),c=a();return i&&c?"middle":i?"bottom":c?"top":"single"},de=(e,t)=>(()=>{var r;return ee(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,fe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>ee(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>ee(e)&&(e.sender.userId===t||e.sendingStatus===Nt.SendingStatus.PENDING)},Yn=e=>e.startsWith("image/"),ut=(e,t)=>{if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}return"FILE"},Ut=e=>e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.message.length>0,dt=e=>{switch(e){case"top":case"middle":return w.GAP_GROUPED;default:return w.GAP_UNGROUPED}},Zn=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(a,...i)=>{const[c,l,u]=i;return o<u&&r.push({type:"text",value:e.slice(o,u).trim()}),r.push({type:"code",value:l.trim(),language:c?c.trim():"plaintext"}),o=u+a.length,a}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),r},Xn=e=>e.replace(/\[([^\]]+)](?!\()/g,"\\[$1\\]").replace(/~~/g,"\\~\\~");function Ve(){}function Jn(){const e=/iPad|iPhone|iPod/.test(navigator.userAgent),t=/Android/.test(navigator.userAgent);return e||t}function Qn(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 vt=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},zt={isStreaming(e){const t=vt(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(de(e,t)){const r=vt(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},checkExtendedFieldPresence(e){const t=e.extendedMessagePayload||{},n=i=>i.some(c=>typeof t[c]<"u"),r=n(Pe.ui),o=n(Pe.trail),a=n(Pe.marking);return{ui:r,trail:o,marking:a}},shouldScrollToBottom(e,t,n=!1){if(de(e,t)){if(this.isGeneratedMessage(e)&&this.isStreaming(e))return!0;const{ui:r,trail:o,marking:a}=this.checkExtendedFieldPresence(e);return r?!(!n&&a):!!(n&&(o||a))}return!0}},Pe={ui:["suggested_replies","cta_button","message_template","csat"],trail:["groundedness","manual","function_calls"],marking:["is_hallucination","is_moderated","flagged_types"]},Le=`@${ie}`,St=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Le}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}-template/message-template/tokens`,messengerSession:o=>{const a=Qn(`${e}/${t}/${o}`);return`${Le}-udata/${a}`},anonUserSession:()=>`${Le}-session/${e}/${t}`};return{template:{set:(o,a)=>n.set(r.template(o),a),get:o=>n.get(r.template(o)),setCachedToken:o=>n.set(r.templateToken(),o),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:o=>{try{const a=n.get(r.messengerSession(o));return a?JSON.parse(a):null}catch{return null}},setSettings:(o,a)=>{try{delete a.auto_created_user;const i=JSON.stringify(a);n.set(r.messengerSession(o),i)}catch{return}},getAnonUser:()=>{try{const o=n.get(r.anonUserSession());return o?JSON.parse(o):null}catch{return null}},setAnonUser:o=>{try{const a=JSON.stringify(o);n.set(r.anonUserSession(),a)}catch{return}},clear:o=>{try{n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}};class er{constructor(t){this.logger=t,this.subscribers={}}async send(t){const n=tr(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(a=>a(t.payload));await Promise.all(o).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(r=>r!==n))}}const tr=()=>{let e=Ve,t=Ve;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var qt=(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))(qt||{});class Wt{constructor(t){this.level=t}verbose(...t){this.level<=0&&console.log(`[${ie}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${ie}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${ie}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${ie}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${ie}/error]`,...t)}}function At(e,t,n){const r=Bn.default.init({appId:e,modules:[new Ce.GroupChannelModule,new z.AIAgentModule],localCacheEnabled:!0,options:new F.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...n});return r.addSendbirdExtensions([{version:jn,product:F.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),r}function nr(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 De={conversation:{isTalkToAgentViewEnabled:!0}},wt=e=>e?{...De,...e,conversation:{...De.conversation,...e==null?void 0:e.conversation}}:De,{Provider:rr,useContext:W}=q("AIAgent");function or({appId:e,aiAgentId:t,keyValueStorage:n,language:r,countryCode:o,context:a,queryParams:i,config:c,chatSDK:l,chatParams:u,children:g,logger:m,dispatcher:h,extensions:p={platform:F.SendbirdPlatform.JS,deviceOSPlatform:Jn()?F.DeviceOsPlatform.MOBILE_WEB:F.DeviceOsPlatform.WEB}}){const[f,C]=d.useState(()=>{const v=m??new Wt(qt.WARN),b=h??new er(v);return{appId:e,aiAgentId:t,language:r,countryCode:o,context:a,queryParams:i,config:wt(c),keyValueStorage:n,logger:v,dispatcher:b,chatSDK:l??At(e,p,u),cache:St({appId:e,aiAgentId:t,storage:n})}});return d.useEffect(()=>{C(v=>{let b=v.logger,T=v.dispatcher,S=v.chatSDK;return m&&m!==v.logger&&(b=m),h&&h!==v.dispatcher&&(T=h),l&&l!==v.chatSDK?S=l:!l&&v.chatSDK.appId!==e&&(S=At(e,p,{newInstance:!0,...u})),{...v,appId:e,aiAgentId:t,keyValueStorage:n,language:r,countryCode:o,context:a,queryParams:i,config:wt(c),logger:b,dispatcher:T,chatSDK:S,cache:St({appId:e,aiAgentId:t,storage:n})}})},[e,t,r,o,a,c,m,h,l]),d.useEffect(()=>()=>{f.chatSDK.disconnectWebSocket()},[f.chatSDK]),nr(f.chatSDK),s.createElement(rr,{value:f},g)}const sr=(e,t,n)=>ct.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0});var Ke=(e=>(e.ConversationClose="conv.close",e))(Ke||{});const Ye={DEFAULT_BOT_MSG_BG:"#eeeeee",WHITE:"#ffffff",BLACK:"#000000"};function Gt(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function ar(e){const t=Gt(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function ir(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function lr(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),a=r-o;let i=0,c=0;const l=(r+o)/2;return r!==o&&(c=l>.5?a/(2-r-o):a/(r+o)),r===e?i=(t-n)/a+(t<n?6:0):r===t?i=(n-e)/a+2:r===n&&(i=(e-t)/a+4),i/=6,[i,c,l]}function cr(e,t,n){let r,o,a;if(t===0)r=o=a=n;else{const i=function(g,m,h){return h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?g+(m-g)*6*h:h<.5?m:h<.6666666666666666?g+(m-g)*(.6666666666666666-h)*6:g},c=n<.5?n*(1+t):n+t-n*t,l=2*n-c;r=i(l,c,e+1/3),o=i(l,c,e),a=i(l,c,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(a*255)]}function pe(e,t,n){const[r,o,a]=ar(e),[i,c,l]=lr(r,o,a),u=Math.max(0,Math.min(1,l*t)),g=Math.max(0,Math.min(1,c*n)),[m,h,p]=cr(i,g,u);return ir([Math.round(m),Math.round(h),Math.round(p)])}function ur(e,t="light"){return{extraDark:pe(e,.6,1.2),dark:pe(e,.85,1.1),main:e,light:pe(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:pe(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function xt(e){const t=Gt(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,a=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+a*.114>n?Ye.BLACK:Ye.WHITE}function dr(e,t,n,r,o){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:o,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100}}}const mr=(e,t,n,r,o)=>({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:o,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400}}),_e={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},Re={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 Tt(e){const t=gr(e),{colors:n,aiAgentColorVariables:r}=hr(e,t),o=pr(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:o}}function gr({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===_e.primary.main?_e.primary:ur(n,e):_e.primary;return{..._e,primary:r,...t}}function hr({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const a=o.primary.main,i=t??xt(a),c=n??Ye.DEFAULT_BOT_MSG_BG,l=r??xt(c);return{colors:(e==="light"?dr:mr)(o,a,i,c,l),aiAgentColorVariables:{primary_color:a,bot_message_bg_color:c,primary_contrast_color:i,bot_message_bg_contrast_color:l}}}function fr(e,t,n){const r={...e};return n.forEach(o=>{const a=t[o];a!=null&&(r[o]=a)}),r}function pr({typography:e}){if(!e)return Re;const t={...Re};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=Re[n],a=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=fr(o,r,a)}}),t}const{Provider:_r,useContext:yr}=q("AIAgentTheme");function br({logger:e,palette:t,typography:n,appearance:r,children:o}){const a=d.useRef(null),[i,c]=d.useState(()=>Tt({selectedTheme:(r==null?void 0:r.theme)??"light",palette:t,typography:n,primary:r==null?void 0:r.primaryColor,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor})),l=d.useCallback((u,g)=>{g&&(a.current=g);const m=(r==null?void 0:r.theme)??u,h=a.current?a.current.themes[m]:null,p={primary:r==null?void 0:r.primaryColor,primaryContrast:void 0,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!p.primary&&(h!=null&&h.primary_color)&&(p.primary=h.primary_color,p.primaryContrast=h.primary_contrast_color),!p.botMessageBackground&&(h!=null&&h.bot_message_bg_color)&&(p.botMessageBackground=h.bot_message_bg_color,p.botMessageBackgroundContrast=h.bot_message_bg_contrast_color);const f=Tt({selectedTheme:m,palette:t,typography:n,...p});c(f),e==null||e.info("theme.update:",m)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor,t,n,e]);return d.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&l(i.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),s.createElement(_r,{value:{theme:i,updateTheme:l}},o)}function jt(){const{chatSDK:e,logger:t}=W();return d.useCallback(async n=>{if(n.userId===""){const r=new Error("userId cannot be empty string for messenger settings request");throw t.error("requestMessengerSettings: invalid userId",r),r}return await e.aiAgent.requestMessengerSettings(n)},[e,t])}function Er(){const{chatSDK:e,logger:t}=W(),n=d.useCallback(async(o,a,i)=>{if(t.debug("useChatConnection.connect: start, session",o.userId),a){const c=new F.SessionHandler({...a,onSessionTokenRequired:Cr(a.onSessionTokenRequired,i)});e.setSessionHandler(c)}try{return await e.connect(o.userId,o.authToken),t.debug("useChatConnection.connect: end, currentUser",e.currentUser),e.currentUser}catch(c){const l=c;if(e.isCacheEnabled){if(Sr(l))t.warn("useChatConnection.connect","offline connect restricted",l.message,l.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",l.message,l.code),l}},[e,t]),r=d.useCallback(async()=>{t.debug("useChatConnection.disconnect: start"),await e.disconnect(),t.debug("useChatConnection.disconnect: end")},[e,t]);return{connect:n,disconnect:r}}function Cr(e,t){if(e)return async(n,r)=>{new Promise((o,a)=>e==null?void 0:e(o,a)).then(o=>{o&&(t==null||t(o)),n(o)}).catch(o=>{r(o)})}}const vr=[400300,400301,400302,400310];function Sr(e){return vr.some(t=>e.code===t)}class mt{constructor({userId:t,authToken:n,sessionHandler:r}){this.userId=t,this.authToken=n,this.sessionHandler=r}}class ve{}const Ar=24*60*60*1e3,wr=e=>{const{logger:t,cache:n}=W(),r=()=>{const a=n.messenger.getAnonUser();return a?a.expireAt-Ar<=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},o=()=>{if(!e||e instanceof ve)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 mt?{type:"manual",userSessionCandidate:o()}:e instanceof ve?{type:"anonymous",userSessionCandidate:r()}:e&&typeof e=="object"?(t.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:o()}):e===void 0?(t.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:r()}):{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 xr({userSessionInfo:e,onUpdateMessengerSettings:t,onPreAuth:n,onPostAuth:r,onErrorAuth:o,onAuthTokenRefreshed:a,onPostDeauth:i,forceCreateChannel:c}){const{aiAgentId:l,language:u,context:g,countryCode:m,logger:h,cache:p}=W(),{connect:f,disconnect:C}=Er(),{type:v,userSessionCandidate:b}=wr(e),T=jt(),S=d.useCallback(async()=>{var L;h.debug("useAuthentication.authenticate: start");const A=b!=null&&b.userId?p.messenger.getSettings(b.userId):null;A!=null&&A.bot&&(t(A),h.debug("useAuthentication.authenticate: cached messenger settings",A));const I=await T({aiAgentId:l,userId:b==null?void 0:b.userId,language:u,country:m,context:g,forceCreateChannel:c,knownActiveChannelUrl:(L=A==null?void 0:A.active_channel)==null?void 0:L.channel_url});h.debug("useAuthentication.authenticate: messenger settings response",I);let E=null;if(I.auto_created_user)if(v==="manual")h.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),E={userId:b.userId,authToken:b.authToken};else{const{user_id:D,session_token:G,expire_at:j}=I.auto_created_user;p.messenger.setAnonUser({userId:D,authToken:G,expireAt:j}),E={userId:D,authToken:G}}else E={userId:(b==null?void 0:b.userId)??"",authToken:(b==null?void 0:b.authToken)??""};p.messenger.setSettings(E.userId,I),t(I);try{await n(I,E),await f(E,b==null?void 0:b.sessionHandler,a),await r(I,E)}catch(D){throw D instanceof Error&&(o(D),h.error("useAuthentication.authenticate: failed to connect",D)),D}return I},[T,f,v,b==null?void 0:b.userId,b==null?void 0:b.sessionHandler,b==null?void 0:b.authToken,p.messenger.setAnonUser,p.messenger.getSettings,p.messenger.setSettings,t,n,r,o,a]),H=d.useCallback(async()=>{h.debug("useAuthentication.deauthenticate: start"),await C(),i(),h.debug("useAuthentication.deauthenticate: completed")},[C,h,i]);return{authenticate:S,deauthenticate:H,userSessionCandidate:b}}const Tr=e=>JSON.parse(e),Ir=()=>{const{chatSDK:e,logger:t,cache:n}=W(),r=d.useCallback(()=>{var c,l;const a=(l=(c=e.appInfo)==null?void 0:c.aiAgentInfo)==null?void 0:l.templateListToken;if(!a)return!1;const i=n.template.getCachedToken();return i?a!==i:!0},[e,n.template.getCachedToken]),o=d.useCallback(async()=>{try{const{templates:a,token:i}=await e.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of a){const{key:l}=Tr(c);n.template.set(l,c)}n.template.setCachedToken(i)}catch(a){t==null||t.error("messageTemplateContext.syncCachedTemplates: error:",a)}},[e,t,n.template.set,n.template.setCachedToken]);return{shouldSyncCachedTemplate:r,syncCachedTemplates:o}};var be=(e=>(e.OFF="off",e.ALWAYS="always",e.HANDED_OFF_ONLY="handed_off_only",e))(be||{});const kr={off:"off",always:"always",handed_off_only:"handed_off_only"},{Provider:Mr,useContext:gt}=q("AIAgentMessengerSession"),Pr=d.forwardRef(function({userSessionInfo:e,forceCreateChannel:t,children:n},r){const{appId:o,aiAgentId:a,chatSDK:i,language:c,countryCode:l,context:u,cache:g,logger:m}=W(),{updateTheme:h}=yr(),[p,f]=d.useState(void 0),[C,v]=d.useState(void 0),[b,T]=d.useState(null),[S,H]=d.useState(null),[A,I]=d.useState(null),[E,L]=d.useState(null),[D,G]=d.useState("handed_off_only"),{shouldSyncCachedTemplate:j,syncCachedTemplates:Y}=Ir(),J=jt(),{authenticate:ne,deauthenticate:se}=xr({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(P=>{const{appearance:k,bot:M,launcher:U,active_channel:ae}=P;h(k.selected_theme,k),I({userId:M.bot_userid,profileUrl:M.bot_profile_url,nickname:M.bot_nickname,replyToFile:M.reply_to_file,specialNotice:M.special_notice,specialNoticeEnabled:M.is_special_notice_enabled,showHandoffButton:M.show_handoff_button??!0,isMultipleActiveConversationsEnabled:M.is_multiple_active_conversations_enabled??!0}),L({type:U.image_type||"default_icon",imageUrl:U.image_url}),G(kr[ae.attachment_mode]??"handed_off_only")},[h]),onPreAuth:d.useCallback((P,k)=>{f(void 0),H(k)},[]),onPostAuth:d.useCallback(async P=>{T(i.currentUser),j()&&await Y(),v({url:P.active_channel.channel_url,status:z.ConversationStatus.OPEN})},[j,Y]),onErrorAuth:d.useCallback(P=>{f(P)},[]),onAuthTokenRefreshed:d.useCallback(P=>{H(k=>k?{...k,authToken:P}:null)},[]),onPostDeauth:d.useCallback(()=>{g.template.clear(),S!=null&&S.userId&&g.messenger.clear(S.userId),T(null),v(void 0),H(null),I(null),L(null)},[g.template.clear,S])}),he=d.useCallback(async()=>{var P;if(S){m.debug("agentMessengerSession.refreshActiveChannel: try to refresh active channel"),v(void 0);const k=await J({aiAgentId:a,userId:S.userId,language:c,country:l,context:u,forceCreateChannel:t,knownActiveChannelUrl:(P=g.messenger.getSettings(S.userId))==null?void 0:P.active_channel.channel_url});return g.messenger.setSettings(S.userId,k),v({url:k.active_channel.channel_url,status:z.ConversationStatus.OPEN}),m.info("agentMessengerSession.refreshActiveChannel: refreshed active channel",k.active_channel.channel_url),k.active_channel.channel_url}else throw m.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")},[J,o,a,S==null?void 0:S.userId,c,l,u,t,g.messenger.getSettings,g.messenger.setSettings]),Z=d.useCallback(async P=>{if(!(S!=null&&S.userId))throw new Error("Current user is not authenticated. Please authenticate first.");const k=await J({...P,userId:S.userId,knownActiveChannelUrl:void 0}),M=k.active_channel.channel_url;return g.messenger.setSettings(S.userId,k),M},[S==null?void 0:S.userId,J]);return ct.useGroupChannelHandler(i,{onChannelChanged:P=>{var k;P.isGroupChannel()&&P.url===(C==null?void 0:C.url)&&(m.info("agentMessengerSession.channelChanged: channel.conversation",P.conversation),v({url:P.url,status:((k=P.conversation)==null?void 0:k.status)??z.ConversationStatus.OPEN}))}}),d.useImperativeHandle(r,()=>{const P=async()=>{if(!C)throw new Error("No active conversation. Please start a conversation first.");return await i.groupChannel.getChannel(C.url)};return{activeChannel:C,chatSDK:i,authenticate:ne,deauthenticate:se,updateContext:async k=>{const U=await(await P()).updateContext(a,k);return{...U,context:U.context??{}}},patchContext:async k=>{const U=await(await P()).patchContext(a,k);return{...U,context:U.context??{}}},getContextObject:async()=>{const M=await(await P()).getContextObject(a);return{...M,context:M.context??{}}}}},[ne,se,C,i,a,m]),s.createElement(Mr,{value:{sdkUser:b,userSessionInfo:e,userSession:S,activeChannel:C,setActiveChannel:v,refreshActiveChannel:he,createConversation:Z,connectionError:p,aiAgentInfo:A,launcherInfo:E,authenticate:ne,deauthenticate:se,attachmentMode:D}},n)}),Vt=e=>{const{chatSDK:t}=W(),[n,r]=d.useState([]);return ct.useGroupChannelHandler(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const a=o.getTypingUsers();r(a)}}}),n},Lr=({channel:e,messages:t})=>{const{aiAgentInfo:n,userSession:r}=gt(),o=Dr(),a=Rr({channel:e,lastMessage:t[t.length-1],aiAgentUserId:(n==null?void 0:n.userId)??""}),i=Nr({shouldApply:!!(e!=null&&e.isAIAgent)&&!ge(e),isDisabledWhileAIResponding:a,lastMessage:t[t.length-1],currentUserId:(r==null?void 0:r.userId)??""});if(!e||!o)return{disabled:!0,disabledBy:"unavailable"};if(me(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Br(e))return{disabled:!0,disabledBy:"form_active"};const c=Hr(e);return c?{disabled:!0,disabledBy:c}:a||i?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},Dr=()=>{const e=d.useId(),{chatSDK:t}=W(),[n,r]=d.useState(!0);return d.useEffect(()=>{const o=new F.ConnectionHandler({onDisconnected:()=>r(!1),onConnected:()=>r(!0),onReconnectSucceeded:()=>r(!0)});return t.addConnectionHandler(e,o),()=>{t.removeConnectionHandler(e)}},[t]),n},Rr=({channel:e,lastMessage:t,aiAgentUserId:n})=>{const[r,o]=d.useState(!1),a=Vt(e);return d.useEffect(()=>{if(!t)return;const i=a.some(l=>l.userId===n),c=de(t,n)&&zt.isStreaming(t);o(!!(c||i))},[a,t,n]),r},Br=e=>{var i;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,o=r&&!r.submitted_at&&!r.canceled_at,a=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return o&&!a},Hr=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},Or=3e4,Nr=({shouldApply:e,lastMessage:t,isDisabledWhileAIResponding:n,currentUserId:r})=>{const[o,a]=d.useState(!1),i=d.useRef(null),c=t&&de(t,r)?t.createdAt:0;return d.useEffect(()=>{const l=()=>{i.current&&(clearTimeout(i.current),i.current=null),a(!1)},u=h=>{i.current&&clearTimeout(i.current),a(!0),i.current=setTimeout(()=>{a(!1),i.current=null},h)},g=Date.now()-c,m=Or-g;return n||m<=0?l():u(m),()=>{i.current&&clearTimeout(i.current)}},[n,c]),o&&e},{Provider:$r}=q("AIAgentConversation");function Fr({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedViaDispatcher:a,onBeforeSendMessage:i,onAfterSendMessage:c=Ve,shouldMarkAsRead:l=!0,sortComparator:u}){var H;const g=()=>l&&(f==null?void 0:f.markAsRead()),{chatSDK:m,logger:h,dispatcher:p}=W(),{channel:f,channelFetchError:C,fetchChannel:v}=Ur(t),b=sr(m,f,{shouldCountNewMessages:()=>!1,onChannelDeleted:n,onMessagesReceived:A=>r==null?void 0:r(A),onMessagesUpdated:A=>o==null?void 0:o(A),logger:h,markAsRead:g,sortComparator:u}),T=Lr({channel:f,messages:b.messages});d.useEffect(()=>{g()},[l]),d.useEffect(()=>{const A=async I=>{const E=typeof(I==null?void 0:I.channelUrl)=="string";f&&E&&I.channelUrl!==f.url||(h.debug("conversation.dispatcher: try to close conversation",f),f!=null&&f.conversation&&f.conversation.status===z.ConversationStatus.OPEN&&(await f.closeConversation(),a==null||a()))};return p.subscribe(Ke.ConversationClose,A),()=>{p.unsubscribe(Ke.ConversationClose,A)}},[p,(H=f==null?void 0:f.conversation)==null?void 0:H.status,a]);const S={conversation:(f==null?void 0:f.conversation)??void 0,channelSource:{channel:f,error:C,refetch:()=>v()},messageSource:{messages:b.messages,initialized:b.initialized,loadPrevious:()=>b.loadPrevious(),loadNext:()=>b.loadNext(),deleteMessage:A=>b.deleteMessage(A),sendUserMessage:async A=>{var E;if(((E=f==null?void 0:f.conversation)==null?void 0:E.status)===z.ConversationStatus.CLOSED)throw new Error("Conversation is closed");i&&(A=await i(A));const I=await b.sendUserMessage(A,c);return c==null||c(I),I},sendFileMessage:async A=>{var E;if(((E=f==null?void 0:f.conversation)==null?void 0:E.status)===z.ConversationStatus.CLOSED)throw new Error("Conversation is closed");i&&(A=await i(A));const I=await b.sendFileMessage(A,c);return c==null||c(I),I}},state:{input:T}};return s.createElement($r,{value:S},e)}function Ur(e){const{chatSDK:t,logger:n}=W(),[r,o]=d.useState(void 0),[a,i]=d.useState(void 0);async function c(){if(n.debug("conversation.fetchChannel: start"),o(void 0),i(void 0),e)try{n.debug("conversation.fetchChannel: get channel",e);const l=await t.groupChannel.getChannel(e);o(l),n.debug("conversation.fetchChannel: fetched channel",l)}catch(l){l instanceof F.SendbirdError&&i(l),n.error("conversation.fetchChannel: error",l)}}return zr(r),d.useEffect(()=>{c()},[t,e]),{channel:r,channelFetchError:a,fetchChannel:c}}function zr(e){const{chatSDK:t}=W(),{activeChannel:n,setActiveChannel:r}=gt(),o=d.useId();d.useEffect(()=>{if(!e||!n)return;const a=new F.ConnectionHandler({onReconnectSucceeded:async()=>{var c;const i=await e.refresh();i.url===n.url&&r({url:i.url,status:((c=i.conversation)==null?void 0:c.status)??z.ConversationStatus.OPEN})}});return t.addConnectionHandler(o,a),()=>{t.removeConnectionHandler(o)}},[t,e,n])}class qr{constructor(t,{filter:n,limit:r=20}){var o,a,i,c,l,u,g;this._isDisposed=!1,this._handlerId=`handler-id-${Date.now()}`,this._order=Ce.GroupChannelListOrder.LATEST_LAST_MESSAGE,this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(o=this.filter)==null?void 0:o.aiAgentChannelFilter,aiAgentConversationStatusFilter:(a=this.filter)==null?void 0:a.aiAgentConversationStatusFilter,aiAgentIds:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(c=this.filter)==null?void 0:c.deskChannelFilter,pinnedChannelUrls:(l=this.filter)==null?void 0:l.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._channelHandler=new Ce.GroupChannelHandler({onChannelChanged:m=>{m.isGroupChannel()&&(this._query.belongsTo(m)?this._addChannelsToView([m],!1):this._removeChannelsFromView([m.url]))},onChannelDeleted:m=>{this._removeChannelsFromView([m])}}),this._connectionHandler=new F.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)??[]),r=t.find(c=>!n.has(c.url));let o;r?o=((i=r.lastMessage)==null?void 0:i.createdAt)??r.createdAt:o=this._query.lastResponseAt,this._timestamp>o&&(this._timestamp=o)}async _syncChannelChangelogs(){if(this._isDisposed)return[];if(this._isSyncing)return[];try{this._isSyncing=!0;let t;for(this._token?t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter):t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByTimestamp(this._timestamp,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls);t.hasMore&&t.token;)t=await this._sdk.aiAgent.getMyGroupChannelChangeLogsByToken(this._token,this.filter),this._token=t.token,this._addChannelsToView(t.updatedChannels),this._removeChannelsFromView(t.deletedChannelUrls)}catch{}finally{this._isSyncing=!1}return[]}_upsertPinnedChannelsToArray(t){var c;const n=((c=this.filter)==null?void 0:c.pinnedChannelUrls)??[],r=new Map(n.map((l,u)=>[l,u])),o=[],a=[],i=[];for(const l of t){if(!this._query.belongsTo(l)){i.push(l.url);continue}const u=r.get(l.url);if(u===void 0)continue;const g=Ze(this._pinnedChannels,l);g>=0?(this._pinnedChannels.splice(g,1),a.push(l)):o.push(l);const h=this._pinnedChannels.findIndex(f=>(r.get(f.url)??1/0)>u),p=h===-1?this._pinnedChannels.length:h;this._pinnedChannels.splice(p,0,l)}return{addedChannels:o,updatedChannels:a,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const r=[],o=[],a=[];for(const i of t){if(!this._query.belongsTo(i)){r.push(i.url);continue}const c=Ze(this._channels,i),l=c<0;!l&&this._channels.splice(c,1);const g=Wr(this._channels,i,this._order).place,m=g===this._channels.length;l?m?(n||!this.hasMore)&&(this._channels.push(i),o.push(i)):(this._channels.splice(g,0,i),o.push(i)):(this._channels.splice(g,0,i),a.push(i))}return{addedChannels:o,updatedChannels:a,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var m,h,p,f,C;const r=new Set(((m=this.filter)==null?void 0:m.pinnedChannelUrls)??[]),o=[],a=[];for(const v of t)r.has(v.url)?o.push(v):a.push(v);const i=this._upsertPinnedChannelsToArray(o),c=this._upsertRegularChannelsToArray(a,n),l=i.addedChannels.concat(c.addedChannels),u=i.updatedChannels.concat(c.updatedChannels),g=i.unmatchedChannelUrls.concat(c.unmatchedChannelUrls);l.length>0&&((p=(h=this._collectionEventHandler)==null?void 0:h.onChannelsAdded)==null||p.call(h,{},l)),u.length>0&&((C=(f=this._collectionEventHandler)==null?void 0:f.onChannelsUpdated)==null||C.call(f,{},u)),g.length>0&&this._removeChannelsFromView(g)}_removeChannelsFromView(t){var o,a,i;const n=new Set(((o=this.filter)==null?void 0:o.pinnedChannelUrls)??[]),r=[];for(const c of t)if(n.has(c)){const l=this._pinnedChannels.findIndex(u=>u.url===c);l>=0&&(r.push(c),this._pinnedChannels.splice(l,1))}else{const l=this._channels.findIndex(u=>u.url===c);l>=0&&(r.push(c),this._channels.splice(l,1))}r.length>0&&((i=(a=this._collectionEventHandler)==null?void 0:a.onChannelsDeleted)==null||i.call(a,{},r))}get channels(){return this._isDisposed?[]:[...this._pinnedChannels,...this._channels]}get hasMore(){return this._isDisposed?!1:this._query.hasNext}async loadMore(){if(this._isDisposed)return[];if(this.hasMore){const t=await this._query.next();return this._setDefaultChangelogsSyncTimestamp(t),this._addChannelsToView(t,!0),t}return[]}setConversationListCollectionHandler(t){this._collectionEventHandler=t}dispose(){this._isDisposed||(this._isDisposed=!0,this._collectionEventHandler=void 0,this._sdk.removeConnectionHandler(this._handlerId),this._sdk.groupChannel.removeGroupChannelHandler(this._handlerId),this._pinnedChannels.length=0,this._channels.length=0)}}const Ze=(e,t)=>e.findIndex(n=>n.isIdentical(t)),Wr=(e,t,n)=>{if(e.length>0){const r=Ze(e,t);let o=0,a=e.length-1,i=Math.floor((o+a)/2);for(;o<a;){const l=It(e[i],t,n);if(l>0)a=i,i=Math.floor((o+a)/2);else if(l<0)o=i+1,i=Math.floor((o+a)/2);else return{place:i,oldPosition:r}}return{place:It(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},It=(e,t,n)=>{switch(n){case Ce.GroupChannelListOrder.LATEST_LAST_MESSAGE:if(e.lastMessage&&t.lastMessage){const r=t.lastMessage.createdAt-e.lastMessage.createdAt;return r===0?t.createdAt-e.createdAt:r}else return e.lastMessage?-1:t.lastMessage?1:t.createdAt-e.createdAt;default:return 0}};function Gr(e,t){var f,C,v,b,T,S,H,A,I,E;const n=d.useId(),[r,o]=d.useState(!1),[a,i]=d.useState(null),[c,l]=d.useState([]),[u,g]=d.useState(null),m=d.useRef(!1),h=d.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,o(!1),i(null),l([]);try{u==null||u.dispose();const L=new qr(e,t);L.setConversationListCollectionHandler({onChannelsAdded:()=>{l(L.channels)},onChannelsUpdated:()=>{l(L.channels)},onChannelsDeleted:()=>{l(L.channels)}}),await L.loadMore(),g(L),i(null)}catch(L){g(null),i(L)}finally{o(!0),m.current=!1}}},[e,e.currentUser,(f=t.filter)==null?void 0:f.aiAgentChannelFilter,(v=(C=t.filter)==null?void 0:C.aiAgentConversationStatusFilter)==null?void 0:v.join(),(T=(b=t.filter)==null?void 0:b.aiAgentIds)==null?void 0:T.join(),(S=t.filter)==null?void 0:S.deskChannelFilter,(A=(H=t.filter)==null?void 0:H.pinnedChannelUrls)==null?void 0:A.join(),(I=t.filter)==null?void 0:I.copilotConversationOnly,(E=t.filter)==null?void 0:E.copilotSupportChannelUrl,t.limit]),p=d.useCallback(async()=>{if(u)try{await u.loadMore()}catch(L){i(L)}},[u]);return d.useEffect(()=>(e.addConnectionHandler(n,new F.ConnectionHandler({onConnected:()=>h()})),()=>e.removeConnectionHandler(n)),[e,n,h]),d.useEffect(()=>{h()},[h]),d.useEffect(()=>()=>{m.current=!1,u==null||u.dispose()},[u]),{initialized:r,error:a,channels:c,loadMore:p}}const{Provider:jr}=q("AIAgentConversationList");function Vr({conversationListLimit:e,conversationListFilter:t,children:n}){var m,h;const{chatSDK:r,aiAgentId:o,queryParams:a}=W(),i={aiAgentIds:[o],aiAgentConversationStatusFilter:[z.ConversationStatus.CLOSED,z.ConversationStatus.OPEN]},c=e??((m=a==null?void 0:a.conversationListParams)==null?void 0:m.limit),l={...i,...(h=a==null?void 0:a.conversationListParams)==null?void 0:h.filter,...t},u=Gr(r,{limit:c,filter:l}),g={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return s.createElement(jr,{value:g},n)}function Kr(e){let t="pending",n=e.then(r=>{t="resolved",n=r}).catch(r=>{t="rejected",n=r});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:Yr}=q("MessageTemplateFetching");function Zr({children:e,internalVariables:t}){const n=d.useRef({}),r=d.useRef({}),[o,a]=d.useState({}),i=d.useCallback((u,g)=>{a(m=>({...m,[u]:{fetching:!1,error:!1,...m[u],...g}}))},[]),c=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:g,templateKey:m,suspense:h=!1})=>{const p=g(m);if(p)return p;const f=r.current[m];if(f)return f;h||i(m,{fetching:!0});const C=u(m).catch(v=>{throw h||i(m,{error:!0}),v}).finally(()=>{h||i(m,{fetching:!1}),delete r.current[m]});return r.current[m]=C,C},[i]),l={internalVariables:t,fetchTemplate:c,suspend:(u,g)=>{if(n.current[u])return n.current[u];const m=Kr(g());return n.current[u]=m,m},getIsFetching:u=>{var g;return((g=o[u])==null?void 0:g.fetching)??!1},getHasError:u=>{var g;return((g=o[u])==null?void 0:g.error)??!1}};return s.createElement(Yr,{value:l},e)}const Xr="remove_powered_by",ht=(e,t)=>{var o,a;const{chatSDK:n}=W(),{aiAgentInfo:r}=gt();if(e==="handoff-button"){const i=!!((o=t==null?void 0:t.conversation)!=null&&o.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&$t(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.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(Xr)),[i])}throw new Error("Unsupported feature")},Kt=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n)return{fallbackIcon:"bot-filled",url:void 0,title:""};const 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)??""}}};if(!e)return r.ai("bot-filled");const o=(()=>{const[a]=e.members.filter(i=>i.userId!==t.userId);return a})();return e.isAIAgent?ge(e)?r.human("agent"):r.ai("bot-filled"):e.isDesk?r.human("agent"):r.channel("user")},kt=e=>d.useReducer((t,n)=>({...t,...n}),e);var Q=(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))(Q||{});const 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.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Talk to agent"},conversation_list:{header_title:"Conversations",ended:"Ended"},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"}},Xe={language:"en",strings:Jr,dateLocale:En.enUS},Qr={conversation:{input_placeholder:"질문하기",input_placeholder_disabled:"이 채널에서는 채팅을 사용할 수 없습니다.",input_placeholder_wait_ai_agent_response:"상담사의 답변을 기다리는 중...",input_placeholder_active_form:"계속 진행하려면 양식을 작성해 주세요.",unknown_message_type:"(알 수 없는 메시지 유형)",powered_by:"Powered by",citation_title:"출처",start_new_conversation_label:"상담사와 대화"},conversation_list:{header_title:"대화",ended:"종료됨"},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:"다시 시도"}},Je={language:"ko",strings:Qr,dateLocale:xn.ko},eo={conversation:{input_placeholder:"質問する",input_placeholder_disabled:"このチャンネルではチャットを利用できません",input_placeholder_wait_ai_agent_response:"エージェントの返信を待っています…",input_placeholder_active_form:"続行するには、フォームに記入してください。",unknown_message_type:"(不明なメッセージタイプ)",powered_by:"Powered by",citation_title:"出典",start_new_conversation_label:"エージェントと話す"},conversation_list:{header_title:"会話",ended:"終了"},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:"再試行"}},Qe={language:"ja",strings:eo,dateLocale:wn.ja},to={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.",unknown_message_type:"(Tipo de mensaje desconocido)",powered_by:"Desarrollado por",citation_title:"Fuente",start_new_conversation_label:"Hablar con un agente"},conversation_list:{header_title:"Conversaciones",ended:"Finalizado"},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"}},et={language:"es",strings:to,dateLocale:Cn.es},no={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.",unknown_message_type:"(Tipo de mensagem desconhecido)",powered_by:"Desenvolvido por",citation_title:"Fonte",start_new_conversation_label:"Falar com agente"},conversation_list:{header_title:"Conversas",ended:"Encerrada"},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"}},tt={language:"pt",strings:no,dateLocale:Tn.pt},ro={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.",unknown_message_type:"(Type de message inconnu)",powered_by:"Propulsé par",citation_title:"Source",start_new_conversation_label:"Parler à un agent"},conversation_list:{header_title:"Conversations",ended:"Terminée"},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"}},nt={language:"fr",strings:ro,dateLocale:vn.fr},oo={conversation:{input_placeholder:"एक प्रश्न पूछें",input_placeholder_disabled:"इस चैनल में चैट उपलब्ध नहीं है",input_placeholder_wait_ai_agent_response:"एजेंट के उत्तर की प्रतीक्षा कर रहे हैं...",input_placeholder_active_form:"आगे बढ़ने के लिए कृपया फॉर्म भरें।",unknown_message_type:"(अज्ञात संदेश प्रकार)",powered_by:"द्वारा संचालित",citation_title:"स्रोत",start_new_conversation_label:"एजेंट से बात करें"},conversation_list:{header_title:"बातचीत",ended:"समाप्त"},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:"पुनः प्रयास करें"}},rt={language:"hi",strings:oo,dateLocale:Sn.hi},so={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.",unknown_message_type:"(Tipo di messaggio sconosciuto)",powered_by:"Powered by",citation_title:"Fonte",start_new_conversation_label:"Parla con un agente"},conversation_list:{header_title:"Conversazioni",ended:"Terminata"},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"}},ot={language:"it",strings:so,dateLocale:An.it},ao={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.",unknown_message_type:"(Unbekannter Nachrichtentyp)",powered_by:"Unterstützt von",citation_title:"Quelle",start_new_conversation_label:"Mit Agent sprechen"},conversation_list:{header_title:"Gespräche",ended:"Beendet"},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"}},st={language:"de",strings:ao,dateLocale:bn.de},io={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.",unknown_message_type:"(Bilinmeyen mesaj türü)",powered_by:"Tarafından desteklenmektedir",citation_title:"Kaynak",start_new_conversation_label:"Temsilciyle konuş"},conversation_list:{header_title:"Görüşmeler",ended:"Sona erdi"},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"}},at={language:"tr",strings:io,dateLocale:In.tr},X=e=>({conversation:e.conversation,conversation_list:e.conversation_list,date_format:e.date_format,csat:e.csat,form:e.form,common:e.common}),Mt=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??we},we="en",ft={borderColor:"red",borderWidth:y.StyleSheet.hairlineWidth},_=({debug:e=!1,style:t,children:n,...r})=>s.createElement(y.View,{style:[t,r,e&&ft],...r},n);_.Animated=({debug:e=!1,style:t,children:n,...r})=>s.createElement(y.Animated.View,{style:[t,r,e&&ft],...r},n);const lo={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},te=(e,t=y.I18nManager.isRTL?"rtl":"ltr")=>{const n=lt.useSafeAreaInsets();return e.reduce((r,o)=>{const a=lo[t][o];return r[a]=n[o],r},{})},{Provider:co,useContext:V}=q("MessengerSession"),uo=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof ve||t.userSessionInfo instanceof mt))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return s.createElement(Pr,{ref:n,...t},r=>s.createElement(mo,{...r},e))}),mo=({children:e,...t})=>{const{userSession:n,aiAgentInfo:r,launcherInfo:o}=t;return s.createElement(co,{value:{...t,userSession:n,aiAgentInfo:r,launcherInfo:o}},e)},{Provider:go,useContext:$}=q("MessengerTheme"),ho=({children:e,...t})=>s.createElement(br,{...t,appearance:{theme:t.mode??"light"}},n=>{const r=fo(n.theme);return s.createElement(go,{value:{...n,themedColor:r}},e)});function fo(e){return e.selectedTheme==="light"?{textHighEmphasis:e.palette.onlight.textHighEmphasis,textMidEmphasis:e.palette.onlight.textMidEmphasis,textLowEmphasis:e.palette.onlight.textLowEmphasis,textDisabled:e.palette.onlight.textDisabled,textHighEmphasisInverse:e.palette.ondark.textHighEmphasis,textMidEmphasisInverse:e.palette.ondark.textMidEmphasis,textLowEmphasisInverse:e.palette.ondark.textLowEmphasis,textDisabledInverse:e.palette.ondark.textDisabled,bg_50_600:e.palette.background50,bg_100_500:e.palette.background100,bg_200_400:e.palette.background200,primary:e.palette.primary.main,secondary:e.palette.secondary.main,error:e.palette.error.main,information:e.palette.information.light,overlay:e.palette.overlay.light}:{textHighEmphasis:e.palette.ondark.textHighEmphasis,textMidEmphasis:e.palette.ondark.textMidEmphasis,textLowEmphasis:e.palette.ondark.textLowEmphasis,textDisabled:e.palette.ondark.textDisabled,textHighEmphasisInverse:e.palette.onlight.textHighEmphasis,textMidEmphasisInverse:e.palette.onlight.textMidEmphasis,textLowEmphasisInverse:e.palette.onlight.textLowEmphasis,textDisabledInverse:e.palette.onlight.textDisabled,bg_50_600:e.palette.background600,bg_100_500:e.palette.background500,bg_200_400:e.palette.background400,primary:e.palette.primary.light,secondary:e.palette.secondary.light,error:e.palette.error.light,information:e.palette.information.light,overlay:e.palette.overlay.dark}}const R={create:e=>{const t=new WeakMap,n=r=>{const o=t.get(r.theme);if(o)return o;const a=e(r),i={},c={};for(const g in a)typeof a[g]=="function"?c[g]=a[g]:i[g]=a[g];const u={...y.StyleSheet.create(i),...c};return t.set(r.theme,u),u};return{use:()=>{const r=$(),o=lt.useSafeAreaInsets();return n({...r,edgeInsets:o,select:a=>a[r.theme.selectedTheme]})}}}},po={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")},_o={send:!0,chat:!0,message:!0},O=({customSource:e,type:t,color:n,size:r=24,style:o})=>{const a=yo.use(),i=y.I18nManager.isRTL&&!!_o[t];return s.createElement(_,{alignItems:"center",justifyContent:"center"},s.createElement(y.Image,{resizeMode:"contain",source:e??po[t],style:[a.icon({color:n,size:r,mirror:i}),o]}))},yo=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})})),x=({variant:e="body1",color:t,style:n,...r})=>{const{theme:o,themedColor:a}=$(),i=d.useMemo(()=>{const c=o.typography[e]??o.typography.body1,l=typeof t=="function"?t(a):t??a.textHighEmphasis;return{includeFontPadding:!1,...c,color:l}},[e,t,o.typography,a.textHighEmphasis]);return s.createElement(y.Text,{style:[i,n],...r})},pt=({iconSize:e=64,icon:t,style:n,label:r,children:o})=>{const{themedColor:a}=$();return s.createElement(_,{style:[Yt.body,n]},t&&s.createElement(O,{type:t,size:e,color:a.textLowEmphasis}),r&&s.createElement(x,{variant:"body1",color:a.textMidEmphasis},r),o)},bo=({children:e})=>{const{theme:t}=$();return s.createElement(_,{backgroundColor:t.colors.base.background,style:Yt.container},e)},Yt=y.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),Be=X(st.strings),Eo={...Be,conversation:{...Be.conversation,attachment_camera:"Kamera",attachment_photo:"Fotobibliothek",attachment_document:"Dateien"},conversation_list:{...Be.conversation_list,footer_title:"Mit Agent sprechen"}},Co={language:st.language,dateLocale:st.dateLocale,strings:Eo},He=X(Xe.strings),vo={...He,conversation:{...He.conversation,attachment_camera:"Camera",attachment_photo:"Photo library",attachment_document:"Files"},conversation_list:{...He.conversation_list,footer_title:"Talk to Agent"}},So={language:Xe.language,dateLocale:Xe.dateLocale,strings:vo},Oe=X(et.strings),Ao={...Oe,conversation:{...Oe.conversation,attachment_camera:"Cámara",attachment_photo:"Biblioteca de fotos",attachment_document:"Archivos"},conversation_list:{...Oe.conversation_list,footer_title:"Hablar con un agente"}},wo={language:et.language,dateLocale:et.dateLocale,strings:Ao},Ne=X(nt.strings),xo={...Ne,conversation:{...Ne.conversation,attachment_camera:"Caméra",attachment_photo:"Photothèque",attachment_document:"Fichiers"},conversation_list:{...Ne.conversation_list,footer_title:"Parler à un agent"}},To={language:nt.language,dateLocale:nt.dateLocale,strings:xo},$e=X(rt.strings),Io={...$e,conversation:{...$e.conversation,attachment_camera:"कैमरा",attachment_photo:"फोटो लाइब्रेरी",attachment_document:"फाइलें"},conversation_list:{...$e.conversation_list,footer_title:"एजेंट से बात करें"}},ko={language:rt.language,dateLocale:rt.dateLocale,strings:Io},Fe=X(ot.strings),Mo={...Fe,conversation:{...Fe.conversation,attachment_camera:"Fotocamera",attachment_photo:"Libreria foto",attachment_document:"File"},conversation_list:{...Fe.conversation_list,footer_title:"Parla con un agente"}},Po={language:ot.language,dateLocale:ot.dateLocale,strings:Mo},Ue=X(Qe.strings),Lo={...Ue,conversation:{...Ue.conversation,attachment_camera:"カメラ",attachment_photo:"フォトライブラリ",attachment_document:"ファイル"},conversation_list:{...Ue.conversation_list,footer_title:"エージェントと話す"}},Do={language:Qe.language,dateLocale:Qe.dateLocale,strings:Lo},ze=X(Je.strings),Ro={...ze,conversation:{...ze.conversation,attachment_camera:"카메라",attachment_photo:"사진 라이브러리",attachment_document:"파일"},conversation_list:{...ze.conversation_list,footer_title:"상담사와 대화"}},Bo={language:Je.language,dateLocale:Je.dateLocale,strings:Ro},qe=X(tt.strings),Ho={...qe,conversation:{...qe.conversation,attachment_camera:"Câmera",attachment_photo:"Biblioteca de fotos",attachment_document:"Arquivos"},conversation_list:{...qe.conversation_list,footer_title:"Falar com agente"}},Oo={language:tt.language,dateLocale:tt.dateLocale,strings:Ho},We=X(at.strings),No={...We,conversation:{...We.conversation,attachment_camera:"Kamera",attachment_photo:"Fotoğraf kitaplığı",attachment_document:"Dosyalar"},conversation_list:{...We.conversation_list,footer_title:"Temsilciyle konuş"}},$o={language:at.language,dateLocale:at.dateLocale,strings:No},Pt=new Map([["en",So],["ko",Bo],["ja",Do],["es",wo],["pt",Oo],["fr",To],["hi",ko],["it",Po],["de",Co],["tr",$o]]),Lt=e=>Pt.get(e)??Pt.get(we),Fo=(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}}:e,{Provider:Uo,useContext:N}=q("Localization"),zo=({language:e=we,logger:t,strings:n,children:r})=>{const[o,a]=d.useState(()=>{const i=Mt(e);return Lt(i)});return d.useEffect(()=>{var l;const i=Mt(e),c=Lt(i);c.language!==o.language&&(a(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:o.language,to:c.language}))},[e,t]),s.createElement(Uo,{value:{language:o.language,strings:Fo(o.strings,n),dateLocale:o.dateLocale,format:(i,c,l)=>ce.format(i,c,{locale:o.dateLocale,...l})}},r)},Zt=350,qo=({children:e,...t})=>s.createElement(y.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:Zt,...t},n=>typeof e=="function"?e(n):e),Wo=({children:e,style:t,...n})=>{const[r,o]=d.useState(!1),a={pressed:r};return s.createElement(y.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:Zt,style:typeof t=="function"?t(a):t,onPressIn:()=>o(!0),onPressOut:()=>o(!1),...n},typeof e=="function"?e(a):e)},B=e=>e.activeOpacity&&e.activeOpacity<1?s.createElement(Wo,{...e}):s.createElement(qo,{...e}),Go=({label:e,icon:t="error",action:n,...r})=>{const{strings:o}=N();return s.createElement(pt,{icon:t,label:e??o.common.placeholder_something_went_wrong,...r},n&&s.createElement(jo,{onPress:n.onPress,label:n.label??o.common.placeholder_something_went_wrong_retry_label}))},jo=({label:e,onPress:t})=>{const{themedColor:n}=$();return s.createElement(B,{onPress:t},s.createElement(_,{style:Vo.button},s.createElement(O,{type:"refresh",size:20}),s.createElement(x,{variant:"button",color:n.primary},e)))},Vo=y.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),Ko=({iconSize:e=48,style:t})=>{const n=d.useRef(new y.Animated.Value(0)).current;d.useEffect(()=>{const o=y.Animated.loop(y.Animated.timing(n,{toValue:1,duration:1e3,easing:y.Easing.linear,useNativeDriver:!0}));return o.start(),()=>{o.stop()}},[n]);const r=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return s.createElement(_.Animated,{style:[{transform:[{rotate:r}]},t]},s.createElement(O,{type:"spinner",size:e}))},Yo=({label:e,icon:t="chat",...n})=>{const{strings:r}=N();return s.createElement(pt,{icon:t,label:e??r.common.placeholder_no_conversations,...n})},Zo=({label:e,icon:t="message",...n})=>{const{strings:r}=N();return s.createElement(pt,{icon:t,label:e??r.common.placeholder_no_messages,...n})},Xo=e=>{const{components:t}=_t.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(bo,null,n)},_t=oe({template:Xo,components:{Loading:Ko,Error:Go,NoChannels:Yo,NoMessages:Zo}}),re=e=>{const{Template:t}=_t.useContext();return s.createElement(t,{...e})},Jo=50,{Provider:Qo,useContext:es}=q("ConversationScroll");function ts({scrollMode:e="auto",children:t}){const n=d.useRef(null),r=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),[o,a]=d.useState(0),[i,c]=d.useState(0),l=d.useCallback(()=>{const{shouldUpdate:T,shouldRecalc:S,contentHeight:H,contentSnapshotHeight:A,viewport:I}=r.current;T&&A<H&&a(E=>{r.current.shouldUpdate=!1;const L=H-E-A,D=Math.max(0,I-L);return E===0||D<E||S?(r.current.shouldRecalc=!1,D):E})},[]),u=d.useCallback(T=>{r.current.viewport=T.nativeEvent.layout.height},[]),g=d.useCallback((T,S)=>{r.current.contentHeight=S,l()},[]),m=d.useCallback(T=>{const S=T.nativeEvent.contentOffset.y;c(S)},[]),h=(()=>{if(e==="fixed")return{minIndexForVisible:1,autoscrollToTopThreshold:-1}})(),p=d.useCallback((T=!0)=>{var S;(S=n.current)==null||S.scrollToOffset({offset:0,animated:T})},[]),f=d.useCallback((T,S=!0)=>{var H;(H=n.current)==null||H.scrollToIndex({index:T,animated:S,viewPosition:1})},[]),C=d.useCallback(()=>{e==="fixed"&&(r.current.contentSnapshotHeight=r.current.contentHeight-o,r.current.shouldUpdate=!0,r.current.shouldRecalc=!0)},[e,o]),v=d.useCallback(()=>{e==="fixed"?f(0):p()},[e,p,f]),b=d.useCallback(()=>{e==="fixed"?r.current.shouldUpdate=!0:p()},[e,p]);return s.createElement(Qo,{value:{ref:n,state:{distanceFromBottom:i,isAtBottom:i<=Jo,bottomSpace:o},props:{maintainVisibleContentPosition:h,onLayout:u,onContentSizeChange:g,onScroll:m},actions:{scrollToBottom:p,scrollToIndex:f,onBeforeMessageSend:C,onAfterMessageSend:v,onStreamingUpdate:b}}},t)}function Xt(e){return new Promise((t,n)=>{y.Image.getSize(e,(r,o)=>{t({width:String(r),height:String(o)})},r=>{n(r)})})}async function ns(e){var t;if("file"in e&&e.file&&typeof e.file=="object"){const n=e.file;if(n.uri&&((t=n.type)!=null&&t.startsWith("image/")))try{const{width:r,height:o}=await Xt(n.uri);return new Nt.MessageMetaArray({key:Ft,value:[r,o]})}catch{return}}}function rs(e,t){let n=0,r=0;return ee(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),ee(t)&&t.sendingStatus!=="succeeded"&&(r=Number.MAX_SAFE_INTEGER),t.createdAt+r-(e.createdAt+n)}const{Provider:os,Context:ss,useContext:K}=q("Conversation"),Jt=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:r,children:o})=>{const a=es(),{activeChannel:i,refreshActiveChannel:c,sdkUser:l,authenticate:u}=V();d.useEffect(()=>{l||u()},[]);const g=d.useCallback(async p=>{a.actions.onBeforeMessageSend();const f=await ns(p);return{...p,metaArrays:f?[f]:void 0}},[a.actions.onBeforeMessageSend]),m=d.useCallback(()=>{a.actions.onAfterMessageSend()},[a.actions.onAfterMessageSend]),h=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]);return l?s.createElement(Fr,{channelUrl:e||(i==null?void 0:i.url),onBeforeSendMessage:g,onAfterSendMessage:m,onMessagesUpdated:a.actions.onStreamingUpdate,onMessagesReceived:a.actions.onStreamingUpdate,onChannelDeleted:h,sortComparator:rs},p=>s.createElement(os,{value:{...p,scrollSource:a,onClose:n,onNavigateToConversationList:r,updateActiveChannel:h}},o)):s.createElement(re,{type:"loading"})},as=({date:e=Date.now(),style:t,...n})=>{const{format:r,strings:o}=N();return s.createElement(_,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},s.createElement(x,{variant:"caption4",color:a=>a.textMidEmphasis},r(e,o.date_format.date_separator)))},is=({loading:e,error:t,data:n,LoadingComponent:r,ErrorComponent:o,EmptyComponent:a,...i},c)=>e?r:t?o:!n||n.length===0?a:s.createElement(y.FlatList,{ref:c,data:n,...i}),Qt=d.memo(d.forwardRef(is)),yt=({name:e,type:t="FILE",onPress:n})=>{const r=ls.use();return s.createElement(B,{onPress:n,style:r.container,activeOpacity:.75},s.createElement(_,{style:r.iconWrapper},s.createElement(O,{type:"file-document",size:24,color:r.icon.tintColor})),s.createElement(_,{flex:1,flexDirection:"column",gap:4,style:r.info},s.createElement(x,{variant:"button",color:o=>o.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),s.createElement(x,{variant:"caption3",color:o=>o.textMidEmphasis},t)))},ls=R.create(({theme:e,themedColor:t})=>({container:{borderRadius:12,gap:8,height:64,minWidth:240,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}})),cs=({file:e,children:t,onClickFile:n=({url:r})=>y.Linking.openURL(r)})=>s.createElement(_,{gap:w.GAP_GROUPED,maxWidth:w.BODY_MAX_WIDTH},s.createElement(yt,{name:e.name,type:ut(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),xe=({style:e,...t})=>s.createElement(y.Image,{style:[e,t],...t}),us=({file:e,onClickMedia:t=({url:r})=>y.Linking.openURL(r),children:n})=>{const r=ds.use();return s.createElement(_,{gap:w.GAP_GROUPED},s.createElement(B,{style:r.mediaContainer,onPress:()=>t==null?void 0:t(e)},s.createElement(xe,{source:{uri:e.url},style:r.media,resizeMode:"cover"})),n)},ds=R.create(({select:e,theme:t})=>({mediaContainer:{width:w.BODY_MAX_WIDTH,height:160,borderRadius:12,overflow:"hidden",backgroundColor:e({light:t.palette.background100,dark:t.palette.background400})},media:{width:"100%",height:"100%"}})),en=({code:e,language:t})=>{const[n,r]=d.useState(!1),o=async()=>{Hn.default.setString(e),r(!0),setTimeout(()=>r(!1),2e3)};return s.createElement(_,{style:ye.container,flexDirection:"row"},s.createElement(y.Pressable,{style:ye.copyButton,onPress:o},s.createElement(O,{type:n?"done":"copy",size:16,color:"#fff"})),s.createElement(_,null,s.createElement(On.default,{hljsStyle:Ln.atomOneDarkReasonable,scrollViewProps:{contentContainerStyle:ye.codeContainer,bounces:!1},textStyle:ye.codeText,language:t},e)))},ye=y.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}}),ue=e=>d.isValidElement(e)&&"children"in e.props,ms=({columns:e})=>{var a;const[t,n]=d.useState(Array((a=e[0])==null?void 0:a.length).fill(0)),r=y.useWindowDimensions(),o=it(.3);return s.createElement(y.View,{style:{flexDirection:"row"}},e.map((i,c)=>{const l=c===0,u=c===e.length-1;return s.createElement(y.View,{key:c,style:{flexDirection:"column",borderStartWidth:1,borderEndWidth:u?1:0,borderTopWidth:1,borderBottomWidth:1,borderColor:o,borderTopStartRadius:l?6:0,borderBottomStartRadius:l?6:0,borderTopEndRadius:u?6:0,borderBottomEndRadius:u?6:0}},i.map((g,m)=>{const h=m===0,p=m===i.length-1;return s.createElement(y.View,{key:m,onLayout:({nativeEvent:{layout:f}})=>{const C=f.height;(t[m]??0)<C&&(t[m]=C,n([...t]))},style:{borderBottomWidth:p?0:1,borderColor:o,backgroundColor:h?it(.15):"transparent",maxWidth:r.width*2/3,minHeight:(t[m]??0)>0?t[m]:void 0,padding:8}},g)}))}))},bt=d.memo(({children:e,textStyle:t,onPressImage:n})=>{const{themedColor:r}=$(),o=y.StyleSheet.compose({fontSize:14,color:r.textHighEmphasis},t),a=y.StyleSheet.flatten(o),i=a.fontSize||14,c=a.lineHeight||i*1.286,l=it(.3),u={color:a.color,textAlign:a.textAlign,fontSize:i,lineHeight:c,fontWeight:a.fontWeight,fontFamily:a.fontFamily,fontStyle:a.fontStyle,letterSpacing:a.letterSpacing,textDecorationLine:a.textDecorationLine,textDecorationStyle:a.textDecorationStyle,textDecorationColor:a.textDecorationColor},g=d.useMemo(()=>({image:m=>{var C,v;const h=((C=m.attributes)==null?void 0:C.src)||((v=m.attributes)==null?void 0:v.href),[p,f]=d.useState("1/1");return d.useLayoutEffect(()=>{h&&Xt(h).then(({width:b,height:T})=>f(`${b}/${T}`))},[h]),h?s.createElement(y.Pressable,{key:m.key,style:{marginTop:8},onPress:()=>n==null?void 0:n(h)},s.createElement(y.Image,{source:{uri:h},style:{width:"100%",aspectRatio:p},resizeMethod:"auto"})):null},code_block:m=>s.createElement(en,{code:m.content,language:"text"}),table:(m,h)=>{try{if(!Array.isArray(h)||h.length<2)return s.createElement(y.View,{key:m.key},h);const p=h[0],f=h[1],C=ue(f)?f.props.children:void 0;if(!C||!Array.isArray(C)||C.length===0)return s.createElement(y.View,{key:m.key},h);const v=C,b=v[0],T=ue(b)?b.props.children:void 0;if(!T||!Array.isArray(T)||T.length===0)return s.createElement(y.View,{key:m.key},h);const S=v.length,H=T.length,A=Array(H).fill(null).map(()=>[]);for(let D=0;D<S;D++){const G=v[D],j=ue(G)?G.props.children:void 0;if(!(!j||!Array.isArray(j)))for(let Y=0;Y<H;Y++){const J=A[Y];J&&Y<j.length&&(J[D]=j[Y])}}const I=ue(p)?p.props.children:void 0,E=Array.isArray(I)?I[0]:void 0,L=ue(E)?E.props.children:void 0;if(L&&Array.isArray(L))for(let D=0;D<H;D++){const G=A[D];G&&D<L.length&&G.unshift(L[D])}return s.createElement(y.View,{key:m.key,style:{marginTop:8}},s.createElement(y.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},s.createElement(ms,{key:m.key,columns:A})))}catch{return s.createElement(y.View,{key:m.key},h)}}}),[n]);return s.createElement(_,{flexDirection:"row",marginTop:-8},s.createElement(Nn.default,{style:{body:{...u,marginBottom:0},paragraph:{...u,marginTop:8,marginBottom:0},heading1:{...u,marginTop:8,marginBottom:0,fontSize:i*1.429,lineHeight:i*1.429*1.4,fontWeight:"700"},heading2:{...u,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:i*1.286,lineHeight:i*1.286*1.333},heading3:{...u,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:i*1.143,lineHeight:i*1.143*1.375},heading4:{...u,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:i*1.143,lineHeight:i*1.143*1.375},heading5:{...u,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:i*1.143,lineHeight:i*1.143*1.375},heading6:{...u,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:i*1.143,lineHeight:i*1.143*1.375},link:{...u,fontWeight:"700",textDecorationLine:"underline"},code_inline:{...u,fontSize:i*.929,lineHeight:i*.929*1.538,fontWeight:"600",backgroundColor:l},code_block:{...u,borderWidth:0,backgroundColor:l,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:i*.929,lineHeight:i*.929*1.538},fence:{...u,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:i*.929,lineHeight:i*.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:{...u,marginTop:4,marginBottom:0},blockquote:{...u,paddingStart:8,marginTop:8,marginBottom:0,paddingVertical:4,borderStartWidth:4,borderStartColor:l,backgroundColor:"transparent",fontWeight:"500",fontSize:i,lineHeight:c},hr:{backgroundColor:l,height:1,marginTop:8,marginBottom:0},th:{...u,padding:4,fontSize:i,lineHeight:i*1.143,fontWeight:"700"},td:{...u,padding:2,fontSize:i,lineHeight:i*1.429},image:{maxHeight:300,maxWidth:"100%"}},rules:g},Xn(e)))});bt.displayName="MarkdownText";const it=(e=.75)=>`rgba(0, 0, 0, ${e})`,Dt=({maxBodyWidth:e,customStyle:t,message:n,children:r})=>{const o=gs.use(),a=e??w.BODY_MAX_WIDTH,i=d.useMemo(()=>Zn(n),[n]),c=d.useCallback(l=>y.Linking.openURL(l),[]);return i.length===0&&!r?null:s.createElement(_,{alignSelf:"flex-start",maxWidth:a,borderRadius:12,paddingVertical:12,style:[o.container,(t==null?void 0:t.bubbleBackgroundColor)&&{backgroundColor:t==null?void 0:t.bubbleBackgroundColor}]},i.map((l,u)=>l.type==="text"?s.createElement(_,{key:u,paddingHorizontal:12},s.createElement(bt,{onPressImage:c,textStyle:o.text},l.value)):l.type==="code"?s.createElement(en,{key:u,code:l.value,language:l.language}):null),r)},gs=R.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),hs=e=>{const{strings:t}=N(),n=Ut(e)?s.createElement(Dt,{...e}):null;return e.messageType==="user"?n:e.messageType==="file"?e.file.type.startsWith("image")?s.createElement(us,{...e},n):s.createElement(cs,{...e},n):s.createElement(Dt,{...e,message:t.conversation.unknown_message_type})};function tn({id:e,src:t,size:n=56,onClick:r,style:o}){const a=fs.use(),i=s.createElement(y.View,{style:[a.container(n),o],testID:e},t?s.createElement(y.Image,{source:{uri:t},style:a.image}):s.createElement(O,{type:"user",size:n}));return r?s.createElement(B,{onPress:r,activeOpacity:.75},i):i}const fs=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"}})),ps=({sender:e,isBotMessage:t})=>{const n=_s.use();return t&&!e.profileUrl?s.createElement(_,{style:n.botContainer},s.createElement(O,{type:"bot-filled",size:w.AVATAR_SIZE-8})):s.createElement(tn,{src:e.profileUrl,size:w.AVATAR_SIZE})},_s=R.create(({theme:e})=>({botContainer:{width:w.AVATAR_SIZE,height:w.AVATAR_SIZE,borderRadius:w.AVATAR_SIZE/2,padding:4,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary}})),ys=({sender:e})=>s.createElement(_,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7},s.createElement(x,{variant:"caption1",color:t=>t.textMidEmphasis,numberOfLines:1,style:bs.senderName},e.nickname)),bs=y.StyleSheet.create({senderName:{textAlign:"left"}}),Es=({createdAt:e})=>{const{strings:t,format:n}=N();return e?s.createElement(x,{variant:"caption4",color:r=>r.textLowEmphasis},n(e,t.date_format.message_timestamp)):null},Cs=({customStyle:e})=>{const{theme:t}=$(),n=d.useRef(new y.Animated.Value(0)).current,r=vs.map(([o,a,i])=>[n.interpolate({inputRange:o,outputRange:a,extrapolate:"clamp"}),n.interpolate({inputRange:o,outputRange:i,extrapolate:"clamp"})]);return d.useEffect(()=>{const o=y.Animated.loop(y.Animated.timing(n,{toValue:1.4,duration:1400,easing:y.Easing.linear,useNativeDriver:!0}));return o.start(),()=>o.reset()},[]),s.createElement(_,{width:60,flexDirection:"row",alignItems:"center",justifyContent:"center",borderRadius:16,paddingHorizontal:12,height:34,backgroundColor:(e==null?void 0:e.bubbleBackgroundColor)??t.colors.messageIncoming.background},r.map(([o,a],i)=>s.createElement(_.Animated,{key:i,style:[Ss.dot,{marginEnd:i===r.length-1?0:6,opacity:a,transform:[{scale:o}],backgroundColor:(e==null?void 0:e.bubbleContentColor)??t.colors.messageIncoming.text}]})))},vs=[[[.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]]],Ss=y.StyleSheet.create({dot:{width:8,height:8,borderRadius:4}}),As=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>y.Linking.openURL(n)})=>{const n=ws.use(),r=e==null?void 0:e.cta_button;return r?s.createElement(B,{onPress:()=>t(r),activeOpacity:.75,style:n.button},s.createElement(x,{variant:"button",color:o=>o.textHighEmphasis,numberOfLines:1},r.label)):null},ws=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})}})),xs=({extendedMessagePayload:e,onClickCitation:t=n=>y.Linking.openURL(n.link)})=>{const{strings:n}=N(),{theme:r}=$(),o=e==null?void 0:e.citations;return!o||o.length===0?null:s.createElement(_,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},s.createElement(x,{variant:"caption1",color:r.colors.messageIncoming.text,style:Rt.sourceLabel},n.conversation.citation_title),s.createElement(_,{gap:8},o.map(a=>s.createElement(B,{key:a.embedding_id,onPress:()=>t(a),activeOpacity:.5},s.createElement(_,{flexDirection:"row",alignItems:"center",gap:4},s.createElement(O,{type:"source",size:16,color:r.colors.messageIncoming.text}),s.createElement(_,{flex:1},s.createElement(x,{variant:"body3",color:r.colors.messageIncoming.text,numberOfLines:1,style:Rt.citationText},a.title)))))))},Rt=y.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),Ts=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},Is=e=>null,nn=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:r,...o})=>s.createElement(y.ScrollView,{style:[t,o,e&&ft],showsHorizontalScrollIndicator:n,...o},r),ks=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const r=Ms.use(),[o,a]=d.useState(!1),i=(e==null?void 0:e.suggested_replies)??[];if(i.length===0||o)return null;const c=n==="vertical",l=g=>{t==null||t({reply:g}),a(!0)},u=()=>i.map((g,m)=>s.createElement(B,{key:m,style:r.itemContainer,onPress:()=>l(g)},s.createElement(x,{variant:"body3",color:h=>h.primary},g)));return c?s.createElement(_,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:w.HORIZONTAL_PADDING},u()):s.createElement(nn,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:r.horizontalContainer},u())},Ms=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:w.HORIZONTAL_PADDING,paddingVertical:16}})),Ps=e=>{var m,h,p,f,C,v,b;const{components:t}=rn.useContext(),n=!!e.isTyping,r=!!((m=e.extendedMessagePayload)!=null&&m.form)&&!((h=e.extendedMessagePayload)!=null&&h.form.canceled_at),o=!!((p=e.extendedMessagePayload)!=null&&p.message_template),a=!!((f=e.extendedMessagePayload)!=null&&f.cta_button),i=!!((C=e.extendedMessagePayload)!=null&&C.citations)&&e.extendedMessagePayload.citations.length>0,c=!!e.createdAt,l=e.groupType==="top"||e.groupType==="single",u=e.groupType==="bottom"||e.groupType==="single",g=w.AVATAR_SIZE;return s.createElement(_,{marginBottom:n?0:dt(e.groupType)},l&&s.createElement(_,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:w.HORIZONTAL_PADDING},s.createElement(t.SenderAvatar,{...e}),s.createElement(t.SenderName,{...e})),s.createElement(_,{gap:w.GAP_GROUPED},s.createElement(_,{paddingHorizontal:w.HORIZONTAL_PADDING,paddingStart:w.HORIZONTAL_PADDING+g},n?s.createElement(t.TypingIndicator,{...e}):s.createElement(t.MessageBody,{...e},a&&s.createElement(_,{marginTop:12,marginHorizontal:12},s.createElement(t.CTAButton,{...e})),i&&s.createElement(t.Citation,{...e}))),o&&s.createElement(t.MessageTemplate,{...e,messageTemplateErrorFallback:e.messageTemplateErrorFallback??s.createElement(_,{paddingHorizontal:w.HORIZONTAL_PADDING,paddingStart:w.HORIZONTAL_PADDING+g},s.createElement(t.MessageBody,{...e,messageType:"user",message:((b=(v=e.extendedMessagePayload)==null?void 0:v.message_template)==null?void 0:b.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:e.messageTemplateLoadingFallback??s.createElement(_,{paddingHorizontal:w.HORIZONTAL_PADDING,paddingStart:w.HORIZONTAL_PADDING+g},s.createElement(t.TypingIndicator,{...e}))}),r&&s.createElement(_,{paddingHorizontal:w.HORIZONTAL_PADDING,paddingStart:w.HORIZONTAL_PADDING+g},s.createElement(t.Form,{...e}))),u&&c&&s.createElement(_,{marginTop:w.BODY_TIME_GAP,paddingHorizontal:w.HORIZONTAL_PADDING,paddingStart:w.HORIZONTAL_PADDING+g+8},s.createElement(t.SentTime,{...e})),e.suggestedRepliesVisible&&s.createElement(t.SuggestedReplies,{...e}))},rn=oe({template:Ps,components:{SenderName:ys,SenderAvatar:ps,SentTime:Es,MessageBody:hs,TypingIndicator:Cs,SuggestedReplies:ks,MessageTemplate:Is,CTAButton:As,Citation:xs,Form:Ts}}),Ls=({file:e,children:t,onClickFile:n=({url:r})=>y.Linking.openURL(r)})=>s.createElement(_,{flexDirection:"column",alignItems:"flex-end",gap:w.GAP_GROUPED},s.createElement(yt,{name:e.name,type:ut(e.name,e.type),onPress:n?()=>n(e):void 0}),t),on=({size:e=26,children:t})=>{const n=d.useRef(new y.Animated.Value(0)).current;d.useEffect(()=>{const o=y.Animated.loop(y.Animated.timing(n,{toValue:1,duration:1e3,easing:y.Easing.linear,useNativeDriver:!0}));return o.start(),()=>{o.stop()}},[n]);const r=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return s.createElement(_.Animated,{style:{transform:[{rotate:r}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??s.createElement(O,{type:"spinner",size:e}))},Ds=({file:e,metadata:t,onClickMedia:n=({url:o})=>y.Linking.openURL(o),children:r})=>{const o=Rs.use(),{aspectRatio:a,localFile:i}=t,[c]=d.useState(()=>i instanceof File?URL.createObjectURL(i):e.url),[l,u]=d.useState(!1);return s.createElement(_,{flexDirection:"column",alignItems:"flex-end",gap:w.GAP_GROUPED},s.createElement(B,{onPress:n?()=>n(e):void 0,style:[o.imageContainer,{aspectRatio:a}]},!l&&s.createElement(_,{alignItems:"center",justifyContent:"center"},s.createElement(on,{size:26},s.createElement(O,{type:"spinner",color:g=>g.textLowEmphasis,size:26}))),s.createElement(xe,{source:{uri:c},style:[o.image,{opacity:l?1:0}],resizeMode:"cover",onLoad:()=>u(!0)})),r)},Rs=R.create(({themedColor:e})=>({imageContainer:{width:w.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}})),Bt=e=>{var n,r;const t=Bs.use();return s.createElement(_,{style:[t.container({maxWidth:e.maxBodyWidth??w.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},s.createElement(x,{variant:"body3",style:[t.text,((r=e.customStyle)==null?void 0:r.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},Bs=R.create(({theme:e})=>({container:t=>({flexDirection:"column",borderRadius:12,overflow:"hidden",maxWidth:t.maxWidth,backgroundColor:e.colors.messageOutgoing.background,paddingVertical:12}),text:{lineHeight:20,paddingHorizontal:12,color:e.colors.messageOutgoing.text}})),Hs=e=>{const{strings:t}=N(),n=Ut(e)?s.createElement(Bt,{...e}):null;return e.messageType==="user"?n:e.messageType==="file"?e.file.type.startsWith("image")?s.createElement(Ds,{...e},n):s.createElement(Ls,{...e},n):s.createElement(Bt,{...e,message:t.unknown_message_type})},Os=({sendingStatus:e})=>{const{themedColor:t}=$();switch(e){case"pending":return s.createElement(_,{marginBottom:2},s.createElement(on,{size:16},s.createElement(O,{type:"spinner",color:t.primary,size:16})));case"failed":return s.createElement(_,{marginBottom:2},s.createElement(O,{type:"error",color:t.error,size:16}));case"scheduled":case"canceled":return null;default:return s.createElement(_,{marginBottom:2},s.createElement(O,{type:"done",color:t.secondary,size:16}))}},Ns=({createdAt:e})=>{const{format:t,strings:n}=N();return e?s.createElement(x,{variant:"caption4",color:r=>r.textLowEmphasis},t(e,n.date_format.message_timestamp)):null},$s=e=>{const{components:t}=sn.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return s.createElement(_,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:dt(e.groupType)},s.createElement(_,{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:w.HORIZONTAL_PADDING},s.createElement(t.MessageBody,{...e})),r&&s.createElement(_,{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingStart:w.HORIZONTAL_PADDING,paddingEnd:w.HORIZONTAL_PADDING+8,marginTop:w.BODY_TIME_GAP},n?s.createElement(t.SentTime,{...e}):s.createElement(t.SendingStatus,{...e})))},sn=oe({template:$s,components:{SendingStatus:Os,SentTime:Ns,MessageBody:Hs}}),Fs=e=>e.messageType!=="admin"?null:s.createElement(x,{variant:"caption2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},Us(e.message)),Us=e=>{try{const t=[];let n=e,r=0;for(;n;){const o=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=n.match(/\*\*([^*]+)\*\*/),i=[o&&{match:o,type:"link"},a&&{match:a,type:"bold"}].filter(m=>!!m);if(!i.length){t.push(n);break}const c=i.reduce((m,h)=>h.match.index<m.match.index?h:m),{match:l,type:u}=c,g=l.index;g>0&&t.push(n.slice(0,g)),u==="link"?t.push(s.createElement(y.Text,{key:r++,onPress:()=>y.Linking.openURL((l==null?void 0:l[2])??""),style:{textDecorationLine:"none"}},l[1])):u==="bold"&&t.push(s.createElement(y.Text,{key:r++,style:{fontWeight:"bold"}},l[1])),n=n.slice(g+l[0].length)}return t.filter(o=>o!=="")}catch{return[e]}},zs=({children:e,style:t})=>s.createElement(x,{variant:"caption4",color:n=>n.error,style:t},e),qs=({children:e,style:t,required:n})=>{const{strings:r}=N();return s.createElement(x,{variant:"caption3",color:o=>o.textMidEmphasis,style:t},e,!n&&s.createElement(x,{variant:"caption3",color:o=>o.textLowEmphasis},` (${r.form.optional_label})`))},Ws=({style:e})=>{const t=Gs.use();return s.createElement(_,{style:[t.separator,e]})},Gs=R.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),js=({value:e="",onChange:t,placeholder:n,variant:r="single-line",error:o=!1,submitted:a=!1,style:i,disabled:c=!1,maxLength:l})=>{const[u,g]=d.useState(!1),m=Vs.use(),{themedColor:h}=$(),p=f=>{l&&f.length>l||t==null||t(f)};return s.createElement(y.TextInput,{value:e,onChangeText:p,placeholder:n,editable:!c&&!a,maxLength:l,multiline:r==="multi-line",style:[m.input(r,o,a,u),i],placeholderTextColor:h.textLowEmphasis,onFocus:()=>g(!0),onBlur:()=>g(!1)})},Vs=R.create(({select:e,theme:t,themedColor:n})=>({input:(r,o,a,i)=>{let c,l;a?(c="transparent",l=e({light:t.palette.ondark.textMidEmphasis,dark:t.palette.onlight.textLowEmphasis})):o?(c=n.error,l=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis})):(c=i?n.primary:n.textDisabled,l=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:c,backgroundColor:l,color:n.textHighEmphasis};return r==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),Ee={Label:qs,ErrorLabel:zs,TextInput:js,Separator:Ws},an=({onClick:e,checked:t,label:n,disabled:r,labelVariant:o="caption2"})=>{const{themedColor:a}=$(),i=Ks.use(),c=t?a.primary:r?a.textDisabled:a.textLowEmphasis;return s.createElement(B,{disabled:r||!e,onPress:e,style:i.container},s.createElement(_,{style:i.iconContainer},s.createElement(O,{size:20,type:t?"radio-on":"radio-off",color:c})),s.createElement(x,{variant:o,style:i.label(t,r)},n))},Ks=R.create(({themedColor:e})=>({container:{flexDirection:"row",alignItems:"flex-start",justifyContent:"flex-start",gap:2},iconContainer:{width:20,height:20},label:(t,n)=>{let r;return t?r=e.textHighEmphasis:n?r=e.textLowEmphasis:r=e.textHighEmphasis,{color:r,lineHeight:20}}})),Ys=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:o})=>(d.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(o==null||o(n))},[r,n,o]),e.cre?s.createElement(_,{flexDirection:"column",gap:8},s.createElement(x,{variant:"caption3",color:a=>a.textMidEmphasis},e.cre.question),s.createElement(_,{flexDirection:"column",gap:8},[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(a=>s.createElement(an,{key:a.label,checked:r===a.value,label:a.label,disabled:t,onClick:()=>o==null?void 0:o(a.value)})))):null),Zs=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{strings:a}=N();return s.createElement(_,{flexDirection:"column",gap:8},s.createElement(Ee.Label,{required:e.required},e.question),e.response_type==="free_text"&&s.createElement(Ee.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>r(i),error:o}),e.response_type==="single_choice"&&s.createElement(_,{flexDirection:"column",gap:8},e.options.map(i=>s.createElement(an,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>r==null?void 0:r(i),labelVariant:"body3"}))),o&&s.createElement(Ee.ErrorLabel,null,a.form.validation_required))},Xs=e=>null,Js=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",a=ln.use();return s.createElement(_,{flexDirection:"column",gap:8},s.createElement(x,{variant:"caption3",color:i=>i.textMidEmphasis},e.csat_question),s.createElement(_,{style:a.scoresContainer},e.csat_scores.map(({label:i,image_url:c},l)=>{const u=l+1,g=n===u;return s.createElement(B,{key:l,disabled:t,onPress:()=>r(u),style:a.scoreButton},s.createElement(Qs,{value:u,selected:o||g,label:i,src:c}),!!i&&s.createElement(x,{style:{textAlign:"center"},variant:"caption3",color:m=>g?m.textHighEmphasis:m.textLowEmphasis},i))})))},Qs=({value:e,src:t,label:n,selected:r})=>{const[o,a]=d.useState(!1),i=ln.use();return o?s.createElement(Xs,{value:e,selected:r,label:n}):s.createElement(xe,{source:{uri:t},style:i.emojiImage(r),onError:()=>a(!0),accessibilityLabel:n})},ln=R.create(()=>({scoresContainer:{flexDirection:"row",justifyContent:"space-between",alignSelf:"center",width:"100%",maxWidth:400,gap:16},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})})),ea=({csatPayload:e})=>s.createElement(x,{variant:"button",color:t=>t.textHighEmphasis},e.title),ta=new Set(["free_text","single_choice"]),Ge=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:a})=>{const[i,c]=kt({csatType:t,csat:r,csatReason:o,isResolved:a}),[l,u]=kt({followUpItem:!1}),g=d.useMemo(()=>{var v;const f=i.csat;if(typeof f!="number")return;const C=(v=e.follow_up)==null?void 0:v.find(b=>b.scores.includes(f));if(ta.has(C==null?void 0:C.response_type))return C},[i.csat,e.follow_up]),m=typeof r=="number"?"submitted":(t===Q.AI_AGENT_CSAT_5||t===Q.HELPDESK_CSAT_5)&&typeof i.csat=="number"||t===Q.AI_AGENT_CSAT_5_WITH_CRE&&typeof i.csat=="number"&&typeof i.isResolved=="boolean"?"submittable":"unsubmittable",h=d.useCallback(()=>typeof i.csat>"u"?!1:g!=null&&g.required&&!i.csatReason?(u({followUpItem:!0}),!1):!0,[i,g,u]);d.useEffect(()=>{o||(c({csatReason:""}),u({followUpItem:!1}))},[o,g,c,u]);const p={csatPayload:e,state:m,submitted:m==="submitted"};return s.createElement(s.Fragment,null,s.createElement(_,{flexDirection:"column",gap:12},s.createElement(ea,{...p}),t===Q.AI_AGENT_CSAT_5_WITH_CRE&&s.createElement(Ys,{...p,defaultValue:a,value:i.isResolved,onChange:f=>c({isResolved:f})}),s.createElement(Js,{...p,value:i.csat,onChange:f=>c({csat:f})}),g&&s.createElement(Zs,{...p,followUpItem:g,value:i.csatReason,onChange:f=>{c({csatReason:f}),u({followUpItem:!1})},hasError:l.followUpItem})),m!=="unsubmittable"&&s.createElement(s.Fragment,null,s.createElement(Ee.Separator,null),n({state:m,params:i,validateParams:h})))},na=e=>{const{strings:t}=N();return zn(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})},ra=()=>{const{strings:e}=N();return s.createElement(x,{variant:"body2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},oa=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n}=e,{csat:r,csatReason:o,csatExpireAt:a,isResolvedWhenDeterminedByUser:i}=e,[,c]=d.useState(0),l=na(t==null?void 0:t.csat),u=sa.use();if(!l||!l.visibility||!Q[l.type])return null;const g=l.type===Q.AI_AGENT_CSAT_5||l.type===Q.AI_AGENT_CSAT_5_WITH_CRE||l.type===Q.HELPDESK_CSAT_5?Ge:()=>null;return s.createElement(_,{style:u.container},!r&&Ct(a)?s.createElement(ra,null):s.createElement(g,{csatPayload:l,type:l.type,initialCsat:r,initialCsatReason:o,initialIsResolved:i,renderSubmitButton:({state:m,params:h,validateParams:p})=>s.createElement(B,{activeOpacity:.75,disabled:m==="submitted",onPress:()=>{!Ct(a)&&p()?n(h):c(f=>f+1)},style:u.submitButton(m)},s.createElement(x,{variant:"button",style:u.submitButtonText(m)},m==="submitted"?l.csat_submitted_label:l.csat_submit_label))}))},sa=R.create(({theme:e,themedColor:t})=>({container:{flexDirection:"column",backgroundColor:e.colors.csat.background,borderRadius:16,gap:16,padding:16},submitButton:n=>{let r;return n==="submitted"||n==="unsubmittable"?r=t.textDisabled:r=e.colors.base.primary,{backgroundColor:r,borderRadius:6,padding:10,paddingHorizontal:20,alignItems:"center",justifyContent:"center"}},submitButtonText:n=>{let r;return n==="submitted"?r=t.textHighEmphasis:n==="unsubmittable"?r=t.textLowEmphasis:r=e.colors.base.primaryContrastContent,{color:r}}})),aa=e=>{const{components:t}=cn.useContext(),n=e.messageType==="admin"?s.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?s.createElement(t.CSATMessage,{...e}):null;return s.createElement(_,{paddingHorizontal:w.HORIZONTAL_PADDING,marginBottom:dt(e.groupType)},n)},cn=oe({template:aa,components:{AdminMessage:Fs,CSATMessage:oa}}),ia=({style:e,...t})=>{const{strings:n}=N();if(!ht("powered-by"))return null;const o=()=>{y.Linking.openURL("https://sendbird.com?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby")};return s.createElement(_,{style:[la.container,e],...t},s.createElement(x,{variant:"caption2",color:a=>a.textLowEmphasis},n.conversation.powered_by+" "),s.createElement(B,{onPress:o},s.createElement(x,{variant:"caption2",color:a=>a.textLowEmphasis},"Sendbird")))},la=y.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),ca=()=>{var c;const{strings:e}=N(),{channelSource:t,scrollSource:n,updateActiveChannel:r}=K(),o=ua.use(),a=me(t.channel),i=d.useRef(a);return d.useEffect(()=>{const l=i.current;i.current=a,!l&&a&&n.actions.scrollToBottom(!0)},[a,n]),!((c=t.channel)!=null&&c.isAIAgent)||!a?null:s.createElement(_,{justifyContent:"center",flexDirection:"row",style:o.wrapper},s.createElement(B,{activeOpacity:.75,onPress:()=>r(),style:o.button},s.createElement(x,{variant:"button",role:"button",color:l=>l.textHighEmphasis},e.conversation.start_new_conversation_label)))},ua=R.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),da=()=>{const{aiAgentInfo:e}=V(),{channelSource:t}=K(),n=Vt(t.channel);return(()=>{const r=n[0];if(!r)return null;const o=r.userId===(e==null?void 0:e.userId);return{user:o?e:r,isBot:o}})()},ma=(e,t)=>!kn.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),ga=({messageStackDirection:e="top"})=>{var I;const{Template:t}=rn.useContext(),{Template:n}=sn.useContext(),{Template:r}=cn.useContext(),{config:o,cache:a,chatSDK:i}=W(),{aiAgentInfo:c,userSession:l}=V(),{messageSource:u,channelSource:g,scrollSource:m}=K(),h=da(),p=ha.use(),f=te(["left","right"]),{state:C,props:v}=m,b=(I=g.channel)==null?void 0:I.conversation,T=(E,L=!1)=>{var D;return L?c??{nickname:"",profileUrl:""}:((D=g.channel)==null?void 0:D.members.find(G=>G.userId===E.sender.userId))??E.sender},S=({item:E,index:L})=>{const D=u.messages[L+1],G=u.messages[L-1],j=(()=>{var se,he;const J=Kn(E,D,G),ne={extendedMessagePayload:E.extendedMessagePayload,message:E.message,createdAt:E.createdAt,groupType:J};if(fe.isAdmin(E))return fe.isCSAT(E)?b?s.createElement(r,{...ne,...b,messageType:"admin.csat",isResolvedWhenDeterminedByUser:Fn(b),onSubmitCSAT:({csat:Z,...P})=>{var k;Z&&((k=g.channel)==null||k.submitCSAT({csat:Z,...P}))}}):null:s.createElement(r,{...ne,messageType:"admin"});if(fe.isOutgoing(E,(l==null?void 0:l.userId)??"")){const Z={...ne,sender:T(E),sendingStatus:E.sendingStatus};if(E.isUserMessage())return s.createElement(n,{...Z,messageType:"user"});if(E.isFileMessage()){const[P,k]=((se=E.metaArrays.find(M=>M.key===Ft))==null?void 0:se.value)??[];return s.createElement(n,{...Z,messageType:"file",file:E,metadata:{aspectRatio:P&&k?`${P}/${k}`:"1/1",localFile:(he=E.messageParams)==null?void 0:he.file}})}}if(fe.isIncoming(E,(l==null?void 0:l.userId)??"")){const Z=E.sender.userId===(c==null?void 0:c.userId),P=L===0,k={...ne,sender:T(E,Z),suggestedRepliesVisible:P,isBotMessage:Z,isStreaming:zt.isStreaming(E),isHandedOff:ge(g.channel),isConversationClosed:me(g.channel),onClickSuggestedReply:async({reply:M})=>{u.sendUserMessage({message:M})},onRequestMessageTemplate:async M=>{const{template:U}=await i.aiAgent.getMessageTemplate(M);return a.template.set(M,U),U},onGetCachedMessageTemplate:M=>a.template.get(M),onHandleTemplateInternalAction:M=>{if(M.type==="internal"&&M.internalData){const{method:U,payload:ae}=M.internalData;U==="message.send"&&(ae!=null&&ae.message)&&u.sendUserMessage({message:ae.message})}},onSubmitForm:({key:M,data:U})=>i.aiAgent.submitForm({messageId:E.messageId,channelUrl:E.channelUrl,formKey:M,formData:U}),onCancelForm:({key:M})=>i.aiAgent.cancelForm({messageId:E.messageId,channelUrl:E.channelUrl,formKey:M})};if(E.isUserMessage())return s.createElement(t,{...k,messageType:"user"});if(E.isFileMessage())return s.createElement(t,{...k,messageType:"file",file:E})}return null})(),Y=ma(E,D)&&s.createElement(as,{date:E.createdAt,style:p.dateSeparator});return s.createElement(_,null,Y,j)},H=()=>s.createElement(ia,{style:p.poweredBy}),A=()=>{var E;return s.createElement(s.Fragment,null,h&&s.createElement(t,{isTyping:!0,isBotMessage:h.isBot,sender:h.user,messageType:"user",groupType:"single",message:""}),((E=o==null?void 0:o.conversation)==null?void 0:E.isTalkToAgentViewEnabled)&&s.createElement(ca,null),C.bottomSpace?s.createElement(_,{height:C.bottomSpace}):null)};return s.createElement(Qt,{ref:m.ref,style:p.list,contentContainerStyle:[p.listContent,f,e==="top"&&p.stackTop],data:u.messages,onEndReached:u.loadPrevious,keyExtractor:Vn,renderItem:S,loading:!u.initialized,error:!!g.error,LoadingComponent:s.createElement(re,{type:"loading"}),EmptyComponent:s.createElement(re,{type:"noMessages"}),ErrorComponent:s.createElement(re,{type:"error",action:{label:"Retry",onPress:g.refetch}}),ListFooterComponent:H(),ListHeaderComponent:A(),inverted:!0,...v})},ha=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}})),{Provider:fa,useContext:un}=q("Modal");function dn({children:e}){const[t,n]=d.useState([]),[r,o]=d.useState(null),a=d.useRef(0);d.useEffect(()=>{if(!r&&t.length>0){const[u,...g]=t;u&&(o(u),n(g))}},[r,t]);const i=d.useCallback(u=>new Promise(g=>{const h={id:`modal-${++a.current}`,render:u,resolve:g};n(p=>[...p,h])}),[]),c=d.useCallback((u,g)=>{o(m=>(m==null?void 0:m.id)===u?(m.resolve(g),null):m)},[]),l={openModal:i,currentModal:r};return s.createElement(fa,{value:l},e,r&&s.createElement(y.Modal,{visible:!0,supportedOrientations:["landscape","portrait"],transparent:!0,animationType:"fade",onRequestClose:()=>c(r.id,null)},r.render(u=>c(r.id,u??null))))}const pa={"image/jpeg":["image/jpeg","image/jpg"],"image/jpg":["image/jpeg","image/jpg"]};function Et(e){const t=new Set;for(const n of e){const r=pa[n];r?r.forEach(o=>t.add(o)):t.add(n)}return Array.from(t)}function Se(e,t){if(!t||t.length===0)return e;const n=Et(t);return e.filter(r=>n.includes(r.type))}function _a(e){return{captureCamera:async t=>{const n=await e.launchCameraAsync({mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});if(n.canceled)return null;const r=n.assets.map(Ht),o=Se(r,t==null?void 0:t.mimeTypes);return o.length>0?o:null},selectFromGallery:async t=>{const n=await e.launchImageLibraryAsync({allowsMultipleSelection:t==null?void 0:t.multiple,mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});if(n.canceled)return null;const r=n.assets.map(Ht),o=Se(r,t==null?void 0:t.mimeTypes);return o.length>0?o:null}}}function ya(e){return{captureCamera:async t=>{const n=await e.launchCamera({mediaType:"photo",assetRepresentationMode:"compatible"});if(n.didCancel)return null;if(n.errorCode)throw new Error(n.errorMessage||`Camera error: ${n.errorCode}`);if(!n.assets||n.assets.length===0)throw new Error("No image captured");const r=n.assets.map(Ot),o=Se(r,t==null?void 0:t.mimeTypes);return o.length>0?o:null},selectFromGallery:async t=>{const n=await e.launchImageLibrary({mediaType:"photo",selectionLimit:t!=null&&t.multiple?0:1,assetRepresentationMode:"compatible"});if(n.didCancel)return null;if(n.errorCode)throw new Error(n.errorMessage||`Gallery error: ${n.errorCode}`);if(!n.assets||n.assets.length===0)throw new Error("No image selected");const r=n.assets.map(Ot),o=Se(r,t==null?void 0:t.mimeTypes);return o.length>0?o:null}}}function ba(e){return{selectFile:async t=>{const n=t!=null&&t.mimeTypes?Et(t.mimeTypes):["*/*"],r=await e.getDocumentAsync({multiple:t==null?void 0:t.multiple,type:n});return r.canceled?null:r.assets.map(Ca)}}}function Ea(e){return{selectFile:async t=>{try{const n=t!=null&&t.mimeTypes?Et(t.mimeTypes):void 0,r=await e.pick({mode:"open",allowMultiSelection:t==null?void 0:t.multiple,type:n});return(Array.isArray(r)?r:[r]).map(va)}catch(n){if(n&&typeof n=="object"&&"message"in n){const r=String(n.message).toLowerCase();if(r.includes("cancel")||r.includes("user cancelled"))return null;throw new Error(String(n.message))}throw new Error("File selection failed")}}}}function Ht(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 Ca(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function Ot(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 va(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function Sa(e){return{keyValueStorage:{get:t=>e.getString(t)??null,set:(t,n)=>e.set(t,n),delete:t=>e.remove(t),getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}}const{Provider:Aa,useContext:mn}=q("NativeAdapter"),gn=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:r,documentPicker:o,mmkv:a}=e,i="launchCameraAsync"in r?_a(r):ya(r),c="getDocumentAsync"in o?ba(o):Ea(o),l=Sa(a);return{...i,...c,...l}},[e]);return s.createElement(Aa,{value:n},t)},{Provider:wa,useContext:hn}=q("BottomSheetAnimation");function xa({onClose:e,children:t}){const n=d.useRef(new y.Animated.Value(500)).current;d.useEffect(()=>{y.Animated.timing(n,{toValue:0,duration:300,useNativeDriver:!0}).start()},[n]);const r=d.useCallback(a=>async()=>{y.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(()=>{a==null||a()})},[n]),o=d.useRef(y.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?y.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(()=>{e==null||e()}):y.Animated.timing(n,{toValue:0,duration:200,useNativeDriver:!0}).start()}})).current;return s.createElement(wa,{value:{wrapWithAnimation:r,translateY:n,panHandlers:o.panHandlers}},t)}const Ta=({icon:e,label:t="",destructive:n=!1,onPress:r})=>{const o=fn.use(),{themedColor:a}=$();return s.createElement(B,{onPress:r,style:o.actionItem,activeOpacity:.75},e&&s.createElement(O,{type:e,size:24,color:a.primary}),s.createElement(x,{variant:"body3",color:n?a.error:a.textHighEmphasis,numberOfLines:1},t))},Ia=({onClose:e,children:t})=>{const n=fn.use(),{translateY:r,panHandlers:o,wrapWithAnimation:a}=hn(),i=te(["left","right"]);return s.createElement(B,{onPress:a(e),style:n.overlay},s.createElement(_.Animated,{style:[n.container,i,{transform:[{translateY:r}]}],...o},t))},Te=oe({template:Ia,components:{ActionItem:Ta}}),le=e=>{const{Template:t}=Te.useContext();return s.createElement(xa,{onClose:e.onClose},s.createElement(t,{...e}))};le.ActionItem=e=>{const{components:t}=Te.useContext(),{wrapWithAnimation:n}=hn();return s.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const fn=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}})),ka=({onPressAddAttachment:e,editable:t})=>s.createElement(B,{disabled:!t,style:Ma.container,activeOpacity:.75,onPress:e},s.createElement(O,{type:"add",size:24,color:n=>t?n.primary:n.textDisabled})),Ma=y.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Pa=({name:e,type:t,url:n,onRemove:r})=>{const o=La.use();return s.createElement(_,{style:o.wrapper},Yn(t)?s.createElement(xe,{source:{uri:n},style:o.image,resizeMode:"cover"}):s.createElement(yt,{name:e,type:ut(e,t)}),r&&s.createElement(B,{onPress:r,style:o.removeButton},s.createElement(O,{type:"remove",size:22,color:o.removeIcon.tintColor})))},La=R.create(({themedColor:e})=>({wrapper:{marginTop:7,marginRight:7,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-7,right:-7,width:26,height:26,borderRadius:13,borderWidth:2,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),Da=e=>{const{theme:t,themedColor:n}=$(),r=Ra.use();return s.createElement(_,{style:r.container},e.attachments&&s.createElement(nn,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),s.createElement(_,null,s.createElement(y.TextInput,{multiline:!0,style:r.input,placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},Ra=R.create(({theme:e})=>({container:{backgroundColor:e.colors.messageInput.background,gap:16,flex:1,paddingHorizontal:16,paddingVertical:8,borderRadius:20,minHeight:36},input:{...e.typography.body3,lineHeight:Number(e.typography.body3.fontSize),color:e.colors.messageInput.text,includeFontPadding:!1,maxHeight:40}})),Ba=({onPressSend:e})=>s.createElement(B,{style:Ha.container,activeOpacity:.75,onPress:e},s.createElement(O,{type:"send",size:24})),Ha=y.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Oa=()=>{const{aiAgentInfo:e,userSession:t}=V(),{messageSource:n,channelSource:r}=K(),o=Na.use(),a=ht("special-notice",r.channel),i=d.useCallback(()=>a?n.messages.some(u=>de(u,(t==null?void 0:t.userId)??"")):!0,[a,n.messages,t==null?void 0:t.userId]),[c,l]=d.useState(i);return d.useEffect(()=>{c||l(i())},[i,c]),c?null:s.createElement(_,{style:o.container},s.createElement(bt,{textStyle:o.text},(e==null?void 0:e.specialNotice)??""))},Na=R.create(({theme:e,themedColor:t})=>({container:{backgroundColor:e.colors.base.background,paddingVertical:8,paddingHorizontal:16,alignItems:"center"},text:{...e.typography.body3,color:t.textLowEmphasis,textAlign:"center"}})),$a=()=>{const{strings:e}=N(),{attachmentMode:t}=V(),{channelSource:n,state:r}=K(),[o,a]=d.useState(""),[i,c]=d.useState([]),l=ge(n.channel),u=(()=>{if(!r.input.disabled)return e.conversation.input_placeholder;switch(r.input.disabledBy){case"form_active":return e.conversation.input_placeholder_active_form;case"ai_responding":return e.conversation.input_placeholder_wait_ai_agent_response;case"unavailable":case"conversation_closed":default:return e.conversation.input_placeholder_disabled}})(),g=d.useMemo(()=>{if(n.channel&&!n.channel.isAIAgent)return!0;switch(t){case be.OFF:return!1;case be.ALWAYS:return!0;case be.HANDED_OFF_ONLY:return l;default:return l}},[t,l,n.channel]);return{files:i,onChangeFiles:c,value:o,onChangeText:a,editable:!r.input.disabled,placeholder:u,sendButtonVisible:!!o.trim(),addAttachmentButtonVisible:g}},Fa=()=>{const e=mn(),{strings:t}=N(),{messageSource:n}=K(),{openModal:r}=un(),o=te(["left","right","bottom"]),a=Ua.use(),{sendButtonVisible:i,addAttachmentButtonVisible:c,...l}=$a(),m={...l,onPressAddAttachment:async()=>{const h=await r(p=>s.createElement(le,{onClose:()=>p()},s.createElement(le.ActionItem,{icon:"camera",label:t.conversation.attachment_camera,onPress:async()=>{const f=await e.captureCamera();p(f)}}),s.createElement(le.ActionItem,{icon:"photo",label:t.conversation.attachment_photo,onPress:async()=>{const f=await e.selectFromGallery({multiple:!1});p(f)}}),s.createElement(le.ActionItem,{icon:"document",label:t.conversation.attachment_document,onPress:async()=>{const f=await e.selectFile({multiple:!1});p(f)}})));h&&l.onChangeFiles(h)},onPressSend:()=>{l.files.length>0?n.sendFileMessage({message:l.value.trim(),file:l.files[0]}):n.sendUserMessage({message:l.value}),l.onChangeFiles([]),l.onChangeText("")}};return s.createElement(y.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-o.paddingBottom},s.createElement(Oa,null),s.createElement(_,{style:a.container(o)},c&&s.createElement(ka,{...m}),s.createElement(Da,{...m,attachments:m.files.length===0?null:m.files.map((h,p)=>s.createElement(Pa,{key:p,name:h.name,type:h.type,url:h.uri,onRemove:()=>m.onChangeFiles(m.files.filter((f,C)=>C!==p))}))}),i&&s.createElement(Ba,{...m})))},Ua=R.create(({theme:e})=>({container:({paddingStart:t,paddingEnd:n,paddingBottom:r})=>({alignItems:"center",flexDirection:"row",gap:8,paddingTop:10,paddingBottom:10+r,paddingStart:12+t,paddingEnd:12+n,backgroundColor:e.colors.base.background})})),pn=({left:e,right:t})=>{const n=za.use();return s.createElement(_,{style:n.container},s.createElement(_,{flexShrink:1},e),s.createElement(_,{flexShrink:0},t))},za=R.create(({theme:e,themedColor:t})=>({container:{width:"100%",height:56,paddingHorizontal:12,gap:8,flexDirection:"row",alignItems:"center",justifyContent:"space-between",backgroundColor:e.colors.base.headerBackground,borderBottomWidth:1,borderBottomColor:t.textDisabled}})),qa=()=>{const{themedColor:e}=$(),{onClose:t}=K();return t?s.createElement(B,{hitSlop:4,onPress:t,activeOpacity:.75},s.createElement(O,{color:e.textHighEmphasis,type:"close",size:24})):null},Wa=()=>{const{themedColor:e}=$(),{channelSource:{channel:t}}=K(),n=ht("handoff-button",t),r=!$t(t)||ge(t);return n?s.createElement(B,{hitSlop:4,disabled:r,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},s.createElement(O,{color:r?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},Ga=()=>{const{themedColor:e}=$(),{onNavigateToConversationList:t}=K();return t?s.createElement(B,{hitSlop:4,onPress:t,activeOpacity:.75},s.createElement(O,{color:e.textHighEmphasis,type:"menu",size:24})):null},_n=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=V(),{fallbackIcon:o,url:a}=Kt({channel:e,aiAgentInfo:r,userSession:n}),{theme:i}=$();return a?s.createElement(tn,{src:a,size:t}):s.createElement(_,{width:t,height:t,borderRadius:t/2,alignItems:"center",justifyContent:"center",flexShrink:0,style:{backgroundColor:i.colors.base.primary}},s.createElement(O,{type:o,size:t*.55,color:i.colors.base.primaryContrastContent}))},ja=()=>{const{channelSource:{channel:e}}=K(),{userSession:t,aiAgentInfo:n}=V(),r=Kt({channel:e,userSession:t,aiAgentInfo:n});return s.createElement(_,{gap:6,flexDirection:"row",alignItems:"center"},s.createElement(_n,{channel:e,size:34}),s.createElement(x,{numberOfLines:1,variant:"h1"},r.title))},Va=()=>{const{paddingStart:e,paddingEnd:t}=te(["left","right"]);return s.createElement(pn,{left:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:6,paddingStart:e},s.createElement(Ga,null),s.createElement(ja,null)),right:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:10,paddingEnd:t},s.createElement(Wa,null),s.createElement(qa,null))})},Ka=e=>{const{components:t}=Ie.useContext(),n=te(["top"]);return s.createElement(_,{flex:1,style:n},s.createElement(t.Header,null),s.createElement(t.Body,null),s.createElement(t.Footer,null))},Ie=oe({template:Ka,components:{Header:Va,Body:ga,Footer:Fa}}),Ya=({children:e,...t})=>{const{Template:n}=Ie.useContext();return s.createElement(ts,null,s.createElement(Jt,{...t},s.createElement(n,null),e))},{Provider:Za,Context:Xa,useContext:ke}=q("ConversationList"),yn=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:r,children:o})=>{const{sdkUser:a,authenticate:i}=V();return d.useEffect(()=>{a||i()},[]),a?s.createElement(Vr,{conversationListLimit:e,conversationListFilter:t},c=>s.createElement(Za,{value:{...c,onClose:r,onNavigateToConversation:n}},o)):s.createElement(re,{type:"loading"})},je=99,Ja=e=>{const{channel:t,onClick:n}=e,{strings:r,format:o}=N(),{themedColor:a}=$(),i=ei.use(),c=qn(t),l=Wn(t,{justNow:r.date_format.just_now,minutesAgo:r.date_format.minutes_ago,hoursAgo:r.date_format.hours_ago,dateShortFormat:r.date_format.date_short},o),u=t.unreadMessageCount;return s.createElement(B,{onPress:n,activeOpacity:.75},s.createElement(_,{flexDirection:"row",alignItems:"center",width:"100%",height:72,gap:16},s.createElement(_,{marginStart:16,alignItems:"center",justifyContent:"center"},s.createElement(_n,{channel:t})),s.createElement(_,{flexDirection:"row",alignItems:"center",flex:1,paddingEnd:16,height:"100%",gap:8,style:i.rightContainer},s.createElement(_,{flexDirection:"column",justifyContent:"center",flex:1,gap:4},s.createElement(x,{variant:"subtitle1",color:a.textHighEmphasis,numberOfLines:1},c),s.createElement(_,{flexDirection:"row",alignItems:"center",gap:6},me(t)&&s.createElement(s.Fragment,null,s.createElement(x,{variant:"caption1",color:a.textMidEmphasis,numberOfLines:1},r.conversation_list.ended),s.createElement(_,{width:2,height:2,borderRadius:1,backgroundColor:a.textLowEmphasis})),s.createElement(x,{variant:"caption2",color:a.textLowEmphasis,numberOfLines:1},l))),u>0&&s.createElement(_,{alignItems:"center",justifyContent:"center",height:20,width:u<=je?20:void 0,padding:4,borderRadius:10,backgroundColor:a.error},s.createElement(x,{variant:"caption3",color:a.textHighEmphasisInverse,style:{lineHeight:12}},u<=je?u:`${je}+`)))))},Qa=oe({template:Ja,components:{}}),ei=R.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),ti=()=>{const{listSource:e,onNavigateToConversation:t}=ke(),{Template:n}=Qa.useContext(),r=te(["left","right"]),o=ni.use();return s.createElement(Qt,{style:o.list,contentContainerStyle:[o.listContent,r],data:e.channels,onEndReached:e.loadMore,keyExtractor:d.useCallback(a=>a.url,[]),renderItem:d.useCallback(({item:a})=>s.createElement(n,{channel:a,onClick:()=>t==null?void 0:t(a.url,me(a)?"closed":"open")}),[n,t]),loading:!e.initialized,error:!!e.error,LoadingComponent:s.createElement(re,{type:"loading"}),EmptyComponent:s.createElement(re,{type:"noChannels"}),ErrorComponent:s.createElement(re,{type:"error"})})},ni=R.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),ri=()=>{const{strings:e}=N(),{language:t,countryCode:n,context:r}=W(),{aiAgentInfo:o,refreshActiveChannel:a,createConversation:i,setActiveChannel:c}=V(),{onNavigateToConversation:l}=ke(),u=te(["left","right","bottom"]),g=oi.use();return s.createElement(B,{activeOpacity:.75,onPress:async()=>{if(o!=null&&o.isMultipleActiveConversationsEnabled){const m=await i({aiAgentId:o.userId,language:t,country:n,context:r});c({url:m,status:z.ConversationStatus.OPEN}),l==null||l(m,z.ConversationStatus.OPEN)}else{const m=await a();l==null||l(m,z.ConversationStatus.OPEN)}}},s.createElement(_,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+u.paddingBottom,style:[g.container,u]},s.createElement(x,{variant:"h1",color:m=>m.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},oi=R.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),si=()=>{const{aiAgentInfo:e}=V();return e?s.createElement(ri,null):null},ai=()=>{const{themedColor:e}=$(),{onClose:t}=ke();return t?s.createElement(B,{hitSlop:4,onPress:t,activeOpacity:.75},s.createElement(O,{color:e.textHighEmphasis,type:"close",size:24})):null},ii=()=>{const{strings:e}=N();return s.createElement(x,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},li=()=>{const{paddingStart:e,paddingEnd:t}=te(["left","right"]);return s.createElement(pn,{left:s.createElement(_,{gap:6,flexDirection:"row",alignItems:"center",paddingStart:e},s.createElement(ii,null)),right:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:10,paddingEnd:t},s.createElement(ai,null))})},ci=()=>{const{components:e}=Me.useContext(),t=te(["top"]);return s.createElement(_,{flex:1,style:t},s.createElement(e.Header,null),s.createElement(e.Body,null),s.createElement(e.Footer,null))},Me=oe({template:ci,components:{Header:li,Body:ti,Footer:si}}),ui=({children:e,...t})=>{const{Template:n}=Me.useContext();return s.createElement(yn,{...t},s.createElement(n,null),e)},di=d.forwardRef(function({logLevel:t=F.LogLevel.WARN,language:n=we,userSessionInfo:r,children:o,strings:a,...i},c){const[l]=d.useState(()=>new Wt(t));l.level!==t&&(l.level=t);const{nativeModules:u,chatParams:g={},...m}=i;return s.createElement(gn,{config:u},({keyValueStorage:h})=>s.createElement(gi,{logger:l,theme:m.theme,language:n,strings:a},s.createElement(or,{language:n,logger:l,chatSDK:m.customChatSDK,keyValueStorage:h,chatParams:{...g,useMMKVStorageStore:{getString:p=>u.mmkv.getString(p),set:(p,f)=>u.mmkv.set(p,f),getAllKeys:()=>u.mmkv.getAllKeys(),delete:p=>u.mmkv.remove(p)}},extensions:{platform:F.SendbirdPlatform.REACT_NATIVE,deviceOSPlatform:y.Platform.select({web:F.DeviceOsPlatform.WEB,ios:F.DeviceOsPlatform.IOS,default:F.DeviceOsPlatform.ANDROID})},...m},s.createElement(uo,{ref:c,userSessionInfo:r},o))))}),mi=$n(Ie,Me,_t,Te),gi=({children:e,logger:t,theme:n,language:r,strings:o})=>s.createElement(lt.SafeAreaProvider,null,s.createElement(ho,{logger:t,...n},s.createElement(dn,null,s.createElement(zo,{language:r,logger:t,strings:o},s.createElement(Zr,null,s.createElement(mi,null,e))))));exports.AIAgentProviderContainer=di;exports.AnonymousSessionInfo=ve;exports.BottomSheet=le;exports.BottomSheetLayout=Te;exports.Conversation=Ya;exports.ConversationContext=ss;exports.ConversationContextProvider=Jt;exports.ConversationLayout=Ie;exports.ConversationList=ui;exports.ConversationListContext=Xa;exports.ConversationListContextProvider=yn;exports.ConversationListLayout=Me;exports.ManualSessionInfo=mt;exports.ModalProvider=dn;exports.NativeAdapterProvider=gn;exports.useConversationContext=K;exports.useConversationListContext=ke;exports.useMessengerSessionContext=V;exports.useModalContext=un;exports.useNativeAdapterContext=mn;
|