@sendbird/ai-agent-messenger-react-native 0.0.1-beta.2 โ 0.0.1-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +582 -2
- package/dist/index.js +248 -241
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +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"),le=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 re(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=le.differenceInMinutes(r,o);return a<1?t.justNow:a<60?t.minutesAgo(a):le.isToday(o)?t.hoursAgo(le.differenceInHours(r,o)):n(o,t.dateShortFormat)}const Gn="1.6.4",ae="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=le.isSameMinute(t.createdAt,e.createdAt);return l&&u},a=()=>{if(!n||!ee(n))return!1;const l=n.sender.userId===e.sender.userId,u=le.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=`@${ae}`,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(`[${ae}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${ae}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${ae}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${ae}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${ae}/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:te,deauthenticate:oe}=xr({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(P=>{const{appearance:k,bot:M,launcher:U,active_channel:se}=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[se.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:te,deauthenticate:oe,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??{}}}}},[te,oe,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:te,deauthenticate:oe,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{Provider:lo,useContext:V}=q("MessengerSession"),co=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(uo,{...r},e))}),uo=({children:e,...t})=>{const{userSession:n,aiAgentInfo:r,launcherInfo:o}=t;return s.createElement(lo,{value:{...t,userSession:n,aiAgentInfo:r,launcherInfo:o}},e)},{Provider:mo,useContext:$}=q("MessengerTheme"),go=({children:e,...t})=>s.createElement(br,{...t,appearance:{theme:t.mode??"light"}},n=>{const r=ho(n.theme);return s.createElement(mo,{value:{...n,themedColor:r}},e)});function ho(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]})}}}},fo={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")},po={send:!0,chat:!0,message:!0},O=({customSource:e,type:t,color:n,size:r=24,style:o})=>{const a=_o.use(),i=y.I18nManager.isRTL&&!!po[t];return s.createElement(_,{alignItems:"center",justifyContent:"center"},s.createElement(y.Image,{resizeMode:"contain",source:e??fo[t],style:[a.icon({color:n,size:r,mirror:i}),o]}))},_o=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)},yo=({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),bo={...Be,conversation:{...Be.conversation,attachment_camera:"Kamera",attachment_photo:"Fotobibliothek",attachment_document:"Dateien"},conversation_list:{...Be.conversation_list,footer_title:"Mit Agent sprechen"}},Eo={language:st.language,dateLocale:st.dateLocale,strings:bo},He=X(Xe.strings),Co={...He,conversation:{...He.conversation,attachment_camera:"Camera",attachment_photo:"Photo library",attachment_document:"Files"},conversation_list:{...He.conversation_list,footer_title:"Talk to Agent"}},vo={language:Xe.language,dateLocale:Xe.dateLocale,strings:Co},Oe=X(et.strings),So={...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"}},Ao={language:et.language,dateLocale:et.dateLocale,strings:So},Ne=X(nt.strings),wo={...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"}},xo={language:nt.language,dateLocale:nt.dateLocale,strings:wo},$e=X(rt.strings),To={...$e,conversation:{...$e.conversation,attachment_camera:"เคเฅเคฎเคฐเคพ",attachment_photo:"เคซเฅเคเฅ เคฒเคพเคเคฌเฅเคฐเฅเคฐเฅ",attachment_document:"เคซเคพเคเคฒเฅเค"},conversation_list:{...$e.conversation_list,footer_title:"เคเคเฅเคเค เคธเฅ เคฌเคพเคค เคเคฐเฅเค"}},Io={language:rt.language,dateLocale:rt.dateLocale,strings:To},Fe=X(ot.strings),ko={...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"}},Mo={language:ot.language,dateLocale:ot.dateLocale,strings:ko},Ue=X(Qe.strings),Po={...Ue,conversation:{...Ue.conversation,attachment_camera:"ใซใกใฉ",attachment_photo:"ใใฉใใฉใคใใฉใช",attachment_document:"ใใกใคใซ"},conversation_list:{...Ue.conversation_list,footer_title:"ใจใผใธใงใณใใจ่ฉฑใ"}},Lo={language:Qe.language,dateLocale:Qe.dateLocale,strings:Po},ze=X(Je.strings),Do={...ze,conversation:{...ze.conversation,attachment_camera:"์นด๋ฉ๋ผ",attachment_photo:"์ฌ์ง ๋ผ์ด๋ธ๋ฌ๋ฆฌ",attachment_document:"ํ์ผ"},conversation_list:{...ze.conversation_list,footer_title:"์๋ด์ฌ์ ๋ํ"}},Ro={language:Je.language,dateLocale:Je.dateLocale,strings:Do},qe=X(tt.strings),Bo={...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"}},Ho={language:tt.language,dateLocale:tt.dateLocale,strings:Bo},We=X(at.strings),Oo={...We,conversation:{...We.conversation,attachment_camera:"Kamera",attachment_photo:"Fotoฤraf kitaplฤฑฤฤฑ",attachment_document:"Dosyalar"},conversation_list:{...We.conversation_list,footer_title:"Temsilciyle konuล"}},No={language:at.language,dateLocale:at.dateLocale,strings:Oo},Pt=new Map([["en",vo],["ko",Ro],["ja",Lo],["es",Ao],["pt",Ho],["fr",xo],["hi",Io],["it",Mo],["de",Eo],["tr",No]]),Lt=e=>Pt.get(e)??Pt.get(we),$o=(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:Fo,useContext:N}=q("Localization"),Uo=({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(Fo,{value:{language:o.language,strings:$o(o.strings,n),dateLocale:o.dateLocale,format:(i,c,l)=>le.format(i,c,{locale:o.dateLocale,...l})}},r)},Zt=350,zo=({children:e,...t})=>s.createElement(y.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:Zt,...t},n=>typeof e=="function"?e(n):e),qo=({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(qo,{...e}):s.createElement(zo,{...e}),Wo=({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(Go,{onPress:n.onPress,label:n.label??o.common.placeholder_something_went_wrong_retry_label}))},Go=({label:e,onPress:t})=>{const{themedColor:n}=$();return s.createElement(B,{onPress:t},s.createElement(_,{style:jo.button},s.createElement(O,{type:"refresh",size:20}),s.createElement(x,{variant:"button",color:n.primary},e)))},jo=y.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),Vo=({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}))},Ko=({label:e,icon:t="chat",...n})=>{const{strings:r}=N();return s.createElement(pt,{icon:t,label:e??r.common.placeholder_no_conversations,...n})},Yo=({label:e,icon:t="message",...n})=>{const{strings:r}=N();return s.createElement(pt,{icon:t,label:e??r.common.placeholder_no_messages,...n})},Zo=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(yo,null,n)},_t=re({template:Zo,components:{Loading:Vo,Error:Wo,NoChannels:Ko,NoMessages:Yo}}),ne=e=>{const{Template:t}=_t.useContext();return s.createElement(t,{...e})},Xo=50,{Provider:Jo,useContext:Qo}=q("ConversationScroll");function es({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(Jo,{value:{ref:n,state:{distanceFromBottom:i,isAtBottom:i<=Xo,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 ts(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 ns(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:rs,Context:os,useContext:K}=q("Conversation"),Jt=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:r,children:o})=>{const a=Qo(),{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 ts(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:ns},p=>s.createElement(rs,{value:{...p,scrollSource:a,onClose:n,onNavigateToConversationList:r,updateActiveChannel:h}},o)):s.createElement(ne,{type:"loading"})},ss=({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)))},as=({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(as)),is={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},ce=(e,t=y.I18nManager.isRTL?"rtl":"ltr")=>{const n=lt.useSafeAreaInsets();return e.reduce((r,o)=>{const a=is[t][o];return r[a]=n[o],r},{})},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=re({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=re({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=re({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=ce(["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 oe,he;const J=Kn(E,D,G),te={extendedMessagePayload:E.extendedMessagePayload,message:E.message,createdAt:E.createdAt,groupType:J};if(fe.isAdmin(E))return fe.isCSAT(E)?b?s.createElement(r,{...te,...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,{...te,messageType:"admin"});if(fe.isOutgoing(E,(l==null?void 0:l.userId)??"")){const Z={...te,sender:T(E),sendingStatus:E.sendingStatus};if(E.isUserMessage())return s.createElement(n,{...Z,messageType:"user"});if(E.isFileMessage()){const[P,k]=((oe=E.metaArrays.find(M=>M.key===Ft))==null?void 0:oe.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={...te,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:se}=M.internalData;U==="message.send"&&(se!=null&&se.message)&&u.sendUserMessage({message:se.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(ss,{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(ne,{type:"loading"}),EmptyComponent:s.createElement(ne,{type:"noMessages"}),ErrorComponent:s.createElement(ne,{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=ce(["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=re({template:Ia,components:{ActionItem:Ta}}),ie=e=>{const{Template:t}=Te.useContext();return s.createElement(xa,{onClose:e.onClose},s.createElement(t,{...e}))};ie.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=ce(["left","right","bottom"]),a=Ua.use(),{sendButtonVisible:i,addAttachmentButtonVisible:c,...l}=$a(),m={...l,onPressAddAttachment:async()=>{const h=await r(p=>s.createElement(ie,{onClose:()=>p()},s.createElement(ie.ActionItem,{icon:"camera",label:t.conversation.attachment_camera,onPress:async()=>{const f=await e.captureCamera();p(f)}}),s.createElement(ie.ActionItem,{icon:"photo",label:t.conversation.attachment_photo,onPress:async()=>{const f=await e.selectFromGallery({multiple:!1});p(f)}}),s.createElement(ie.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=ce(["left","right","top"]),r=za.use();return s.createElement(_,{style:r.container(n)},s.createElement(_,{flexShrink:1},e),s.createElement(_,{flexShrink:0},t))},za=R.create(({theme:e,themedColor:t})=>({container:n=>({width:"100%",paddingTop:n.paddingTop,height:56+n.paddingTop,paddingStart:n.paddingStart+12,paddingEnd:n.paddingEnd+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=()=>s.createElement(pn,{left:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:6},s.createElement(Ga,null),s.createElement(ja,null)),right:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:10},s.createElement(Wa,null),s.createElement(qa,null))}),Ka=e=>{const{components:t}=Ie.useContext();return s.createElement(_,{flex:1},s.createElement(t.Header,null),s.createElement(t.Body,null),s.createElement(t.Footer,null))},Ie=re({template:Ka,components:{Header:Va,Body:ga,Footer:Fa}}),Ya=({children:e,...t})=>{const{Template:n}=Ie.useContext();return s.createElement(es,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(ne,{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=re({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=ce(["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(ne,{type:"loading"}),EmptyComponent:s.createElement(ne,{type:"noChannels"}),ErrorComponent:s.createElement(ne,{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=ce(["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=()=>s.createElement(pn,{left:s.createElement(_,{gap:6,flexDirection:"row",alignItems:"center"},s.createElement(ii,null)),right:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:10},s.createElement(ai,null))}),ci=()=>{const{components:e}=Me.useContext();return s.createElement(_,{flex:1},s.createElement(e.Header,null),s.createElement(e.Body,null),s.createElement(e.Footer,null))},Me=re({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(co,{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(go,{logger:t,...n},s.createElement(dn,null,s.createElement(Uo,{language:r,logger:t,strings:o},s.createElement(Zr,null,s.createElement(mi,null,e))))));exports.AIAgentProviderContainer=di;exports.AnonymousSessionInfo=ve;exports.BottomSheet=ie;exports.BottomSheetLayout=Te;exports.Conversation=Ya;exports.ConversationContext=os;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;
|
|
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"),le=require("date-fns"),Ut=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 re(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")},zt=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 At(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=le.differenceInMinutes(r,o);return a<1?t.justNow:a<60?t.minutesAgo(a):le.isToday(o)?t.hoursAgo(le.differenceInHours(r,o)):n(o,t.dateShortFormat)}const Gn="1.6.4",ae="sb-agent",jn=Gn,qt="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=le.isSameMinute(t.createdAt,e.createdAt);return l&&u},a=()=>{if(!n||!ee(n))return!1;const l=n.sender.userId===e.sender.userId,u=le.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===Ut.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"},Wt=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 wt=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Gt={isStreaming(e){const t=wt(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=wt(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=`@${ae}`,xt=({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 jt=(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))(jt||{});class Vt{constructor(t){this.level=t}verbose(...t){this.level<=0&&console.log(`[${ae}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${ae}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${ae}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${ae}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${ae}/error]`,...t)}}function Tt(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}},It=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 Vt(jt.WARN),b=h??new er(v);return{appId:e,aiAgentId:t,language:r,countryCode:o,context:a,queryParams:i,config:It(c),keyValueStorage:n,logger:v,dispatcher:b,chatSDK:l??Tt(e,p,u),cache:xt({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=Tt(e,p,{newInstance:!0,...u})),{...v,appId:e,aiAgentId:t,keyValueStorage:n,language:r,countryCode:o,context:a,queryParams:i,config:It(c),logger:b,dispatcher:T,chatSDK:S,cache:xt({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 Kt(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function ar(e){const t=Kt(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 kt(e){const t=Kt(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 Mt(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??kt(a),c=n??Ye.DEFAULT_BOT_MSG_BG,l=r??kt(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(()=>Mt({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=Mt({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 Yt(){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=Yt(),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=Yt(),{authenticate:te,deauthenticate:oe}=xr({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(P=>{const{appearance:k,bot:M,launcher:U,active_channel:se}=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[se.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:te,deauthenticate:oe,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??{}}}}},[te,oe,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:te,deauthenticate:oe,attachmentMode:D}},n)}),Zt=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=Zt(e);return d.useEffect(()=>{if(!t)return;const i=a.some(l=>l.userId===n),c=de(t,n)&&Gt.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=Pt(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:Pt(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},Pt=(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&&zt(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")},Xt=({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")},Lt=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}),Dt=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{Provider:lo,useContext:V}=q("MessengerSession"),co=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(uo,{...r},e))}),uo=({children:e,...t})=>{const{userSession:n,aiAgentInfo:r,launcherInfo:o}=t;return s.createElement(lo,{value:{...t,userSession:n,aiAgentInfo:r,launcherInfo:o}},e)},{Provider:mo,useContext:$}=q("MessengerTheme"),go=({children:e,...t})=>s.createElement(br,{...t,appearance:{theme:t.mode??"light"}},n=>{const r=ho(n.theme);return s.createElement(mo,{value:{...n,themedColor:r}},e)});function ho(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]})}}}},fo={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")},po={send:!0,chat:!0,message:!0},O=({customSource:e,type:t,color:n,size:r=24,style:o})=>{const a=_o.use(),i=y.I18nManager.isRTL&&!!po[t];return s.createElement(_,{alignItems:"center",justifyContent:"center"},s.createElement(y.Image,{resizeMode:"contain",source:e??fo[t],style:[a.icon({color:n,size:r,mirror:i}),o]}))},_o=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:[Jt.body,n]},t&&s.createElement(O,{type:t,size:e,color:a.textLowEmphasis}),r&&s.createElement(x,{variant:"body1",color:a.textMidEmphasis},r),o)},yo=({children:e})=>{const{theme:t}=$();return s.createElement(_,{backgroundColor:t.colors.base.background,style:Jt.container},e)},Jt=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),bo={...Be,conversation:{...Be.conversation,attachment_camera:"Kamera",attachment_photo:"Fotobibliothek",attachment_document:"Dateien"},conversation_list:{...Be.conversation_list,footer_title:"Mit Agent sprechen"}},Eo={language:st.language,dateLocale:st.dateLocale,strings:bo},He=X(Xe.strings),Co={...He,conversation:{...He.conversation,attachment_camera:"Camera",attachment_photo:"Photo library",attachment_document:"Files"},conversation_list:{...He.conversation_list,footer_title:"Talk to Agent"}},vo={language:Xe.language,dateLocale:Xe.dateLocale,strings:Co},Oe=X(et.strings),So={...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"}},Ao={language:et.language,dateLocale:et.dateLocale,strings:So},Ne=X(nt.strings),wo={...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"}},xo={language:nt.language,dateLocale:nt.dateLocale,strings:wo},$e=X(rt.strings),To={...$e,conversation:{...$e.conversation,attachment_camera:"เคเฅเคฎเคฐเคพ",attachment_photo:"เคซเฅเคเฅ เคฒเคพเคเคฌเฅเคฐเฅเคฐเฅ",attachment_document:"เคซเคพเคเคฒเฅเค"},conversation_list:{...$e.conversation_list,footer_title:"เคเคเฅเคเค เคธเฅ เคฌเคพเคค เคเคฐเฅเค"}},Io={language:rt.language,dateLocale:rt.dateLocale,strings:To},Fe=X(ot.strings),ko={...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"}},Mo={language:ot.language,dateLocale:ot.dateLocale,strings:ko},Ue=X(Qe.strings),Po={...Ue,conversation:{...Ue.conversation,attachment_camera:"ใซใกใฉ",attachment_photo:"ใใฉใใฉใคใใฉใช",attachment_document:"ใใกใคใซ"},conversation_list:{...Ue.conversation_list,footer_title:"ใจใผใธใงใณใใจ่ฉฑใ"}},Lo={language:Qe.language,dateLocale:Qe.dateLocale,strings:Po},ze=X(Je.strings),Do={...ze,conversation:{...ze.conversation,attachment_camera:"์นด๋ฉ๋ผ",attachment_photo:"์ฌ์ง ๋ผ์ด๋ธ๋ฌ๋ฆฌ",attachment_document:"ํ์ผ"},conversation_list:{...ze.conversation_list,footer_title:"์๋ด์ฌ์ ๋ํ"}},Ro={language:Je.language,dateLocale:Je.dateLocale,strings:Do},qe=X(tt.strings),Bo={...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"}},Ho={language:tt.language,dateLocale:tt.dateLocale,strings:Bo},We=X(at.strings),Oo={...We,conversation:{...We.conversation,attachment_camera:"Kamera",attachment_photo:"Fotoฤraf kitaplฤฑฤฤฑ",attachment_document:"Dosyalar"},conversation_list:{...We.conversation_list,footer_title:"Temsilciyle konuล"}},No={language:at.language,dateLocale:at.dateLocale,strings:Oo},Rt=new Map([["en",vo],["ko",Ro],["ja",Lo],["es",Ao],["pt",Ho],["fr",xo],["hi",Io],["it",Mo],["de",Eo],["tr",No]]),Bt=e=>Rt.get(e)??Rt.get(we),$o=(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:Fo,useContext:N}=q("Localization"),Uo=({language:e=we,logger:t,strings:n,children:r})=>{const[o,a]=d.useState(()=>{const i=Dt(e);return Bt(i)});return d.useEffect(()=>{var l;const i=Dt(e),c=Bt(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(Fo,{value:{language:o.language,strings:$o(o.strings,n),dateLocale:o.dateLocale,format:(i,c,l)=>le.format(i,c,{locale:o.dateLocale,...l})}},r)},Qt=350,zo=({children:e,...t})=>s.createElement(y.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:Qt,...t},n=>typeof e=="function"?e(n):e),qo=({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:Qt,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(qo,{...e}):s.createElement(zo,{...e}),Wo=({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(Go,{onPress:n.onPress,label:n.label??o.common.placeholder_something_went_wrong_retry_label}))},Go=({label:e,onPress:t})=>{const{themedColor:n}=$();return s.createElement(B,{onPress:t},s.createElement(_,{style:jo.button},s.createElement(O,{type:"refresh",size:20}),s.createElement(x,{variant:"button",color:n.primary},e)))},jo=y.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),Vo=({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}))},Ko=({label:e,icon:t="chat",...n})=>{const{strings:r}=N();return s.createElement(pt,{icon:t,label:e??r.common.placeholder_no_conversations,...n})},Yo=({label:e,icon:t="message",...n})=>{const{strings:r}=N();return s.createElement(pt,{icon:t,label:e??r.common.placeholder_no_messages,...n})},Zo=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(yo,null,n)},_t=re({template:Zo,components:{Loading:Vo,Error:Wo,NoChannels:Ko,NoMessages:Yo}}),ne=e=>{const{Template:t}=_t.useContext();return s.createElement(t,{...e})},Xo=50,{Provider:Jo,useContext:Qo}=q("ConversationScroll");function es({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(Jo,{value:{ref:n,state:{distanceFromBottom:i,isAtBottom:i<=Xo,bottomSpace:o},props:{maintainVisibleContentPosition:h,onLayout:u,onContentSizeChange:g,onScroll:m},actions:{scrollToBottom:p,scrollToIndex:f,onBeforeMessageSend:C,onAfterMessageSend:v,onStreamingUpdate:b}}},t)}function en(e){return new Promise((t,n)=>{y.Image.getSize(e,(r,o)=>{t({width:String(r),height:String(o)})},r=>{n(r)})})}async function ts(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 en(n.uri);return new Ut.MessageMetaArray({key:qt,value:[r,o]})}catch{return}}}function ns(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:rs,Context:os,useContext:K}=q("Conversation"),tn=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:r,children:o})=>{const a=Qo(),{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 ts(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:ns},p=>s.createElement(rs,{value:{...p,scrollSource:a,onClose:n,onNavigateToConversationList:r,updateActiveChannel:h}},o)):s.createElement(ne,{type:"loading"})},ss=({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)))},as=({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}),nn=d.memo(d.forwardRef(as)),is={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},ce=(e,t=y.I18nManager.isRTL?"rtl":"ltr")=>{const n=lt.useSafeAreaInsets();return e.reduce((r,o)=>{const a=is[t][o];return r[a]=n[o],r},{})},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%"}})),rn=({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&&en(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(rn,{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})`,Ht=({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(rn,{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=Wt(e)?s.createElement(Ht,{...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(Ht,{...e,message:t.conversation.unknown_message_type})};function on({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(on,{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:Ot.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:Ot.citationText},a.title)))))))},Ot=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,sn=({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(sn,{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}=Et.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}))},Et=re({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),an=({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}))};function Ds(e){return typeof e=="object"&&e!==null&&"uri"in e}const Rs=({file:e,metadata:t,onClickMedia:n=({url:o})=>y.Linking.openURL(o),children:r})=>{const o=Bs.use(),{aspectRatio:a,localFile:i}=t,[c]=d.useState(()=>Ds(i)?i.uri: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(an,{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)},Bs=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}})),Nt=e=>{var n,r;const t=Hs.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))},Hs=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}})),Os=e=>{const{strings:t}=N(),n=Wt(e)?s.createElement(Nt,{...e}):null;return e.messageType==="user"?n:e.messageType==="file"?e.file.type.startsWith("image")?s.createElement(Rs,{...e},n):s.createElement(Ls,{...e},n):s.createElement(Nt,{...e,message:t.unknown_message_type})},Ns=({sendingStatus:e})=>{const{themedColor:t}=$();switch(e){case"pending":return s.createElement(_,{marginBottom:2},s.createElement(an,{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}))}},$s=({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},Fs=e=>{const{components:t}=Ct.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})))},Ct=re({template:Fs,components:{SendingStatus:Ns,SentTime:$s,MessageBody:Os}}),Us=e=>e.messageType!=="admin"?null:s.createElement(x,{variant:"caption2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},zs(e.message)),zs=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]}},qs=({children:e,style:t})=>s.createElement(x,{variant:"caption4",color:n=>n.error,style:t},e),Ws=({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})`))},Gs=({style:e})=>{const t=js.use();return s.createElement(_,{style:[t.separator,e]})},js=R.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),Vs=({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=Ks.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)})},Ks=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:Ws,ErrorLabel:qs,TextInput:Vs,Separator:Gs},ln=({onClick:e,checked:t,label:n,disabled:r,labelVariant:o="caption2"})=>{const{themedColor:a}=$(),i=Ys.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))},Ys=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}}})),Zs=({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(ln,{key:a.label,checked:r===a.value,label:a.label,disabled:t,onClick:()=>o==null?void 0:o(a.value)})))):null),Xs=({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(ln,{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))},Js=e=>null,Qs=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",a=cn.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(ea,{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))})))},ea=({value:e,src:t,label:n,selected:r})=>{const[o,a]=d.useState(!1),i=cn.use();return o?s.createElement(Js,{value:e,selected:r,label:n}):s.createElement(xe,{source:{uri:t},style:i.emojiImage(r),onError:()=>a(!0),accessibilityLabel:n})},cn=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})})),ta=({csatPayload:e})=>s.createElement(x,{variant:"button",color:t=>t.textHighEmphasis},e.title),na=new Set(["free_text","single_choice"]),Ge=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:a})=>{const[i,c]=Lt({csatType:t,csat:r,csatReason:o,isResolved:a}),[l,u]=Lt({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(na.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(ta,{...p}),t===Q.AI_AGENT_CSAT_5_WITH_CRE&&s.createElement(Zs,{...p,defaultValue:a,value:i.isResolved,onChange:f=>c({isResolved:f})}),s.createElement(Qs,{...p,value:i.csat,onChange:f=>c({csat:f})}),g&&s.createElement(Xs,{...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})))},ra=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})},oa=()=>{const{strings:e}=N();return s.createElement(x,{variant:"body2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},sa=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=ra(t==null?void 0:t.csat),u=aa.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&&At(a)?s.createElement(oa,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:()=>{!At(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))}))},aa=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}}})),ia=e=>{const{components:t}=vt.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)},vt=re({template:ia,components:{AdminMessage:Us,CSATMessage:sa}}),la=({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:[ca.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")))},ca=y.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),ua=()=>{var c;const{strings:e}=N(),{channelSource:t,scrollSource:n,updateActiveChannel:r}=K(),o=da.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)))},da=R.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),ma=()=>{const{aiAgentInfo:e}=V(),{channelSource:t}=K(),n=Zt(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}})()},ga=(e,t)=>!kn.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),ha=({messageStackDirection:e="top"})=>{var I;const{Template:t}=Et.useContext(),{Template:n}=Ct.useContext(),{Template:r}=vt.useContext(),{config:o,cache:a,chatSDK:i}=W(),{aiAgentInfo:c,userSession:l}=V(),{messageSource:u,channelSource:g,scrollSource:m}=K(),h=ma(),p=fa.use(),f=ce(["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 oe,he;const J=Kn(E,D,G),te={extendedMessagePayload:E.extendedMessagePayload,message:E.message,createdAt:E.createdAt,groupType:J};if(fe.isAdmin(E))return fe.isCSAT(E)?b?s.createElement(r,{...te,...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,{...te,messageType:"admin"});if(fe.isOutgoing(E,(l==null?void 0:l.userId)??"")){const Z={...te,sender:T(E),sendingStatus:E.sendingStatus};if(E.isUserMessage())return s.createElement(n,{...Z,messageType:"user"});if(E.isFileMessage()){const[P,k]=((oe=E.metaArrays.find(M=>M.key===qt))==null?void 0:oe.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={...te,sender:T(E,Z),suggestedRepliesVisible:P,isBotMessage:Z,isStreaming:Gt.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:se}=M.internalData;U==="message.send"&&(se!=null&&se.message)&&u.sendUserMessage({message:se.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=ga(E,D)&&s.createElement(ss,{date:E.createdAt,style:p.dateSeparator});return s.createElement(_,null,Y,j)},H=()=>s.createElement(la,{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(ua,null),C.bottomSpace?s.createElement(_,{height:C.bottomSpace}):null)};return s.createElement(nn,{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(ne,{type:"loading"}),EmptyComponent:s.createElement(ne,{type:"noMessages"}),ErrorComponent:s.createElement(ne,{type:"error",action:{label:"Retry",onPress:g.refetch}}),ListFooterComponent:H(),ListHeaderComponent:A(),inverted:!0,...v})},fa=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:pa,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(pa,{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 _a={"image/jpeg":["image/jpeg","image/jpg"],"image/jpg":["image/jpeg","image/jpg"]};function St(e){const t=new Set;for(const n of e){const r=_a[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=St(t);return e.filter(r=>n.includes(r.type))}function ya(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($t),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($t),o=Se(r,t==null?void 0:t.mimeTypes);return o.length>0?o:null}}}function ba(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(Ft),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(Ft),o=Se(r,t==null?void 0:t.mimeTypes);return o.length>0?o:null}}}function Ea(e){return{selectFile:async t=>{const n=t!=null&&t.mimeTypes?St(t.mimeTypes):["*/*"],r=await e.getDocumentAsync({multiple:t==null?void 0:t.multiple,type:n});return r.canceled?null:r.assets.map(va)}}}function Ca(e){return{selectFile:async t=>{try{const n=t!=null&&t.mimeTypes?St(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(Sa)}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 $t(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 va(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function Ft(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 Sa(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function Aa(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:wa,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?ya(r):ba(r),c="getDocumentAsync"in o?Ea(o):Ca(o),l=Aa(a);return{...i,...c,...l}},[e]);return s.createElement(wa,{value:n},t)},{Provider:xa,useContext:hn}=q("BottomSheetAnimation");function Ta({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(xa,{value:{wrapWithAnimation:r,translateY:n,panHandlers:o.panHandlers}},t)}const Ia=({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))},ka=({onClose:e,children:t})=>{const n=fn.use(),{translateY:r,panHandlers:o,wrapWithAnimation:a}=hn(),i=ce(["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=re({template:ka,components:{ActionItem:Ia}}),ie=e=>{const{Template:t}=Te.useContext();return s.createElement(Ta,{onClose:e.onClose},s.createElement(t,{...e}))};ie.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}})),Ma=({onPressAddAttachment:e,editable:t})=>s.createElement(B,{disabled:!t,style:Pa.container,activeOpacity:.75,onPress:e},s.createElement(O,{type:"add",size:24,color:n=>t?n.primary:n.textDisabled})),Pa=y.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),La=({name:e,type:t,url:n,onRemove:r})=>{const o=Da.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})))},Da=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}})),Ra=e=>{const{theme:t,themedColor:n}=$(),r=Ba.use();return s.createElement(_,{style:r.container},e.attachments&&s.createElement(sn,{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})))},Ba=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}})),Ha=({onPressSend:e})=>s.createElement(B,{style:Oa.container,activeOpacity:.75,onPress:e},s.createElement(O,{type:"send",size:24})),Oa=y.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Na=()=>{const{aiAgentInfo:e,userSession:t}=V(),{messageSource:n,channelSource:r}=K(),o=$a.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)??""))},$a=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"}})),Fa=()=>{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()||i.length>0,addAttachmentButtonVisible:g}},Ua=()=>{const e=mn(),{strings:t}=N(),{messageSource:n}=K(),{openModal:r}=un(),o=ce(["left","right","bottom"]),a=za.use(),{sendButtonVisible:i,addAttachmentButtonVisible:c,...l}=Fa(),m={...l,onPressAddAttachment:async()=>{const h=await r(p=>s.createElement(ie,{onClose:()=>p()},s.createElement(ie.ActionItem,{icon:"camera",label:t.conversation.attachment_camera,onPress:async()=>{const f=await e.captureCamera();p(f)}}),s.createElement(ie.ActionItem,{icon:"photo",label:t.conversation.attachment_photo,onPress:async()=>{const f=await e.selectFromGallery({multiple:!1});p(f)}}),s.createElement(ie.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(Na,null),s.createElement(_,{style:a.container(o)},c&&s.createElement(Ma,{...m}),s.createElement(Ra,{...m,attachments:m.files.length===0?null:m.files.map((h,p)=>s.createElement(La,{key:p,name:h.name,type:h.type,url:h.uri,onRemove:()=>m.onChangeFiles(m.files.filter((f,C)=>C!==p))}))}),i&&s.createElement(Ha,{...m})))},za=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=ce(["left","right","top"]),r=qa.use();return s.createElement(_,{style:r.container(n)},s.createElement(_,{flexShrink:1},e),s.createElement(_,{flexShrink:0},t))},qa=R.create(({theme:e,themedColor:t})=>({container:n=>({width:"100%",paddingTop:n.paddingTop,height:56+n.paddingTop,paddingStart:n.paddingStart+12,paddingEnd:n.paddingEnd+12,gap:8,flexDirection:"row",alignItems:"center",justifyContent:"space-between",backgroundColor:e.colors.base.headerBackground,borderBottomWidth:1,borderBottomColor:t.textDisabled})})),Wa=()=>{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},Ga=()=>{const{themedColor:e}=$(),{channelSource:{channel:t}}=K(),n=ht("handoff-button",t),r=!zt(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},ja=()=>{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}=Xt({channel:e,aiAgentInfo:r,userSession:n}),{theme:i}=$();return a?s.createElement(on,{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}))},Va=()=>{const{channelSource:{channel:e}}=K(),{userSession:t,aiAgentInfo:n}=V(),r=Xt({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))},Ka=()=>s.createElement(pn,{left:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:6},s.createElement(ja,null),s.createElement(Va,null)),right:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:10},s.createElement(Ga,null),s.createElement(Wa,null))}),Ya=e=>{const{components:t}=Ie.useContext();return s.createElement(_,{flex:1},s.createElement(t.Header,null),s.createElement(t.Body,null),s.createElement(t.Footer,null))},Ie=re({template:Ya,components:{Header:Ka,Body:ha,Footer:Ua}}),Za=({children:e,...t})=>{const{Template:n}=Ie.useContext();return s.createElement(es,null,s.createElement(tn,{...t},s.createElement(n,null),e))},{Provider:Xa,Context:Ja,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(Xa,{value:{...c,onClose:r,onNavigateToConversation:n}},o)):s.createElement(ne,{type:"loading"})},je=99,Qa=e=>{const{channel:t,onClick:n}=e,{strings:r,format:o}=N(),{themedColor:a}=$(),i=ti.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}+`)))))},ei=re({template:Qa,components:{}}),ti=R.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),ni=()=>{const{listSource:e,onNavigateToConversation:t}=ke(),{Template:n}=ei.useContext(),r=ce(["left","right"]),o=ri.use();return s.createElement(nn,{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(ne,{type:"loading"}),EmptyComponent:s.createElement(ne,{type:"noChannels"}),ErrorComponent:s.createElement(ne,{type:"error"})})},ri=R.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),oi=()=>{const{strings:e}=N(),{language:t,countryCode:n,context:r}=W(),{aiAgentInfo:o,refreshActiveChannel:a,createConversation:i,setActiveChannel:c}=V(),{onNavigateToConversation:l}=ke(),u=ce(["left","right","bottom"]),g=si.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)))},si=R.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),ai=()=>{const{aiAgentInfo:e}=V();return e?s.createElement(oi,null):null},ii=()=>{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},li=()=>{const{strings:e}=N();return s.createElement(x,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},ci=()=>s.createElement(pn,{left:s.createElement(_,{gap:6,flexDirection:"row",alignItems:"center"},s.createElement(li,null)),right:s.createElement(_,{flexDirection:"row",alignItems:"center",gap:10},s.createElement(ii,null))}),ui=()=>{const{components:e}=Me.useContext();return s.createElement(_,{flex:1},s.createElement(e.Header,null),s.createElement(e.Body,null),s.createElement(e.Footer,null))},Me=re({template:ui,components:{Header:ci,Body:ni,Footer:ai}}),di=({children:e,...t})=>{const{Template:n}=Me.useContext();return s.createElement(yn,{...t},s.createElement(n,null),e)},mi=d.forwardRef(function({logLevel:t=F.LogLevel.WARN,language:n=we,userSessionInfo:r,children:o,strings:a,...i},c){const[l]=d.useState(()=>new Vt(t));l.level!==t&&(l.level=t);const{nativeModules:u,chatParams:g={},...m}=i;return s.createElement(gn,{config:u},({keyValueStorage:h})=>s.createElement(hi,{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(co,{ref:c,userSessionInfo:r},o))))}),gi=$n(Ie,Me,_t,Te),hi=({children:e,logger:t,theme:n,language:r,strings:o})=>s.createElement(lt.SafeAreaProvider,null,s.createElement(go,{logger:t,...n},s.createElement(dn,null,s.createElement(Uo,{language:r,logger:t,strings:o},s.createElement(Zr,null,s.createElement(gi,null,e))))));exports.AIAgentProviderContainer=mi;exports.AnonymousSessionInfo=ve;exports.BottomSheet=ie;exports.BottomSheetLayout=Te;exports.Conversation=Za;exports.ConversationContext=os;exports.ConversationContextProvider=tn;exports.ConversationLayout=Ie;exports.ConversationList=di;exports.ConversationListContext=Ja;exports.ConversationListContextProvider=yn;exports.ConversationListLayout=Me;exports.IncomingMessageLayout=Et;exports.ManualSessionInfo=mt;exports.ModalProvider=dn;exports.NativeAdapterProvider=gn;exports.OutgoingMessageLayout=Ct;exports.SystemMessageLayout=vt;exports.useConversationContext=K;exports.useConversationListContext=ke;exports.useMessengerSessionContext=V;exports.useModalContext=un;exports.useNativeAdapterContext=mn;
|