@sendbird/ai-agent-messenger-react-native 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +46 -24
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var or=Object.defineProperty;var sr=(e,t,n)=>t in e?or(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var N=(e,t,n)=>sr(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react"),f=require("react-native"),fe=require("react-native-safe-area-context"),V=require("@sendbird/chat"),G=require("@sendbird/chat/aiAgent"),Nt=require("@sendbird/uikit-tools"),Ee=require("date-fns"),Ce=require("@sendbird/chat/message"),We=require("@sendbird/chat/groupChannel"),ar=require("date-fns/isSameDay"),ir=require("date-fns/locale/de"),lr=require("date-fns/locale/en-US"),cr=require("date-fns/locale/es"),ur=require("date-fns/locale/fr"),dr=require("date-fns/locale/hi"),mr=require("date-fns/locale/it"),gr=require("date-fns/locale/ja"),hr=require("date-fns/locale/ko"),fr=require("date-fns/locale/pt"),pr=require("date-fns/locale/tr"),_r=require("@react-native-clipboard/clipboard"),yr=require("react-native-code-highlighter"),br=require("react-syntax-highlighter/dist/esm/styles/hljs"),Er=require("react-native-markdown-display"),Ge=e=>e&&e.__esModule?e:{default:e};function Cr(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 a=Cr(d),vr=Ge(V),Sr=Ge(_r),Ar=Ge(yr),xr=Ge(Er),j=(e,t)=>{const n=d.createContext(null),r=({children:i,value:l})=>a.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),o=({children:i})=>a.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),s=()=>{const i=d.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,o.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:s}};function oe(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){const[i,l]=d.useState(()=>e.template),[c,u]=d.useState(e.components),m={Template:i,updateTemplate:h=>l(()=>h),components:c,updateComponent:(h,g)=>u(_=>({..._,[h]:g}))};return a.createElement(t.Provider,{value:m},s)}function r({template:s,children:i}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{s&&l(s)},[s]),a.createElement(a.Fragment,null,i)}function o({children:s}){return a.createElement(n,null,s)}return o.defaults=e,o.useContext=()=>d.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(s=>{o[s]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),o}function wr(...e){return function({children:n}){return e.reduce((r,o)=>a.createElement(o,null,r),n)}}const we=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===G.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Cn=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===G.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function Se(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 Ir(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Qt(e){return!!e&&e<Date.now()}function Tr(e){return!e.title}function kr(e,t){var n;if(e)return Tr(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}function Mr(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 Lr(e,t,n){var i;const r=new Date,o=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),s=Ee.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Ee.isToday(o)?n.hoursAgo(Ee.differenceInHours(r,o)):t(o,n.dateShortFormat)}const be="sb-agent",vn="KEY_IMG_ASPECT_RATIO",Sn="*/*",M={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},re=e=>!!e&&"sender"in e,Rr=e=>re(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Pr=(e,t,n,r=!0)=>{if(!r||!re(e))return"single";const o=()=>{if(!t||!re(t))return!1;const c=t.sender.userId===e.sender.userId,u=Ee.isSameMinute(t.createdAt,e.createdAt);return c&&u},s=()=>{if(!n||!re(n))return!1;const c=n.sender.userId===e.sender.userId,u=Ee.isSameMinute(n.createdAt,e.createdAt);return c&&u},i=o(),l=s();return i&&l?"middle":i?"bottom":l?"top":"single"},Ae=(e,t)=>(()=>{var r;return re(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Oe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>re(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>re(e)&&(e.sender.userId===t||e.sendingStatus===Ce.SendingStatus.PENDING)},Dr=e=>e.startsWith("image/"),Ht=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},An=e=>e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.message.length>0,zt=e=>{switch(e){case"top":case"middle":return M.GAP_GROUPED;default:return M.GAP_UNGROUPED}},Or=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(s,...i)=>{const[l,c,u]=i;return o<u&&r.push({type:"text",value:e.slice(o,u).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),o=u+s.length,s}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),r},Br=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Nr=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Hr=e=>e.replace(/~~/g,"\\~\\~"),zr=e=>{let t=e;return t=Br(t),t=Nr(t),t=Hr(t),t},Fr=typeof navigator<"u"&&navigator.product==="ReactNative",en=(e,t)=>{const n=r=>!t||t.length===0?!0:re(r)&&t.includes(r.sendingStatus);return Fr?e.find(n):e.findLast(n)};function Et(){}function $r(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Ur(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const tn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ue={isStreaming(e){const t=tn(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(Ae(e,t)){const r=tn(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)},checkExtendedFieldPresence(e){const t=e.extendedMessagePayload||{},n=i=>i.some(l=>["suggested_replies"].includes(l)?Array.isArray(t[l])&&t[l].length>0:typeof t[l]<"u"),r=n(rt.ui),o=n(rt.trail),s=n(rt.unusedAsync);return{ui:r,trail:o,unusedAsync:s}},shouldScrollToBottom(e,t,n=!1){if(Ae(e,t)){if(this.isGeneratedMessage(e)&&this.isStreaming(e))return!0;const{ui:r,trail:o,unusedAsync:s}=this.checkExtendedFieldPresence(e);return r?!(!n&&s):!!(n&&(o||s))}return!0}},rt={ui:["suggested_replies","cta_button","message_template","csat"],trail:["groundedness","manual","function_calls"],unusedAsync:["is_hallucination","is_moderated","flagged_types","is_last_in_turn","flagged_reason","used_sources"]},ot=`@${be}`,nn=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${ot}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}-template/message-template/tokens`,messengerSession:o=>{const s=Ur(`${e}/${t}/${o}`);return`${ot}-udata/${s}`},anonUserSession:()=>`${ot}-session/${e}/${t}`};return{template:{set:(o,s)=>n.set(r.template(o),s),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 s=n.get(r.messengerSession(o));return s?JSON.parse(s):null}catch{return null}},setSettings:(o,s)=>{try{delete s.auto_created_user;const i=JSON.stringify(s);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 s=JSON.stringify(o);n.set(r.anonUserSession(),s)}catch{return}},clear:o=>{try{o&&n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}};class qr{constructor(t){N(this,"subscribers",{});this.logger=t}async send(t){const n=Wr(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(s=>s(t.payload));await Promise.all(o).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(r=>r!==n))}}const Wr=()=>{let e=Et,t=Et;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var xn=(e=>(e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(xn||{});class wn{constructor(t){N(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${be}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${be}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${be}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${be}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${be}/error]`,...t)}}function rn(e,t,n,r){const o=vr.default.init({appId:e,modules:[new We.GroupChannelModule,new G.AIAgentModule],localCacheEnabled:!0,options:new V.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:V.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function Vr(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 ye={conversation:{isTalkToAgentViewEnabled:!0,input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0}}},Gr=e=>{var t,n,r,o,s,i,l,c,u,m;return e?{...ye,...e,conversation:{...ye.conversation,...e==null?void 0:e.conversation,input:{...(t=ye.conversation)==null?void 0:t.input,...(n=e==null?void 0:e.conversation)==null?void 0:n.input,camera:{...(o=(r=ye.conversation)==null?void 0:r.input)==null?void 0:o.camera,...(i=(s=e==null?void 0:e.conversation)==null?void 0:s.input)==null?void 0:i.camera},gallery:{...(c=(l=ye.conversation)==null?void 0:l.input)==null?void 0:c.gallery,...(m=(u=e==null?void 0:e.conversation)==null?void 0:u.input)==null?void 0:m.gallery}}}}:ye},{Provider:jr,useContext:U}=j("AIAgent");function Kr({appId:e,aiAgentId:t,keyValueStorage:n,networkStateAdapter:r,language:o,countryCode:s,context:i,queryParams:l,config:c,chatSDK:u,chatParams:m,children:h,logger:g,dispatcher:_,messengerVersion:p,extensions:S={platform:V.SendbirdPlatform.JS,deviceOSPlatform:$r()?V.DeviceOsPlatform.MOBILE_WEB:V.DeviceOsPlatform.WEB}}){const[b,E]=d.useState(()=>{const v=g??new wn(xn.WARN),C=_??new qr(v);return{logger:v,dispatcher:C,chatSDK:u??rn(e,S,p,m),cache:nn({appId:e,aiAgentId:t,storage:n})}});return d.useEffect(()=>{E(v=>{let C=v.logger,x=v.dispatcher,T=v.chatSDK;return g&&g!==v.logger&&(C=g),_&&_!==v.dispatcher&&(x=_),u&&u!==v.chatSDK?T=u:!u&&v.chatSDK.appId!==e&&(T=rn(e,S,p,{newInstance:!0,...m})),{...v,logger:C,dispatcher:x,chatSDK:T,cache:nn({appId:e,aiAgentId:t,storage:n})}})},[e,t,g,_,u,n]),d.useEffect(()=>()=>{b.chatSDK.disconnectWebSocket()},[b.chatSDK]),Vr(b.chatSDK),a.createElement(jr,{value:{...b,appId:e,aiAgentId:t,context:i,language:o,countryCode:s,queryParams:l,config:Gr(c),networkStateAdapter:r}},h)}const Yr=(e,t,n)=>Nt.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0});var Ct=(e=>(e.ConversationClose="conv.close",e))(Ct||{});const In=(e,t,n={})=>{let r=null,o=null,s=null;const{leading:i=!0,trailing:l=!0}=n,c=(...u)=>{const m=Date.now();if(s===null||m-s>=t)i?(e(...u),s=m):(o=u,s=m);else if(o=u,l&&!r){const h=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},h)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},c},vt={DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Tn(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Xr(e){const t=Tn(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Zr(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Jr(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),s=r-o;let i=0,l=0;const c=(r+o)/2;return r!==o&&(l=c>.5?s/(2-r-o):s/(r+o)),r===e?i=(t-n)/s+(t<n?6:0):r===t?i=(n-e)/s+2:r===n&&(i=(e-t)/s+4),i/=6,[i,l,c]}function Qr(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const i=function(m,h,g){return g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(h-m)*6*g:g<.5?h:g<.6666666666666666?m+(h-m)*(.6666666666666666-g)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=i(c,l,e+1/3),o=i(c,l,e),s=i(c,l,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(s*255)]}function Be(e,t,n){const[r,o,s]=Xr(e),[i,l,c]=Jr(r,o,s),u=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,g,_]=Qr(i,m,u);return Zr([Math.round(h),Math.round(g),Math.round(_)])}function eo(e,t="light"){return{extraDark:Be(e,.6,1.2),dark:Be(e,.85,1.1),main:e,light:Be(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Be(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function on(e){const t=Tn(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+s*.114>n?vt.BLACK:vt.WHITE}function to(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 no=(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}}),Ne={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},st={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function sn(e){const t=ro(e),{colors:n,aiAgentColorVariables:r}=oo(e,t),o=ao(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:o}}function ro({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ne.primary.main?Ne.primary:eo(n,e):Ne.primary;return{...Ne,primary:r,...t}}function oo({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,i=t??on(s),l=n??vt.DEFAULT_BOT_MSG_BG,c=r??on(l);return{colors:(e==="light"?to:no)(o,s,i,l,c),aiAgentColorVariables:{primary_color:s,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function so(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function ao({typography:e}){if(!e)return st;const t={...st};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=st[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=so(o,r,s)}}),t}const{Provider:io,useContext:lo}=j("AIAgentTheme");function co({logger:e,palette:t,typography:n,appearance:r,children:o}){const s=d.useRef(null),[i,l]=d.useState(()=>sn({selectedTheme:(r==null?void 0:r.theme)??"light",palette:t,typography:n,primary:r==null?void 0:r.primaryColor,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor})),c=d.useCallback((u,m)=>{m&&(s.current=m);const h=(r==null?void 0:r.theme)??u,g=s.current?s.current.themes[h]:null,_={primary:r==null?void 0:r.primaryColor,primaryContrast:void 0,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!_.primary&&(g!=null&&g.primary_color)&&(_.primary=g.primary_color,_.primaryContrast=g.primary_contrast_color),!_.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(_.botMessageBackground=g.bot_message_bg_color,_.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const p=sn({selectedTheme:h,palette:t,typography:n,..._});l(p),e==null||e.info("theme.update:",h)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor,t,n,e]);return d.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&c(i.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),a.createElement(io,{value:{theme:i,updateTheme:c}},o)}const an=25*1024*1024,uo={off:"off",always:"always",handed_off_only:"handed_off_only"},mo=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:1,attachmentMode:"handed_off_only",defaultUploadSizeLimit:an,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:new Set(["image/png","image/jpeg","image/jpg"]),supportedFileMimeTypes:new Set(["application/pdf"])})),n=d.useCallback(({active_channel:o,upload_restriction:s})=>{const{maxAttachmentCount:i,attachmentMode:l,defaultUploadSizeLimit:c,supportedImageMimeTypes:u,supportedFileMimeTypes:m}=e;t({maxAttachmentCount:i,attachmentMode:uo[o.attachment_mode]??l,defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??c,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??u),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??m)})},[]),r=d.useCallback(o=>{const{channel:s,uploadSizeLimit:i=an}=o,l=(u=!0)=>s!=null&&s.isAIAgent?u?Se(s):!1:!0,c=u=>{if(l())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(u)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(l(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return Se(s);default:return!0}},get supportedMimeTypes(){return l()?[Sn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:u=>l()?!0:e.supportedImageMimeTypes.has(u)||e.supportedFileMimeTypes.has(u),getUploadSizeLimit:c,getUploadSizeLimitInMB:u=>c(u)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}};function kn(){const{chatSDK:e,logger:t}=U();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 go(){const{chatSDK:e,logger:t}=U(),n=d.useCallback(async(o,s,i)=>{if(t.debug("useChatConnection.connect: start, session",o.userId),s){const l=new V.SessionHandler({...s,onSessionTokenRequired:ho(s.onSessionTokenRequired,i)});e.setSessionHandler(l)}try{return await e.connect(o.userId,o.authToken),t.debug("useChatConnection.connect: end, currentUser",e.currentUser),e.currentUser}catch(l){const c=l;if(e.isCacheEnabled){if(po(c))t.warn("useChatConnection.connect","offline connect restricted",c.message,c.code),t.warn("useChatConnection.connect","clear cached-data"),await e.clearCachedData().catch(u=>t.warn("useChatConnection.connect","clear cached-data failure",u));else if(e.currentUser)return t.debug("useChatConnection.connect: end (offline), currentUser",e.currentUser),e.currentUser}throw t.warn("useChatConnection.connect","connect failure",c.message,c.code),c}},[e,t]),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 ho(e,t){if(e)return async(n,r)=>{new Promise((o,s)=>e==null?void 0:e(o,s)).then(o=>{o&&(t==null||t(o)),n(o)}).catch(o=>{r(o)})}}const fo=[400300,400301,400302,400310];function po(e){return fo.some(t=>e.code===t)}class Ft{constructor({userId:t,authToken:n,sessionHandler:r}){N(this,"userId");N(this,"authToken");N(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class Ve{constructor(){N(this,"userId");N(this,"authToken");N(this,"sessionHandler")}}const _o=1440*60*1e3,yo=e=>{const{logger:t,cache:n}=U(),r=()=>{const s=n.messenger.getAnonUser();return s?s.expireAt-_o<=Date.now()?(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session expired, clear cache"),n.messenger.clear(s.userId),null):(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session info detected"),s):null},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 s=["userId","authToken","sessionHandler"].filter(i=>!(i in e));return s.length>0&&t.error(`useUserSessionCandidate.getManualSessionInfo: missing required keys in userSessionInfo: ${s.join(", ")}`),t.debug("useUserSessionCandidate.getManualSessionInfo: manual session info detected"),e};return d.useMemo(()=>e instanceof Ft?{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 bo({userSessionInfo:e,onUpdateMessengerSettings:t,onPreAuth:n,onPostAuth:r,onErrorAuth:o,onAuthTokenRefreshed:s,onPostDeauth:i,forceCreateChannel:l}){const{aiAgentId:c,language:u,context:m,countryCode:h,logger:g,cache:_}=U(),{connect:p,disconnect:S}=go(),{type:b,userSessionCandidate:E}=yo(e),v=kn(),C=d.useCallback(async()=>{var L;g.debug("useAuthentication.authenticate: start");const T=E!=null&&E.userId?_.messenger.getSettings(E.userId):null;T!=null&&T.bot&&(t(T),g.debug("useAuthentication.authenticate: cached messenger settings",T));const A=await v({aiAgentId:c,userId:E==null?void 0:E.userId,language:u,country:h,context:m,forceCreateChannel:l,knownActiveChannelUrl:(L=T==null?void 0:T.active_channel)==null?void 0:L.channel_url});g.debug("useAuthentication.authenticate: messenger settings response",A);let w=null;if(A.auto_created_user)if(b==="manual")g.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),w={userId:E.userId,authToken:E.authToken};else{const{user_id:$,session_token:Y,expire_at:q}=A.auto_created_user;_.messenger.setAnonUser({userId:$,authToken:Y,expireAt:q}),w={userId:$,authToken:Y}}else w={userId:(E==null?void 0:E.userId)??"",authToken:(E==null?void 0:E.authToken)??""};_.messenger.setSettings(w.userId,A),t(A);try{await n(A,w),await p(w,E==null?void 0:E.sessionHandler,s),await r(A,w)}catch($){throw $ instanceof Error&&(o($),g.error("useAuthentication.authenticate: failed to connect",$)),$}return A},[v,p,b,E==null?void 0:E.userId,E==null?void 0:E.sessionHandler,E==null?void 0:E.authToken,c,u,m,h,l,_.messenger.setAnonUser,_.messenger.getSettings,_.messenger.setSettings,t,n,r,o,s]),x=d.useCallback(async()=>{g.debug("useAuthentication.deauthenticate: start"),await S(),i(),g.debug("useAuthentication.deauthenticate: completed")},[S,g,i]);return{authenticate:C,deauthenticate:x,userSessionCandidate:E}}const Eo=e=>JSON.parse(e),Co=()=>{const{chatSDK:e,logger:t,cache:n}=U(),r=d.useCallback(()=>{var l,c;const s=(c=(l=e.appInfo)==null?void 0:l.aiAgentInfo)==null?void 0:c.templateListToken;if(!s)return!1;const i=n.template.getCachedToken();return i?s!==i:!0},[e,n.template.getCachedToken]),o=d.useCallback(async()=>{try{const{templates:s,token:i}=await e.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=Eo(l);n.template.set(c,l)}n.template.setCachedToken(i)}catch(s){t==null||t.error("messageTemplateContext.syncCachedTemplates: error:",s)}},[e,t,n.template.set,n.template.setCachedToken]);return{shouldSyncCachedTemplate:r,syncCachedTemplates:o}},{Provider:vo,useContext:je}=j("AIAgentMessengerSession"),So=d.forwardRef(function({userSessionInfo:e,forceCreateChannel:t,children:n},r){const{appId:o,aiAgentId:s,chatSDK:i,language:l,countryCode:c,context:u,cache:m,logger:h}=U(),{updateTheme:g}=lo(),[_,p]=d.useState(void 0),[S,b]=d.useState(void 0),[E,v]=d.useState(null),[C,x]=d.useState(null),[T,A]=d.useState(null),[w,L]=d.useState(null),{updateBaseAttachmentRules:$,createAttachmentRules:Y}=mo(),{shouldSyncCachedTemplate:q,syncCachedTemplates:K}=Co(),ne=kn(),{authenticate:I,deauthenticate:X}=bo({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(D=>{const{appearance:B,bot:W,launcher:Z}=D;g(B.selected_theme,B),A({userId:W.bot_userid,profileUrl:W.bot_profile_url,nickname:W.bot_nickname,replyToFile:W.reply_to_file,specialNotice:W.special_notice,specialNoticeEnabled:W.is_special_notice_enabled,showHandoffButton:W.show_handoff_button??!0,isMultipleActiveConversationsEnabled:W.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:D.bot.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:D.bot.is_user_feedback_comment_option_enabled??!1}),L({type:Z.image_type||"default_icon",imageUrl:Z.image_url}),$(D)},[g]),onPreAuth:d.useCallback((D,B)=>{p(void 0),x(B)},[]),onPostAuth:d.useCallback(async D=>{v(i.currentUser),q()&&await K(),b({url:D.active_channel.channel_url,status:G.ConversationStatus.OPEN})},[i,q,K]),onErrorAuth:d.useCallback(D=>{p(D)},[]),onAuthTokenRefreshed:d.useCallback(D=>{x(B=>B?{...B,authToken:D}:null)},[]),onPostDeauth:d.useCallback(()=>{m.template.clear(),m.messenger.clear(C==null?void 0:C.userId),v(null),b(void 0),x(null),A(null),L(null)},[m.template.clear,m.messenger.clear,C])}),de=d.useCallback(async()=>{var D;if(C){h.debug("agentMessengerSession.refreshActiveChannel: try to refresh active channel"),b(void 0);const B=await ne({aiAgentId:s,userId:C.userId,language:l,country:c,context:u,forceCreateChannel:t,knownActiveChannelUrl:(D=m.messenger.getSettings(C.userId))==null?void 0:D.active_channel.channel_url});return m.messenger.setSettings(C.userId,B),b({url:B.active_channel.channel_url,status:G.ConversationStatus.OPEN}),h.info("agentMessengerSession.refreshActiveChannel: refreshed active channel",B.active_channel.channel_url),B.active_channel.channel_url}else throw h.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")},[ne,o,s,C==null?void 0:C.userId,l,c,u,t,m.messenger.getSettings,m.messenger.setSettings]),ke=d.useCallback(async D=>{if(!(C!=null&&C.userId))throw new Error("Current user is not authenticated. Please authenticate first.");const B=await ne({...D,userId:C.userId,knownActiveChannelUrl:void 0}),W=B.active_channel.channel_url;return m.messenger.setSettings(C.userId,B),W},[C==null?void 0:C.userId,ne]),[Me]=d.useState(()=>In(D=>{var B;h.info("agentMessengerSession.channelChanged: channel.conversation",D.conversation),b({url:D.url,status:((B=D.conversation)==null?void 0:B.status)??G.ConversationStatus.OPEN})},250,{trailing:!1,leading:!0}));return Nt.useGroupChannelHandler(i,{onChannelChanged:D=>{D.isGroupChannel()&&D.url===(S==null?void 0:S.url)&&Me(D)}}),d.useEffect(()=>()=>{Me.cancel()},[Me]),d.useImperativeHandle(r,()=>{const D=async()=>{if(!S)throw new Error("No active conversation. Please start a conversation first.");return await i.groupChannel.getChannel(S.url)};return{activeChannel:S,chatSDK:i,authenticate:I,deauthenticate:X,updateContext:async B=>{const Z=await(await D()).updateContext(s,B);return{...Z,context:Z.context??{}}},patchContext:async B=>{const Z=await(await D()).patchContext(s,B);return{...Z,context:Z.context??{}}},getContextObject:async()=>{const W=await(await D()).getContextObject(s);return{...W,context:W.context??{}}}}},[I,X,S,i,s,h]),a.createElement(vo,{value:{sdkUser:E,userSessionInfo:e,userSession:C,activeChannel:S,setActiveChannel:b,refreshActiveChannel:de,createConversation:ke,connectionError:_,aiAgentInfo:T,launcherInfo:w,authenticate:I,deauthenticate:X,createAttachmentRules:Y}},n)}),Ao=()=>{const e=d.useId(),{chatSDK:t,networkStateAdapter:n}=U(),[r,o]=d.useState(()=>n?n.isOnline()?"connected":"reconnecting":"connected");return d.useEffect(()=>{const s=new V.ConnectionHandler({onDisconnected:()=>o("disconnected"),onConnected:()=>o("connected"),onReconnectStarted:()=>o("reconnecting"),onReconnectSucceeded:()=>o("connected"),onReconnectFailed:()=>o("disconnected")});return t.addConnectionHandler(e,s),()=>{t.removeConnectionHandler(e)}},[t,e]),d.useEffect(()=>{if(n)return n.subscribe(()=>{o("reconnecting")})},[n]),r},Mn=e=>{const{chatSDK:t}=U(),[n,r]=d.useState([]);return Nt.useGroupChannelHandler(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},xo=({channel:e,messages:t,isStreamAnimating:n})=>{const{aiAgentInfo:r,userSession:o}=je(),s=Ao(),i=wo({channel:e,lastMessage:en(t,[Ce.SendingStatus.SUCCEEDED]),aiAgentUserId:(r==null?void 0:r.userId)??"",isStreamAnimating:n}),l=Mo({shouldApply:!!(e!=null&&e.isAIAgent)&&!Se(e),isDisabledWhileAIResponding:i,lastMessage:en(t,[Ce.SendingStatus.PENDING,Ce.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""});if(!e||s==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(s==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(we(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Io(e))return{disabled:!0,disabledBy:"form_active"};const c=To(e);return c?{disabled:!0,disabledBy:c}:i||l?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},wo=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=d.useState(!1),i=Mn(e);return d.useEffect(()=>{if(!t)return;const l=i.some(u=>u.userId===n),c=Ae(t,n)&&(Ue.isStreaming(t)||r);s(!!(c||l))},[i,t,n,r]),o},Io=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,s=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return o&&!s},To=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},ko=3e4,Mo=({shouldApply:e,lastMessage:t,isDisabledWhileAIResponding:n,currentUserId:r})=>{const[o,s]=d.useState(!1),i=d.useRef(null),l=t&&Ae(t,r)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),s(!1)},u=g=>{i.current&&clearTimeout(i.current),s(!0),i.current=setTimeout(()=>{s(!1),i.current=null},g)},m=Date.now()-l,h=ko-m;return n||h<=0?c():u(h),()=>{i.current&&clearTimeout(i.current)}},[n,l]),o&&e},Lo=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(o=>{t(s=>{if(s.has(o))return s;const i=new Set(s);return i.add(o),i})},[]),r=d.useCallback(o=>{t(s=>{if(!s.has(o))return s;const i=new Set(s);return i.delete(o),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Ro}=j("AIAgentConversation");function Po({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedViaDispatcher:s,onBeforeSendMessage:i,onAfterSendMessage:l=Et,shouldMarkAsRead:c=!0,sortComparator:u}){var T;const m=()=>c&&(p==null?void 0:p.markAsRead()),{chatSDK:h,logger:g,dispatcher:_}=U(),{channel:p,channelFetchError:S,fetchChannel:b}=Do(t),E=Yr(h,p,{replyType:Ce.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:()=>!1,onChannelDeleted:n,onMessagesReceived:A=>r==null?void 0:r(A),onMessagesUpdated:A=>o==null?void 0:o(A),logger:g,markAsRead:m,sortComparator:u}),v=Lo(),C=xo({channel:p,messages:E.messages,isStreamAnimating:v.isAnimating});d.useEffect(()=>{m()},[c]),d.useEffect(()=>{const A=async w=>{const L=typeof(w==null?void 0:w.channelUrl)=="string";p&&L&&w.channelUrl!==p.url||(g.debug("conversation.dispatcher: try to close conversation",p),p!=null&&p.conversation&&p.conversation.status===G.ConversationStatus.OPEN&&(await p.closeConversation(),s==null||s()))};return _.subscribe(Ct.ConversationClose,A),()=>{_.unsubscribe(Ct.ConversationClose,A)}},[_,(T=p==null?void 0:p.conversation)==null?void 0:T.status,s]);const x={conversation:(p==null?void 0:p.conversation)??void 0,channelSource:{channel:p,error:S,refetch:()=>b(),closeConversation:async()=>{we(p)||await(p==null?void 0:p.closeConversation())}},messageSource:{messages:E.messages,initialized:E.initialized,loadPrevious:()=>E.loadPrevious(),loadNext:()=>E.loadNext(),deleteMessage:A=>E.deleteMessage(A),resendMessage:A=>E.resendMessage(A),sendUserMessage:async A=>{var L;if(((L=p==null?void 0:p.conversation)==null?void 0:L.status)===G.ConversationStatus.CLOSED)throw new Error("Conversation is closed");i&&(A=await i(A));const w=await E.sendUserMessage(A,l);return l==null||l(w),w},sendFileMessage:async A=>{var L;if(((L=p==null?void 0:p.conversation)==null?void 0:L.status)===G.ConversationStatus.CLOSED)throw new Error("Conversation is closed");i&&(A=await i(A));const w=await E.sendFileMessage(A,l);return l==null||l(w),w}},state:{streamAnimation:v,input:C}};return a.createElement(Ro,{value:x},e)}function Do(e){const{chatSDK:t,logger:n}=U(),{sdkUser:r}=je(),[o,s]=d.useState(void 0),[i,l]=d.useState(void 0);async function c(){if(!r){n.debug("conversation.fetchChannel: no sdk user, skip fetching channel");return}if(n.debug("conversation.fetchChannel: start"),s(void 0),l(void 0),e)try{n.debug("conversation.fetchChannel: get channel",e);const u=await t.groupChannel.getChannel(e);s(u),n.debug("conversation.fetchChannel: fetched channel",u)}catch(u){u instanceof V.SendbirdError&&l(u),n.error("conversation.fetchChannel: error",u)}}return Oo(o),d.useEffect(()=>{c()},[t,r,e]),{channel:o,channelFetchError:i,fetchChannel:c}}function Oo(e){const{chatSDK:t}=U(),{activeChannel:n,setActiveChannel:r}=je(),o=d.useId();d.useEffect(()=>{if(!e||!n)return;const s=new V.ConnectionHandler({onReconnectSucceeded:async()=>{var l;const i=await e.refresh();i.url===n.url&&r({url:i.url,status:((l=i.conversation)==null?void 0:l.status)??G.ConversationStatus.OPEN})}});return t.addConnectionHandler(o,s),()=>{t.removeConnectionHandler(o)}},[t,e,n])}class Bo{constructor(t,{filter:n,limit:r=20}){N(this,"filter");N(this,"_sdk");N(this,"_pinnedChannels");N(this,"_channels");N(this,"_isDisposed",!1);N(this,"_handlerId",`handler-id-${Date.now()}`);N(this,"_order",We.GroupChannelListOrder.LATEST_LAST_MESSAGE);N(this,"_limit");N(this,"_query");N(this,"_token");N(this,"_timestamp");N(this,"_isSyncing");N(this,"_channelHandler");N(this,"_connectionHandler");N(this,"_collectionEventHandler");N(this,"_throttledOnChannelChanged");var o,s,i,l,c,u,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(o=this.filter)==null?void 0:o.aiAgentChannelFilter,aiAgentConversationStatusFilter:(s=this.filter)==null?void 0:s.aiAgentConversationStatusFilter,aiAgentIds:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.pinnedChannelUrls,copilotConversationOnly:(u=this.filter)==null?void 0:u.copilotConversationOnly,copilotSupportChannelUrl:(m=this.filter)==null?void 0:m.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=In(h=>{h.isGroupChannel()&&(this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url]))},250,{trailing:!1,leading:!0}),this._channelHandler=new We.GroupChannelHandler({onChannelChanged:this._throttledOnChannelChanged,onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new V.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var s,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.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 l;const n=((l=this.filter)==null?void 0:l.pinnedChannelUrls)??[],r=new Map(n.map((c,u)=>[c,u])),o=[],s=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const u=r.get(c.url);if(u===void 0)continue;const m=St(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),s.push(c)):o.push(c);const g=this._pinnedChannels.findIndex(p=>(r.get(p.url)??1/0)>u),_=g===-1?this._pinnedChannels.length:g;this._pinnedChannels.splice(_,0,c)}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const r=[],o=[],s=[];for(const i of t){if(!this._query.belongsTo(i)){r.push(i.url);continue}const l=St(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=No(this._channels,i,this._order).place,h=m===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(i),o.push(i)):(this._channels.splice(m,0,i),o.push(i)):(this._channels.splice(m,0,i),s.push(i))}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var h,g,_,p,S;const r=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),o=[],s=[];for(const b of t)r.has(b.url)?o.push(b):s.push(b);const i=this._upsertPinnedChannelsToArray(o),l=this._upsertRegularChannelsToArray(s,n),c=i.addedChannels.concat(l.addedChannels),u=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((_=(g=this._collectionEventHandler)==null?void 0:g.onChannelsAdded)==null||_.call(g,{},c)),u.length>0&&((S=(p=this._collectionEventHandler)==null?void 0:p.onChannelsUpdated)==null||S.call(p,{},u)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var o,s,i;const n=new Set(((o=this.filter)==null?void 0:o.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(u=>u.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(u=>u.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((i=(s=this._collectionEventHandler)==null?void 0:s.onChannelsDeleted)==null||i.call(s,{},r))}get channels(){return this._isDisposed?[]:[...this._pinnedChannels,...this._channels]}get hasMore(){return this._isDisposed?!1:this._query.hasNext}async loadMore(){if(this._isDisposed)return[];if(this.hasMore){const t=await this._query.next();return this._setDefaultChangelogsSyncTimestamp(t),this._addChannelsToView(t,!0),t}return[]}setConversationListCollectionHandler(t){this._collectionEventHandler=t}dispose(){this._isDisposed||(this._isDisposed=!0,this._throttledOnChannelChanged.cancel(),this._collectionEventHandler=void 0,this._sdk.removeConnectionHandler(this._handlerId),this._sdk.groupChannel.removeGroupChannelHandler(this._handlerId),this._pinnedChannels.length=0,this._channels.length=0)}}const St=(e,t)=>e.findIndex(n=>n.isIdentical(t)),No=(e,t,n)=>{if(e.length>0){const r=St(e,t);let o=0,s=e.length-1,i=Math.floor((o+s)/2);for(;o<s;){const c=ln(e[i],t,n);if(c>0)s=i,i=Math.floor((o+s)/2);else if(c<0)o=i+1,i=Math.floor((o+s)/2);else return{place:i,oldPosition:r}}return{place:ln(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},ln=(e,t,n)=>{switch(n){case We.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 Ho(e,t){var p,S,b,E,v,C,x,T,A,w;const n=d.useId(),[r,o]=d.useState(!1),[s,i]=d.useState(null),[l,c]=d.useState([]),[u,m]=d.useState(null),h=d.useRef(!1),g=d.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,o(!1),i(null),c([]);try{u==null||u.dispose();const L=new Bo(e,t);L.setConversationListCollectionHandler({onChannelsAdded:()=>{c(L.channels)},onChannelsUpdated:()=>{c(L.channels)},onChannelsDeleted:()=>{c(L.channels)}}),await L.loadMore(),m(L),i(null)}catch(L){m(null),i(L)}finally{o(!0),h.current=!1}}},[e,e.currentUser,(p=t.filter)==null?void 0:p.aiAgentChannelFilter,(b=(S=t.filter)==null?void 0:S.aiAgentConversationStatusFilter)==null?void 0:b.join(),(v=(E=t.filter)==null?void 0:E.aiAgentIds)==null?void 0:v.join(),(C=t.filter)==null?void 0:C.deskChannelFilter,(T=(x=t.filter)==null?void 0:x.pinnedChannelUrls)==null?void 0:T.join(),(A=t.filter)==null?void 0:A.copilotConversationOnly,(w=t.filter)==null?void 0:w.copilotSupportChannelUrl,t.limit]),_=d.useCallback(async()=>{if(u)try{await u.loadMore()}catch(L){i(L)}},[u]);return d.useEffect(()=>(e.addConnectionHandler(n,new V.ConnectionHandler({onConnected:()=>g()})),()=>e.removeConnectionHandler(n)),[e,n,g]),d.useEffect(()=>{g()},[g]),d.useEffect(()=>()=>{h.current=!1,u==null||u.dispose()},[u]),{initialized:r,error:s,channels:l,loadMore:_}}const{Provider:zo}=j("AIAgentConversationList");function Fo({conversationListLimit:e,conversationListFilter:t,children:n}){var h,g;const{chatSDK:r,aiAgentId:o,queryParams:s}=U(),i={aiAgentIds:[o],aiAgentConversationStatusFilter:[G.ConversationStatus.CLOSED,G.ConversationStatus.OPEN]},l=e??((h=s==null?void 0:s.conversationListParams)==null?void 0:h.limit),c={...i,...(g=s==null?void 0:s.conversationListParams)==null?void 0:g.filter,...t},u=Ho(r,{limit:l,filter:c}),m={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return a.createElement(zo,{value:m},n)}function $o(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:Uo}=j("MessageTemplateFetching");function qo({children:e,internalVariables:t}){const n=d.useRef({}),r=d.useRef({}),[o,s]=d.useState({}),i=d.useCallback((u,m)=>{s(h=>({...h,[u]:{fetching:!1,error:!1,...h[u],...m}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const _=m(h);if(_)return _;const p=r.current[h];if(p)return p;g||i(h,{fetching:!0});const S=u(h).catch(b=>{throw g||i(h,{error:!0}),b}).finally(()=>{g||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=S,S},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(u,m)=>{if(n.current[u])return n.current[u];const h=$o(m());return n.current[u]=h,h},getIsFetching:u=>{var m;return((m=o[u])==null?void 0:m.fetching)??!1},getHasError:u=>{var m;return((m=o[u])==null?void 0:m.error)??!1}};return a.createElement(Uo,{value:c},e)}const Wo="remove_powered_by",$t=(e,t)=>{var o,s;const{chatSDK:n}=U(),{aiAgentInfo:r}=je();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&&Cn(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return d.useMemo(()=>!(Array.isArray(i)&&i.includes(Wo)),[i])}throw new Error("Unsupported feature")},Ln=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[s]=e.members.filter(i=>i.userId!==t.userId);return s})(),o={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?Se(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},At=e=>d.useReducer((t,n)=>({...t,...n}),e);var ie=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(ie||{});const Vo=new Set(["free_text","single_choice"]),Go=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,i]=At({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=At({followUpItem:!1}),u=d.useMemo(()=>{var S;const _=s.csat;if(typeof _!="number")return;const p=(S=e.follow_up)==null?void 0:S.find(b=>b.scores.includes(_));if(Vo.has(p==null?void 0:p.response_type))return p},[s.csat,e.follow_up]),m=(()=>{var _;if(typeof n=="number")return"submitted";if((t===ie.AI_AGENT_CSAT_5||t===ie.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===ie.AI_AGENT_CSAT_5_WITH_CRE){const p=typeof s.csat=="number",S=!((_=e.cre)!=null&&_.required)||typeof s.isResolved=="boolean";if(p&&S)return"submittable"}return"unsubmittable"})(),h=d.useCallback(()=>typeof s.csat>"u"?!1:u!=null&&u.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,u,c]);return d.useEffect(()=>{r||(i({csatReason:""}),c({followUpItem:!1}))},[r,u,i,c]),{params:s,setParams:i,error:l,setError:c,followUpItem:u,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},at=5,jo=50,cn=e=>Math.max(0,e-jo),Ko=e=>e<1e3?{speed:at*.5,chunkSize:2}:e<2e3?{speed:at*.8,chunkSize:2}:{speed:at*.6,chunkSize:3},Yo=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationComplete:o}=e,[s,i]=d.useState(()=>cn(t.length)),l=d.useRef(null),c=d.useRef(0),u=d.useRef(0),m=d.useRef(n),h=d.useRef(r),g=d.useRef(o),_=d.useRef(!1),p=d.useRef(!1),S=d.useRef(t.length),b=d.useRef(n),E=n,v=s<t.length,C=m.current&&(E||v);return d.useLayoutEffect(()=>{h.current=r,g.current=o,S.current=t.length,b.current=n}),d.useLayoutEffect(()=>{var x;m.current&&(_.current||(_.current=!0,(x=h.current)==null||x.call(h)),i(T=>t.length<T?t.length:T))},[t]),d.useEffect(()=>{if(!m.current)return;let x=cn(t.length);c.current=0,u.current=0;const T=A=>{c.current===0&&(c.current=A,u.current=A);const w=S.current,L=A-c.current,$=A-u.current,{speed:Y,chunkSize:q}=Ko($),K=Y*q;L>=K&&x<w&&(x=Math.min(x+q,w),i(x),c.current=A),(x<w||b.current)&&(l.current=requestAnimationFrame(T))};return l.current=requestAnimationFrame(T),()=>{l.current&&cancelAnimationFrame(l.current)}},[]),d.useEffect(()=>{var w;const x=m.current&&_.current,T=!n,A=s>=t.length&&t.length>0;x&&T&&A&&!p.current&&(p.current=!0,(w=g.current)==null||w.call(g))},[n,s,t.length]),{streamText:m.current?t.slice(0,s):t,isAnimating:C}},Xo={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available."},conversation_list:{header_title:"Conversations",ended:"Ended",footer_title:"Start a conversation"},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended."},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"}},xt={language:"en",strings:Xo,dateLocale:lr.enUS},Zo={conversation:{input_placeholder:"질문하기",input_placeholder_disabled:"이 채널에서는 채팅을 사용할 수 없습니다.",input_placeholder_wait_ai_agent_response:"상담사의 답변을 기다리는 중...",input_placeholder_active_form:"계속 진행하려면 양식을 작성해 주세요.",input_placeholder_reconnecting:"재연결 시도 중. 계속되면 새로고침하세요.",unknown_message_type:"(알 수 없는 메시지 유형)",powered_by:"Powered by",citation_title:"출처",start_new_conversation_label:"대화 시작",failed_message_resend:"다시 시도",failed_message_remove:"삭제",file_upload_no_supported_files:"사용 가능한 지원 파일 형식이 없습니다."},conversation_list:{header_title:"대화",ended:"종료됨",footer_title:"대화 시작"},date_format:{just_now:"방금",minutes_ago:e=>`${e}분 전`,hours_ago:e=>`${e}시간 전`,date_short:"yyyy/MM/dd",date_separator:"yyyy년 M월 d일",message_timestamp:"p"},csat:{title:"귀하의 피드백은 우리에게 중요합니다.",submitted_label:"성공적으로 제출되었습니다!",cre_question:"문제가 해결되었나요?",cre_positive_label:"네, 감사합니다! 👍",cre_negative_label:"아니요, 도움이 되지 않았어요.",reason_placeholder:"의견을 공유해주세요.",question:"귀하의 경험을 어떻게 평가하시겠습니까?",submit_label:"제출",submission_expired:"죄송합니다. 설문 응답 기간이 종료되었습니다."},form:{optional_label:"선택",validation_required:"이 항목은 필수입니다"},common:{placeholder_something_went_wrong:"문제가 발생했습니다.",placeholder_no_messages:"메시지가 없습니다.",placeholder_no_conversations:"아직 대화가 없습니다",placeholder_something_went_wrong_retry_label:"다시 시도"},feedback:{title:"피드백 제출",good:"좋아요",bad:"별로예요",comment_label:"코멘트 (선택사항)",comment_placeholder:"코멘트를 남겨주세요",cancel:"취소",submit:"제출",save:"저장",edit:"피드백 수정",remove:"피드백 삭제"}},wt={language:"ko",strings:Zo,dateLocale:hr.ko},Jo={conversation:{input_placeholder:"質問する",input_placeholder_disabled:"このチャンネルではチャットを利用できません",input_placeholder_wait_ai_agent_response:"エージェントの返信を待っています…",input_placeholder_active_form:"続行するには、フォームに記入してください。",input_placeholder_reconnecting:"再接続中。続く場合は更新してください。",unknown_message_type:"(不明なメッセージタイプ)",powered_by:"Powered by",citation_title:"出典",start_new_conversation_label:"会話を始める",failed_message_resend:"再試行",failed_message_remove:"削除",file_upload_no_supported_files:"サポートされているファイルタイプがありません。"},conversation_list:{header_title:"会話",ended:"終了",footer_title:"会話を始める"},date_format:{just_now:"たった今",minutes_ago:e=>`${e}分前`,hours_ago:e=>`${e}時間前`,date_short:"yyyy/MM/dd",date_separator:"yyyy年 M月 d日",message_timestamp:"p"},csat:{title:"あなたのフィードバックは私たちにとって重要です",submitted_label:"正常に送信されました!",cre_question:"問題は解決されましたか?",cre_positive_label:"はい、ありがとうございます! 👍",cre_negative_label:"いいえ、役に立ちませんでした。",reason_placeholder:"フィードバックを共有する",question:"あなたの経験をどう評価しますか?",submit_label:"送信",submission_expired:"申し訳ありません、アンケートの受付期間は終了しました。"},form:{optional_label:"任意",validation_required:"この質問は必須です"},common:{placeholder_something_went_wrong:"問題が発生しました",placeholder_no_messages:"メッセージがありません",placeholder_no_conversations:"まだ会話がありません",placeholder_something_went_wrong_retry_label:"再試行"},feedback:{title:"フィードバックを送信",good:"良い",bad:"悪い",comment_label:"コメント(オプション)",comment_placeholder:"コメントを残してください",cancel:"キャンセル",submit:"送信",save:"保存",edit:"フィードバックを編集",remove:"フィードバックを削除"}},It={language:"ja",strings:Jo,dateLocale:gr.ja},Qo={conversation:{input_placeholder:"Hacer una pregunta",input_placeholder_disabled:"El chat no está disponible en este canal",input_placeholder_wait_ai_agent_response:"Esperando la respuesta del agente...",input_placeholder_active_form:"Por favor, complete el formulario para continuar.",input_placeholder_reconnecting:"Reconectando. Actualiza si persiste.",unknown_message_type:"(Tipo de mensaje desconocido)",powered_by:"Desarrollado por",citation_title:"Fuente",start_new_conversation_label:"Iniciar una conversación",failed_message_resend:"Reintentar",failed_message_remove:"Eliminar",file_upload_no_supported_files:"No hay tipos de archivo compatibles disponibles."},conversation_list:{header_title:"Conversaciones",ended:"Finalizado",footer_title:"Iniciar una conversación"},date_format:{just_now:"Ahora mismo",minutes_ago:e=>`Hace ${e} minutos`,hours_ago:e=>`Hace ${e} horas`,date_short:"dd/MM/yyyy",date_separator:"d 'de' MMMM 'de' yyyy",message_timestamp:"p"},csat:{title:"Tus comentarios nos importan",submitted_label:"Enviado con éxito!",cre_question:"¿Se resolvió su problema?",cre_positive_label:"¡Sí, gracias! 👍",cre_negative_label:"No, eso no ayudó.",reason_placeholder:"Comparte tu opinión",question:"¿Cómo calificarías tu experiencia?",submit_label:"Enviar",submission_expired:"Lo sentimos, el período de la encuesta ha terminado."},form:{optional_label:"opcional",validation_required:"Esta pregunta es obligatoria"},common:{placeholder_something_went_wrong:"Algo salió mal",placeholder_no_messages:"No hay mensajes",placeholder_no_conversations:"Aún no hay conversaciones",placeholder_something_went_wrong_retry_label:"Reintentar"},feedback:{title:"Enviar comentarios",good:"Bueno",bad:"Malo",comment_label:"Comentario (opcional)",comment_placeholder:"Deja un comentario",cancel:"Cancelar",submit:"Enviar",save:"Guardar",edit:"Editar comentarios",remove:"Eliminar comentarios"}},Tt={language:"es",strings:Qo,dateLocale:cr.es},es={conversation:{input_placeholder:"Fazer uma pergunta",input_placeholder_disabled:"O chat não está disponível neste canal",input_placeholder_wait_ai_agent_response:"Aguardando a resposta do agente...",input_placeholder_active_form:"Por favor, preencha o formulário para prosseguir.",input_placeholder_reconnecting:"Reconectando. Atualize se persistir.",unknown_message_type:"(Tipo de mensagem desconhecido)",powered_by:"Desenvolvido por",citation_title:"Fonte",start_new_conversation_label:"Iniciar uma conversa",failed_message_resend:"Tentar novamente",failed_message_remove:"Remover",file_upload_no_supported_files:"Nenhum tipo de arquivo suportado disponível."},conversation_list:{header_title:"Conversas",ended:"Encerrada",footer_title:"Iniciar uma conversa"},date_format:{just_now:"Agora mesmo",minutes_ago:e=>`Há ${e} minutos`,hours_ago:e=>`Há ${e} horas`,date_short:"dd/MM/yyyy",date_separator:"d 'de' MMMM 'de' yyyy",message_timestamp:"p"},csat:{title:"Seu feedback é importante para nós",submitted_label:"Enviado com sucesso!",cre_question:"Seu problema foi resolvido?",cre_positive_label:"Sim, obrigado! 👍",cre_negative_label:"Não, isso não ajudou.",reason_placeholder:"Compartilhe seu feedback",question:"Como você avaliaria sua experiência?",submit_label:"Enviar",submission_expired:"Desculpe, o período da pesquisa foi encerrado."},form:{optional_label:"opcional",validation_required:"Esta pergunta é obrigatória"},common:{placeholder_something_went_wrong:"Algo deu errado",placeholder_no_messages:"Nenhuma mensagem",placeholder_no_conversations:"Nenhuma conversa ainda",placeholder_something_went_wrong_retry_label:"Tentar novamente"},feedback:{title:"Enviar feedback",good:"Bom",bad:"Ruim",comment_label:"Comentário (opcional)",comment_placeholder:"Deixe um comentário",cancel:"Cancelar",submit:"Enviar",save:"Salvar",edit:"Editar feedback",remove:"Remover feedback"}},kt={language:"pt",strings:es,dateLocale:fr.pt},ts={conversation:{input_placeholder:"Poser une question",input_placeholder_disabled:"Le chat n'est pas disponible dans ce canal",input_placeholder_wait_ai_agent_response:"En attente de la réponse de l'agent...",input_placeholder_active_form:"Veuillez remplir le formulaire pour continuer.",input_placeholder_reconnecting:"Reconnexion. Actualisez si persiste.",unknown_message_type:"(Type de message inconnu)",powered_by:"Propulsé par",citation_title:"Source",start_new_conversation_label:"Démarrer une conversation",failed_message_resend:"Réessayer",failed_message_remove:"Supprimer",file_upload_no_supported_files:"Aucun type de fichier pris en charge disponible."},conversation_list:{header_title:"Conversations",ended:"Terminée",footer_title:"Démarrer une conversation"},date_format:{just_now:"À l'instant",minutes_ago:e=>`Il y a ${e} minutes`,hours_ago:e=>`Il y a ${e} heures`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Vos commentaires comptent pour nous",submitted_label:"Soumis avec succès!",cre_question:"Votre problème a-t-il été résolu ?",cre_positive_label:"Oui, merci ! 👍",cre_negative_label:"Non, cela n'a pas aidé.",reason_placeholder:"Partagez votre avis",question:"Comment évalueriez-vous votre expérience ?",submit_label:"Envoyer",submission_expired:"Désolé, la période de l'enquête est terminée."},form:{optional_label:"optionnel",validation_required:"Cette question est obligatoire"},common:{placeholder_something_went_wrong:"Une erreur est survenue",placeholder_no_messages:"Aucun message",placeholder_no_conversations:"Aucune conversation pour le moment",placeholder_something_went_wrong_retry_label:"Réessayer"},feedback:{title:"Envoyer des commentaires",good:"Bien",bad:"Mauvais",comment_label:"Commentaire (optionnel)",comment_placeholder:"Laissez un commentaire",cancel:"Annuler",submit:"Envoyer",save:"Enregistrer",edit:"Modifier les commentaires",remove:"Supprimer les commentaires"}},Mt={language:"fr",strings:ts,dateLocale:ur.fr},ns={conversation:{input_placeholder:"एक प्रश्न पूछें",input_placeholder_disabled:"इस चैनल में चैट उपलब्ध नहीं है",input_placeholder_wait_ai_agent_response:"एजेंट के उत्तर की प्रतीक्षा कर रहे हैं...",input_placeholder_active_form:"आगे बढ़ने के लिए कृपया फॉर्म भरें।",input_placeholder_reconnecting:"पुनः कनेक्ट हो रहा है। जारी रहे तो रिफ्रेश करें।",unknown_message_type:"(अज्ञात संदेश प्रकार)",powered_by:"द्वारा संचालित",citation_title:"स्रोत",start_new_conversation_label:"एक बातचीत शुरू करें",failed_message_resend:"पुनः प्रयास करें",failed_message_remove:"हटाएं",file_upload_no_supported_files:"कोई समर्थित फ़ाइल प्रकार उपलब्ध नहीं हैं।"},conversation_list:{header_title:"बातचीत",ended:"समाप्त",footer_title:"एक बातचीत शुरू करें"},date_format:{just_now:"अभी",minutes_ago:e=>`${e} मिनट पहले`,hours_ago:e=>`${e} घंटे पहले`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"आपकी प्रतिक्रिया हमारे लिए मायने रखती है",submitted_label:"सफलतापूर्वक सबमिट किया गया!",cre_question:"क्या आपकी समस्या का समाधान हुआ?",cre_positive_label:"हाँ, धन्यवाद! 👍",cre_negative_label:"नहीं, इससे मदद नहीं मिली।",reason_placeholder:"अपनी प्रतिक्रिया साझा करें",question:"आप अपने अनुभव का मूल्यांकन कैसे करेंगे?",submit_label:"सबमिट करें",submission_expired:"क्षमा करें, सर्वेक्षण अवधि समाप्त हो गई है।"},form:{optional_label:"वैकल्पिक",validation_required:"यह प्रश्न आवश्यक है"},common:{placeholder_something_went_wrong:"कुछ गलत हो गया",placeholder_no_messages:"कोई संदेश नहीं",placeholder_no_conversations:"अभी तक कोई बातचीत नहीं",placeholder_something_went_wrong_retry_label:"पुनः प्रयास करें"},feedback:{title:"प्रतिक्रिया भेजें",good:"अच्छा",bad:"बुरा",comment_label:"टिप्पणी (वैकल्पिक)",comment_placeholder:"एक टिप्पणी छोड़ें",cancel:"रद्द करें",submit:"भेजें",save:"सहेजें",edit:"प्रतिक्रिया संपादित करें",remove:"प्रतिक्रिया हटाएं"}},Lt={language:"hi",strings:ns,dateLocale:dr.hi},rs={conversation:{input_placeholder:"Fai una domanda",input_placeholder_disabled:"La chat non è disponibile in questo canale",input_placeholder_wait_ai_agent_response:"In attesa della risposta dell'agente...",input_placeholder_active_form:"Compila il modulo per procedere.",input_placeholder_reconnecting:"Riconnessione. Aggiorna se persiste.",unknown_message_type:"(Tipo di messaggio sconosciuto)",powered_by:"Powered by",citation_title:"Fonte",start_new_conversation_label:"Inizia una conversazione",failed_message_resend:"Riprova",failed_message_remove:"Rimuovi",file_upload_no_supported_files:"Nessun tipo di file supportato disponibile."},conversation_list:{header_title:"Conversazioni",ended:"Terminata",footer_title:"Inizia una conversazione"},date_format:{just_now:"Proprio ora",minutes_ago:e=>`${e} minuti fa`,hours_ago:e=>`${e} ore fa`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Il tuo feedback è importante per noi",submitted_label:"Inviato con successo!",cre_question:"Il tuo problema è stato risolto?",cre_positive_label:"Sì, grazie! 👍",cre_negative_label:"No, non è servito.",reason_placeholder:"Condividi il tuo feedback",question:"Come valuteresti la tua esperienza?",submit_label:"Invia",submission_expired:"Ci dispiace, il periodo per partecipare al sondaggio è terminato."},form:{optional_label:"opzionale",validation_required:"Questa domanda è obbligatoria"},common:{placeholder_something_went_wrong:"Qualcosa è andato storto",placeholder_no_messages:"Nessun messaggio",placeholder_no_conversations:"Nessuna conversazione ancora",placeholder_something_went_wrong_retry_label:"Riprova"},feedback:{title:"Invia feedback",good:"Buono",bad:"Cattivo",comment_label:"Commento (opzionale)",comment_placeholder:"Lascia un commento",cancel:"Annulla",submit:"Invia",save:"Salva",edit:"Modifica feedback",remove:"Rimuovi feedback"}},Rt={language:"it",strings:rs,dateLocale:mr.it},os={conversation:{input_placeholder:"Eine Frage stellen",input_placeholder_disabled:"Chat ist in diesem Kanal nicht verfügbar",input_placeholder_wait_ai_agent_response:"Warten auf die Antwort des Agenten...",input_placeholder_active_form:"Bitte fülle das Formular aus, um fortzufahren.",input_placeholder_reconnecting:"Neu verbinden. Aktualisieren falls anhaltend.",unknown_message_type:"(Unbekannter Nachrichtentyp)",powered_by:"Unterstützt von",citation_title:"Quelle",start_new_conversation_label:"Ein Gespräch starten",failed_message_resend:"Erneut versuchen",failed_message_remove:"Entfernen",file_upload_no_supported_files:"Keine unterstützten Dateitypen verfügbar."},conversation_list:{header_title:"Gespräche",ended:"Beendet",footer_title:"Ein Gespräch starten"},date_format:{just_now:"Gerade eben",minutes_ago:e=>`Vor ${e} Minuten`,hours_ago:e=>`Vor ${e} Stunden`,date_short:"dd.MM.yyyy",date_separator:"d. MMMM yyyy",message_timestamp:"p"},csat:{title:"Ihr Feedback ist uns wichtig",submitted_label:"Erfolgreich gesendet!",cre_question:"Wurde Ihr Problem gelöst?",cre_positive_label:"Ja, danke! 👍",cre_negative_label:"Nein, das hat nicht geholfen.",reason_placeholder:"Dein Feedback teilen",question:"Wie würden Sie Ihre Erfahrung bewerten?",submit_label:"Absenden",submission_expired:"Die Umfrage ist leider nicht mehr verfügbar."},form:{optional_label:"optional",validation_required:"Diese Frage ist erforderlich"},common:{placeholder_something_went_wrong:"Etwas ist schiefgelaufen",placeholder_no_messages:"Keine Nachrichten",placeholder_no_conversations:"Noch keine Unterhaltungen",placeholder_something_went_wrong_retry_label:"Erneut versuchen"},feedback:{title:"Feedback senden",good:"Gut",bad:"Schlecht",comment_label:"Kommentar (optional)",comment_placeholder:"Hinterlasse einen Kommentar",cancel:"Abbrechen",submit:"Senden",save:"Speichern",edit:"Feedback bearbeiten",remove:"Feedback entfernen"}},Pt={language:"de",strings:os,dateLocale:ir.de},ss={conversation:{input_placeholder:"Bir soru sor",input_placeholder_disabled:"Bu kanalda sohbet mevcut değil",input_placeholder_wait_ai_agent_response:"Temsilcinin yanıtını bekliyor...",input_placeholder_active_form:"İlerlemek için lütfen formu doldurun.",input_placeholder_reconnecting:"Yeniden bağlanıyor. Devam ederse yenile.",unknown_message_type:"(Bilinmeyen mesaj türü)",powered_by:"Tarafından desteklenmektedir",citation_title:"Kaynak",start_new_conversation_label:"Bir sohbet başlat",failed_message_resend:"Tekrar dene",failed_message_remove:"Kaldır",file_upload_no_supported_files:"Desteklenen dosya türü mevcut değil."},conversation_list:{header_title:"Görüşmeler",ended:"Sona erdi",footer_title:"Bir sohbet başlat"},date_format:{just_now:"Az önce",minutes_ago:e=>`${e} dakika önce`,hours_ago:e=>`${e} saat önce`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Görüşleriniz bizim için önemli",submitted_label:"Başarıyla gönderildi!",cre_question:"Sorununuz çözüldü mü?",cre_positive_label:"Evet, teşekkürler! 👍",cre_negative_label:"Hayır, bu yardımcı olmadı.",reason_placeholder:"Geri bildiriminizi paylaşın",question:"Deneyiminizi nasıl değerlendirirsiniz?",submit_label:"Gönder",submission_expired:"Üzgünüz, anket süresi sona erdi."},form:{optional_label:"İsteğe bağlı",validation_required:"Bu soru gereklidir"},common:{placeholder_something_went_wrong:"Bir şeyler ters gitti",placeholder_no_messages:"Mesaj yok",placeholder_no_conversations:"Henüz görüşme yok",placeholder_something_went_wrong_retry_label:"Tekrar dene"},feedback:{title:"Geri bildirim gönder",good:"İyi",bad:"Kötü",comment_label:"Yorum (isteğe bağlı)",comment_placeholder:"Bir yorum bırakın",cancel:"İptal",submit:"Gönder",save:"Kaydet",edit:"Geri bildirimi düzenle",remove:"Geri bildirimi kaldır"}},Dt={language:"tr",strings:ss,dateLocale:pr.tr},se=e=>({conversation:e.conversation,conversation_list:e.conversation_list,date_format:e.date_format,csat:e.csat,form:e.form,common:e.common,feedback:e.feedback}),un=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Ke},Ke="en",Ut={borderColor:"red",borderWidth:f.StyleSheet.hairlineWidth},y=({debug:e=!1,style:t,children:n,...r})=>a.createElement(f.View,{style:[t,r,e&&Ut],...r},n);y.Animated=({debug:e=!1,style:t,children:n,...r})=>a.createElement(f.Animated.View,{style:[t,r,e&&Ut],...r},n);const{Provider:as,useContext:J}=j("MessengerSession"),is=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof Ve||t.userSessionInfo instanceof Ft))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return a.createElement(So,{ref:n,...t},r=>a.createElement(ls,{...r},e))}),ls=({children:e,...t})=>{const{userSession:n,aiAgentInfo:r,launcherInfo:o}=t;return a.createElement(as,{value:{...t,userSession:n,aiAgentInfo:r,launcherInfo:o}},e)},cs=50,{Provider:us,useContext:ds}=j("ConversationScroll"),ms=({children:e})=>{var T;const{config:t}=U(),n=((T=t==null?void 0:t.conversation)==null?void 0:T.scrollMode)??"auto",r=d.useRef(null),o=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),[s,i]=d.useState(0),[l,c]=d.useState(0),[u,m]=d.useState(!1),h=d.useCallback(()=>{const{shouldUpdate:A,shouldRecalc:w,contentHeight:L,contentSnapshotHeight:$,viewport:Y}=o.current;A&&$<L&&i(q=>{o.current.shouldUpdate=!1;const K=L-q-$,ne=Math.max(0,Y-K);return q===0||ne<q||w?(o.current.shouldRecalc=!1,ne):q})},[]),g=d.useCallback(A=>{o.current.viewport=A.nativeEvent.layout.height},[]),_=d.useCallback((A,w)=>{o.current.contentHeight=w;const L=o.current.viewport;m(w>L),h()},[h]),p=d.useCallback(A=>{const w=A.nativeEvent.contentOffset.y;c(w)},[]),S=(()=>{if(n==="fixed")return{minIndexForVisible:1,autoscrollToTopThreshold:-1}})(),b=d.useCallback((A=!0)=>{var w;(w=r.current)==null||w.scrollToOffset({offset:0,animated:A})},[]),E=d.useCallback((A,w=!0)=>{var L;(L=r.current)==null||L.scrollToIndex({index:A,animated:w,viewPosition:1})},[]),v=d.useCallback(()=>{n==="fixed"&&(o.current.contentSnapshotHeight=o.current.contentHeight-s,o.current.shouldUpdate=!0,o.current.shouldRecalc=!0)},[n,s]),C=d.useCallback(()=>{n==="fixed"?E(0):b()},[n,b,E]),x=d.useCallback(()=>{n==="fixed"?o.current.shouldUpdate=!0:b()},[n,b]);return a.createElement(us,{value:{ref:r,state:{distanceFromBottom:l,shouldShowScrollButton:u&&l>cs,bottomSpace:s},props:{maintainVisibleContentPosition:S,onLayout:g,onContentSizeChange:_,onScroll:p},actions:{scrollToBottom:b,scrollToIndex:E,onBeforeMessageSend:v,onAfterMessageSend:C,onStreamingUpdate:x}}},e)};function Rn(e){return new Promise((t,n)=>{f.Image.getSize(e,(r,o)=>{t({width:String(r),height:String(o)})},r=>{n(r)})})}async function gs(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 Rn(n.uri);return new Ce.MessageMetaArray({key:vn,value:[r,o]})}catch{return}}}function hs(e,t){let n=0,r=0;return re(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),re(t)&&t.sendingStatus!=="succeeded"&&(r=Number.MAX_SAFE_INTEGER),t.createdAt+r-(e.createdAt+n)}const{Provider:fs,Context:ps,useContext:te}=j("Conversation"),Pn=e=>a.createElement(ms,null,a.createElement(_s,{...e})),_s=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:r,shouldMarkAsRead:o,children:s})=>{const i=ds(),{activeChannel:l,refreshActiveChannel:c,sdkUser:u,authenticate:m}=J();d.useEffect(()=>{u||m()},[]);const h=d.useCallback(async S=>{i.actions.onBeforeMessageSend();const b=await gs(S);return{...S,metaArrays:b?[b]:void 0}},[i.actions.onBeforeMessageSend]),g=d.useCallback(()=>{i.actions.onAfterMessageSend()},[i.actions.onAfterMessageSend]),_=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]),p=e??(l==null?void 0:l.url);return a.createElement(Po,{key:p,channelUrl:p,onBeforeSendMessage:h,onAfterSendMessage:g,onMessagesUpdated:i.actions.onStreamingUpdate,onMessagesReceived:i.actions.onStreamingUpdate,onChannelDeleted:_,sortComparator:hs,shouldMarkAsRead:o},S=>a.createElement(fs,{value:{...S,scrollSource:i,onClose:n,onNavigateToConversationList:r,updateActiveChannel:_}},s))},it=se(Pt.strings),ys={...it,conversation:{...it.conversation,attachment_camera:"Kamera",attachment_photo:"Fotobibliothek",attachment_document:"Dateien",file_upload_notification_count_limit:e=>`Sie können nur ${e} Datei${e>1?"en":""} gleichzeitig hochladen.`,file_upload_notification_size_limit:e=>`Die maximale Dateigröße beträgt ${e} MB.`,file_upload_not_supported_file:"Bitte wählen Sie einen unterstützten Dateityp aus."},conversation_list:{...it.conversation_list}},bs={language:Pt.language,dateLocale:Pt.dateLocale,strings:ys},lt=se(xt.strings),Es={...lt,conversation:{...lt.conversation,attachment_camera:"Camera",attachment_photo:"Photo library",attachment_document:"Files",file_upload_notification_count_limit:e=>`You can only upload ${e} file${e>1?"s":""} at a time.`,file_upload_notification_size_limit:e=>`Maximum file size is ${e} MB.`,file_upload_not_supported_file:"Please select a supported file type."},conversation_list:{...lt.conversation_list}},Cs={language:xt.language,dateLocale:xt.dateLocale,strings:Es},ct=se(Tt.strings),vs={...ct,conversation:{...ct.conversation,attachment_camera:"Cámara",attachment_photo:"Biblioteca de fotos",attachment_document:"Archivos",file_upload_notification_count_limit:e=>`Solo puede cargar ${e} archivo${e>1?"s":""} a la vez.`,file_upload_notification_size_limit:e=>`El tamaño máximo del archivo es ${e} MB.`,file_upload_not_supported_file:"Por favor, seleccione un tipo de archivo compatible."},conversation_list:{...ct.conversation_list}},Ss={language:Tt.language,dateLocale:Tt.dateLocale,strings:vs},ut=se(Mt.strings),As={...ut,conversation:{...ut.conversation,attachment_camera:"Caméra",attachment_photo:"Photothèque",attachment_document:"Fichiers",file_upload_notification_count_limit:e=>`Vous ne pouvez télécharger que ${e} fichier${e>1?"s":""} à la fois.`,file_upload_notification_size_limit:e=>`La taille maximale du fichier est de ${e} MB.`,file_upload_not_supported_file:"Veuillez sélectionner un type de fichier pris en charge."},conversation_list:{...ut.conversation_list}},xs={language:Mt.language,dateLocale:Mt.dateLocale,strings:As},dt=se(Lt.strings),ws={...dt,conversation:{...dt.conversation,attachment_camera:"कैमरा",attachment_photo:"फोटो लाइब्रेरी",attachment_document:"फाइलें",file_upload_notification_count_limit:e=>`आप एक बार में केवल ${e} फ़ाइल${e>1?"ें":""} अपलोड कर सकते हैं।`,file_upload_notification_size_limit:e=>`अधिकतम फ़ाइल आकार ${e} MB है।`,file_upload_not_supported_file:"कृपया समर्थित फ़ाइल प्रकार चुनें।"},conversation_list:{...dt.conversation_list}},Is={language:Lt.language,dateLocale:Lt.dateLocale,strings:ws},mt=se(Rt.strings),Ts={...mt,conversation:{...mt.conversation,attachment_camera:"Fotocamera",attachment_photo:"Libreria foto",attachment_document:"File",file_upload_notification_count_limit:e=>`Puoi caricare solo ${e} file alla volta.`,file_upload_notification_size_limit:e=>`La dimensione massima del file è ${e} MB.`,file_upload_not_supported_file:"Seleziona un tipo di file supportato."},conversation_list:{...mt.conversation_list}},ks={language:Rt.language,dateLocale:Rt.dateLocale,strings:Ts},gt=se(It.strings),Ms={...gt,conversation:{...gt.conversation,attachment_camera:"カメラ",attachment_photo:"フォトライブラリ",attachment_document:"ファイル",file_upload_notification_count_limit:e=>`一度にアップロードできるのは${e}ファイルまでです。`,file_upload_notification_size_limit:e=>`ファイルの最大サイズは${e}MBです。`,file_upload_not_supported_file:"サポートされているファイル形式を選択してください。"},conversation_list:{...gt.conversation_list}},Ls={language:It.language,dateLocale:It.dateLocale,strings:Ms},ht=se(wt.strings),Rs={...ht,conversation:{...ht.conversation,attachment_camera:"카메라",attachment_photo:"사진 라이브러리",attachment_document:"파일",file_upload_notification_count_limit:e=>`한 번에 ${e}개의 파일만 업로드할 수 있습니다.`,file_upload_notification_size_limit:e=>`파일당 최대 크기는 ${e} MB입니다.`,file_upload_not_supported_file:"지원되는 파일 형식을 선택해 주세요."},conversation_list:{...ht.conversation_list}},Ps={language:wt.language,dateLocale:wt.dateLocale,strings:Rs},ft=se(kt.strings),Ds={...ft,conversation:{...ft.conversation,attachment_camera:"Câmera",attachment_photo:"Biblioteca de fotos",attachment_document:"Arquivos",file_upload_notification_count_limit:e=>`Você só pode carregar ${e} arquivo${e>1?"s":""} por vez.`,file_upload_notification_size_limit:e=>`O tamanho máximo do arquivo é ${e} MB.`,file_upload_not_supported_file:"Por favor, selecione um tipo de arquivo suportado."},conversation_list:{...ft.conversation_list}},Os={language:kt.language,dateLocale:kt.dateLocale,strings:Ds},pt=se(Dt.strings),Bs={...pt,conversation:{...pt.conversation,attachment_camera:"Kamera",attachment_photo:"Fotoğraf kitaplığı",attachment_document:"Dosyalar",file_upload_notification_count_limit:e=>`Bir seferde yalnızca ${e} dosya yükleyebilirsiniz.`,file_upload_notification_size_limit:e=>`Maksimum dosya boyutu ${e} MB'dir.`,file_upload_not_supported_file:"Lütfen desteklenen bir dosya türü seçin."},conversation_list:{...pt.conversation_list}},Ns={language:Dt.language,dateLocale:Dt.dateLocale,strings:Bs},dn=new Map([["en",Cs],["ko",Ps],["ja",Ls],["es",Ss],["pt",Os],["fr",xs],["hi",Is],["it",ks],["de",bs],["tr",Ns]]),mn=e=>dn.get(e)??dn.get(Ke),Hs=(e,t)=>t?{conversation:{...e.conversation,...t.conversation},conversation_list:{...e.conversation_list,...t.conversation_list},date_format:{...e.date_format,...t.date_format},csat:{...e.csat,...t.csat},form:{...e.form,...t.form},common:{...e.common,...t.common},feedback:{...e.feedback,...t.feedback}}:e,{Provider:zs,useContext:H}=j("Localization"),Fs=({language:e=Ke,logger:t,strings:n,children:r})=>{const[o,s]=d.useState(()=>{const i=un(e);return mn(i)});return d.useEffect(()=>{var l;const i=un(e);if(o.language!==i){const c=mn(i);s(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:o.language,to:c.language})}},[e,t]),a.createElement(zs,{value:{language:o.language,strings:Hs(o.strings,n),dateLocale:o.dateLocale,format:(i,l,c)=>Ee.format(i,l,{locale:o.dateLocale,...c})}},r)},{Provider:$s,useContext:Ye}=j("Modal");function Dn({children:e}){const[t,n]=d.useState([]),[r,o]=d.useState(null),s=d.useRef(0);d.useEffect(()=>{if(!r&&t.length>0){const[u,...m]=t;u&&(o(u),n(m))}},[r,t]);const i=d.useCallback(u=>new Promise(m=>{const g={id:`modal-${++s.current}`,render:u,resolve:m};n(_=>[..._,g])}),[]),l=d.useCallback((u,m)=>{o(h=>(h==null?void 0:h.id)===u?(h.resolve(m),null):h)},[]),c={openModal:i,currentModal:r};return a.createElement($s,{value:c},e,r&&a.createElement(f.Modal,{visible:!0,supportedOrientations:["landscape","portrait"],transparent:!0,animationType:"fade",onRequestClose:()=>l(r.id,null),style:{height:0}},r.render(u=>l(r.id,u??null))))}const{Provider:Us,useContext:z}=j("MessengerTheme"),qs=({children:e,...t})=>a.createElement(co,{...t,appearance:{theme:t.mode??"light"}},n=>{const r=Ws(n.theme);return a.createElement(Us,{value:{...n,themedColor:r}},e)});function Ws(e){const t=n=>n[e.selectedTheme];return{textHighEmphasis:t({light:e.palette.onlight.textHighEmphasis,dark:e.palette.ondark.textHighEmphasis}),textMidEmphasis:t({light:e.palette.onlight.textMidEmphasis,dark:e.palette.ondark.textMidEmphasis}),textLowEmphasis:t({light:e.palette.onlight.textLowEmphasis,dark:e.palette.ondark.textLowEmphasis}),textDisabled:t({light:e.palette.onlight.textDisabled,dark:e.palette.ondark.textDisabled}),textHighEmphasisInverse:t({light:e.palette.ondark.textHighEmphasis,dark:e.palette.onlight.textHighEmphasis}),textMidEmphasisInverse:t({light:e.palette.ondark.textMidEmphasis,dark:e.palette.onlight.textMidEmphasis}),textLowEmphasisInverse:t({light:e.palette.ondark.textLowEmphasis,dark:e.palette.onlight.textLowEmphasis}),textDisabledInverse:t({light:e.palette.ondark.textDisabled,dark:e.palette.onlight.textDisabled}),bg_50_600:t({light:e.palette.background50,dark:e.palette.background600}),bg_100_500:t({light:e.palette.background100,dark:e.palette.background500}),bg_200_400:t({light:e.palette.background200,dark:e.palette.background400}),primary:t({light:e.palette.primary.main,dark:e.palette.primary.light}),secondary:t({light:e.palette.secondary.main,dark:e.palette.secondary.light}),error:t({light:e.palette.error.main,dark:e.palette.error.light}),information:t({light:e.palette.information.light,dark:e.palette.information.light}),overlay:t({light:e.palette.overlay.light,dark:e.palette.overlay.dark})}}const R={create:e=>{const t=new WeakMap,n=r=>{const o=t.get(r.theme);if(o)return o;const s=e(r),i={},l={};for(const m in s)typeof s[m]=="function"?l[m]=s[m]:i[m]=s[m];const u={...f.StyleSheet.create(i),...l};return t.set(r.theme,u),u};return{use:()=>{const r=z(),o=fe.useSafeAreaInsets();return n({...r,edgeInsets:o,select:s=>s[r.theme.selectedTheme]})}}}},Vs={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},Ie=(e,t=f.I18nManager.isRTL?"rtl":"ltr")=>{const n=fe.useSafeAreaInsets();return e.reduce((r,o)=>{const s=Vs[t][o];return r[s]=n[o],r},{})},Gs={send:require("./icons/icon-send.png"),close:require("./icons/icon-close.png"),menu:require("./icons/icon-menu.png"),chat:require("./icons/icon-chat.png"),message:require("./icons/icon-message.png"),spinner:require("./icons/icon-spinner.png"),error:require("./icons/icon-error.png"),refresh:require("./icons/icon-refresh.png"),"chevron-down":require("./icons/icon-chevron-down.png"),done:require("./icons/icon-done.png"),"done-all":require("./icons/icon-done-all.png"),user:require("./icons/icon-user.png"),"file-document":require("./icons/icon-file-document.png"),remove:require("./icons/icon-remove.png"),add:require("./icons/icon-add.png"),agent:require("./icons/icon-agent.png"),camera:require("./icons/icon-camera.png"),photo:require("./icons/icon-photo.png"),document:require("./icons/icon-document.png"),"bot-filled":require("./icons/icon-bot-filled.png"),copy:require("./icons/icon-copy.png"),source:require("./icons/icon-source.png"),"radio-on":require("./icons/icon-radio-on.png"),"radio-off":require("./icons/icon-radio-off.png"),good:require("./icons/icon-good.png"),bad:require("./icons/icon-bad.png"),"good-filled":require("./icons/icon-good-filled.png"),"bad-filled":require("./icons/icon-bad-filled.png"),delight:require("./icons/icon-delight.png"),"thumbnail-none":require("./icons/icon-thumbnail-none.png")},js={send:!0,chat:!0,message:!0,good:!0,bad:!0,"good-filled":!0,"bad-filled":!0},O=({customSource:e,type:t,color:n,size:r=24,style:o})=>{const s=Ks.use(),i=f.I18nManager.isRTL&&!!js[t];return a.createElement(y,{alignItems:"center",justifyContent:"center"},a.createElement(f.Image,{resizeMode:"contain",source:e??Gs[t],style:[s.icon({color:n,size:r,mirror:i}),o]}))},Ks=R.create(({theme:e,themedColor:t})=>({icon:n=>({tintColor:typeof n.color=="function"?n.color(t):n.color??e.colors.base.primary,width:n.size,height:n.size,transform:n.mirror?[{scaleX:-1}]:void 0})})),qt=(e,t)=>{if(!t||t.length===0)return!1;const n=t.trimStart();if(n.length===0)return!1;const r=e==="start"?Array.from(n)[0]:Array.from(n).pop(),o=r==null?void 0:r.codePointAt(0);return o===void 0?!1:Zs(o)},On=e=>qt("start",e),Ys=e=>qt("end",e),Xs=e=>{const{text:t,style:n,isTextInput:r}=e;return n!=null&&n.textAlign&&n.textAlign!=="left"&&n.textAlign!=="right"?n.textAlign:f.I18nManager.isRTL&&typeof t=="string"&&On(t)?r?"right":f.I18nManager.doLeftAndRightSwapInRTL?"left":"right":n==null?void 0:n.textAlign},Zs=e=>{for(const[t,n]of Js)if(e>=t&&e<=n)return!0;return!1},Js=[[1424,1535],[1536,1791],[1872,1919],[2208,2303],[64285,64335],[65136,65279],[126464,126719]],Wt={isStartsWithRTL:On,isEndsWithRTL:Ys,isRTLString:qt,useTextAlign:Xs},k=({variant:e="body1",color:t,style:n,...r})=>{const{theme:o,themedColor:s}=z(),i=d.useMemo(()=>{if(typeof t=="function")return t(s);if(typeof t=="string")return t;const u=f.StyleSheet.flatten(n);return u&&u.color?u.color:t??s.textHighEmphasis},[n,t,s.textHighEmphasis]),l=d.useMemo(()=>{const u=o.typography[e]??o.typography.body1;return f.StyleSheet.flatten([{includeFontPadding:!1,...u,color:i},n])},[e,i,o.typography,s.textHighEmphasis]),c=Wt.useTextAlign({text:r.children,style:l});return a.createElement(f.Text,{style:[l,{textAlign:c}],...r})},Bn=350,Qs=({children:e,...t})=>a.createElement(f.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:Bn,...t},n=>typeof e=="function"?e(n):e),ea=({children:e,style:t,...n})=>{const[r,o]=d.useState(!1),s={pressed:r};return a.createElement(f.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:Bn,style:typeof t=="function"?t(s):t,onPressIn:()=>o(!0),onPressOut:()=>o(!1),...n},typeof e=="function"?e(s):e)},P=e=>e.activeOpacity&&e.activeOpacity<1?a.createElement(ea,{...e}):a.createElement(Qs,{...e}),{Provider:ta,useContext:Nn}=j("BottomSheetAnimation");function na({onClose:e,children:t}){const n=d.useRef(new f.Animated.Value(500)).current;d.useEffect(()=>{f.Animated.timing(n,{toValue:0,duration:300,useNativeDriver:!0}).start()},[n]);const r=d.useCallback(s=>async()=>{f.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(async()=>{try{await(s==null?void 0:s())}catch{e==null||e()}})},[n]),o=d.useRef(f.PanResponder.create({onMoveShouldSetPanResponder:(s,i)=>i.dy>5,onPanResponderMove:(s,i)=>{i.dy>0&&n.setValue(i.dy)},onPanResponderRelease:(s,i)=>{i.dy>100||i.vy>.5?f.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(()=>{e==null||e()}):f.Animated.timing(n,{toValue:0,duration:200,useNativeDriver:!0}).start()}})).current;return a.createElement(ta,{value:{wrapWithAnimation:r,translateY:n,panHandlers:o.panHandlers}},t)}const ra=({icon:e,label:t="",destructive:n=!1,onPress:r})=>{const o=Hn.use(),{themedColor:s}=z();return a.createElement(P,{onPress:r,style:o.actionItem,activeOpacity:.75},e&&a.createElement(O,{type:e,size:24,color:s.primary}),a.createElement(k,{variant:"body3",color:n?s.error:s.textHighEmphasis,numberOfLines:1},t))},oa=({onClose:e,children:t})=>{const n=Hn.use(),{translateY:r,panHandlers:o,wrapWithAnimation:s}=Nn(),i=Ie(["left","right"]);return a.createElement(P,{onPress:s(e),style:n.overlay},a.createElement(y.Animated,{style:[n.container,i,{transform:[{translateY:r}]}],...o},t))},Xe=oe({template:oa,components:{ActionItem:ra}}),ee=e=>{const{Template:t}=Xe.useContext();return a.createElement(na,{onClose:e.onClose},a.createElement(t,{...e}))};ee.ActionItem=e=>{const{components:t}=Xe.useContext(),{wrapWithAnimation:n}=Nn();return a.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const Hn=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}})),sa=({date:e=Date.now(),style:t,...n})=>{const{format:r,strings:o}=H();return a.createElement(y,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},a.createElement(k,{variant:"caption4",color:s=>s.textMidEmphasis},r(e,o.date_format.date_separator)))},Vt=({iconSize:e=64,icon:t,style:n,label:r,children:o})=>{const{themedColor:s}=z();return a.createElement(y,{style:[zn.body,n]},t&&a.createElement(O,{type:t,size:e,color:s.textLowEmphasis}),r&&a.createElement(k,{variant:"body1",color:s.textMidEmphasis},r),o)},aa=({children:e})=>{const{theme:t}=z();return a.createElement(y,{backgroundColor:t.colors.base.background,style:zn.container},e)},zn=f.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),ia=({label:e,icon:t="error",action:n,...r})=>{const{strings:o}=H();return a.createElement(Vt,{icon:t,label:e??o.common.placeholder_something_went_wrong,...r},n&&a.createElement(la,{onPress:n.onPress,label:n.label??o.common.placeholder_something_went_wrong_retry_label}))},la=({label:e,onPress:t})=>{const{themedColor:n}=z();return a.createElement(P,{onPress:t},a.createElement(y,{style:ca.button},a.createElement(O,{type:"refresh",size:20}),a.createElement(k,{variant:"button",color:n.primary},e)))},ca=f.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),ua=({iconSize:e=48,style:t})=>{const n=d.useRef(new f.Animated.Value(0)).current;d.useEffect(()=>{const o=f.Animated.loop(f.Animated.timing(n,{toValue:1,duration:1e3,easing:f.Easing.linear,useNativeDriver:!0}));return o.start(),()=>{o.stop()}},[n]);const r=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(y.Animated,{style:[{transform:[{rotate:r}]},t]},a.createElement(O,{type:"spinner",size:e}))},da=({label:e,icon:t="chat",...n})=>{const{strings:r}=H();return a.createElement(Vt,{icon:t,label:e??r.common.placeholder_no_conversations,...n})},ma=({label:e,icon:t="message",...n})=>{const{strings:r}=H();return a.createElement(Vt,{icon:t,label:e??r.common.placeholder_no_messages,...n})},ga=e=>{const{components:t}=Gt.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(aa,null,n)},Gt=oe({template:ga,components:{Loading:ua,Error:ia,NoChannels:da,NoMessages:ma}}),ve=e=>{const{Template:t}=Gt.useContext();return a.createElement(t,{...e})},ha=({style:e,onPress:t})=>{const n=fa.use(),{theme:r}=z();return a.createElement(P,{style:[n.button,e],onPress:t},a.createElement(y,{alignItems:"center",justifyContent:"center"},a.createElement(O,{size:24,type:"chevron-down",color:r.colors.base.primary})))},fa=R.create(({select:e,theme:t})=>({button:{width:40,height:40,borderRadius:24,alignItems:"center",justifyContent:"center",backgroundColor:e({light:t.palette.background50,dark:t.palette.background400}),boxShadow:[{color:"rgba(0, 0, 0, 0.08)",offsetX:0,offsetY:2,blurRadius:8,spreadDistance:0},{color:"rgba(0, 0, 0, 0.12)",offsetX:0,offsetY:4,blurRadius:6,spreadDistance:0}]}})),pa=({loading:e,error:t,data:n,LoadingComponent:r,ErrorComponent:o,EmptyComponent:s,...i},l)=>t?o:e?r:!n||n.length===0?s:a.createElement(f.FlatList,{ref:l,data:n,...i}),Fn=d.memo(d.forwardRef(pa)),jt=({name:e,type:t="FILE",onPress:n})=>{const r=_a.use();return a.createElement(P,{onPress:n,style:r.container,activeOpacity:.75},a.createElement(y,{style:r.iconWrapper},a.createElement(O,{type:"file-document",size:24,color:r.icon.tintColor})),a.createElement(y,{flex:1,flexDirection:"column",gap:4,style:r.info},a.createElement(k,{variant:"button",color:o=>o.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),a.createElement(k,{variant:"caption3",color:o=>o.textMidEmphasis},t)))},_a=R.create(({theme:e,themedColor:t})=>({container:{width:220,borderRadius:12,gap:8,height:64,flexDirection:"row",alignItems:"center",padding:12,borderWidth:1,borderColor:t.textDisabled,backgroundColor:t.bg_50_600},iconWrapper:{borderRadius:8,width:40,height:40,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary},icon:{tintColor:e.colors.base.primaryContrastContent},info:{alignItems:"flex-start",minWidth:0}})),ya=({file:e,children:t,onClickFile:n=({url:r})=>f.Linking.openURL(r)})=>a.createElement(y,{gap:M.GAP_GROUPED,width:M.BODY_MAX_WIDTH,maxWidth:M.BODY_MAX_WIDTH},a.createElement(jt,{name:e.name,type:Ht(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),xe=({style:e,...t})=>a.createElement(f.Image,{style:[e,t],...t}),ba=({file:e,onClickMedia:t=({url:r})=>f.Linking.openURL(r),children:n})=>{const r=Ea.use();return a.createElement(y,{gap:M.GAP_GROUPED},a.createElement(P,{style:r.mediaContainer,onPress:()=>t==null?void 0:t(e)},a.createElement(xe,{source:{uri:e.url},style:r.media,resizeMode:"cover"})),n)},Ea=R.create(({select:e,theme:t})=>({mediaContainer:{width:M.BODY_MAX_WIDTH,height:160,borderRadius:12,overflow:"hidden",backgroundColor:e({light:t.palette.background100,dark:t.palette.background400})},media:{width:"100%",height:"100%"}})),$n=({code:e,language:t})=>{const[n,r]=d.useState(!1),o=async()=>{Sr.default.setString(e),r(!0),setTimeout(()=>r(!1),2e3)};return a.createElement(y,{style:He.container,flexDirection:"row"},a.createElement(f.Pressable,{style:He.copyButton,onPress:o},a.createElement(O,{type:n?"done":"copy",size:16,color:"#fff"})),a.createElement(y,null,a.createElement(Ar.default,{hljsStyle:br.atomOneDarkReasonable,scrollViewProps:{contentContainerStyle:He.codeContainer,bounces:!1},textStyle:He.codeText,language:t},e)))},He=f.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}}),Un=d.memo(({src:e,onPress:t})=>{const[n,r]=d.useState("1/1"),[o,s]=d.useState(!1),i=Ca.use();return d.useLayoutEffect(()=>{e&&Rn(e).then(({width:l,height:c})=>r(`${l}/${c}`))},[e]),a.createElement(f.Pressable,{style:{marginTop:8},onPress:t},a.createElement(y,{style:[i.container,{aspectRatio:n}]},o?a.createElement(O,{size:28,type:"thumbnail-none",color:l=>l.textHighEmphasisInverse}):a.createElement(f.Image,{source:{uri:e},style:f.StyleSheet.absoluteFillObject,onError:()=>s(!0)})))}),Ca=R.create(({themedColor:e})=>({container:{width:"100%",backgroundColor:e.textDisabled,borderRadius:4,overflow:"hidden",justifyContent:"center",alignItems:"center"}}));Un.displayName="MarkdownImage";const Le=e=>d.isValidElement(e)&&"children"in e.props,Ot=(e=.75)=>`rgba(0, 0, 0, ${e})`,va=({children:e})=>{var i;const t=f.useWindowDimensions(),n=Ot(.3),r=d.useMemo(()=>{try{if(!Array.isArray(e)||e.length<2)return null;const l=e[0],c=e[1],u=Le(c)?c.props.children:void 0;if(!u||!Array.isArray(u)||u.length===0)return null;const m=u,h=m[0],g=Le(h)?h.props.children:void 0;if(!g||!Array.isArray(g)||g.length===0)return null;const _=m.length,p=g.length,S=Array(p).fill(null).map(()=>[]);for(let C=0;C<_;C++){const x=m[C],T=Le(x)?x.props.children:void 0;if(!(!T||!Array.isArray(T)))for(let A=0;A<p;A++){const w=S[A];w&&A<T.length&&(w[C]=T[A])}}const b=Le(l)?l.props.children:void 0,E=Array.isArray(b)?b[0]:void 0,v=Le(E)?E.props.children:void 0;if(v&&Array.isArray(v))for(let C=0;C<p;C++){const x=S[C];x&&C<v.length&&x.unshift(v[C])}return S}catch{return null}},[e]),[o,s]=d.useState(Array(((i=r==null?void 0:r[0])==null?void 0:i.length)??0).fill(0));return r?a.createElement(f.View,{style:{flexDirection:"row"}},r.map((l,c)=>{const u=c===0,m=c===r.length-1;return a.createElement(f.View,{key:c,style:{flexDirection:"column",borderStartWidth:1,borderEndWidth:m?1:0,borderTopWidth:1,borderBottomWidth:1,borderColor:n,borderTopStartRadius:u?6:0,borderBottomStartRadius:u?6:0,borderTopEndRadius:m?6:0,borderBottomEndRadius:m?6:0}},l.map((h,g)=>{const _=g===0,p=g===l.length-1;return a.createElement(f.View,{key:g,onLayout:({nativeEvent:{layout:S}})=>{const b=S.height;(o[g]??0)<b&&(o[g]=b,s([...o]))},style:{borderBottomWidth:p?0:1,borderColor:n,backgroundColor:_?Ot(.15):"transparent",maxWidth:t.width*2/3,minHeight:(o[g]??0)>0?o[g]:void 0,padding:8}},h)}))})):a.createElement(f.View,null,e)},Kt=d.memo(({children:e,textStyle:t,linkStyle:n,onPressImage:r})=>{const{themedColor:o}=z(),s=f.StyleSheet.compose({fontSize:14,color:o.textHighEmphasis,textAlign:"left"},t),i=f.StyleSheet.flatten(s),l=i.fontSize||14,c=i.lineHeight||l*1.286,u=Ot(.3),m={color:i.color,textAlign:Wt.useTextAlign({text:e,style:i}),fontSize:l,lineHeight:c,fontWeight:i.fontWeight,fontFamily:i.fontFamily,fontStyle:i.fontStyle,letterSpacing:i.letterSpacing,textDecorationLine:i.textDecorationLine,textDecorationStyle:i.textDecorationStyle,textDecorationColor:i.textDecorationColor},h=d.useMemo(()=>({image:g=>{var p,S;const _=((p=g.attributes)==null?void 0:p.src)||((S=g.attributes)==null?void 0:S.href);return _?a.createElement(Un,{key:g.key,src:_,onPress:()=>r==null?void 0:r(_)}):null},code_block:g=>a.createElement($n,{code:g.content,language:"text"}),table:(g,_)=>a.createElement(f.View,{key:g.key,style:{marginTop:8}},a.createElement(f.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},a.createElement(va,null,_)))}),[r]);return a.createElement(y,{flexDirection:"row",marginTop:-8},a.createElement(xr.default,{style:{body:{...m,width:e.length>50?"100%":void 0,marginBottom:0},paragraph:{...m,marginTop:8,marginBottom:0},heading1:{...m,marginTop:8,marginBottom:0,fontSize:l*1.429,lineHeight:l*1.429*1.4,fontWeight:"700"},heading2:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.286,lineHeight:l*1.286*1.333},heading3:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading4:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading5:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading6:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},link:f.StyleSheet.flatten(f.StyleSheet.compose({...m,fontWeight:"700",textDecorationLine:"underline"},n)),code_inline:{...m,fontSize:l*.929,lineHeight:l*.929*1.538,fontWeight:"600",backgroundColor:u},code_block:{...m,borderWidth:0,backgroundColor:u,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538},fence:{...m,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538,backgroundColor:o.textDisabled},bullet_list:{marginTop:4,marginBottom:0},bullet_list_icon:{marginLeft:0,marginRight:4,fontWeight:"900"},ordered_list:{marginTop:4,marginBottom:0},ordered_list_icon:{marginLeft:0,marginRight:4},list_item:{...m,marginTop:4,marginBottom:0},blockquote:{...m,paddingStart:8,marginTop:8,marginBottom:0,paddingVertical:4,borderStartWidth:4,borderStartColor:u,backgroundColor:"transparent",fontWeight:"500",fontSize:l,lineHeight:c},hr:{backgroundColor:u,height:1,marginTop:8,marginBottom:0},th:{...m,padding:4,fontSize:l,lineHeight:l*1.143,fontWeight:"700"},td:{...m,padding:2,fontSize:l,lineHeight:l*1.429},image:{maxHeight:300,maxWidth:"100%"}},rules:h},zr(e)))});Kt.displayName="MarkdownText";const gn=({maxBodyWidth:e,customStyle:t,message:n,children:r})=>{const o=Sa.use(),s=e??M.BODY_MAX_WIDTH,i=d.useMemo(()=>Or(n),[n]),l=d.useCallback(c=>f.Linking.openURL(c),[]);return i.length===0&&!r?null:a.createElement(y,{alignSelf:"flex-start",maxWidth:s,borderRadius:12,paddingVertical:12,style:[o.container,(t==null?void 0:t.bubbleBackgroundColor)&&{backgroundColor:t==null?void 0:t.bubbleBackgroundColor}]},i.map((c,u)=>c.type==="text"?a.createElement(y,{key:u,paddingHorizontal:12},a.createElement(Kt,{onPressImage:l,textStyle:o.text},c.value)):c.type==="code"?a.createElement($n,{key:u,code:c.value,language:c.language}):null),r)},Sa=R.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),Aa=e=>{const{strings:t}=H(),n=()=>{const r=An(e)?a.createElement(gn,{...e}):null;return e.messageType==="user"?r:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(ba,{...e},r):a.createElement(ya,{...e},r):a.createElement(gn,{...e,message:t.conversation.unknown_message_type})};return a.createElement(y,{style:e.containerStyle},n())};function qn({id:e,src:t,size:n=56,onClick:r,style:o}){const s=xa.use(),i=a.createElement(f.View,{style:[s.container(n),o],testID:e},t?a.createElement(f.Image,{source:{uri:t},style:s.image}):a.createElement(O,{type:"user",size:n}));return r?a.createElement(P,{onPress:r,activeOpacity:.75},i):i}const xa=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"}})),wa=({sender:e,isBotMessage:t})=>{const n=Ia.use();return t&&!e.profileUrl?a.createElement(y,{style:n.botContainer},a.createElement(O,{type:"delight",size:M.AVATAR_SIZE-8})):a.createElement(qn,{src:e.profileUrl,size:M.AVATAR_SIZE})},Ia=R.create(({theme:e})=>({botContainer:{width:M.AVATAR_SIZE,height:M.AVATAR_SIZE,borderRadius:M.AVATAR_SIZE/2,padding:4,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary}})),Ta=({sender:e})=>a.createElement(y,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7,alignItems:"flex-start"},a.createElement(k,{variant:"caption1",color:t=>t.textMidEmphasis,numberOfLines:1},e.nickname)),ka=({createdAt:e,containerStyle:t})=>{const{strings:n,format:r}=H();return e?a.createElement(y,{alignItems:"flex-start",style:t},a.createElement(k,{variant:"caption4",color:o=>o.textLowEmphasis},r(e,n.date_format.message_timestamp))):null},Ma=({customStyle:e,containerStyle:t})=>{const{theme:n}=z(),r=d.useRef(new f.Animated.Value(0)).current,o=La.map(([s,i,l])=>[r.interpolate({inputRange:s,outputRange:i,extrapolate:"clamp"}),r.interpolate({inputRange:s,outputRange:l,extrapolate:"clamp"})]);return d.useEffect(()=>{const s=f.Animated.loop(f.Animated.timing(r,{toValue:1.4,duration:1400,easing:f.Easing.linear,useNativeDriver:!0}));return s.start(),()=>s.reset()},[]),a.createElement(y,{style:t},a.createElement(y,{width:60,flexDirection:"row",alignItems:"center",justifyContent:"center",borderRadius:16,paddingHorizontal:12,height:34,backgroundColor:(e==null?void 0:e.bubbleBackgroundColor)??n.colors.messageIncoming.background},o.map(([s,i],l)=>a.createElement(y.Animated,{key:l,style:[Ra.dot,{marginEnd:l===o.length-1?0:6,opacity:i,transform:[{scale:s}],backgroundColor:(e==null?void 0:e.bubbleContentColor)??n.colors.messageIncoming.text}]}))))},La=[[[.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]]],Ra=f.StyleSheet.create({dot:{width:8,height:8,borderRadius:4}}),Pa=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>f.Linking.openURL(n)})=>{const n=Da.use(),r=e==null?void 0:e.cta_button;return r?a.createElement(P,{onPress:()=>t(r),activeOpacity:.75,style:n.button},a.createElement(k,{variant:"button",color:o=>o.textHighEmphasis,numberOfLines:1},r.label)):null},Da=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})}})),Oa=({extendedMessagePayload:e,onClickCitation:t=n=>f.Linking.openURL(n.link)})=>{const{strings:n}=H(),{theme:r}=z(),o=e==null?void 0:e.citations;return!o||o.length===0?null:a.createElement(y,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},a.createElement(k,{variant:"caption1",color:r.colors.messageIncoming.text,style:hn.sourceLabel},n.conversation.citation_title),a.createElement(y,{gap:8},o.map(s=>a.createElement(P,{key:s.embedding_id,onPress:()=>t(s),activeOpacity:.5},a.createElement(y,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(O,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(y,{flex:1},a.createElement(k,{variant:"body3",color:r.colors.messageIncoming.text,numberOfLines:1,style:hn.citationText},s.title)))))))},hn=f.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),Bt=e=>`${e}-filled`,Ba=e=>e==="good"?G.AIAgentMessageFeedbackRating.GOOD:G.AIAgentMessageFeedbackRating.BAD,fn=({onClose:e,isEdit:t,initialRating:n,initialComment:r="",isCommentEnabled:o=!1})=>{const{strings:s}=H(),{themedColor:i,theme:l}=z(),c=Na.use(),[u,m]=d.useState(r),[h,g]=d.useState(n),_=()=>{h&&e({rating:h,comment:u.trim()||void 0})},p=()=>{e()},S={good:i.secondary,bad:i.error};return a.createElement(f.KeyboardAvoidingView,{style:{flex:1},behavior:"padding"},a.createElement(P,{onPress:p,style:c.overlay},a.createElement(y,{width:280,backgroundColor:l.colors.base.modalContentBackground,borderRadius:12,overflow:"hidden",onStartShouldSetResponder:()=>!0},a.createElement(y,{padding:24},a.createElement(k,{variant:"h2",color:i.textHighEmphasis},s.feedback.title)),a.createElement(y,{paddingHorizontal:24,gap:24},a.createElement(y,{flexDirection:"row",gap:4},["good","bad"].map(b=>{const E=h===b,v=b==="good"?s.feedback.good:s.feedback.bad;return a.createElement(P,{key:b,onPress:()=>g(b),activeOpacity:.6,style:c.ratingButton(E)},a.createElement(O,{type:E?Bt(b):b,size:24,color:E?S[b]:i.textLowEmphasis}),a.createElement(k,{variant:"caption1",color:E?S[b]:i.textLowEmphasis},v))})),o&&a.createElement(y,{gap:6},a.createElement(k,{variant:"caption3",color:i.textHighEmphasis},s.feedback.comment_label),a.createElement(f.TextInput,{value:u,onChangeText:b=>m(b),placeholder:s.feedback.comment_placeholder,placeholderTextColor:i.textLowEmphasis,multiline:!0,maxLength:100,style:c.commentInput}))),a.createElement(y,{paddingHorizontal:24,paddingVertical:16,flexDirection:"row",justifyContent:"flex-end",gap:4},a.createElement(P,{onPress:p,activeOpacity:.6,style:c.cancelButton},a.createElement(k,{variant:"button",color:i.textHighEmphasis},s.feedback.cancel)),a.createElement(P,{onPress:_,disabled:!h,activeOpacity:.6,style:c.submitButton(!h)},a.createElement(k,{variant:"button",color:l.colors.base.primaryContrastContent},t?s.feedback.save:s.feedback.submit))))))},Na=R.create(({select:e,theme:t,themedColor:n})=>({overlay:{flex:1,backgroundColor:t.palette.overlay.dark,alignItems:"center",justifyContent:"center"},ratingButton:r=>({width:114,height:64,borderRadius:12,borderWidth:1,borderColor:n.textDisabled,alignItems:"center",justifyContent:"center",gap:0,backgroundColor:r?e({light:t.palette.background100,dark:t.palette.background600}):"transparent"}),commentInput:{width:"100%",maxHeight:118,borderRadius:4,borderWidth:1,borderColor:n.textDisabled,backgroundColor:n.textLowEmphasisInverse,color:n.textHighEmphasis,paddingHorizontal:12,paddingVertical:6,fontSize:12,lineHeight:16,textAlignVertical:"top"},cancelButton:{width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},submitButton:r=>({width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center",backgroundColor:t.colors.base.primary,opacity:r?.4:1})})),Ha=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:o,extendedMessagePayload:s,onFeedbackUpdate:i,containerStyle:l})=>{const{strings:c}=H(),{themedColor:u}=z(),{openModal:m}=Ye(),h=za.use(),g=s==null?void 0:s.feedback,_=(g==null?void 0:g.rating)??"none";if(_!=="none"?!1:!!(n||!e||!r||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const S={good:u.secondary,bad:u.error},b=async C=>{const x=await m(T=>a.createElement(fn,{onClose:T,isEdit:!1,initialRating:C,initialComment:"",isCommentEnabled:o}));x&&(i==null||i(x))},E=async()=>{const C=await m(x=>a.createElement(ee,{onClose:()=>x()},a.createElement(ee.ActionItem,{onPress:()=>x("edit"),label:c.feedback.edit}),a.createElement(ee.ActionItem,{onPress:()=>x("remove"),label:c.feedback.remove,destructive:!0})));if(C==="edit"){const x=await m(T=>a.createElement(fn,{onClose:T,isEdit:!0,initialRating:g==null?void 0:g.rating,initialComment:g==null?void 0:g.comment,isCommentEnabled:o}));x&&(i==null||i(x))}else C==="remove"&&(i==null||i(null))},v=()=>t&&_!=="none"?a.createElement(y,{flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:M.BODY_MAX_WIDTH},a.createElement(y,{padding:2,flexShrink:0,alignItems:"center"},a.createElement(O,{type:Bt(_),size:12,color:S[_]})),(g==null?void 0:g.comment)&&a.createElement(k,{variant:"caption2",style:h.commentText},g.comment)):a.createElement(y,{gap:4,maxWidth:M.BODY_MAX_WIDTH},a.createElement(y,{flexDirection:"row",gap:2},["good","bad"].map(C=>{const x=_===C;return a.createElement(P,{key:C,onPress:()=>{_==="none"?b(C):E()},activeOpacity:.6,style:h.feedbackButton(x)},a.createElement(O,{type:x?Bt(C):C,size:14,color:x?S[C]:u.textMidEmphasis}))})),_!=="none"&&(g==null?void 0:g.comment)&&a.createElement(k,{variant:"caption2",style:h.commentText},g.comment));return a.createElement(y,{style:l},v())},za=R.create(({select:e,theme:t,themedColor:n})=>({feedbackButton:r=>({width:38,height:20,borderRadius:18,alignItems:"center",justifyContent:"center",borderWidth:1,borderColor:e({light:t.palette.background200,dark:t.palette.background400}),backgroundColor:r?e({light:t.palette.background100,dark:t.palette.background500}):"transparent"}),commentText:{lineHeight:16,color:e({light:n.textMidEmphasis,dark:n.textHighEmphasis})}})),Fa=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},$a=e=>null,Wn=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:r,...o})=>a.createElement(f.ScrollView,{style:[t,o,e&&Ut],showsHorizontalScrollIndicator:n,...o},r),Ua=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const r=qa.use(),[o,s]=d.useState(!1),i=(e==null?void 0:e.suggested_replies)??[];if(i.length===0||o)return null;const l=n==="vertical",c=m=>{t==null||t({reply:m}),s(!0)},u=()=>i.map((m,h)=>a.createElement(P,{key:h,style:r.itemContainer,onPress:()=>c(m)},a.createElement(k,{variant:"body3",color:g=>g.primary},m)));return l?a.createElement(y,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:M.HORIZONTAL_PADDING},u()):a.createElement(Wn,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:r.horizontalContainer},u())},qa=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:M.HORIZONTAL_PADDING,paddingVertical:16}})),Wa=e=>{var _,p,S,b,E,v,C;const{components:t}=Ze.useContext(),{streamText:n,isAnimating:r}=Yo({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationComplete:e.onStreamAnimationComplete}),o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},s=!!o.isTyping,i=!!((_=o.extendedMessagePayload)!=null&&_.form)&&!((p=o.extendedMessagePayload)!=null&&p.form.canceled_at),l=!!((S=o.extendedMessagePayload)!=null&&S.message_template),c=!!((b=o.extendedMessagePayload)!=null&&b.cta_button),u=!!((E=o.extendedMessagePayload)!=null&&E.citations)&&o.extendedMessagePayload.citations.length>0,m=!!o.createdAt,h=o.groupType==="top"||o.groupType==="single",g=o.groupType==="bottom"||o.groupType==="single";return a.createElement(y,{marginBottom:s?0:zt(o.groupType)},h&&a.createElement(y,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:M.HORIZONTAL_PADDING},a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(y,{gap:M.GAP_GROUPED},s?a.createElement(t.TypingIndicator,{...o,containerStyle:ge.middleArea}):a.createElement(t.MessageBody,{...o,containerStyle:ge.middleArea},c&&a.createElement(y,{marginTop:12,marginHorizontal:12},a.createElement(t.CTAButton,{...o})),u&&a.createElement(t.Citation,{...o})),l&&a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(t.MessageBody,{...o,messageType:"user",message:((C=(v=o.extendedMessagePayload)==null?void 0:v.message_template)==null?void 0:C.fallback_message)??"Cannot read this template.",containerStyle:ge.middleArea}),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??a.createElement(t.TypingIndicator,{...o,containerStyle:ge.middleArea})}),i&&a.createElement(t.Form,{...o,containerStyle:ge.middleArea})),g&&m&&a.createElement(t.SentTime,{...o,containerStyle:ge.bottomArea}),a.createElement(d.Fragment,null,!s&&a.createElement(t.Feedback,{...o,containerStyle:ge.feedbackArea}),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},Ze=oe({template:Wa,components:{SenderName:Ta,SenderAvatar:wa,SentTime:ka,MessageBody:Aa,TypingIndicator:Ma,SuggestedReplies:Ua,MessageTemplate:$a,CTAButton:Pa,Citation:Oa,Form:Fa,Feedback:Ha}}),ge=f.StyleSheet.create({middleArea:{paddingStart:M.HORIZONTAL_PADDING+M.AVATAR_SIZE,paddingEnd:M.HORIZONTAL_PADDING},bottomArea:{marginTop:M.BODY_TIME_GAP,paddingStart:M.HORIZONTAL_PADDING+M.AVATAR_SIZE+8,paddingEnd:M.HORIZONTAL_PADDING},feedbackArea:{marginTop:8,paddingStart:M.HORIZONTAL_PADDING+M.AVATAR_SIZE+8,paddingEnd:M.HORIZONTAL_PADDING}}),Va=({file:e,children:t,sendingStatus:n,onClickFile:r=({url:o})=>f.Linking.openURL(o)})=>{const o=(()=>{if(!(!r||n!=="succeeded"))return()=>r(e)})();return a.createElement(y,{flexDirection:"column",alignItems:"flex-end",gap:M.GAP_GROUPED,width:M.BODY_MAX_WIDTH,maxWidth:M.BODY_MAX_WIDTH},a.createElement(jt,{name:e.name,type:Ht(e.name,e.type),onPress:o}),t)},Vn=({size:e=26,children:t})=>{const n=d.useRef(new f.Animated.Value(0)).current;d.useEffect(()=>{const o=f.Animated.loop(f.Animated.timing(n,{toValue:1,duration:1e3,easing:f.Easing.linear,useNativeDriver:!0}));return o.start(),()=>{o.stop()}},[n]);const r=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(y.Animated,{style:{transform:[{rotate:r}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??a.createElement(O,{type:"spinner",size:e}))};function Ga(e){return typeof e=="object"&&e!==null&&"uri"in e}const ja=({file:e,metadata:t,sendingStatus:n,onClickMedia:r=({url:s})=>f.Linking.openURL(s),children:o})=>{const s=Ka.use(),{aspectRatio:i,localFile:l}=t,[c]=d.useState(()=>Ga(l)?l.uri:e.url),[u,m]=d.useState(!1),h=(()=>{if(!(!r||n!=="succeeded"))return()=>r(e)})();return a.createElement(y,{flexDirection:"column",alignItems:"flex-end",gap:M.GAP_GROUPED},a.createElement(P,{onPress:h,style:[s.imageContainer,{aspectRatio:i}],activeOpacity:.75},!u&&a.createElement(y,{alignItems:"center",justifyContent:"center"},a.createElement(Vn,{size:26},a.createElement(O,{type:"spinner",color:g=>g.textLowEmphasis,size:26}))),a.createElement(xe,{source:{uri:c},style:[s.image,{opacity:u?1:0}],resizeMode:"cover",onLoad:()=>m(!0)})),o)},Ka=R.create(({themedColor:e})=>({imageContainer:{width:M.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}})),pn=e=>{var n,r;const t=Ya.use();return a.createElement(y,{style:[t.container({maxWidth:e.maxBodyWidth??M.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},a.createElement(k,{variant:"body3",style:[t.text,((r=e.customStyle)==null?void 0:r.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},Ya=R.create(({theme:e})=>({container:t=>({flexDirection:"column",borderRadius:12,overflow:"hidden",maxWidth:t.maxWidth,backgroundColor:e.colors.messageOutgoing.background,paddingVertical:12}),text:{textAlign:"left",lineHeight:20,paddingHorizontal:12,color:e.colors.messageOutgoing.text}})),Xa=e=>{const{strings:t}=H(),n=()=>{const r=An(e)?a.createElement(pn,{...e}):null;return e.messageType==="user"?r:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(ja,{...e},r):a.createElement(Va,{...e},r):a.createElement(pn,{...e,message:t.unknown_message_type})};return a.createElement(P,{onPress:e.sendingStatus==="failed"?e.onClickFailedMessage:void 0,activeOpacity:.75},a.createElement(y,{style:e.containerStyle},n()))},Za=({sendingStatus:e,containerStyle:t})=>{const{themedColor:n}=z(),r=()=>{switch(e){case"pending":return a.createElement(y,{marginBottom:2},a.createElement(Vn,{size:16},a.createElement(O,{type:"spinner",color:n.primary,size:16})));case"failed":return a.createElement(y,{marginBottom:2},a.createElement(O,{type:"error",color:n.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement(y,{marginBottom:2},a.createElement(O,{type:"done",color:n.secondary,size:16}))}};return a.createElement(y,{style:t},r())},Ja=({createdAt:e,containerStyle:t})=>{const{format:n,strings:r}=H();return e?a.createElement(y,{style:t},a.createElement(k,{variant:"caption4",color:o=>o.textLowEmphasis},n(e,r.date_format.message_timestamp))):null},Qa=e=>{const{components:t}=Je.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(y,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:zt(e.groupType)},a.createElement(t.MessageBody,{...e,containerStyle:_t.middleArea}),r&&(n?a.createElement(t.SentTime,{...e,containerStyle:_t.bottomArea}):a.createElement(t.SendingStatus,{...e,containerStyle:_t.bottomArea})))},Je=oe({template:Qa,components:{SendingStatus:Za,SentTime:Ja,MessageBody:Xa}}),_t=f.StyleSheet.create({middleArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:M.HORIZONTAL_PADDING},bottomArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingStart:M.HORIZONTAL_PADDING,paddingEnd:M.HORIZONTAL_PADDING+8,marginTop:M.BODY_TIME_GAP}}),ei=e=>e.messageType!=="admin"?null:a.createElement(k,{variant:"caption2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},ti(e.message)),ti=e=>{try{const t=[];let n=e,r=0;for(;n;){const o=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),s=n.match(/\*\*([^*]+)\*\*/),i=[o&&{match:o,type:"link"},s&&{match:s,type:"bold"}].filter(h=>!!h);if(!i.length){t.push(n);break}const l=i.reduce((h,g)=>g.match.index<h.match.index?g:h),{match:c,type:u}=l,m=c.index;m>0&&t.push(n.slice(0,m)),u==="link"?t.push(a.createElement(f.Text,{key:r++,onPress:()=>f.Linking.openURL((c==null?void 0:c[2])??""),style:{textDecorationLine:"underline"}},c[1])):u==="bold"&&t.push(a.createElement(f.Text,{key:r++,style:{fontWeight:"bold"}},c[1])),n=n.slice(m+c[0].length)}return t.filter(o=>o!=="")}catch{return[e]}},ni=({children:e,style:t})=>a.createElement(k,{variant:"caption4",color:n=>n.error,style:t},e),ri=({children:e,style:t,required:n})=>{const{strings:r}=H();return a.createElement(k,{variant:"caption3",color:o=>o.textMidEmphasis,style:t},e,!n&&a.createElement(k,{variant:"caption3",color:o=>o.textLowEmphasis},` (${r.form.optional_label})`))},oi=({style:e})=>{const t=si.use();return a.createElement(y,{style:[t.separator,e]})},si=R.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),ai=({value:e="",onChange:t,placeholder:n,variant:r="single-line",error:o=!1,submitted:s=!1,style:i,disabled:l=!1,maxLength:c})=>{const[u,m]=d.useState(!1),h=ii.use(),{themedColor:g}=z(),_=p=>{c&&p.length>c||t==null||t(p)};return a.createElement(f.TextInput,{value:e,onChangeText:_,placeholder:n,editable:!l&&!s,maxLength:c,multiline:r==="multi-line",style:[h.input(r,o,s,u),i],placeholderTextColor:g.textLowEmphasis,onFocus:()=>m(!0),onBlur:()=>m(!1)})},ii=R.create(({select:e,theme:t,themedColor:n})=>({input:(r,o,s,i)=>{let l,c;s?(l="transparent",c=e({light:t.palette.ondark.textMidEmphasis,dark:t.palette.onlight.textLowEmphasis})):o?(l=n.error,c=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis})):(l=i?n.primary:n.textDisabled,c=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis}));const u={width:"100%",padding:8,paddingHorizontal:12,borderRadius:6,fontSize:14,fontWeight:"400",lineHeight:20,borderWidth:1,borderColor:l,backgroundColor:c,color:s?n.textLowEmphasis:n.textHighEmphasis};return r==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),Pe={Label:ri,ErrorLabel:ni,TextInput:ai,Separator:oi},Gn=({onClick:e,checked:t,label:n,disabled:r,labelVariant:o="caption2"})=>{const{themedColor:s}=z(),i=li.use(),l=t?s.primary:r?s.textDisabled:s.textLowEmphasis;return a.createElement(P,{disabled:r||!e,onPress:e},a.createElement(y,{style:i.container},a.createElement(y,{style:i.iconContainer},a.createElement(O,{size:20,type:t?"radio-on":"radio-off",color:l})),a.createElement(k,{variant:o,style:i.label(t,r)},n)))},li=R.create(({themedColor:e})=>({container:{flexDirection:"row",alignItems:"flex-start",justifyContent:"flex-start",width:"100%",gap:2},iconContainer:{width:20,height:20},label:(t,n)=>{let r;return t?r=e.textHighEmphasis:n?r=e.textLowEmphasis:r=e.textHighEmphasis,{flex:1,color:r,lineHeight:20}}})),ci=({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?a.createElement(y,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(Pe.Label,{required:e.cre.required},e.cre.question),a.createElement(y,{flexDirection:"column",gap:8,width:"100%"},[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(s=>a.createElement(Gn,{key:s.label,checked:r===s.value,label:s.label,disabled:t,onClick:()=>o==null?void 0:o(s.value)})))):null),ui=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{strings:s}=H();return a.createElement(y,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(Pe.Label,{required:e.required},e.question),e.response_type==="free_text"&&a.createElement(Pe.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>r(i),error:o}),e.response_type==="single_choice"&&a.createElement(y,{flexDirection:"column",gap:8,width:"100%"},e.options.map(i=>a.createElement(Gn,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>r==null?void 0:r(i),labelVariant:"body3"}))),o&&a.createElement(Pe.ErrorLabel,null,s.form.validation_required))},di=e=>null,mi=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",s=jn.use(),[i,l]=d.useState(16);return a.createElement(y,{onLayout:c=>{c.nativeEvent.layout.width<300&&l(0)},flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(k,{variant:"caption3",color:c=>c.textMidEmphasis},e.csat_question),a.createElement(y,{style:[s.scoresContainer,{gap:i}]},e.csat_scores.map(({label:c,image_url:u},m)=>{const h=m+1,g=n===h;return a.createElement(P,{key:m,disabled:t,onPress:()=>r(h),style:s.scoreButton},a.createElement(gi,{value:h,selected:o||g,label:c,src:u}),!!c&&a.createElement(k,{style:{textAlign:"center"},variant:"caption3",color:_=>g?_.textHighEmphasis:_.textLowEmphasis,lineBreakStrategyIOS:"standard",textBreakStrategy:"simple"},c))})))},gi=({value:e,src:t,label:n,selected:r})=>{const[o,s]=d.useState(!1),i=jn.use();return o?a.createElement(di,{value:e,selected:r,label:n}):a.createElement(xe,{source:{uri:t},style:i.emojiImage(r),onError:()=>s(!0),accessibilityLabel:n})},jn=R.create(()=>({scoresContainer:{flexDirection:"row",justifyContent:"space-between",alignSelf:"center",width:"100%",maxWidth:400},scoreButton:{backgroundColor:"transparent",gap:4,flexDirection:"column",alignItems:"center",justifyContent:"flex-start",minWidth:48,maxWidth:68,flex:1},emojiImage:e=>({width:40,height:40,opacity:e?1:.38})})),hi=({csatPayload:e})=>a.createElement(k,{style:{textAlign:"left"},variant:"button",color:t=>t.textHighEmphasis},e.title),yt=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:s})=>{const{params:i,setParams:l,error:c,setError:u,followUpItem:m,state:h,validateParams:g,itemProps:_}=Go({csatPayload:e,type:t,initialCsat:r,initialCsatReason:o,initialIsResolved:s});return a.createElement(a.Fragment,null,a.createElement(y,{flexDirection:"column",gap:12},a.createElement(hi,{..._}),t===ie.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(ci,{..._,defaultValue:s,value:i.isResolved,onChange:p=>l({isResolved:p})}),a.createElement(mi,{..._,value:i.csat,onChange:p=>l({csat:p})}),m&&a.createElement(ui,{..._,followUpItem:m,value:i.csatReason,onChange:p=>{l({csatReason:p}),u({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Pe.Separator,null),n({state:h,params:i,validateParams:g})))},fi=e=>{const{strings:t}=H();return kr(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})},pi=()=>{const{strings:e}=H();return a.createElement(k,{variant:"body2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},_i=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n}=e,{csat:r,csatReason:o,csatExpireAt:s,isResolvedWhenDeterminedByUser:i}=e,[,l]=d.useState(0),c=fi(t==null?void 0:t.csat),u=yi.use();if(!c||!c.visibility||!ie[c.type])return null;const m=c.type===ie.AI_AGENT_CSAT_5||c.type===ie.AI_AGENT_CSAT_5_WITH_CRE||c.type===ie.HELPDESK_CSAT_5?yt:()=>null;return a.createElement(y,{style:u.container},!r&&Qt(s)?a.createElement(pi,null):a.createElement(m,{csatPayload:c,type:c.type,initialCsat:r,initialCsatReason:o,initialIsResolved:i,renderSubmitButton:({state:h,params:g,validateParams:_})=>a.createElement(P,{activeOpacity:.75,disabled:h==="submitted",onPress:()=>{!Qt(s)&&_()?n(g):l(p=>p+1)},style:u.submitButton(h)},a.createElement(k,{variant:"button",style:u.submitButtonText(h)},h==="submitted"?c.csat_submitted_label:c.csat_submit_label))}))},yi=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}}})),bi=e=>{const{components:t}=Qe.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(y,{paddingHorizontal:M.HORIZONTAL_PADDING,marginBottom:zt(e.groupType)},n)},Qe=oe({template:bi,components:{AdminMessage:ei,CSATMessage:_i}}),Ei=({style:e,...t})=>{const{strings:n}=H();if(!$t("powered-by"))return null;const o=()=>{f.Linking.openURL("https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby")};return a.createElement(y,{style:[Ci.container,e],...t},a.createElement(k,{variant:"caption2",color:s=>s.textLowEmphasis},n.conversation.powered_by+" "),a.createElement(P,{onPress:o},a.createElement(k,{variant:"caption2",color:s=>s.textLowEmphasis},"Sendbird")))},Ci=f.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),vi=()=>{var l;const{strings:e}=H(),{channelSource:t,scrollSource:n,updateActiveChannel:r}=te(),o=Si.use(),s=we(t.channel),i=d.useRef(s);return d.useEffect(()=>{const c=i.current;i.current=s,!c&&s&&n.actions.scrollToBottom(!0)},[s,n]),!((l=t.channel)!=null&&l.isAIAgent)||!s?null:a.createElement(y,{justifyContent:"center",flexDirection:"row",style:o.wrapper},a.createElement(P,{activeOpacity:.75,onPress:()=>r(),style:o.button},a.createElement(k,{variant:"button",role:"button",color:c=>c.textHighEmphasis},e.conversation.start_new_conversation_label)))},Si=R.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),Ai=()=>{const{aiAgentInfo:e}=J(),{channelSource:t}=te(),n=Mn(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}})()},xi=(e,t)=>!ar.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),wi=({messageStackDirection:e="top"})=>{var K,ne;const{Template:t}=Ze.useContext(),{Template:n}=Je.useContext(),{Template:r}=Qe.useContext(),{openModal:o}=Ye(),{strings:s}=H(),{config:i,cache:l,chatSDK:c}=U(),{aiAgentInfo:u,userSession:m,connectionError:h}=J(),{messageSource:g,channelSource:_,scrollSource:p,state:{input:S,streamAnimation:b}}=te(),E=Ai(),v=Ii.use(),C=Ie(["left","right"]),{state:x,props:T}=p,A=(K=_.channel)==null?void 0:K.conversation,w=(I,X=!1)=>{var de;return X?u??{nickname:"",profileUrl:""}:((de=_.channel)==null?void 0:de.members.find(ke=>ke.userId===I.sender.userId))??I.sender},L=I=>{if(I.sendingStatus==="failed"&&!S.disabled)return()=>{o(X=>a.createElement(ee,{onClose:()=>X()},a.createElement(ee.ActionItem,{label:s.conversation.failed_message_resend,onPress:async()=>{g.resendMessage(I),X()}}),a.createElement(ee.ActionItem,{destructive:!0,label:s.conversation.failed_message_remove,onPress:async()=>{g.deleteMessage(I),X()}})))}},$=({item:I,index:X})=>{const de=g.messages[X+1],ke=g.messages[X-1],Me=(()=>{var Zt,Jt;const B=!(u!=null&&u.isUserFeedbackEnabled&&Ae(I,u==null?void 0:u.userId)&&!Ue.isWelcomeMessage(I)),W=Pr(I,de,ke,B),Z={extendedMessagePayload:I.extendedMessagePayload,message:I.message,createdAt:I.createdAt,groupType:W};if(Oe.isAdmin(I))return Oe.isCSAT(I)?A?a.createElement(r,{...Z,...A,messageType:"admin.csat",isResolvedWhenDeterminedByUser:Ir(A),onSubmitCSAT:({csat:ce,..._e})=>{var ue;ce&&((ue=_.channel)==null||ue.submitCSAT({csat:ce,..._e}))}}):null:a.createElement(r,{...Z,messageType:"admin"});if(Oe.isOutgoing(I,(m==null?void 0:m.userId)??"")){const ce={...Z,sender:w(I),sendingStatus:I.sendingStatus,onClickFailedMessage:L(I)};if(I.isUserMessage())return a.createElement(n,{...ce,messageType:"user"});if(I.isFileMessage()){const[_e,ue]=((Zt=I.metaArrays.find(F=>F.key===vn))==null?void 0:Zt.value)??[];return a.createElement(n,{...ce,messageType:"file",file:I,metadata:{aspectRatio:_e&&ue?`${_e}/${ue}`:"1/1",localFile:(Jt=I.messageParams)==null?void 0:Jt.file}})}}if(Oe.isIncoming(I,(m==null?void 0:m.userId)??"")){const ce=I.sender.userId===(u==null?void 0:u.userId),_e=X===0,ue={...Z,sender:w(I,ce),suggestedRepliesVisible:_e,isBotMessage:ce,isStreaming:Ue.isStreaming(I),isHandedOff:Se(_.channel),isConversationClosed:we(_.channel),isFeedbackEnabled:u==null?void 0:u.isUserFeedbackEnabled,isFeedbackCommentEnabled:u==null?void 0:u.isUserFeedbackCommentOptionEnabled,onClickSuggestedReply:async({reply:F})=>{g.sendUserMessage({message:F})},onRequestMessageTemplate:async F=>{const{template:ae}=await c.aiAgent.getMessageTemplate(F);return l.template.set(F,ae),ae},onGetCachedMessageTemplate:F=>l.template.get(F),onHandleTemplateInternalAction:F=>{if(F.type==="internal"&&F.internalData){const{method:ae,payload:me}=F.internalData;ae==="message.send"&&(me!=null&&me.message)&&g.sendUserMessage({message:me.message})}},onFeedbackUpdate:F=>{const ae={messageId:I.messageId,channelUrl:I.channelUrl};if(!F)return c.aiAgent.deleteMessageFeedback(ae);const me={...ae,rating:Ba(F.rating),comment:F.comment};return Ue.hasFeedback(I)?c.aiAgent.updateMessageFeedback(me):c.aiAgent.createMessageFeedback(me)},onSubmitForm:({key:F,data:ae})=>c.aiAgent.submitForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:F,formData:ae}),onCancelForm:({key:F})=>c.aiAgent.cancelForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:F}),onStreamAnimationStart:()=>{b.start(I.messageId)},onStreamAnimationComplete:()=>{b.stop(I.messageId)}};if(I.isUserMessage())return a.createElement(t,{...ue,messageType:"user"});if(I.isFileMessage())return a.createElement(t,{...ue,messageType:"file",file:I})}return null})(),D=xi(I,de)&&a.createElement(sa,{date:I.createdAt,style:v.dateSeparator});return a.createElement(y,null,D,Me)},Y=()=>a.createElement(Ei,{style:v.poweredBy}),q=()=>{var I;return a.createElement(a.Fragment,null,E&&a.createElement(t,{isTyping:!0,isBotMessage:E.isBot,sender:E.user,messageType:"user",groupType:"single",message:""}),((I=i==null?void 0:i.conversation)==null?void 0:I.isTalkToAgentViewEnabled)&&a.createElement(vi,null),x.bottomSpace?a.createElement(y,{height:x.bottomSpace}):null)};return a.createElement(y,{flex:1},a.createElement(Fn,{ref:p.ref,style:v.list,contentContainerStyle:[v.listContent,C,e==="top"&&v.stackTop],data:g.messages,onEndReached:g.loadPrevious,keyExtractor:Rr,renderItem:$,loading:!g.initialized,error:!!(h||_.error),LoadingComponent:a.createElement(ve,{type:"loading"}),EmptyComponent:a.createElement(ve,{type:"noMessages",label:s.common.placeholder_no_messages}),ErrorComponent:a.createElement(ve,{type:"error",label:(h==null?void 0:h.message)??((ne=_.error)==null?void 0:ne.message),action:_.error?{label:s.common.placeholder_something_went_wrong_retry_label,onPress:()=>_.refetch()}:void 0}),ListFooterComponent:Y(),ListHeaderComponent:q(),inverted:!0,...T}),x.shouldShowScrollButton&&a.createElement(y,{style:v.scrollButtonContainer},a.createElement(ha,{onPress:()=>p.actions.scrollToBottom(!0)})))},Ii=R.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background},stackTop:{flexGrow:1,justifyContent:"flex-end"},dateSeparator:{marginVertical:16},poweredBy:{marginTop:16},scrollButtonContainer:{position:"absolute",bottom:20,end:20}})),le={CAMERA_PERMISSION_DENIED:"Camera permission is not granted",GALLERY_PERMISSION_DENIED:"Photo library permission is not granted",IMAGE_PICKER_NOT_CONFIGURED:"Image picker is not configured. Please provide imagePicker in NativeAdapterConfig to use camera or gallery features.",DOCUMENT_PICKER_NOT_CONFIGURED:"Document picker is not configured. Please provide documentPicker in NativeAdapterConfig to use file selection features."};function Ti(e){return{captureCamera:async()=>{if(e.requestCameraPermissionsAsync&&!(await e.requestCameraPermissionsAsync()).granted)throw new Error(le.CAMERA_PERMISSION_DENIED);const t=await e.launchCameraAsync({mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});return t.canceled||!t.assets||t.assets.length===0?null:t.assets.map(_n)},selectFromGallery:async t=>{if(e.requestMediaLibraryPermissionsAsync&&!(await e.requestMediaLibraryPermissionsAsync()).granted)throw new Error(le.GALLERY_PERMISSION_DENIED);const n=await e.launchImageLibraryAsync({selectionLimit:(t==null?void 0:t.selectionLimit)??1,allowsMultipleSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});return n.canceled||!n.assets||n.assets.length===0?null:n.assets.map(_n)}}}function ki(e,t){const n=async()=>{const o=f.Platform.select({ios:t.PERMISSIONS.IOS.CAMERA,android:t.PERMISSIONS.ANDROID.CAMERA});if(!o)return;const s=await t.request(o);if(s!=="granted"&&s!=="limited")throw new Error(le.CAMERA_PERMISSION_DENIED)},r=async()=>{const o=f.Platform.select({ios:[t.PERMISSIONS.IOS.PHOTO_LIBRARY],android:typeof f.Platform.Version=="number"&&f.Platform.Version>32?[]:typeof f.Platform.Version=="number"&&f.Platform.Version>28?[t.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]:[t.PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,t.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]});if(!o||o.length===0)return;const s=await t.requestMultiple(o);if(!Object.values(s).every(l=>l==="granted"||l==="limited"))throw new Error(le.GALLERY_PERMISSION_DENIED)};return{captureCamera:async()=>{await n();const o=await e.launchCamera({mediaType:"photo",assetRepresentationMode:"compatible"});if(o.didCancel)return null;if(o.errorCode)throw o.errorCode==="permission"?new Error(le.CAMERA_PERMISSION_DENIED):new Error(o.errorMessage||`Camera error: ${o.errorCode}`);return!o.assets||o.assets.length===0?null:o.assets.map(yn)},selectFromGallery:async o=>{await r();const s=await e.launchImageLibrary({mediaType:"photo",selectionLimit:(o==null?void 0:o.selectionLimit)??1,assetRepresentationMode:"compatible"});if(s.didCancel)return null;if(s.errorCode)throw s.errorCode==="permission"?new Error(le.GALLERY_PERMISSION_DENIED):new Error(s.errorMessage||`Gallery error: ${s.errorCode}`);return!s.assets||s.assets.length===0?null:s.assets.map(yn)}}}function Mi(e){return{selectFile:async t=>{const n=(t==null?void 0:t.mimeTypes)??["*/*"],r=await e.getDocumentAsync({multiple:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:n});return r.canceled||!r.assets||r.assets.length===0?null:r.assets.map(Ri)}}}function Li(e){return{selectFile:async t=>{try{const n=(t==null?void 0:t.mimeTypes)??["*/*"],r=f.Platform.select({android:n,ios:void 0}),o=await e.pick({mode:"open",allowMultiSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:r});return(Array.isArray(o)?o:[o]).map(Pi)}catch(n){if(n&&typeof n=="object"&&"message"in n){const r=String(n.message).toLowerCase();if(r.includes("cancel")||r.includes("user cancelled"))return null;throw new Error(String(n.message))}throw new Error("File selection failed")}}}}function _n(e){return{uri:e.uri,type:e.mimeType||"image/jpeg",size:e.fileSize||0,name:e.fileName||"image.jpg",width:e.width,height:e.height}}function Ri(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function yn(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 Pi(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function Di(e){return{keyValueStorage:{get:t=>e.getString(t)??null,set:(t,n)=>e.set(t,n),delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}}function Oi(){return{captureCamera:async()=>{throw new Error(le.IMAGE_PICKER_NOT_CONFIGURED)},selectFromGallery:async()=>{throw new Error(le.IMAGE_PICKER_NOT_CONFIGURED)}}}function Bi(){return{selectFile:async()=>{throw new Error(le.DOCUMENT_PICKER_NOT_CONFIGURED)}}}const{Provider:Ni,useContext:Kn}=j("NativeAdapter"),Yn=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:r,documentPicker:o,mmkv:s}=e,i=r?(Hi(e),"launchCameraAsync"in r?Ti(r):ki(r,e.permissions)):Oi(),l=o?"getDocumentAsync"in o?Mi(o):Li(o):Bi(),c=Di(s);return{...i,...l,...c}},[e.imagePicker,e.documentPicker,e.mmkv,e.permissions]);return a.createElement(Ni,{value:n},t)};function Hi(e){if(!e.imagePicker)return;if(!("launchCameraAsync"in e.imagePicker)&&!e.permissions)throw new Error("react-native-permissions is required when using react-native-image-picker. Please install react-native-permissions and provide it in nativeModules.permissions")}const zi=({onPressAddAttachment:e,disabled:t})=>a.createElement(P,{disabled:t,style:Fi.container,activeOpacity:.75,onPress:e},a.createElement(O,{type:"add",size:24,color:n=>t?n.textDisabled:n.primary})),Fi=f.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),$i=({name:e,type:t,url:n,onRemove:r})=>{const o=Ui.use();return a.createElement(y,{style:o.wrapper},Dr(t)?a.createElement(xe,{source:{uri:n},style:o.image,resizeMode:"cover"}):a.createElement(jt,{name:e,type:Ht(e,t)}),r&&a.createElement(P,{onPress:r,style:o.removeButton},a.createElement(O,{type:"remove",size:20,color:o.removeIcon.tintColor})))},ze=7,Ui=R.create(({themedColor:e})=>({wrapper:{marginTop:ze,marginRight:ze,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-ze,right:-ze,width:22,height:22,borderRadius:11,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),qi=e=>{const{theme:t,themedColor:n}=z(),r=Wi.use(),o=Wt.useTextAlign({text:e.value??e.placeholder,style:r.input,isTextInput:!0});return a.createElement(y,{style:r.container},e.attachments&&a.createElement(Wn,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),a.createElement(y,null,a.createElement(f.TextInput,{multiline:!0,style:[r.input,{textAlign:o}],placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},Wi=R.create(({theme:e})=>({container:{backgroundColor:e.colors.messageInput.background,gap:16,flex:1,paddingHorizontal:16,paddingVertical:8,justifyContent:"center",borderRadius:20,minHeight:36},input:{...Vi(e.typography.body3),color:e.colors.messageInput.text,includeFontPadding:!1,padding:0,margin:0,textAlignVertical:"center"}}));function Vi(e){const t={maxHeight:52};return e.fontFamily&&(t.fontFamily=e.fontFamily),typeof e.fontSize=="number"&&(t.fontSize=e.fontSize,t.maxHeight=e.fontSize*3.5),typeof e.lineHeight=="number"&&(t.lineHeight=e.lineHeight,t.maxHeight=e.lineHeight*3.5),e.fontWeight&&(t.fontWeight=e.fontWeight),t}const Gi=({onPressSend:e})=>a.createElement(P,{style:ji.container,activeOpacity:.75,onPress:e},a.createElement(O,{type:"send",size:24})),ji=f.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Ki=()=>{const e=Yi.use(),{aiAgentInfo:t,userSession:n}=J(),{messageSource:r,channelSource:o}=te(),[s,i]=d.useState(null),l=$t("special-notice",o.channel),c=d.useCallback(()=>o.channel?l?r.messages.some(u=>Ae(u,(n==null?void 0:n.userId)??"")):!0:null,[o.channel,l,r.messages,n==null?void 0:n.userId]);return d.useEffect(()=>{s||i(c())},[c,s]),s||!(t!=null&&t.specialNotice)?null:a.createElement(y,{style:e.container},a.createElement(Kt,{textStyle:e.text,linkStyle:e.link},(t==null?void 0:t.specialNotice)??""))},Yi=R.create(({theme:e,themedColor:t,select:n})=>({container:{backgroundColor:e.colors.base.background,paddingVertical:8,paddingHorizontal:16,alignItems:"center"},text:{...e.typography.body3,color:t.textLowEmphasis,textAlign:"center"},link:{fontWeight:"700",textDecorationLine:"none",color:n({light:e.palette.information.light,dark:e.palette.information.main})}})),Xi=()=>{var S;const{chatSDK:e}=U(),{strings:t}=H(),{createAttachmentRules:n}=J(),{channelSource:r,state:o}=te(),[s,i]=d.useState(""),[l,c]=d.useState([]),u=n({channel:r.channel,uploadSizeLimit:(S=e.appInfo)==null?void 0:S.uploadSizeLimit}),m=(b,E)=>{const v=E.filter(A=>u.isSupportedMimeType(A.type));if(v.length===0&&E.length>0)return f.Alert.alert("",t.conversation.file_upload_not_supported_file),b;const C=A=>{const w=u.getUploadSizeLimit(A.type);return A.size&&A.size>w},x=v.find(A=>C(A));if(x){const A=u.getUploadSizeLimitInMB(x.type);return f.Alert.alert("",t.conversation.file_upload_notification_size_limit(A)),b}return b.length+v.length>u.maxAttachmentCount?(f.Alert.alert("",t.conversation.file_upload_notification_count_limit(u.maxAttachmentCount)),b):[...b,...v]},h=b=>{c(E=>m(E,b))},g=b=>{c(E=>E.filter((v,C)=>C!==b))},_=()=>{c([])},p=(()=>{if(!o.input.disabled)return t.conversation.input_placeholder;switch(o.input.disabledBy){case"form_active":return t.conversation.input_placeholder_active_form;case"ai_responding":return t.conversation.input_placeholder_wait_ai_agent_response;case"reconnecting":return t.conversation.input_placeholder_reconnecting;case"unavailable":case"conversation_closed":default:return t.conversation.input_placeholder_disabled}})();return d.useEffect(()=>{o.input.disabled&&(i(""),_())},[o.input.disabled]),{files:l,addFiles:h,removeFile:g,clearFiles:_,value:s,onChangeText:i,editable:!o.input.disabled,placeholder:p,sendButtonVisible:!o.input.disabled&&(!!s.trim()||l.length>0),addAttachmentButtonVisible:u.isEnabled(),addAttachmentButtonDisabled:o.input.disabled||l.length>=u.maxAttachmentCount,hasImageMimeTypes:()=>u.supportedMimeTypes.filter(E=>E.startsWith("image/")||E===Sn).length>0,hasFileMimeTypes:()=>u.supportedMimeTypes.length>0,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount}},Zi=()=>{const{config:e}=U(),t=Kn(),{strings:n}=H(),{messageSource:r}=te(),{openModal:o}=Ye(),s=Ie(["left","right","bottom"]),i=Ji.use(),{maxAttachmentCount:l,sendButtonVisible:c,addAttachmentButtonVisible:u,addAttachmentButtonDisabled:m,acceptableMimeTypes:h,hasImageMimeTypes:g,hasFileMimeTypes:_,...p}=Xi(),E={...p,onPressAddAttachment:async()=>{const v=await o(C=>{var x,T,A,w,L,$,Y,q;return a.createElement(ee,{onClose:()=>C()},((A=(T=(x=e==null?void 0:e.conversation)==null?void 0:x.input)==null?void 0:T.camera)==null?void 0:A.photoEnabled)&&a.createElement(ee.ActionItem,{icon:"camera",label:n.conversation.attachment_camera,onPress:async()=>{if(!g())return f.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const K=await t.captureCamera();C(K)}}),(($=(L=(w=e==null?void 0:e.conversation)==null?void 0:w.input)==null?void 0:L.gallery)==null?void 0:$.photoEnabled)&&a.createElement(ee.ActionItem,{icon:"photo",label:n.conversation.attachment_photo,onPress:async()=>{if(!g())return f.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const K=await t.selectFromGallery({selectionLimit:l-p.files.length});C(K)}}),((q=(Y=e==null?void 0:e.conversation)==null?void 0:Y.input)==null?void 0:q.fileEnabled)&&a.createElement(ee.ActionItem,{icon:"document",label:n.conversation.attachment_document,onPress:async()=>{if(!_())return f.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const K=await t.selectFile({selectionLimit:l-p.files.length,mimeTypes:h});C(K)}}))});v&&p.addFiles(v)},onPressSend:()=>{p.files.length>0?r.sendFileMessage({message:p.value.trim(),file:p.files[0]}):r.sendUserMessage({message:p.value}),p.clearFiles(),p.onChangeText("")}};return a.createElement(f.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-s.paddingBottom},a.createElement(Ki,null),a.createElement(y,{style:i.container(s)},u&&a.createElement(zi,{...E,disabled:m}),a.createElement(qi,{...E,value:E.editable?E.value:"",attachments:E.files.length===0?null:E.files.map((v,C)=>a.createElement($i,{key:C,name:v.name,type:v.type,url:v.uri,onRemove:()=>E.removeFile(C)}))}),c&&a.createElement(Gi,{...E})))},Ji=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})})),Xn=({start:e,title:t,titleAlign:n="start",end:r})=>{const o=Ie(["left","right","top"]),[s,i]=d.useState(0),[l,c]=d.useState(0),u=g=>{i(g.nativeEvent.layout.width)},m=g=>{c(g.nativeEvent.layout.width)},h=Qi.use();return a.createElement(y,{style:h.container},a.createElement(y,{height:o.paddingTop}),a.createElement(y,{style:h.contentContainer(o)},n==="center"&&t&&a.createElement(y,{style:h.centerTitleContainer(Math.max(s,l))},a.createElement(y,{style:h.centerTitle},t)),a.createElement(y,{style:h.rowContainer},a.createElement(y,{style:h.startSide,onLayout:u},e),(n==="start"||n==="end")&&t&&a.createElement(y,{style:h.titleSide(n,e,r)},t),a.createElement(y,{style:h.endSide,onLayout:m},r))))},Qi=R.create(({theme:e,themedColor:t})=>({container:{width:"100%",backgroundColor:e.colors.base.headerBackground,borderBottomWidth:1,borderBottomColor:t.textDisabled},contentContainer:n=>({position:"relative",height:56,paddingStart:n.paddingStart+12,paddingEnd:n.paddingEnd+12}),centerTitleContainer:n=>({position:"absolute",left:n,right:n,top:0,bottom:0,alignItems:"center",justifyContent:"center"}),centerTitle:{maxWidth:"100%",overflow:"hidden"},rowContainer:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",height:"100%",zIndex:1},startSide:{flexShrink:0},endSide:{flexShrink:0},titleSide:(n,r,o)=>({flex:1,overflow:"hidden",alignItems:`flex-${n}`,marginStart:r?8:0,marginEnd:o?8:0})})),el=()=>{const{themedColor:e}=z(),{onClose:t}=te();return t?a.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(O,{color:e.textHighEmphasis,type:"close",size:24})):null},tl=()=>{const{themedColor:e}=z(),{channelSource:{channel:t}}=te(),n=$t("handoff-button",t),r=!Cn(t)||Se(t);return n?a.createElement(P,{hitSlop:4,disabled:r,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},a.createElement(O,{color:r?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},nl=()=>{const{themedColor:e}=z(),{onNavigateToConversationList:t}=te();return t?a.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(O,{color:e.textHighEmphasis,type:"menu",size:24})):null},Zn=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=J(),{fallbackIcon:o,url:s}=Ln({channel:e,aiAgentInfo:r,userSession:n}),{theme:i}=z();return s?a.createElement(qn,{src:s,size:t}):a.createElement(y,{width:t,height:t,borderRadius:t/2,alignItems:"center",justifyContent:"center",flexShrink:0,style:{backgroundColor:i.colors.base.primary}},a.createElement(O,{type:o,size:t*.55,color:i.colors.base.primaryContrastContent}))},rl=()=>{const{channelSource:{channel:e}}=te(),{userSession:t,aiAgentInfo:n}=J(),r=Ln({channel:e,userSession:t,aiAgentInfo:n});return a.createElement(y,{gap:6,flexDirection:"row",alignItems:"center",maxWidth:"100%"},a.createElement(Zn,{channel:e,size:34}),a.createElement(y,{flexShrink:1},a.createElement(k,{numberOfLines:1,variant:"h1"},r.title)))},ol=e=>{const{components:t}=pe.useContext();return a.createElement(Xn,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},sl=()=>{const{components:e}=pe.useContext();return a.createElement(e.MenuButton,null)},al=()=>{const{components:e}=pe.useContext();return a.createElement(e.Title,null)},il=()=>{const{components:e}=pe.useContext();return a.createElement(y,{flexDirection:"row",alignItems:"center",gap:10},a.createElement(e.HandoffButton,null),a.createElement(e.CloseButton,null))},pe=oe({template:ol,components:{StartArea:sl,TitleArea:al,EndArea:il,MenuButton:nl,Title:rl,HandoffButton:tl,CloseButton:el}}),ll=()=>{const{Template:e}=pe.useContext();return a.createElement(e,{titleAlign:"start"})},cl=e=>{const{components:t}=et.useContext();return a.createElement(y,{flex:1},a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},et=oe({template:cl,components:{Header:ll,Body:wi,Footer:Zi}}),Jn=({children:e,...t})=>{const{Template:n}=et.useContext();return a.createElement(Pn,{...t},a.createElement(n,null),e)},{Provider:ul,Context:dl,useContext:tt}=j("ConversationList"),Qn=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:r,children:o})=>{const{sdkUser:s,authenticate:i}=J();return d.useEffect(()=>{s||i()},[]),a.createElement(Fo,{conversationListLimit:e,conversationListFilter:t},l=>a.createElement(ul,{value:{...l,onClose:r,onNavigateToConversation:n}},o))},bt=99,ml=d.memo(function(t){const{channel:n,onClick:r}=t,{strings:o,format:s}=H(),{themedColor:i}=z(),l=hl.use(),c=Mr(n),u=Lr(n,s,{justNow:o.date_format.just_now,minutesAgo:o.date_format.minutes_ago,hoursAgo:o.date_format.hours_ago,dateShortFormat:o.date_format.date_short}),m=n.unreadMessageCount;return a.createElement(P,{onPress:r,activeOpacity:.75},a.createElement(y,{flexDirection:"row",alignItems:"center",width:"100%",height:72,gap:16},a.createElement(y,{marginStart:16,alignItems:"center",justifyContent:"center"},a.createElement(Zn,{channel:n})),a.createElement(y,{flexDirection:"row",alignItems:"center",flex:1,paddingEnd:16,height:"100%",gap:8,style:l.rightContainer},a.createElement(y,{flexDirection:"column",justifyContent:"center",flex:1,gap:4},a.createElement(k,{variant:"subtitle1",color:i.textHighEmphasis,numberOfLines:1},c),a.createElement(y,{flexDirection:"row",alignItems:"center",gap:6},we(n)&&a.createElement(a.Fragment,null,a.createElement(k,{variant:"caption1",color:i.textMidEmphasis,numberOfLines:1},o.conversation_list.ended),a.createElement(y,{width:2,height:2,borderRadius:1,backgroundColor:i.textLowEmphasis})),a.createElement(k,{variant:"caption2",color:i.textLowEmphasis,numberOfLines:1},u))),m>0&&a.createElement(y,{alignItems:"center",justifyContent:"center",height:20,width:m<=bt?20:void 0,padding:4,borderRadius:10,backgroundColor:i.error},a.createElement(k,{variant:"caption3",color:i.textHighEmphasisInverse,style:{lineHeight:12}},m<=bt?m:`${bt}+`)))))}),gl=oe({template:ml,components:{}}),hl=R.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),fl=()=>{var l;const{Template:e}=gl.useContext(),{strings:t}=H(),{connectionError:n}=J(),{listSource:r,onNavigateToConversation:o}=tt(),s=Ie(["left","right"]),i=pl.use();return a.createElement(Fn,{style:i.list,contentContainerStyle:[i.listContent,s],data:r.channels,onEndReached:r.loadMore,keyExtractor:d.useCallback(c=>c.url,[]),renderItem:d.useCallback(({item:c})=>a.createElement(e,{channel:c,onClick:()=>o==null?void 0:o(c.url,we(c)?"closed":"open")}),[e,o]),loading:!r.initialized,error:!!(n||r.error),LoadingComponent:a.createElement(ve,{type:"loading"}),EmptyComponent:a.createElement(ve,{type:"noChannels",label:t.common.placeholder_no_conversations}),ErrorComponent:a.createElement(ve,{type:"error",label:(n==null?void 0:n.message)??((l=r.error)==null?void 0:l.message)})})},pl=R.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),_l=()=>{const{strings:e}=H(),{language:t,countryCode:n,context:r}=U(),{aiAgentInfo:o,refreshActiveChannel:s,createConversation:i,setActiveChannel:l,sdkUser:c}=J(),{onNavigateToConversation:u}=tt(),m=Ie(["left","right","bottom"]),h=yl.use();return a.createElement(P,{activeOpacity:.75,disabled:!c,onPress:async()=>{if(o!=null&&o.isMultipleActiveConversationsEnabled){const g=await i({aiAgentId:o.userId,language:t,country:n,context:r});l({url:g,status:G.ConversationStatus.OPEN}),u==null||u(g,G.ConversationStatus.OPEN)}else{const g=await s();u==null||u(g,G.ConversationStatus.OPEN)}}},a.createElement(y,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+m.paddingBottom,style:[h.container,m]},a.createElement(k,{variant:"h1",color:g=>g.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},yl=R.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),bl=()=>{const{aiAgentInfo:e}=J();return e?a.createElement(_l,null):null},El=()=>{const{themedColor:e}=z(),{onClose:t}=tt();return t?a.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(O,{color:e.textHighEmphasis,type:"close",size:24})):null},Cl=()=>{const{strings:e}=H();return a.createElement(k,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},vl=e=>{const{components:t}=Te.useContext();return a.createElement(Xn,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},Sl=()=>null,Al=()=>{const{components:e}=Te.useContext();return a.createElement(e.Title,null)},xl=()=>{const{components:e}=Te.useContext();return a.createElement(e.CloseButton,null)},Te=oe({template:vl,components:{StartArea:Sl,TitleArea:Al,EndArea:xl,Title:Cl,CloseButton:El}}),wl=()=>{const{Template:e}=Te.useContext();return a.createElement(e,{titleAlign:"start"})},Il=()=>{const{components:e}=nt.useContext();return a.createElement(y,{flex:1},a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},nt=oe({template:Il,components:{Header:wl,Body:fl,Footer:bl}}),er=({children:e,...t})=>{const{Template:n}=nt.useContext();return a.createElement(Qn,{...t},a.createElement(n,null),e)},Tl="1.0.0",kl=Tl,Ml=d.forwardRef(function({logLevel:t=V.LogLevel.WARN,language:n=Ke,userSessionInfo:r,children:o,strings:s,...i},l){const[c]=d.useState(()=>new wn(t));c.level!==t&&(c.level=t);const{nativeModules:u,chatParams:m={},...h}=i;return a.createElement(Yn,{config:u},({keyValueStorage:g})=>a.createElement(Rl,{logger:c,theme:h.theme,language:n,strings:s},a.createElement(Kr,{language:n,logger:c,chatSDK:h.customChatSDK,keyValueStorage:g,chatParams:{...m,useMMKVStorageStore:u.mmkv},messengerVersion:kl,extensions:{platform:V.SendbirdPlatform.REACT_NATIVE,deviceOSPlatform:f.Platform.select({web:V.DeviceOsPlatform.WEB,ios:V.DeviceOsPlatform.IOS,default:V.DeviceOsPlatform.ANDROID})},...h},a.createElement(is,{ref:l,userSessionInfo:r},o))))}),Ll=wr(et,pe,nt,Te,Gt,Xe,Ze,Je,Qe),Rl=({children:e,logger:t,theme:n,language:r,strings:o})=>a.createElement(fe.SafeAreaProvider,null,a.createElement(qs,{logger:t,...n},a.createElement(Fs,{language:r,logger:t,strings:o},a.createElement(Dn,null,a.createElement(qo,null,a.createElement(Ll,null,e)))))),{Provider:Pl,useContext:Yt}=j("FixedMessengerStyle"),Dl={useNativeDriver:!0},Fe={OPEN_START:"0deg",OPEN_END:"-180deg",CLOSE_START:"180deg",CLOSE_END:"0deg"},$e={VISIBLE:1,HIDDEN:0},Ol=({isOpened:e})=>{const t=d.useRef(new f.Animated.Value(e?1:0)).current;d.useEffect(()=>{const o=e?1:0;f.Animated.spring(t,{toValue:o,...Dl}).start()},[e,t]);const n={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[Fe.OPEN_START,Fe.OPEN_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[$e.VISIBLE,$e.HIDDEN]})}]},r={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[Fe.CLOSE_START,Fe.CLOSE_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[$e.HIDDEN,$e.VISIBLE]})}]};return{openIconStyle:n,closeIconStyle:r}},Bl=2/3,Nl=({isOpened:e,onPress:t})=>{const n=Fl.use(),{launcherInfo:r}=J(),{theme:o}=z(),{launcherSize:s,horizontal:i}=Yt(),l=Math.round(s*Bl),c=o.colors.base.primary,u=o.colors.base.primaryContrastContent,{openIconStyle:m,closeIconStyle:h}=Ol({isOpened:e});return a.createElement(y,{alignSelf:i==="start"?"flex-start":"flex-end"},a.createElement(P,{onPress:t,activeOpacity:.8},({pressed:g})=>a.createElement(y,{style:[n.container({backgroundColor:c,size:s}),g&&n.pressed]},a.createElement(y.Animated,{style:[n.iconWrapper,m]},a.createElement(Hl,{url:(r==null?void 0:r.imageUrl)??"",isDefaultIcon:(r==null?void 0:r.type)==="default_icon",size:l,fillColor:u})),a.createElement(y.Animated,{style:[n.iconWrapper,h]},a.createElement(zl,{size:l,fillColor:u})))))},Hl=({url:e,isDefaultIcon:t,size:n,fillColor:r})=>e?t?a.createElement(xe,{source:{uri:e},width:n,height:n,tintColor:r,resizeMode:"contain"}):a.createElement(xe,{source:{uri:e},width:n,height:n,resizeMode:"cover"}):a.createElement(O,{type:"delight",size:n,color:r}),zl=({size:e,fillColor:t})=>a.createElement(O,{type:"chevron-down",size:e,color:t}),Fl=R.create(()=>({container:e=>({position:"relative",width:e.size,height:e.size,backgroundColor:e.backgroundColor,borderRadius:e.size/2,justifyContent:"center",alignItems:"center",boxShadow:"0px 8px 16px 0px rgba(33, 33, 33, 0.3)"}),pressed:{transform:[{scale:.9}]},iconWrapper:{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"}})),Q={TRANSLATE_OFFSET:40,DURATION:300,OPACITY_DURATION:83,EASING:f.Easing.out(f.Easing.ease)},$l=e=>e==="entered"?0:Q.TRANSLATE_OFFSET,Ul=e=>e==="entered"?1:0,ql=({transitionState:e,isActive:t})=>{const[n,r]=d.useState(!1),o=d.useRef(new f.Animated.Value($l(e))).current,s=d.useRef(new f.Animated.Value(Ul(e))).current;return d.useEffect(()=>{if(!n){e==="entered"?(o.setValue(0),s.setValue(1)):e==="exited"&&(o.setValue(Q.TRANSLATE_OFFSET),s.setValue(0)),r(!0);return}e==="entering"?(o.setValue(Q.TRANSLATE_OFFSET),s.setValue(0),f.Animated.parallel([f.Animated.timing(o,{toValue:0,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),f.Animated.timing(s,{toValue:1,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()):e==="exiting"&&f.Animated.parallel([f.Animated.timing(o,{toValue:Q.TRANSLATE_OFFSET,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),f.Animated.timing(s,{toValue:0,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()},[e,o,s,n]),d.useMemo(()=>({position:"absolute",top:0,left:0,width:"100%",height:"100%",transform:[{translateY:o}],opacity:s,zIndex:t?999:1,pointerEvents:t?"auto":"none",display:e==="exited"?"none":"flex"}),[o,s,t,e])},tr=d.createContext(null),Wl=()=>{const e=d.useContext(tr);if(!e)throw new Error("useNavigatorContext() must be used within <Navigator />");return e},nr=({children:e})=>{const t=Wl();return typeof e=="function"?a.createElement(a.Fragment,null,e(t)):a.createElement(a.Fragment,null,e)},Vl=d.memo(({transitionState:e,isActive:t,children:n})=>{const r=ql({transitionState:e,isActive:t});return a.createElement(f.Animated.View,{style:r},n)}),bn=300,qe=({initialId:e,children:t})=>{const[n,r]=d.useState([e]),o=n[n.length-1],s=d.useCallback((b,E)=>{r(v=>[...v,b]),h(v=>({...v,[b]:!0})),E!=null&&E.reset&&S(v=>({...v,[b]:(v[b]||0)+1})),_(v=>({...v,[b]:"entering"})),setTimeout(()=>{_(v=>({...v,[b]:"entered"}))},bn)},[]),i=d.useCallback(()=>{r(b=>{if(b.length<=1)return b;const E=b[b.length-1];return _(v=>({...v,[E]:"exiting"})),setTimeout(()=>{_(v=>({...v,[E]:"exited"})),r(v=>v.slice(0,-1))},bn),b})},[]),l=d.useMemo(()=>({navigation:{navigate:s,pop:i},activeScreenId:o}),[s,i,o]),c=d.useMemo(()=>d.Children.toArray(t).filter(b=>b.type===nr),[t]),u=d.useMemo(()=>{const b={};return c.forEach(E=>{const{id:v,lazy:C,children:x}=E.props;b[v]={lazy:C,element:typeof x=="function"?x(l):x}}),b},[c,l]),[m,h]=d.useState(()=>{const b={};return Object.entries(u).forEach(([E,{lazy:v}])=>{v===!1&&(b[E]=!0)}),b[e]=!0,b}),[g,_]=d.useState(()=>{const b={};return Object.keys(u).forEach(E=>{b[E]=E===e?"entered":"exited"}),b}),[p,S]=d.useState({});return a.createElement(tr.Provider,{value:l},a.createElement(y,{style:{position:"relative",width:"100%",height:"100%"}},Object.keys(u).map(b=>{var x;if(!m[b])return null;const E=g[b]||"exited",v=b===o,C=`${b}-${p[b]||0}`;return a.createElement(Vl,{key:C,transitionState:E,isActive:v},(x=u[b])==null?void 0:x.element)})))};qe.Screen=nr;const{Provider:Gl,useContext:Xt}=j("PageChildren"),jl=({children:e})=>{const[t,n]=d.useState(null),[r,o]=d.useState(null);return a.createElement(Gl,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:o}},e)},he={conv:"conv",convList:"conv-list"},Kl=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onClose:o})=>{const{conversationChildren:s,conversationListChildren:i}=Xt(),l=t==="ConversationList"?he.convList:he.conv;return a.createElement(qe,{initialId:l},a.createElement(qe.Screen,{id:he.conv},({navigation:c,activeScreenId:u})=>a.createElement(Jn,{channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>c.navigate(he.convList),onClose:o,shouldMarkAsRead:e&&u===he.conv},s)),a.createElement(qe.Screen,{id:he.convList,lazy:!0},({navigation:c})=>a.createElement(er,{onNavigateToConversation:u=>{r(u),c.navigate(he.conv,{reset:!0})},onClose:o},i)))},De=.15,Yl=150,En=(e,t)=>e.interpolate({inputRange:[De,1],outputRange:[t,0],extrapolate:"clamp"}),Xl=(e,t)=>{if(e<=0)return 0;const n=(1-De)*e/2,r=t==="start"?-1:1,o=f.I18nManager.isRTL?-1:1;return n*r*o},Zl=(e,t)=>e<=0?0:(1-De)*e/2*(t==="top"?-1:1),Jl=({isOpened:e,horizontal:t,vertical:n})=>{const[r,o]=d.useState({width:0,height:0}),s=d.useRef(new f.Animated.Value(e?1:De)).current,i=d.useRef(new f.Animated.Value(e?1:0)).current,l=d.useMemo(()=>Xl(r.width,t),[r.width,t]),c=d.useMemo(()=>Zl(r.height,n),[r.height,n]),{translateXInterpolation:u,translateYInterpolation:m}=d.useMemo(()=>({translateXInterpolation:En(s,l),translateYInterpolation:En(s,c)}),[s,l,c]);d.useEffect(()=>{const _=e?"open":"close",p=_==="open"?1:De,S=_==="open"?1:0,b=_==="open"?f.Easing.out(f.Easing.quad):f.Easing.in(f.Easing.quad),E={duration:Yl,useNativeDriver:!0,easing:b};_==="close"&&f.Keyboard.dismiss(),f.Animated.parallel([f.Animated.timing(s,{toValue:p,...E}),f.Animated.timing(i,{toValue:S,...E})]).start()},[e,s,i]);const h=d.useMemo(()=>({opacity:i,transform:[{translateX:u},{translateY:m},{scale:s}]}),[i,u,m,s]),g=d.useMemo(()=>_=>{const{width:p,height:S}=_.nativeEvent.layout;o(b=>b.width===p&&b.height===S?b:{width:p,height:S})},[]);return{animatedStyle:h,handleLayout:g,pointerEvents:e?"auto":"none"}},Ql={top:0,left:0,right:0,bottom:0},ec=({children:e,isOpened:t})=>{const n=tc.use(),{horizontal:r,vertical:o}=Yt(),{animatedStyle:s,handleLayout:i,pointerEvents:l}=Jl({isOpened:t,horizontal:r,vertical:o});return a.createElement(fe.SafeAreaInsetsContext.Provider,{value:Ql},a.createElement(y,{flex:1},a.createElement(y.Animated,{pointerEvents:l,onLayout:i,style:[n.windowContainer,s]},e)))},tc=R.create(({theme:e})=>({windowContainer:{width:"100%",height:"100%",borderRadius:16,overflow:"hidden",zIndex:999,backgroundColor:e.colors.base.background,boxShadow:"0px 4px 24px 0px rgba(0, 0, 0, 0.12)"}})),rr=()=>{const[e,t]=d.useState(0);return d.useEffect(()=>{const n=f.Platform.OS==="ios"?"keyboardWillShow":"keyboardDidShow",r=f.Platform.OS==="ios"?"keyboardWillHide":"keyboardDidHide",o=f.Keyboard.addListener(n,i=>{const{endCoordinates:l}=i,c=(l==null?void 0:l.height)||0;t(c)}),s=f.Keyboard.addListener(r,()=>{t(0)});return()=>{o.remove(),s.remove()}},[]),e},nc=e=>{const t=d.useRef(new f.Animated.Value(0)).current,[n,r]=d.useState(!1);return d.useEffect(()=>{const s=e?"open":"close",i={toValue:s==="open"?1:0,useNativeDriver:!0,duration:300};s==="open"&&r(!0),f.Animated.timing(t,i).start(()=>{s==="close"&&(r(!1),f.Keyboard.dismiss())})},[e,t]),{windowAnimatedStyle:{opacity:t,display:n?"flex":"none"},pointerEvents:e?"auto":"none"}},rc=({children:e,insets:t,isOpened:n})=>{const r=oc.use(),s={...fe.useSafeAreaInsets(),...t},i=rr(),{windowAnimatedStyle:l,pointerEvents:c}=nc(n);return a.createElement(fe.SafeAreaInsetsContext.Provider,{value:s},a.createElement(y.Animated,{flex:1,style:[r.bg,l],pointerEvents:c},a.createElement(y,{flex:1},e),a.createElement(y,{height:Math.max(0,i-f.Platform.select({android:0,default:s.bottom})),style:r.bg})))},oc=R.create(({theme:e})=>({bg:{backgroundColor:e.colors.base.background}})),sc="end-bottom",Re={top:24,bottom:24,start:24,end:24},ac=({mode:e,edgeToEdgeEnabled:t})=>{const n=e==="floating"?ec:rc,[r,o]=At({position:sc,margin:Re,launcherSize:48,spacing:12}),{bottom:s}=fe.useSafeAreaInsets(),i=rr(),[l,c]=r.position.split("-"),u=(()=>{const g=f.Platform.select({android:t?s:0,default:0}),_=c==="top"?r.spacing:-r.launcherSize,p=i>0?i+_+g:0;return p>0?p:r.margin.bottom})(),m={position:"absolute",zIndex:1e3,...c==="top"?{top:r.margin.top}:{bottom:r.margin.bottom},...l==="start"?{left:r.margin.start}:{right:r.margin.end}},h=(()=>{if(e==="floating"){const g=r.launcherSize+r.spacing;return{position:"absolute",top:r.margin.top+(c==="top"?g:0),bottom:u+(c==="bottom"?g:0),left:r.margin.start,right:r.margin.end,zIndex:999}}return{position:"absolute",top:0,bottom:0,left:0,right:0,zIndex:1001}})();return{Window:n,windowContainerStyle:h,launcherContainerStyle:m,styleContext:{...r,horizontal:l,vertical:c,setPosition:g=>o({position:g}),setMargin:({top:g=Re.top,bottom:_=Re.bottom,start:p=Re.start,end:S=Re.end})=>o({margin:{top:g,bottom:_,start:p,end:S}}),setLauncherSize:g=>o({launcherSize:g}),setSpacing:g=>o({spacing:g})}}},ic=e=>{var s,i,l,c;const{setPosition:t,setMargin:n,setLauncherSize:r,setSpacing:o}=Yt();return d.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n(e.margin),e.launcherSize!==void 0&&r(e.launcherSize),e.spacing!==void 0&&o(e.spacing)},[e.position,(s=e.margin)==null?void 0:s.top,(i=e.margin)==null?void 0:i.bottom,(l=e.margin)==null?void 0:l.start,(c=e.margin)==null?void 0:c.end,e.launcherSize,e.spacing]),null},lc=({children:e})=>{const{setConversationChildren:t}=Xt();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},cc=({children:e})=>{const{setConversationListChildren:t}=Xt();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},uc=({entryPoint:e="Conversation",edgeToEdgeEnabled:t=!0,windowMode:n="floating",fullscreenInsets:r,initialChannelUrl:o,windowContainerProps:s,children:i})=>{const[l,c]=d.useState(!1),[u,m]=d.useState(o),{Window:h,windowContainerStyle:g,launcherContainerStyle:_,styleContext:p}=ac({mode:n,edgeToEdgeEnabled:t});return d.useEffect(()=>{const S=f.BackHandler.addEventListener("hardwareBackPress",()=>l?(c(!1),!0):!1);return()=>S.remove()},[l]),a.createElement(Pl,{value:p},a.createElement(jl,null,a.createElement(y,{style:g,backgroundColor:"transparent",pointerEvents:l?"auto":"box-none",...s},a.createElement(h,{isOpened:l,insets:r},a.createElement(Kl,{isOpened:l,entryPoint:e,selectedChannelUrl:u,setSelectedChannelUrl:m,onClose:()=>c(!1)}))),a.createElement(y,{style:_,backgroundColor:"transparent",pointerEvents:"box-none"},a.createElement(Nl,{isOpened:l,onPress:()=>c(!l)})),i))},dc=Object.assign(uc,{Style:ic,ConversationChildren:lc,ConversationListChildren:cc});exports.AIAgentProviderContainer=Ml;exports.AnonymousSessionInfo=Ve;exports.BottomSheet=ee;exports.BottomSheetLayout=Xe;exports.Conversation=Jn;exports.ConversationContext=ps;exports.ConversationContextProvider=Pn;exports.ConversationHeaderLayout=pe;exports.ConversationLayout=et;exports.ConversationList=er;exports.ConversationListContext=dl;exports.ConversationListContextProvider=Qn;exports.ConversationListHeaderLayout=Te;exports.ConversationListLayout=nt;exports.FixedMessenger=dc;exports.IncomingMessageLayout=Ze;exports.ManualSessionInfo=Ft;exports.ModalProvider=Dn;exports.NativeAdapterProvider=Yn;exports.OutgoingMessageLayout=Je;exports.SystemMessageLayout=Qe;exports.useConversationContext=te;exports.useConversationListContext=tt;exports.useMessengerSessionContext=J;exports.useModalContext=Ye;exports.useNativeAdapterContext=Kn;
|
|
1
|
+
"use strict";var or=Object.defineProperty;var sr=(e,t,n)=>t in e?or(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var N=(e,t,n)=>sr(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react"),f=require("react-native"),fe=require("react-native-safe-area-context"),V=require("@sendbird/chat"),G=require("@sendbird/chat/aiAgent"),Nt=require("@sendbird/uikit-tools"),Ee=require("date-fns"),Ce=require("@sendbird/chat/message"),We=require("@sendbird/chat/groupChannel"),ar=require("date-fns/isSameDay"),ir=require("date-fns/locale/de"),lr=require("date-fns/locale/en-US"),cr=require("date-fns/locale/es"),ur=require("date-fns/locale/fr"),dr=require("date-fns/locale/hi"),mr=require("date-fns/locale/it"),gr=require("date-fns/locale/ja"),hr=require("date-fns/locale/ko"),fr=require("date-fns/locale/pt"),pr=require("date-fns/locale/tr"),_r=require("@react-native-clipboard/clipboard"),yr=require("react-native-code-highlighter"),br=require("react-syntax-highlighter/dist/esm/styles/hljs"),Er=require("react-native-markdown-display"),Ge=e=>e&&e.__esModule?e:{default:e};function Cr(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 a=Cr(d),vr=Ge(V),Sr=Ge(_r),Ar=Ge(yr),xr=Ge(Er),j=(e,t)=>{const n=d.createContext(null),r=({children:i,value:l})=>a.createElement(n.Provider,{value:l},typeof i=="function"?i(l):i),o=({children:i})=>a.createElement(n.Consumer,null,l=>l?typeof i=="function"?i(l):i:null),s=()=>{const i=d.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,o.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:s}};function oe(e){const t=d.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){const[i,l]=d.useState(()=>e.template),[c,u]=d.useState(e.components),m={Template:i,updateTemplate:h=>l(()=>h),components:c,updateComponent:(h,g)=>u(_=>({..._,[h]:g}))};return a.createElement(t.Provider,{value:m},s)}function r({template:s,children:i}){const{updateTemplate:l}=d.useContext(t);return d.useLayoutEffect(()=>{s&&l(s)},[s]),a.createElement(a.Fragment,null,i)}function o({children:s}){return a.createElement(n,null,s)}return o.defaults=e,o.useContext=()=>d.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(s=>{o[s]=function({component:l}){const{updateComponent:c}=d.useContext(t);return d.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),o}function wr(...e){return function({children:n}){return e.reduce((r,o)=>a.createElement(o,null,r),n)}}const we=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===G.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Cn=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===G.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function Se(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 Ir(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Qt(e){return!!e&&e<Date.now()}function Tr(e){return!e.title}function kr(e,t){var n;if(e)return Tr(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}function Mr(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 Lr(e,t,n){var i;const r=new Date,o=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),s=Ee.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Ee.isToday(o)?n.hoursAgo(Ee.differenceInHours(r,o)):t(o,n.dateShortFormat)}const be="sb-agent",vn="KEY_IMG_ASPECT_RATIO",Sn="*/*",M={BODY_MAX_WIDTH:244,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16},re=e=>!!e&&"sender"in e,Rr=e=>re(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Pr=(e,t,n,r=!0)=>{if(!r||!re(e))return"single";const o=()=>{if(!t||!re(t))return!1;const c=t.sender.userId===e.sender.userId,u=Ee.isSameMinute(t.createdAt,e.createdAt);return c&&u},s=()=>{if(!n||!re(n))return!1;const c=n.sender.userId===e.sender.userId,u=Ee.isSameMinute(n.createdAt,e.createdAt);return c&&u},i=o(),l=s();return i&&l?"middle":i?"bottom":l?"top":"single"},Ae=(e,t)=>(()=>{var r;return re(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Oe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isIncoming:(e,t)=>re(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>re(e)&&(e.sender.userId===t||e.sendingStatus===Ce.SendingStatus.PENDING)},Dr=e=>e.startsWith("image/"),Ht=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},An=e=>e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.message.length>0,zt=e=>{switch(e){case"top":case"middle":return M.GAP_GROUPED;default:return M.GAP_UNGROUPED}},Or=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(s,...i)=>{const[l,c,u]=i;return o<u&&r.push({type:"text",value:e.slice(o,u).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),o=u+s.length,s}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),r},Br=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Nr=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Hr=e=>e.replace(/~~/g,"\\~\\~"),zr=e=>{let t=e;return t=Br(t),t=Nr(t),t=Hr(t),t},Fr=typeof navigator<"u"&&navigator.product==="ReactNative",en=(e,t)=>{const n=r=>!t||t.length===0?!0:re(r)&&t.includes(r.sendingStatus);return Fr?e.find(n):e.findLast(n)};function Et(){}function $r(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Ur(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const tn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ue={isStreaming(e){const t=tn(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(Ae(e,t)){const r=tn(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)},checkExtendedFieldPresence(e){const t=e.extendedMessagePayload||{},n=i=>i.some(l=>["suggested_replies"].includes(l)?Array.isArray(t[l])&&t[l].length>0:typeof t[l]<"u"),r=n(rt.ui),o=n(rt.trail),s=n(rt.unusedAsync);return{ui:r,trail:o,unusedAsync:s}},shouldScrollToBottom(e,t,n=!1){if(Ae(e,t)){if(this.isGeneratedMessage(e)&&this.isStreaming(e))return!0;const{ui:r,trail:o,unusedAsync:s}=this.checkExtendedFieldPresence(e);return r?!(!n&&s):!!(n&&(o||s))}return!0}},rt={ui:["suggested_replies","cta_button","message_template","csat"],trail:["groundedness","manual","function_calls"],unusedAsync:["is_hallucination","is_moderated","flagged_types","is_last_in_turn","flagged_reason","used_sources"]},ot=`@${be}`,nn=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${ot}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}-template/message-template/tokens`,messengerSession:o=>{const s=Ur(`${e}/${t}/${o}`);return`${ot}-udata/${s}`},anonUserSession:()=>`${ot}-session/${e}/${t}`};return{template:{set:(o,s)=>n.set(r.template(o),s),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 s=n.get(r.messengerSession(o));return s?JSON.parse(s):null}catch{return null}},setSettings:(o,s)=>{try{delete s.auto_created_user;const i=JSON.stringify(s);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 s=JSON.stringify(o);n.set(r.anonUserSession(),s)}catch{return}},clear:o=>{try{o&&n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}};class qr{constructor(t){N(this,"subscribers",{});this.logger=t}async send(t){const n=Wr(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(s=>s(t.payload));await Promise.all(o).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter(r=>r!==n))}}const Wr=()=>{let e=Et,t=Et;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var xn=(e=>(e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(xn||{});class wn{constructor(t){N(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${be}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${be}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${be}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${be}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${be}/error]`,...t)}}function rn(e,t,n,r){const o=vr.default.init({appId:e,modules:[new We.GroupChannelModule,new G.AIAgentModule],localCacheEnabled:!0,options:new V.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:V.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function Vr(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 ye={conversation:{isTalkToAgentViewEnabled:!0,input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0}}},Gr=e=>{var t,n,r,o,s,i,l,c,u,m;return e?{...ye,...e,conversation:{...ye.conversation,...e==null?void 0:e.conversation,input:{...(t=ye.conversation)==null?void 0:t.input,...(n=e==null?void 0:e.conversation)==null?void 0:n.input,camera:{...(o=(r=ye.conversation)==null?void 0:r.input)==null?void 0:o.camera,...(i=(s=e==null?void 0:e.conversation)==null?void 0:s.input)==null?void 0:i.camera},gallery:{...(c=(l=ye.conversation)==null?void 0:l.input)==null?void 0:c.gallery,...(m=(u=e==null?void 0:e.conversation)==null?void 0:u.input)==null?void 0:m.gallery}}}}:ye},{Provider:jr,useContext:U}=j("AIAgent");function Kr({appId:e,aiAgentId:t,keyValueStorage:n,networkStateAdapter:r,language:o,countryCode:s,context:i,queryParams:l,config:c,chatSDK:u,chatParams:m,children:h,logger:g,dispatcher:_,messengerVersion:p,extensions:S={platform:V.SendbirdPlatform.JS,deviceOSPlatform:$r()?V.DeviceOsPlatform.MOBILE_WEB:V.DeviceOsPlatform.WEB}}){const[b,E]=d.useState(()=>{const v=g??new wn(xn.WARN),C=_??new qr(v);return{logger:v,dispatcher:C,chatSDK:u??rn(e,S,p,m),cache:nn({appId:e,aiAgentId:t,storage:n})}});return d.useEffect(()=>{E(v=>{let C=v.logger,x=v.dispatcher,T=v.chatSDK;return g&&g!==v.logger&&(C=g),_&&_!==v.dispatcher&&(x=_),u&&u!==v.chatSDK?T=u:!u&&v.chatSDK.appId!==e&&(T=rn(e,S,p,{newInstance:!0,...m})),{...v,logger:C,dispatcher:x,chatSDK:T,cache:nn({appId:e,aiAgentId:t,storage:n})}})},[e,t,g,_,u,n]),d.useEffect(()=>()=>{b.chatSDK.disconnectWebSocket()},[b.chatSDK]),Vr(b.chatSDK),a.createElement(jr,{value:{...b,appId:e,aiAgentId:t,context:i,language:o,countryCode:s,queryParams:l,config:Gr(c),networkStateAdapter:r}},h)}const Yr=(e,t,n)=>Nt.useGroupChannelMessages(e,t,{...n,strictStreamingOrder:!0});var Ct=(e=>(e.ConversationClose="conv.close",e))(Ct||{});const In=(e,t,n={})=>{let r=null,o=null,s=null;const{leading:i=!0,trailing:l=!0}=n,c=(...u)=>{const m=Date.now();if(s===null||m-s>=t)i?(e(...u),s=m):(o=u,s=m);else if(o=u,l&&!r){const h=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},h)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},c},vt={DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Tn(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Xr(e){const t=Tn(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Zr(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Jr(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),s=r-o;let i=0,l=0;const c=(r+o)/2;return r!==o&&(l=c>.5?s/(2-r-o):s/(r+o)),r===e?i=(t-n)/s+(t<n?6:0):r===t?i=(n-e)/s+2:r===n&&(i=(e-t)/s+4),i/=6,[i,l,c]}function Qr(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const i=function(m,h,g){return g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(h-m)*6*g:g<.5?h:g<.6666666666666666?m+(h-m)*(.6666666666666666-g)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=i(c,l,e+1/3),o=i(c,l,e),s=i(c,l,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(s*255)]}function Be(e,t,n){const[r,o,s]=Xr(e),[i,l,c]=Jr(r,o,s),u=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[h,g,_]=Qr(i,m,u);return Zr([Math.round(h),Math.round(g),Math.round(_)])}function eo(e,t="light"){return{extraDark:Be(e,.6,1.2),dark:Be(e,.85,1.1),main:e,light:Be(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Be(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function on(e){const t=Tn(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+s*.114>n?vt.BLACK:vt.WHITE}function to(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 no=(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}}),Ne={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 0.88)",textMidEmphasis:"rgba(0, 0, 0, 0.5)",textLowEmphasis:"rgba(0, 0, 0, 0.38)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 0.88)",textMidEmphasis:"rgba(255, 255, 255, 0.5)",textLowEmphasis:"rgba(255, 255, 255, 0.38)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},st={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function sn(e){const t=ro(e),{colors:n,aiAgentColorVariables:r}=oo(e,t),o=ao(e);return{selectedTheme:e.selectedTheme,palette:t,colors:n,aiAgentColorVariables:r,typography:o}}function ro({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ne.primary.main?Ne.primary:eo(n,e):Ne.primary;return{...Ne,primary:r,...t}}function oo({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,i=t??on(s),l=n??vt.DEFAULT_BOT_MSG_BG,c=r??on(l);return{colors:(e==="light"?to:no)(o,s,i,l,c),aiAgentColorVariables:{primary_color:s,bot_message_bg_color:l,primary_contrast_color:i,bot_message_bg_contrast_color:c}}}function so(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function ao({typography:e}){if(!e)return st;const t={...st};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=st[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=so(o,r,s)}}),t}const{Provider:io,useContext:lo}=j("AIAgentTheme");function co({logger:e,palette:t,typography:n,appearance:r,children:o}){const s=d.useRef(null),[i,l]=d.useState(()=>sn({selectedTheme:(r==null?void 0:r.theme)??"light",palette:t,typography:n,primary:r==null?void 0:r.primaryColor,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor})),c=d.useCallback((u,m)=>{m&&(s.current=m);const h=(r==null?void 0:r.theme)??u,g=s.current?s.current.themes[h]:null,_={primary:r==null?void 0:r.primaryColor,primaryContrast:void 0,botMessageBackground:r==null?void 0:r.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!_.primary&&(g!=null&&g.primary_color)&&(_.primary=g.primary_color,_.primaryContrast=g.primary_contrast_color),!_.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(_.botMessageBackground=g.bot_message_bg_color,_.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const p=sn({selectedTheme:h,palette:t,typography:n,..._});l(p),e==null||e.info("theme.update:",h)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor,t,n,e]);return d.useEffect(()=>{(r!=null&&r.theme||r!=null&&r.primaryColor||r!=null&&r.botMessageBackgroundColor)&&c(i.selectedTheme)},[r==null?void 0:r.theme,r==null?void 0:r.primaryColor,r==null?void 0:r.botMessageBackgroundColor]),a.createElement(io,{value:{theme:i,updateTheme:c}},o)}const an=25*1024*1024,uo={off:"off",always:"always",handed_off_only:"handed_off_only"},mo=()=>{const[e,t]=d.useState(()=>({maxAttachmentCount:1,attachmentMode:"handed_off_only",defaultUploadSizeLimit:an,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:new Set(["image/png","image/jpeg","image/jpg"]),supportedFileMimeTypes:new Set(["application/pdf"])})),n=d.useCallback(({active_channel:o,upload_restriction:s})=>{const{maxAttachmentCount:i,attachmentMode:l,defaultUploadSizeLimit:c,supportedImageMimeTypes:u,supportedFileMimeTypes:m}=e;t({maxAttachmentCount:i,attachmentMode:uo[o.attachment_mode]??l,defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??c,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??u),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??m)})},[]),r=d.useCallback(o=>{const{channel:s,uploadSizeLimit:i=an}=o,l=(u=!0)=>s!=null&&s.isAIAgent?u?Se(s):!1:!0,c=u=>{if(l())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(u)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(l(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return Se(s);default:return!0}},get supportedMimeTypes(){return l()?[Sn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:u=>l()?!0:e.supportedImageMimeTypes.has(u)||e.supportedFileMimeTypes.has(u),getUploadSizeLimit:c,getUploadSizeLimitInMB:u=>c(u)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}};function kn(){const{chatSDK:e,logger:t}=U();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 go(){const{chatSDK:e,logger:t}=U(),n=d.useCallback(async(o,s,i)=>{if(t.debug("useChatConnection.connect: start, session",o.userId),s){const l=new V.SessionHandler({...s,onSessionTokenRequired:ho(s.onSessionTokenRequired,i)});e.setSessionHandler(l)}try{return await e.connect(o.userId,o.authToken),t.debug("useChatConnection.connect: end, currentUser",e.currentUser),e.currentUser}catch(l){const c=l;if(e.isCacheEnabled){if(po(c))t.warn("useChatConnection.connect","offline connect restricted",c.message,c.code),t.warn("useChatConnection.connect","clear cached-data"),await e.clearCachedData().catch(u=>t.warn("useChatConnection.connect","clear cached-data failure",u));else if(e.currentUser)return t.debug("useChatConnection.connect: end (offline), currentUser",e.currentUser),e.currentUser}throw t.warn("useChatConnection.connect","connect failure",c.message,c.code),c}},[e,t]),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 ho(e,t){if(e)return async(n,r)=>{new Promise((o,s)=>e==null?void 0:e(o,s)).then(o=>{o&&(t==null||t(o)),n(o)}).catch(o=>{r(o)})}}const fo=[400300,400301,400302,400310];function po(e){return fo.some(t=>e.code===t)}class Ft{constructor({userId:t,authToken:n,sessionHandler:r}){N(this,"userId");N(this,"authToken");N(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class Ve{constructor(){N(this,"userId");N(this,"authToken");N(this,"sessionHandler")}}const _o=1440*60*1e3,yo=e=>{const{logger:t,cache:n}=U(),r=()=>{const s=n.messenger.getAnonUser();return s?s.expireAt-_o<=Date.now()?(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session expired, clear cache"),n.messenger.clear(s.userId),null):(t.debug("useUserSessionCandidate.getAnonymousSessionInfo: auto session info detected"),s):null},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 s=["userId","authToken","sessionHandler"].filter(i=>!(i in e));return s.length>0&&t.error(`useUserSessionCandidate.getManualSessionInfo: missing required keys in userSessionInfo: ${s.join(", ")}`),t.debug("useUserSessionCandidate.getManualSessionInfo: manual session info detected"),e};return d.useMemo(()=>e instanceof Ft?{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 bo({userSessionInfo:e,onUpdateMessengerSettings:t,onPreAuth:n,onPostAuth:r,onErrorAuth:o,onAuthTokenRefreshed:s,onPostDeauth:i,forceCreateChannel:l}){const{aiAgentId:c,language:u,context:m,countryCode:h,logger:g,cache:_}=U(),{connect:p,disconnect:S}=go(),{type:b,userSessionCandidate:E}=yo(e),v=kn(),C=d.useCallback(async()=>{var L;g.debug("useAuthentication.authenticate: start");const T=E!=null&&E.userId?_.messenger.getSettings(E.userId):null;T!=null&&T.bot&&(t(T),g.debug("useAuthentication.authenticate: cached messenger settings",T));const A=await v({aiAgentId:c,userId:E==null?void 0:E.userId,language:u,country:h,context:m,forceCreateChannel:l,knownActiveChannelUrl:(L=T==null?void 0:T.active_channel)==null?void 0:L.channel_url});g.debug("useAuthentication.authenticate: messenger settings response",A);let w=null;if(A.auto_created_user)if(b==="manual")g.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),w={userId:E.userId,authToken:E.authToken};else{const{user_id:$,session_token:Y,expire_at:q}=A.auto_created_user;_.messenger.setAnonUser({userId:$,authToken:Y,expireAt:q}),w={userId:$,authToken:Y}}else w={userId:(E==null?void 0:E.userId)??"",authToken:(E==null?void 0:E.authToken)??""};_.messenger.setSettings(w.userId,A),t(A);try{await n(A,w),await p(w,E==null?void 0:E.sessionHandler,s),await r(A,w)}catch($){throw $ instanceof Error&&(o($),g.error("useAuthentication.authenticate: failed to connect",$)),$}return A},[v,p,b,E==null?void 0:E.userId,E==null?void 0:E.sessionHandler,E==null?void 0:E.authToken,c,u,m,h,l,_.messenger.setAnonUser,_.messenger.getSettings,_.messenger.setSettings,t,n,r,o,s]),x=d.useCallback(async()=>{g.debug("useAuthentication.deauthenticate: start"),await S(),i(),g.debug("useAuthentication.deauthenticate: completed")},[S,g,i]);return{authenticate:C,deauthenticate:x,userSessionCandidate:E}}const Eo=e=>JSON.parse(e),Co=()=>{const{chatSDK:e,logger:t,cache:n}=U(),r=d.useCallback(()=>{var l,c;const s=(c=(l=e.appInfo)==null?void 0:l.aiAgentInfo)==null?void 0:c.templateListToken;if(!s)return!1;const i=n.template.getCachedToken();return i?s!==i:!0},[e,n.template.getCachedToken]),o=d.useCallback(async()=>{try{const{templates:s,token:i}=await e.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=Eo(l);n.template.set(c,l)}n.template.setCachedToken(i)}catch(s){t==null||t.error("messageTemplateContext.syncCachedTemplates: error:",s)}},[e,t,n.template.set,n.template.setCachedToken]);return{shouldSyncCachedTemplate:r,syncCachedTemplates:o}},{Provider:vo,useContext:je}=j("AIAgentMessengerSession"),So=d.forwardRef(function({userSessionInfo:e,forceCreateChannel:t,children:n},r){const{appId:o,aiAgentId:s,chatSDK:i,language:l,countryCode:c,context:u,cache:m,logger:h}=U(),{updateTheme:g}=lo(),[_,p]=d.useState(void 0),[S,b]=d.useState(void 0),[E,v]=d.useState(null),[C,x]=d.useState(null),[T,A]=d.useState(null),[w,L]=d.useState(null),{updateBaseAttachmentRules:$,createAttachmentRules:Y}=mo(),{shouldSyncCachedTemplate:q,syncCachedTemplates:K}=Co(),ne=kn(),{authenticate:I,deauthenticate:X}=bo({userSessionInfo:e,forceCreateChannel:t,onUpdateMessengerSettings:d.useCallback(D=>{const{appearance:B,bot:W,launcher:Z}=D;g(B.selected_theme,B),A({userId:W.bot_userid,profileUrl:W.bot_profile_url,nickname:W.bot_nickname,replyToFile:W.reply_to_file,specialNotice:W.special_notice,specialNoticeEnabled:W.is_special_notice_enabled,showHandoffButton:W.show_handoff_button??!0,isMultipleActiveConversationsEnabled:W.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:D.bot.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:D.bot.is_user_feedback_comment_option_enabled??!1}),L({type:Z.image_type||"default_icon",imageUrl:Z.image_url}),$(D)},[g]),onPreAuth:d.useCallback((D,B)=>{p(void 0),x(B)},[]),onPostAuth:d.useCallback(async D=>{v(i.currentUser),q()&&await K(),b({url:D.active_channel.channel_url,status:G.ConversationStatus.OPEN})},[i,q,K]),onErrorAuth:d.useCallback(D=>{p(D)},[]),onAuthTokenRefreshed:d.useCallback(D=>{x(B=>B?{...B,authToken:D}:null)},[]),onPostDeauth:d.useCallback(()=>{m.template.clear(),m.messenger.clear(C==null?void 0:C.userId),v(null),b(void 0),x(null),A(null),L(null)},[m.template.clear,m.messenger.clear,C])}),de=d.useCallback(async()=>{var D;if(C){h.debug("agentMessengerSession.refreshActiveChannel: try to refresh active channel"),b(void 0);const B=await ne({aiAgentId:s,userId:C.userId,language:l,country:c,context:u,forceCreateChannel:t,knownActiveChannelUrl:(D=m.messenger.getSettings(C.userId))==null?void 0:D.active_channel.channel_url});return m.messenger.setSettings(C.userId,B),b({url:B.active_channel.channel_url,status:G.ConversationStatus.OPEN}),h.info("agentMessengerSession.refreshActiveChannel: refreshed active channel",B.active_channel.channel_url),B.active_channel.channel_url}else throw h.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")},[ne,o,s,C==null?void 0:C.userId,l,c,u,t,m.messenger.getSettings,m.messenger.setSettings]),ke=d.useCallback(async D=>{if(!(C!=null&&C.userId))throw new Error("Current user is not authenticated. Please authenticate first.");const B=await ne({...D,userId:C.userId,knownActiveChannelUrl:void 0}),W=B.active_channel.channel_url;return m.messenger.setSettings(C.userId,B),W},[C==null?void 0:C.userId,ne]),[Me]=d.useState(()=>In(D=>{var B;h.info("agentMessengerSession.channelChanged: channel.conversation",D.conversation),b({url:D.url,status:((B=D.conversation)==null?void 0:B.status)??G.ConversationStatus.OPEN})},250,{trailing:!1,leading:!0}));return Nt.useGroupChannelHandler(i,{onChannelChanged:D=>{D.isGroupChannel()&&D.url===(S==null?void 0:S.url)&&Me(D)}}),d.useEffect(()=>()=>{Me.cancel()},[Me]),d.useImperativeHandle(r,()=>{const D=async()=>{if(!S)throw new Error("No active conversation. Please start a conversation first.");return await i.groupChannel.getChannel(S.url)};return{activeChannel:S,chatSDK:i,authenticate:I,deauthenticate:X,updateContext:async B=>{const Z=await(await D()).updateContext(s,B);return{...Z,context:Z.context??{}}},patchContext:async B=>{const Z=await(await D()).patchContext(s,B);return{...Z,context:Z.context??{}}},getContextObject:async()=>{const W=await(await D()).getContextObject(s);return{...W,context:W.context??{}}}}},[I,X,S,i,s,h]),a.createElement(vo,{value:{sdkUser:E,userSessionInfo:e,userSession:C,activeChannel:S,setActiveChannel:b,refreshActiveChannel:de,createConversation:ke,connectionError:_,aiAgentInfo:T,launcherInfo:w,authenticate:I,deauthenticate:X,createAttachmentRules:Y}},n)}),Ao=()=>{const e=d.useId(),{chatSDK:t,networkStateAdapter:n}=U(),[r,o]=d.useState(()=>n?n.isOnline()?"connected":"reconnecting":"connected");return d.useEffect(()=>{const s=new V.ConnectionHandler({onDisconnected:()=>o("disconnected"),onConnected:()=>o("connected"),onReconnectStarted:()=>o("reconnecting"),onReconnectSucceeded:()=>o("connected"),onReconnectFailed:()=>o("disconnected")});return t.addConnectionHandler(e,s),()=>{t.removeConnectionHandler(e)}},[t,e]),d.useEffect(()=>{if(n)return n.subscribe(()=>{o("reconnecting")})},[n]),r},Mn=e=>{const{chatSDK:t}=U(),[n,r]=d.useState([]);return Nt.useGroupChannelHandler(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},xo=({channel:e,messages:t,isStreamAnimating:n})=>{const{aiAgentInfo:r,userSession:o}=je(),s=Ao(),i=wo({channel:e,lastMessage:en(t,[Ce.SendingStatus.SUCCEEDED]),aiAgentUserId:(r==null?void 0:r.userId)??"",isStreamAnimating:n}),l=Mo({shouldApply:!!(e!=null&&e.isAIAgent)&&!Se(e),isDisabledWhileAIResponding:i,lastMessage:en(t,[Ce.SendingStatus.PENDING,Ce.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""});if(!e||s==="disconnected")return{disabled:!0,disabledBy:"unavailable"};if(s==="reconnecting")return{disabled:!0,disabledBy:"reconnecting"};if(we(e))return{disabled:!0,disabledBy:"conversation_closed"};if(Io(e))return{disabled:!0,disabledBy:"form_active"};const c=To(e);return c?{disabled:!0,disabledBy:c}:i||l?{disabled:!0,disabledBy:"ai_responding"}:{disabled:!1,disabledBy:""}},wo=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=d.useState(!1),i=Mn(e);return d.useEffect(()=>{if(!t)return;const l=i.some(u=>u.userId===n),c=Ae(t,n)&&(Ue.isStreaming(t)||r);s(!!(c||l))},[i,t,n,r]),o},Io=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,s=e.isAIAgent&&!!((i=e.conversation)!=null&&i.handedOverAt);return o&&!s},To=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},ko=3e4,Mo=({shouldApply:e,lastMessage:t,isDisabledWhileAIResponding:n,currentUserId:r})=>{const[o,s]=d.useState(!1),i=d.useRef(null),l=t&&Ae(t,r)?t.createdAt:0;return d.useEffect(()=>{const c=()=>{i.current&&(clearTimeout(i.current),i.current=null),s(!1)},u=g=>{i.current&&clearTimeout(i.current),s(!0),i.current=setTimeout(()=>{s(!1),i.current=null},g)},m=Date.now()-l,h=ko-m;return n||h<=0?c():u(h),()=>{i.current&&clearTimeout(i.current)}},[n,l]),o&&e},Lo=()=>{const[e,t]=d.useState(new Set),n=d.useCallback(o=>{t(s=>{if(s.has(o))return s;const i=new Set(s);return i.add(o),i})},[]),r=d.useCallback(o=>{t(s=>{if(!s.has(o))return s;const i=new Set(s);return i.delete(o),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Ro}=j("AIAgentConversation");function Po({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedViaDispatcher:s,onBeforeSendMessage:i,onAfterSendMessage:l=Et,shouldMarkAsRead:c=!0,sortComparator:u}){var T;const m=()=>c&&(p==null?void 0:p.markAsRead()),{chatSDK:h,logger:g,dispatcher:_}=U(),{channel:p,channelFetchError:S,fetchChannel:b}=Do(t),E=Yr(h,p,{replyType:Ce.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:()=>!1,onChannelDeleted:n,onMessagesReceived:A=>r==null?void 0:r(A),onMessagesUpdated:A=>o==null?void 0:o(A),logger:g,markAsRead:m,sortComparator:u}),v=Lo(),C=xo({channel:p,messages:E.messages,isStreamAnimating:v.isAnimating});d.useEffect(()=>{m()},[c]),d.useEffect(()=>{const A=async w=>{const L=typeof(w==null?void 0:w.channelUrl)=="string";p&&L&&w.channelUrl!==p.url||(g.debug("conversation.dispatcher: try to close conversation",p),p!=null&&p.conversation&&p.conversation.status===G.ConversationStatus.OPEN&&(await p.closeConversation(),s==null||s()))};return _.subscribe(Ct.ConversationClose,A),()=>{_.unsubscribe(Ct.ConversationClose,A)}},[_,(T=p==null?void 0:p.conversation)==null?void 0:T.status,s]);const x={conversation:(p==null?void 0:p.conversation)??void 0,channelSource:{channel:p,error:S,refetch:()=>b(),closeConversation:async()=>{we(p)||await(p==null?void 0:p.closeConversation())}},messageSource:{messages:E.messages,initialized:E.initialized,loadPrevious:()=>E.loadPrevious(),loadNext:()=>E.loadNext(),deleteMessage:A=>E.deleteMessage(A),resendMessage:A=>E.resendMessage(A),sendUserMessage:async A=>{var L;if(((L=p==null?void 0:p.conversation)==null?void 0:L.status)===G.ConversationStatus.CLOSED)throw new Error("Conversation is closed");i&&(A=await i(A));const w=await E.sendUserMessage(A,l);return l==null||l(w),w},sendFileMessage:async A=>{var L;if(((L=p==null?void 0:p.conversation)==null?void 0:L.status)===G.ConversationStatus.CLOSED)throw new Error("Conversation is closed");i&&(A=await i(A));const w=await E.sendFileMessage(A,l);return l==null||l(w),w}},state:{streamAnimation:v,input:C}};return a.createElement(Ro,{value:x},e)}function Do(e){const{chatSDK:t,logger:n}=U(),{sdkUser:r}=je(),[o,s]=d.useState(void 0),[i,l]=d.useState(void 0);async function c(){if(!r){n.debug("conversation.fetchChannel: no sdk user, skip fetching channel");return}if(n.debug("conversation.fetchChannel: start"),s(void 0),l(void 0),e)try{n.debug("conversation.fetchChannel: get channel",e);const u=await t.groupChannel.getChannel(e);s(u),n.debug("conversation.fetchChannel: fetched channel",u)}catch(u){u instanceof V.SendbirdError&&l(u),n.error("conversation.fetchChannel: error",u)}}return Oo(o),d.useEffect(()=>{c()},[t,r,e]),{channel:o,channelFetchError:i,fetchChannel:c}}function Oo(e){const{chatSDK:t}=U(),{activeChannel:n,setActiveChannel:r}=je(),o=d.useId();d.useEffect(()=>{if(!e||!n)return;const s=new V.ConnectionHandler({onReconnectSucceeded:async()=>{var l;const i=await e.refresh();i.url===n.url&&r({url:i.url,status:((l=i.conversation)==null?void 0:l.status)??G.ConversationStatus.OPEN})}});return t.addConnectionHandler(o,s),()=>{t.removeConnectionHandler(o)}},[t,e,n])}class Bo{constructor(t,{filter:n,limit:r=20}){N(this,"filter");N(this,"_sdk");N(this,"_pinnedChannels");N(this,"_channels");N(this,"_isDisposed",!1);N(this,"_handlerId",`handler-id-${Date.now()}`);N(this,"_order",We.GroupChannelListOrder.LATEST_LAST_MESSAGE);N(this,"_limit");N(this,"_query");N(this,"_token");N(this,"_timestamp");N(this,"_isSyncing");N(this,"_channelHandler");N(this,"_connectionHandler");N(this,"_collectionEventHandler");N(this,"_throttledOnChannelChanged");var o,s,i,l,c,u,m;this.filter=n,this._sdk=t,this._pinnedChannels=[],this._channels=[],this._limit=r,this._query=this._sdk.aiAgent.createMyGroupChannelListQuery({aiAgentChannelFilter:(o=this.filter)==null?void 0:o.aiAgentChannelFilter,aiAgentConversationStatusFilter:(s=this.filter)==null?void 0:s.aiAgentConversationStatusFilter,aiAgentIds:(i=this.filter)==null?void 0:i.aiAgentIds,deskChannelFilter:(l=this.filter)==null?void 0:l.deskChannelFilter,pinnedChannelUrls:(c=this.filter)==null?void 0:c.pinnedChannelUrls,copilotConversationOnly:(u=this.filter)==null?void 0:u.copilotConversationOnly,copilotSupportChannelUrl:(m=this.filter)==null?void 0:m.copilotSupportChannelUrl,limit:this._limit}),this._token="",this._timestamp=Number.MAX_SAFE_INTEGER,this._isSyncing=!1,this._throttledOnChannelChanged=In(h=>{h.isGroupChannel()&&(this._query.belongsTo(h)?this._addChannelsToView([h],!1):this._removeChannelsFromView([h.url]))},250,{trailing:!1,leading:!0}),this._channelHandler=new We.GroupChannelHandler({onChannelChanged:this._throttledOnChannelChanged,onChannelDeleted:h=>{this._removeChannelsFromView([h])}}),this._connectionHandler=new V.ConnectionHandler({onReconnectSucceeded:()=>{this._isDefaultChangelogSyncTimestampUpdated&&this._syncChannelChangelogs()}}),this._sdk.addConnectionHandler(this._handlerId,this._connectionHandler),this._sdk.groupChannel.addGroupChannelHandler(this._handlerId,this._channelHandler)}get _isDefaultChangelogSyncTimestampUpdated(){return this._timestamp!==Number.MAX_SAFE_INTEGER}_setDefaultChangelogsSyncTimestamp(t){var s,i;const n=new Set(((s=this.filter)==null?void 0:s.pinnedChannelUrls)??[]),r=t.find(l=>!n.has(l.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 l;const n=((l=this.filter)==null?void 0:l.pinnedChannelUrls)??[],r=new Map(n.map((c,u)=>[c,u])),o=[],s=[],i=[];for(const c of t){if(!this._query.belongsTo(c)){i.push(c.url);continue}const u=r.get(c.url);if(u===void 0)continue;const m=St(this._pinnedChannels,c);m>=0?(this._pinnedChannels.splice(m,1),s.push(c)):o.push(c);const g=this._pinnedChannels.findIndex(p=>(r.get(p.url)??1/0)>u),_=g===-1?this._pinnedChannels.length:g;this._pinnedChannels.splice(_,0,c)}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:i}}_upsertRegularChannelsToArray(t,n=!1){const r=[],o=[],s=[];for(const i of t){if(!this._query.belongsTo(i)){r.push(i.url);continue}const l=St(this._channels,i),c=l<0;!c&&this._channels.splice(l,1);const m=No(this._channels,i,this._order).place,h=m===this._channels.length;c?h?(n||!this.hasMore)&&(this._channels.push(i),o.push(i)):(this._channels.splice(m,0,i),o.push(i)):(this._channels.splice(m,0,i),s.push(i))}return{addedChannels:o,updatedChannels:s,unmatchedChannelUrls:r}}_addChannelsToView(t,n=!1){var h,g,_,p,S;const r=new Set(((h=this.filter)==null?void 0:h.pinnedChannelUrls)??[]),o=[],s=[];for(const b of t)r.has(b.url)?o.push(b):s.push(b);const i=this._upsertPinnedChannelsToArray(o),l=this._upsertRegularChannelsToArray(s,n),c=i.addedChannels.concat(l.addedChannels),u=i.updatedChannels.concat(l.updatedChannels),m=i.unmatchedChannelUrls.concat(l.unmatchedChannelUrls);c.length>0&&((_=(g=this._collectionEventHandler)==null?void 0:g.onChannelsAdded)==null||_.call(g,{},c)),u.length>0&&((S=(p=this._collectionEventHandler)==null?void 0:p.onChannelsUpdated)==null||S.call(p,{},u)),m.length>0&&this._removeChannelsFromView(m)}_removeChannelsFromView(t){var o,s,i;const n=new Set(((o=this.filter)==null?void 0:o.pinnedChannelUrls)??[]),r=[];for(const l of t)if(n.has(l)){const c=this._pinnedChannels.findIndex(u=>u.url===l);c>=0&&(r.push(l),this._pinnedChannels.splice(c,1))}else{const c=this._channels.findIndex(u=>u.url===l);c>=0&&(r.push(l),this._channels.splice(c,1))}r.length>0&&((i=(s=this._collectionEventHandler)==null?void 0:s.onChannelsDeleted)==null||i.call(s,{},r))}get channels(){return this._isDisposed?[]:[...this._pinnedChannels,...this._channels]}get hasMore(){return this._isDisposed?!1:this._query.hasNext}async loadMore(){if(this._isDisposed)return[];if(this.hasMore){const t=await this._query.next();return this._setDefaultChangelogsSyncTimestamp(t),this._addChannelsToView(t,!0),t}return[]}setConversationListCollectionHandler(t){this._collectionEventHandler=t}dispose(){this._isDisposed||(this._isDisposed=!0,this._throttledOnChannelChanged.cancel(),this._collectionEventHandler=void 0,this._sdk.removeConnectionHandler(this._handlerId),this._sdk.groupChannel.removeGroupChannelHandler(this._handlerId),this._pinnedChannels.length=0,this._channels.length=0)}}const St=(e,t)=>e.findIndex(n=>n.isIdentical(t)),No=(e,t,n)=>{if(e.length>0){const r=St(e,t);let o=0,s=e.length-1,i=Math.floor((o+s)/2);for(;o<s;){const c=ln(e[i],t,n);if(c>0)s=i,i=Math.floor((o+s)/2);else if(c<0)o=i+1,i=Math.floor((o+s)/2);else return{place:i,oldPosition:r}}return{place:ln(e[i],t,n)>=0?i:i+1,oldPosition:r}}return{place:e.length,oldPosition:-1}},ln=(e,t,n)=>{switch(n){case We.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 Ho(e,t){var p,S,b,E,v,C,x,T,A,w;const n=d.useId(),[r,o]=d.useState(!1),[s,i]=d.useState(null),[l,c]=d.useState([]),[u,m]=d.useState(null),h=d.useRef(!1),g=d.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,o(!1),i(null),c([]);try{u==null||u.dispose();const L=new Bo(e,t);L.setConversationListCollectionHandler({onChannelsAdded:()=>{c(L.channels)},onChannelsUpdated:()=>{c(L.channels)},onChannelsDeleted:()=>{c(L.channels)}}),await L.loadMore(),m(L),i(null)}catch(L){m(null),i(L)}finally{o(!0),h.current=!1}}},[e,e.currentUser,(p=t.filter)==null?void 0:p.aiAgentChannelFilter,(b=(S=t.filter)==null?void 0:S.aiAgentConversationStatusFilter)==null?void 0:b.join(),(v=(E=t.filter)==null?void 0:E.aiAgentIds)==null?void 0:v.join(),(C=t.filter)==null?void 0:C.deskChannelFilter,(T=(x=t.filter)==null?void 0:x.pinnedChannelUrls)==null?void 0:T.join(),(A=t.filter)==null?void 0:A.copilotConversationOnly,(w=t.filter)==null?void 0:w.copilotSupportChannelUrl,t.limit]),_=d.useCallback(async()=>{if(u)try{await u.loadMore()}catch(L){i(L)}},[u]);return d.useEffect(()=>(e.addConnectionHandler(n,new V.ConnectionHandler({onConnected:()=>g()})),()=>e.removeConnectionHandler(n)),[e,n,g]),d.useEffect(()=>{g()},[g]),d.useEffect(()=>()=>{h.current=!1,u==null||u.dispose()},[u]),{initialized:r,error:s,channels:l,loadMore:_}}const{Provider:zo}=j("AIAgentConversationList");function Fo({conversationListLimit:e,conversationListFilter:t,children:n}){var h,g;const{chatSDK:r,aiAgentId:o,queryParams:s}=U(),i={aiAgentIds:[o],aiAgentConversationStatusFilter:[G.ConversationStatus.CLOSED,G.ConversationStatus.OPEN]},l=e??((h=s==null?void 0:s.conversationListParams)==null?void 0:h.limit),c={...i,...(g=s==null?void 0:s.conversationListParams)==null?void 0:g.filter,...t},u=Ho(r,{limit:l,filter:c}),m={listSource:{initialized:u.initialized,error:u.error??void 0,channels:u.channels,loadMore:()=>u.loadMore()}};return a.createElement(zo,{value:m},n)}function $o(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:Uo}=j("MessageTemplateFetching");function qo({children:e,internalVariables:t}){const n=d.useRef({}),r=d.useRef({}),[o,s]=d.useState({}),i=d.useCallback((u,m)=>{s(h=>({...h,[u]:{fetching:!1,error:!1,...h[u],...m}}))},[]),l=d.useCallback(async({onRequestTemplate:u,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const _=m(h);if(_)return _;const p=r.current[h];if(p)return p;g||i(h,{fetching:!0});const S=u(h).catch(b=>{throw g||i(h,{error:!0}),b}).finally(()=>{g||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=S,S},[i]),c={internalVariables:t,fetchTemplate:l,suspend:(u,m)=>{if(n.current[u])return n.current[u];const h=$o(m());return n.current[u]=h,h},getIsFetching:u=>{var m;return((m=o[u])==null?void 0:m.fetching)??!1},getHasError:u=>{var m;return((m=o[u])==null?void 0:m.error)??!1}};return a.createElement(Uo,{value:c},e)}const Wo="remove_powered_by",$t=(e,t)=>{var o,s;const{chatSDK:n}=U(),{aiAgentInfo:r}=je();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&&Cn(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return d.useMemo(()=>!(Array.isArray(i)&&i.includes(Wo)),[i])}throw new Error("Unsupported feature")},Ln=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=(()=>{const[s]=e.members.filter(i=>i.userId!==t.userId);return s})(),o={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?Se(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},At=e=>d.useReducer((t,n)=>({...t,...n}),e);var ie=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(ie||{});const Vo=new Set(["free_text","single_choice"]),Go=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,i]=At({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=At({followUpItem:!1}),u=d.useMemo(()=>{var S;const _=s.csat;if(typeof _!="number")return;const p=(S=e.follow_up)==null?void 0:S.find(b=>b.scores.includes(_));if(Vo.has(p==null?void 0:p.response_type))return p},[s.csat,e.follow_up]),m=(()=>{var _;if(typeof n=="number")return"submitted";if((t===ie.AI_AGENT_CSAT_5||t===ie.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===ie.AI_AGENT_CSAT_5_WITH_CRE){const p=typeof s.csat=="number",S=!((_=e.cre)!=null&&_.required)||typeof s.isResolved=="boolean";if(p&&S)return"submittable"}return"unsubmittable"})(),h=d.useCallback(()=>typeof s.csat>"u"?!1:u!=null&&u.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,u,c]);return d.useEffect(()=>{r||(i({csatReason:""}),c({followUpItem:!1}))},[r,u,i,c]),{params:s,setParams:i,error:l,setError:c,followUpItem:u,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},at=5,jo=50,cn=e=>Math.max(0,e-jo),Ko=e=>e<1e3?{speed:at*.5,chunkSize:2}:e<2e3?{speed:at*.8,chunkSize:2}:{speed:at*.6,chunkSize:3},Yo=e=>{const{text:t,enabled:n=!1,onAnimationStart:r,onAnimationComplete:o}=e,[s,i]=d.useState(()=>cn(t.length)),l=d.useRef(null),c=d.useRef(0),u=d.useRef(0),m=d.useRef(n),h=d.useRef(r),g=d.useRef(o),_=d.useRef(!1),p=d.useRef(!1),S=d.useRef(t.length),b=d.useRef(n),E=n,v=s<t.length,C=m.current&&(E||v);return d.useLayoutEffect(()=>{h.current=r,g.current=o,S.current=t.length,b.current=n}),d.useLayoutEffect(()=>{var x;m.current&&(_.current||(_.current=!0,(x=h.current)==null||x.call(h)),i(T=>t.length<T?t.length:T))},[t]),d.useEffect(()=>{if(!m.current)return;let x=cn(t.length);c.current=0,u.current=0;const T=A=>{c.current===0&&(c.current=A,u.current=A);const w=S.current,L=A-c.current,$=A-u.current,{speed:Y,chunkSize:q}=Ko($),K=Y*q;L>=K&&x<w&&(x=Math.min(x+q,w),i(x),c.current=A),(x<w||b.current)&&(l.current=requestAnimationFrame(T))};return l.current=requestAnimationFrame(T),()=>{l.current&&cancelAnimationFrame(l.current)}},[]),d.useEffect(()=>{var w;const x=m.current&&_.current,T=!n,A=s>=t.length&&t.length>0;x&&T&&A&&!p.current&&(p.current=!0,(w=g.current)==null||w.call(g))},[n,s,t.length]),{streamText:m.current?t.slice(0,s):t,isAnimating:C}},Xo={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom"},conversation_list:{header_title:"Conversations",ended:"Ended",footer_title:"Start a conversation"},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended."},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"}},xt={language:"en",strings:Xo,dateLocale:lr.enUS},Zo={conversation:{input_placeholder:"질문하기",input_placeholder_disabled:"이 채널에서는 채팅을 사용할 수 없습니다.",input_placeholder_wait_ai_agent_response:"상담사의 답변을 기다리는 중...",input_placeholder_active_form:"계속 진행하려면 양식을 작성해 주세요.",input_placeholder_reconnecting:"재연결 시도 중. 계속되면 새로고침하세요.",unknown_message_type:"(알 수 없는 메시지 유형)",powered_by:"Powered by",citation_title:"출처",start_new_conversation_label:"대화 시작",failed_message_resend:"다시 시도",failed_message_remove:"삭제",file_upload_no_supported_files:"사용 가능한 지원 파일 형식이 없습니다.",a11y_message_list:"채팅 메시지",a11y_scroll_to_bottom:"맨 아래로 스크롤"},conversation_list:{header_title:"대화",ended:"종료됨",footer_title:"대화 시작"},date_format:{just_now:"방금",minutes_ago:e=>`${e}분 전`,hours_ago:e=>`${e}시간 전`,date_short:"yyyy/MM/dd",date_separator:"yyyy년 M월 d일",message_timestamp:"p"},csat:{title:"귀하의 피드백은 우리에게 중요합니다.",submitted_label:"성공적으로 제출되었습니다!",cre_question:"문제가 해결되었나요?",cre_positive_label:"네, 감사합니다! 👍",cre_negative_label:"아니요, 도움이 되지 않았어요.",reason_placeholder:"의견을 공유해주세요.",question:"귀하의 경험을 어떻게 평가하시겠습니까?",submit_label:"제출",submission_expired:"죄송합니다. 설문 응답 기간이 종료되었습니다."},form:{optional_label:"선택",validation_required:"이 항목은 필수입니다"},common:{placeholder_something_went_wrong:"문제가 발생했습니다.",placeholder_no_messages:"메시지가 없습니다.",placeholder_no_conversations:"아직 대화가 없습니다",placeholder_something_went_wrong_retry_label:"다시 시도"},feedback:{title:"피드백 제출",good:"좋아요",bad:"별로예요",comment_label:"코멘트 (선택사항)",comment_placeholder:"코멘트를 남겨주세요",cancel:"취소",submit:"제출",save:"저장",edit:"피드백 수정",remove:"피드백 삭제"}},wt={language:"ko",strings:Zo,dateLocale:hr.ko},Jo={conversation:{input_placeholder:"質問する",input_placeholder_disabled:"このチャンネルではチャットを利用できません",input_placeholder_wait_ai_agent_response:"エージェントの返信を待っています…",input_placeholder_active_form:"続行するには、フォームに記入してください。",input_placeholder_reconnecting:"再接続中。続く場合は更新してください。",unknown_message_type:"(不明なメッセージタイプ)",powered_by:"Powered by",citation_title:"出典",start_new_conversation_label:"会話を始める",failed_message_resend:"再試行",failed_message_remove:"削除",file_upload_no_supported_files:"サポートされているファイルタイプがありません。",a11y_message_list:"チャットメッセージ",a11y_scroll_to_bottom:"一番下にスクロール"},conversation_list:{header_title:"会話",ended:"終了",footer_title:"会話を始める"},date_format:{just_now:"たった今",minutes_ago:e=>`${e}分前`,hours_ago:e=>`${e}時間前`,date_short:"yyyy/MM/dd",date_separator:"yyyy年 M月 d日",message_timestamp:"p"},csat:{title:"あなたのフィードバックは私たちにとって重要です",submitted_label:"正常に送信されました!",cre_question:"問題は解決されましたか?",cre_positive_label:"はい、ありがとうございます! 👍",cre_negative_label:"いいえ、役に立ちませんでした。",reason_placeholder:"フィードバックを共有する",question:"あなたの経験をどう評価しますか?",submit_label:"送信",submission_expired:"申し訳ありません、アンケートの受付期間は終了しました。"},form:{optional_label:"任意",validation_required:"この質問は必須です"},common:{placeholder_something_went_wrong:"問題が発生しました",placeholder_no_messages:"メッセージがありません",placeholder_no_conversations:"まだ会話がありません",placeholder_something_went_wrong_retry_label:"再試行"},feedback:{title:"フィードバックを送信",good:"良い",bad:"悪い",comment_label:"コメント(オプション)",comment_placeholder:"コメントを残してください",cancel:"キャンセル",submit:"送信",save:"保存",edit:"フィードバックを編集",remove:"フィードバックを削除"}},It={language:"ja",strings:Jo,dateLocale:gr.ja},Qo={conversation:{input_placeholder:"Hacer una pregunta",input_placeholder_disabled:"El chat no está disponible en este canal",input_placeholder_wait_ai_agent_response:"Esperando la respuesta del agente...",input_placeholder_active_form:"Por favor, complete el formulario para continuar.",input_placeholder_reconnecting:"Reconectando. Actualiza si persiste.",unknown_message_type:"(Tipo de mensaje desconocido)",powered_by:"Desarrollado por",citation_title:"Fuente",start_new_conversation_label:"Iniciar una conversación",failed_message_resend:"Reintentar",failed_message_remove:"Eliminar",file_upload_no_supported_files:"No hay tipos de archivo compatibles disponibles.",a11y_message_list:"Mensajes del chat",a11y_scroll_to_bottom:"Desplazarse hacia abajo"},conversation_list:{header_title:"Conversaciones",ended:"Finalizado",footer_title:"Iniciar una conversación"},date_format:{just_now:"Ahora mismo",minutes_ago:e=>`Hace ${e} minutos`,hours_ago:e=>`Hace ${e} horas`,date_short:"dd/MM/yyyy",date_separator:"d 'de' MMMM 'de' yyyy",message_timestamp:"p"},csat:{title:"Tus comentarios nos importan",submitted_label:"Enviado con éxito!",cre_question:"¿Se resolvió su problema?",cre_positive_label:"¡Sí, gracias! 👍",cre_negative_label:"No, eso no ayudó.",reason_placeholder:"Comparte tu opinión",question:"¿Cómo calificarías tu experiencia?",submit_label:"Enviar",submission_expired:"Lo sentimos, el período de la encuesta ha terminado."},form:{optional_label:"opcional",validation_required:"Esta pregunta es obligatoria"},common:{placeholder_something_went_wrong:"Algo salió mal",placeholder_no_messages:"No hay mensajes",placeholder_no_conversations:"Aún no hay conversaciones",placeholder_something_went_wrong_retry_label:"Reintentar"},feedback:{title:"Enviar comentarios",good:"Bueno",bad:"Malo",comment_label:"Comentario (opcional)",comment_placeholder:"Deja un comentario",cancel:"Cancelar",submit:"Enviar",save:"Guardar",edit:"Editar comentarios",remove:"Eliminar comentarios"}},Tt={language:"es",strings:Qo,dateLocale:cr.es},es={conversation:{input_placeholder:"Fazer uma pergunta",input_placeholder_disabled:"O chat não está disponível neste canal",input_placeholder_wait_ai_agent_response:"Aguardando a resposta do agente...",input_placeholder_active_form:"Por favor, preencha o formulário para prosseguir.",input_placeholder_reconnecting:"Reconectando. Atualize se persistir.",unknown_message_type:"(Tipo de mensagem desconhecido)",powered_by:"Desenvolvido por",citation_title:"Fonte",start_new_conversation_label:"Iniciar uma conversa",failed_message_resend:"Tentar novamente",failed_message_remove:"Remover",file_upload_no_supported_files:"Nenhum tipo de arquivo suportado disponível.",a11y_message_list:"Mensagens do chat",a11y_scroll_to_bottom:"Rolar para baixo"},conversation_list:{header_title:"Conversas",ended:"Encerrada",footer_title:"Iniciar uma conversa"},date_format:{just_now:"Agora mesmo",minutes_ago:e=>`Há ${e} minutos`,hours_ago:e=>`Há ${e} horas`,date_short:"dd/MM/yyyy",date_separator:"d 'de' MMMM 'de' yyyy",message_timestamp:"p"},csat:{title:"Seu feedback é importante para nós",submitted_label:"Enviado com sucesso!",cre_question:"Seu problema foi resolvido?",cre_positive_label:"Sim, obrigado! 👍",cre_negative_label:"Não, isso não ajudou.",reason_placeholder:"Compartilhe seu feedback",question:"Como você avaliaria sua experiência?",submit_label:"Enviar",submission_expired:"Desculpe, o período da pesquisa foi encerrado."},form:{optional_label:"opcional",validation_required:"Esta pergunta é obrigatória"},common:{placeholder_something_went_wrong:"Algo deu errado",placeholder_no_messages:"Nenhuma mensagem",placeholder_no_conversations:"Nenhuma conversa ainda",placeholder_something_went_wrong_retry_label:"Tentar novamente"},feedback:{title:"Enviar feedback",good:"Bom",bad:"Ruim",comment_label:"Comentário (opcional)",comment_placeholder:"Deixe um comentário",cancel:"Cancelar",submit:"Enviar",save:"Salvar",edit:"Editar feedback",remove:"Remover feedback"}},kt={language:"pt",strings:es,dateLocale:fr.pt},ts={conversation:{input_placeholder:"Poser une question",input_placeholder_disabled:"Le chat n'est pas disponible dans ce canal",input_placeholder_wait_ai_agent_response:"En attente de la réponse de l'agent...",input_placeholder_active_form:"Veuillez remplir le formulaire pour continuer.",input_placeholder_reconnecting:"Reconnexion. Actualisez si persiste.",unknown_message_type:"(Type de message inconnu)",powered_by:"Propulsé par",citation_title:"Source",start_new_conversation_label:"Démarrer une conversation",failed_message_resend:"Réessayer",failed_message_remove:"Supprimer",file_upload_no_supported_files:"Aucun type de fichier pris en charge disponible.",a11y_message_list:"Messages du chat",a11y_scroll_to_bottom:"Faire défiler vers le bas"},conversation_list:{header_title:"Conversations",ended:"Terminée",footer_title:"Démarrer une conversation"},date_format:{just_now:"À l'instant",minutes_ago:e=>`Il y a ${e} minutes`,hours_ago:e=>`Il y a ${e} heures`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Vos commentaires comptent pour nous",submitted_label:"Soumis avec succès!",cre_question:"Votre problème a-t-il été résolu ?",cre_positive_label:"Oui, merci ! 👍",cre_negative_label:"Non, cela n'a pas aidé.",reason_placeholder:"Partagez votre avis",question:"Comment évalueriez-vous votre expérience ?",submit_label:"Envoyer",submission_expired:"Désolé, la période de l'enquête est terminée."},form:{optional_label:"optionnel",validation_required:"Cette question est obligatoire"},common:{placeholder_something_went_wrong:"Une erreur est survenue",placeholder_no_messages:"Aucun message",placeholder_no_conversations:"Aucune conversation pour le moment",placeholder_something_went_wrong_retry_label:"Réessayer"},feedback:{title:"Envoyer des commentaires",good:"Bien",bad:"Mauvais",comment_label:"Commentaire (optionnel)",comment_placeholder:"Laissez un commentaire",cancel:"Annuler",submit:"Envoyer",save:"Enregistrer",edit:"Modifier les commentaires",remove:"Supprimer les commentaires"}},Mt={language:"fr",strings:ts,dateLocale:ur.fr},ns={conversation:{input_placeholder:"एक प्रश्न पूछें",input_placeholder_disabled:"इस चैनल में चैट उपलब्ध नहीं है",input_placeholder_wait_ai_agent_response:"एजेंट के उत्तर की प्रतीक्षा कर रहे हैं...",input_placeholder_active_form:"आगे बढ़ने के लिए कृपया फॉर्म भरें।",input_placeholder_reconnecting:"पुनः कनेक्ट हो रहा है। जारी रहे तो रिफ्रेश करें।",unknown_message_type:"(अज्ञात संदेश प्रकार)",powered_by:"द्वारा संचालित",citation_title:"स्रोत",start_new_conversation_label:"एक बातचीत शुरू करें",failed_message_resend:"पुनः प्रयास करें",failed_message_remove:"हटाएं",file_upload_no_supported_files:"कोई समर्थित फ़ाइल प्रकार उपलब्ध नहीं हैं।",a11y_message_list:"चैट संदेश",a11y_scroll_to_bottom:"नीचे स्क्रॉल करें"},conversation_list:{header_title:"बातचीत",ended:"समाप्त",footer_title:"एक बातचीत शुरू करें"},date_format:{just_now:"अभी",minutes_ago:e=>`${e} मिनट पहले`,hours_ago:e=>`${e} घंटे पहले`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"आपकी प्रतिक्रिया हमारे लिए मायने रखती है",submitted_label:"सफलतापूर्वक सबमिट किया गया!",cre_question:"क्या आपकी समस्या का समाधान हुआ?",cre_positive_label:"हाँ, धन्यवाद! 👍",cre_negative_label:"नहीं, इससे मदद नहीं मिली।",reason_placeholder:"अपनी प्रतिक्रिया साझा करें",question:"आप अपने अनुभव का मूल्यांकन कैसे करेंगे?",submit_label:"सबमिट करें",submission_expired:"क्षमा करें, सर्वेक्षण अवधि समाप्त हो गई है।"},form:{optional_label:"वैकल्पिक",validation_required:"यह प्रश्न आवश्यक है"},common:{placeholder_something_went_wrong:"कुछ गलत हो गया",placeholder_no_messages:"कोई संदेश नहीं",placeholder_no_conversations:"अभी तक कोई बातचीत नहीं",placeholder_something_went_wrong_retry_label:"पुनः प्रयास करें"},feedback:{title:"प्रतिक्रिया भेजें",good:"अच्छा",bad:"बुरा",comment_label:"टिप्पणी (वैकल्पिक)",comment_placeholder:"एक टिप्पणी छोड़ें",cancel:"रद्द करें",submit:"भेजें",save:"सहेजें",edit:"प्रतिक्रिया संपादित करें",remove:"प्रतिक्रिया हटाएं"}},Lt={language:"hi",strings:ns,dateLocale:dr.hi},rs={conversation:{input_placeholder:"Fai una domanda",input_placeholder_disabled:"La chat non è disponibile in questo canale",input_placeholder_wait_ai_agent_response:"In attesa della risposta dell'agente...",input_placeholder_active_form:"Compila il modulo per procedere.",input_placeholder_reconnecting:"Riconnessione. Aggiorna se persiste.",unknown_message_type:"(Tipo di messaggio sconosciuto)",powered_by:"Powered by",citation_title:"Fonte",start_new_conversation_label:"Inizia una conversazione",failed_message_resend:"Riprova",failed_message_remove:"Rimuovi",file_upload_no_supported_files:"Nessun tipo di file supportato disponibile.",a11y_message_list:"Messaggi della chat",a11y_scroll_to_bottom:"Scorri in basso"},conversation_list:{header_title:"Conversazioni",ended:"Terminata",footer_title:"Inizia una conversazione"},date_format:{just_now:"Proprio ora",minutes_ago:e=>`${e} minuti fa`,hours_ago:e=>`${e} ore fa`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Il tuo feedback è importante per noi",submitted_label:"Inviato con successo!",cre_question:"Il tuo problema è stato risolto?",cre_positive_label:"Sì, grazie! 👍",cre_negative_label:"No, non è servito.",reason_placeholder:"Condividi il tuo feedback",question:"Come valuteresti la tua esperienza?",submit_label:"Invia",submission_expired:"Ci dispiace, il periodo per partecipare al sondaggio è terminato."},form:{optional_label:"opzionale",validation_required:"Questa domanda è obbligatoria"},common:{placeholder_something_went_wrong:"Qualcosa è andato storto",placeholder_no_messages:"Nessun messaggio",placeholder_no_conversations:"Nessuna conversazione ancora",placeholder_something_went_wrong_retry_label:"Riprova"},feedback:{title:"Invia feedback",good:"Buono",bad:"Cattivo",comment_label:"Commento (opzionale)",comment_placeholder:"Lascia un commento",cancel:"Annulla",submit:"Invia",save:"Salva",edit:"Modifica feedback",remove:"Rimuovi feedback"}},Rt={language:"it",strings:rs,dateLocale:mr.it},os={conversation:{input_placeholder:"Eine Frage stellen",input_placeholder_disabled:"Chat ist in diesem Kanal nicht verfügbar",input_placeholder_wait_ai_agent_response:"Warten auf die Antwort des Agenten...",input_placeholder_active_form:"Bitte fülle das Formular aus, um fortzufahren.",input_placeholder_reconnecting:"Neu verbinden. Aktualisieren falls anhaltend.",unknown_message_type:"(Unbekannter Nachrichtentyp)",powered_by:"Unterstützt von",citation_title:"Quelle",start_new_conversation_label:"Ein Gespräch starten",failed_message_resend:"Erneut versuchen",failed_message_remove:"Entfernen",file_upload_no_supported_files:"Keine unterstützten Dateitypen verfügbar.",a11y_message_list:"Chat-Nachrichten",a11y_scroll_to_bottom:"Nach unten scrollen"},conversation_list:{header_title:"Gespräche",ended:"Beendet",footer_title:"Ein Gespräch starten"},date_format:{just_now:"Gerade eben",minutes_ago:e=>`Vor ${e} Minuten`,hours_ago:e=>`Vor ${e} Stunden`,date_short:"dd.MM.yyyy",date_separator:"d. MMMM yyyy",message_timestamp:"p"},csat:{title:"Ihr Feedback ist uns wichtig",submitted_label:"Erfolgreich gesendet!",cre_question:"Wurde Ihr Problem gelöst?",cre_positive_label:"Ja, danke! 👍",cre_negative_label:"Nein, das hat nicht geholfen.",reason_placeholder:"Dein Feedback teilen",question:"Wie würden Sie Ihre Erfahrung bewerten?",submit_label:"Absenden",submission_expired:"Die Umfrage ist leider nicht mehr verfügbar."},form:{optional_label:"optional",validation_required:"Diese Frage ist erforderlich"},common:{placeholder_something_went_wrong:"Etwas ist schiefgelaufen",placeholder_no_messages:"Keine Nachrichten",placeholder_no_conversations:"Noch keine Unterhaltungen",placeholder_something_went_wrong_retry_label:"Erneut versuchen"},feedback:{title:"Feedback senden",good:"Gut",bad:"Schlecht",comment_label:"Kommentar (optional)",comment_placeholder:"Hinterlasse einen Kommentar",cancel:"Abbrechen",submit:"Senden",save:"Speichern",edit:"Feedback bearbeiten",remove:"Feedback entfernen"}},Pt={language:"de",strings:os,dateLocale:ir.de},ss={conversation:{input_placeholder:"Bir soru sor",input_placeholder_disabled:"Bu kanalda sohbet mevcut değil",input_placeholder_wait_ai_agent_response:"Temsilcinin yanıtını bekliyor...",input_placeholder_active_form:"İlerlemek için lütfen formu doldurun.",input_placeholder_reconnecting:"Yeniden bağlanıyor. Devam ederse yenile.",unknown_message_type:"(Bilinmeyen mesaj türü)",powered_by:"Tarafından desteklenmektedir",citation_title:"Kaynak",start_new_conversation_label:"Bir sohbet başlat",failed_message_resend:"Tekrar dene",failed_message_remove:"Kaldır",file_upload_no_supported_files:"Desteklenen dosya türü mevcut değil.",a11y_message_list:"Sohbet mesajları",a11y_scroll_to_bottom:"Aşağı kaydır"},conversation_list:{header_title:"Görüşmeler",ended:"Sona erdi",footer_title:"Bir sohbet başlat"},date_format:{just_now:"Az önce",minutes_ago:e=>`${e} dakika önce`,hours_ago:e=>`${e} saat önce`,date_short:"dd/MM/yyyy",date_separator:"d MMMM yyyy",message_timestamp:"p"},csat:{title:"Görüşleriniz bizim için önemli",submitted_label:"Başarıyla gönderildi!",cre_question:"Sorununuz çözüldü mü?",cre_positive_label:"Evet, teşekkürler! 👍",cre_negative_label:"Hayır, bu yardımcı olmadı.",reason_placeholder:"Geri bildiriminizi paylaşın",question:"Deneyiminizi nasıl değerlendirirsiniz?",submit_label:"Gönder",submission_expired:"Üzgünüz, anket süresi sona erdi."},form:{optional_label:"İsteğe bağlı",validation_required:"Bu soru gereklidir"},common:{placeholder_something_went_wrong:"Bir şeyler ters gitti",placeholder_no_messages:"Mesaj yok",placeholder_no_conversations:"Henüz görüşme yok",placeholder_something_went_wrong_retry_label:"Tekrar dene"},feedback:{title:"Geri bildirim gönder",good:"İyi",bad:"Kötü",comment_label:"Yorum (isteğe bağlı)",comment_placeholder:"Bir yorum bırakın",cancel:"İptal",submit:"Gönder",save:"Kaydet",edit:"Geri bildirimi düzenle",remove:"Geri bildirimi kaldır"}},Dt={language:"tr",strings:ss,dateLocale:pr.tr},se=e=>({conversation:e.conversation,conversation_list:e.conversation_list,date_format:e.date_format,csat:e.csat,form:e.form,common:e.common,feedback:e.feedback}),un=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Ke},Ke="en",Ut={borderColor:"red",borderWidth:f.StyleSheet.hairlineWidth},y=({debug:e=!1,style:t,children:n,...r})=>a.createElement(f.View,{style:[t,r,e&&Ut],...r},n);y.Animated=({debug:e=!1,style:t,children:n,...r})=>a.createElement(f.Animated.View,{style:[t,r,e&&Ut],...r},n);const{Provider:as,useContext:J}=j("MessengerSession"),is=d.forwardRef(function({children:e,...t},n){if(!t.userSessionInfo||!(t.userSessionInfo instanceof Ve||t.userSessionInfo instanceof Ft))throw new Error(`Invalid userSessionInfo: ${t.userSessionInfo}`);return a.createElement(So,{ref:n,...t},r=>a.createElement(ls,{...r},e))}),ls=({children:e,...t})=>{const{userSession:n,aiAgentInfo:r,launcherInfo:o}=t;return a.createElement(as,{value:{...t,userSession:n,aiAgentInfo:r,launcherInfo:o}},e)},cs=50,{Provider:us,useContext:ds}=j("ConversationScroll"),ms=({children:e})=>{var T;const{config:t}=U(),n=((T=t==null?void 0:t.conversation)==null?void 0:T.scrollMode)??"auto",r=d.useRef(null),o=d.useRef({viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1}),[s,i]=d.useState(0),[l,c]=d.useState(0),[u,m]=d.useState(!1),h=d.useCallback(()=>{const{shouldUpdate:A,shouldRecalc:w,contentHeight:L,contentSnapshotHeight:$,viewport:Y}=o.current;A&&$<L&&i(q=>{o.current.shouldUpdate=!1;const K=L-q-$,ne=Math.max(0,Y-K);return q===0||ne<q||w?(o.current.shouldRecalc=!1,ne):q})},[]),g=d.useCallback(A=>{o.current.viewport=A.nativeEvent.layout.height},[]),_=d.useCallback((A,w)=>{o.current.contentHeight=w;const L=o.current.viewport;m(w>L),h()},[h]),p=d.useCallback(A=>{const w=A.nativeEvent.contentOffset.y;c(w)},[]),S=(()=>{if(n==="fixed")return{minIndexForVisible:1,autoscrollToTopThreshold:-1}})(),b=d.useCallback((A=!0)=>{var w;(w=r.current)==null||w.scrollToOffset({offset:0,animated:A})},[]),E=d.useCallback((A,w=!0)=>{var L;(L=r.current)==null||L.scrollToIndex({index:A,animated:w,viewPosition:1})},[]),v=d.useCallback(()=>{n==="fixed"&&(o.current.contentSnapshotHeight=o.current.contentHeight-s,o.current.shouldUpdate=!0,o.current.shouldRecalc=!0)},[n,s]),C=d.useCallback(()=>{n==="fixed"?E(0):b()},[n,b,E]),x=d.useCallback(()=>{n==="fixed"?o.current.shouldUpdate=!0:b()},[n,b]);return a.createElement(us,{value:{ref:r,state:{distanceFromBottom:l,shouldShowScrollButton:u&&l>cs,bottomSpace:s},props:{maintainVisibleContentPosition:S,onLayout:g,onContentSizeChange:_,onScroll:p},actions:{scrollToBottom:b,scrollToIndex:E,onBeforeMessageSend:v,onAfterMessageSend:C,onStreamingUpdate:x}}},e)};function Rn(e){return new Promise((t,n)=>{f.Image.getSize(e,(r,o)=>{t({width:String(r),height:String(o)})},r=>{n(r)})})}async function gs(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 Rn(n.uri);return new Ce.MessageMetaArray({key:vn,value:[r,o]})}catch{return}}}function hs(e,t){let n=0,r=0;return re(e)&&e.sendingStatus!=="succeeded"&&(n=Number.MAX_SAFE_INTEGER),re(t)&&t.sendingStatus!=="succeeded"&&(r=Number.MAX_SAFE_INTEGER),t.createdAt+r-(e.createdAt+n)}const{Provider:fs,Context:ps,useContext:te}=j("Conversation"),Pn=e=>a.createElement(ms,null,a.createElement(_s,{...e})),_s=({channelUrl:e,onClearChannelUrl:t,onClose:n,onNavigateToConversationList:r,shouldMarkAsRead:o,children:s})=>{const i=ds(),{activeChannel:l,refreshActiveChannel:c,sdkUser:u,authenticate:m}=J();d.useEffect(()=>{u||m()},[]);const h=d.useCallback(async S=>{i.actions.onBeforeMessageSend();const b=await gs(S);return{...S,metaArrays:b?[b]:void 0}},[i.actions.onBeforeMessageSend]),g=d.useCallback(()=>{i.actions.onAfterMessageSend()},[i.actions.onAfterMessageSend]),_=d.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]),p=e??(l==null?void 0:l.url);return a.createElement(Po,{key:p,channelUrl:p,onBeforeSendMessage:h,onAfterSendMessage:g,onMessagesUpdated:i.actions.onStreamingUpdate,onMessagesReceived:i.actions.onStreamingUpdate,onChannelDeleted:_,sortComparator:hs,shouldMarkAsRead:o},S=>a.createElement(fs,{value:{...S,scrollSource:i,onClose:n,onNavigateToConversationList:r,updateActiveChannel:_}},s))},it=se(Pt.strings),ys={...it,conversation:{...it.conversation,attachment_camera:"Kamera",attachment_photo:"Fotobibliothek",attachment_document:"Dateien",file_upload_notification_count_limit:e=>`Sie können nur ${e} Datei${e>1?"en":""} gleichzeitig hochladen.`,file_upload_notification_size_limit:e=>`Die maximale Dateigröße beträgt ${e} MB.`,file_upload_not_supported_file:"Bitte wählen Sie einen unterstützten Dateityp aus."},conversation_list:{...it.conversation_list}},bs={language:Pt.language,dateLocale:Pt.dateLocale,strings:ys},lt=se(xt.strings),Es={...lt,conversation:{...lt.conversation,attachment_camera:"Camera",attachment_photo:"Photo library",attachment_document:"Files",file_upload_notification_count_limit:e=>`You can only upload ${e} file${e>1?"s":""} at a time.`,file_upload_notification_size_limit:e=>`Maximum file size is ${e} MB.`,file_upload_not_supported_file:"Please select a supported file type."},conversation_list:{...lt.conversation_list}},Cs={language:xt.language,dateLocale:xt.dateLocale,strings:Es},ct=se(Tt.strings),vs={...ct,conversation:{...ct.conversation,attachment_camera:"Cámara",attachment_photo:"Biblioteca de fotos",attachment_document:"Archivos",file_upload_notification_count_limit:e=>`Solo puede cargar ${e} archivo${e>1?"s":""} a la vez.`,file_upload_notification_size_limit:e=>`El tamaño máximo del archivo es ${e} MB.`,file_upload_not_supported_file:"Por favor, seleccione un tipo de archivo compatible."},conversation_list:{...ct.conversation_list}},Ss={language:Tt.language,dateLocale:Tt.dateLocale,strings:vs},ut=se(Mt.strings),As={...ut,conversation:{...ut.conversation,attachment_camera:"Caméra",attachment_photo:"Photothèque",attachment_document:"Fichiers",file_upload_notification_count_limit:e=>`Vous ne pouvez télécharger que ${e} fichier${e>1?"s":""} à la fois.`,file_upload_notification_size_limit:e=>`La taille maximale du fichier est de ${e} MB.`,file_upload_not_supported_file:"Veuillez sélectionner un type de fichier pris en charge."},conversation_list:{...ut.conversation_list}},xs={language:Mt.language,dateLocale:Mt.dateLocale,strings:As},dt=se(Lt.strings),ws={...dt,conversation:{...dt.conversation,attachment_camera:"कैमरा",attachment_photo:"फोटो लाइब्रेरी",attachment_document:"फाइलें",file_upload_notification_count_limit:e=>`आप एक बार में केवल ${e} फ़ाइल${e>1?"ें":""} अपलोड कर सकते हैं।`,file_upload_notification_size_limit:e=>`अधिकतम फ़ाइल आकार ${e} MB है।`,file_upload_not_supported_file:"कृपया समर्थित फ़ाइल प्रकार चुनें।"},conversation_list:{...dt.conversation_list}},Is={language:Lt.language,dateLocale:Lt.dateLocale,strings:ws},mt=se(Rt.strings),Ts={...mt,conversation:{...mt.conversation,attachment_camera:"Fotocamera",attachment_photo:"Libreria foto",attachment_document:"File",file_upload_notification_count_limit:e=>`Puoi caricare solo ${e} file alla volta.`,file_upload_notification_size_limit:e=>`La dimensione massima del file è ${e} MB.`,file_upload_not_supported_file:"Seleziona un tipo di file supportato."},conversation_list:{...mt.conversation_list}},ks={language:Rt.language,dateLocale:Rt.dateLocale,strings:Ts},gt=se(It.strings),Ms={...gt,conversation:{...gt.conversation,attachment_camera:"カメラ",attachment_photo:"フォトライブラリ",attachment_document:"ファイル",file_upload_notification_count_limit:e=>`一度にアップロードできるのは${e}ファイルまでです。`,file_upload_notification_size_limit:e=>`ファイルの最大サイズは${e}MBです。`,file_upload_not_supported_file:"サポートされているファイル形式を選択してください。"},conversation_list:{...gt.conversation_list}},Ls={language:It.language,dateLocale:It.dateLocale,strings:Ms},ht=se(wt.strings),Rs={...ht,conversation:{...ht.conversation,attachment_camera:"카메라",attachment_photo:"사진 라이브러리",attachment_document:"파일",file_upload_notification_count_limit:e=>`한 번에 ${e}개의 파일만 업로드할 수 있습니다.`,file_upload_notification_size_limit:e=>`파일당 최대 크기는 ${e} MB입니다.`,file_upload_not_supported_file:"지원되는 파일 형식을 선택해 주세요."},conversation_list:{...ht.conversation_list}},Ps={language:wt.language,dateLocale:wt.dateLocale,strings:Rs},ft=se(kt.strings),Ds={...ft,conversation:{...ft.conversation,attachment_camera:"Câmera",attachment_photo:"Biblioteca de fotos",attachment_document:"Arquivos",file_upload_notification_count_limit:e=>`Você só pode carregar ${e} arquivo${e>1?"s":""} por vez.`,file_upload_notification_size_limit:e=>`O tamanho máximo do arquivo é ${e} MB.`,file_upload_not_supported_file:"Por favor, selecione um tipo de arquivo suportado."},conversation_list:{...ft.conversation_list}},Os={language:kt.language,dateLocale:kt.dateLocale,strings:Ds},pt=se(Dt.strings),Bs={...pt,conversation:{...pt.conversation,attachment_camera:"Kamera",attachment_photo:"Fotoğraf kitaplığı",attachment_document:"Dosyalar",file_upload_notification_count_limit:e=>`Bir seferde yalnızca ${e} dosya yükleyebilirsiniz.`,file_upload_notification_size_limit:e=>`Maksimum dosya boyutu ${e} MB'dir.`,file_upload_not_supported_file:"Lütfen desteklenen bir dosya türü seçin."},conversation_list:{...pt.conversation_list}},Ns={language:Dt.language,dateLocale:Dt.dateLocale,strings:Bs},dn=new Map([["en",Cs],["ko",Ps],["ja",Ls],["es",Ss],["pt",Os],["fr",xs],["hi",Is],["it",ks],["de",bs],["tr",Ns]]),mn=e=>dn.get(e)??dn.get(Ke),Hs=(e,t)=>t?{conversation:{...e.conversation,...t.conversation},conversation_list:{...e.conversation_list,...t.conversation_list},date_format:{...e.date_format,...t.date_format},csat:{...e.csat,...t.csat},form:{...e.form,...t.form},common:{...e.common,...t.common},feedback:{...e.feedback,...t.feedback}}:e,{Provider:zs,useContext:H}=j("Localization"),Fs=({language:e=Ke,logger:t,strings:n,children:r})=>{const[o,s]=d.useState(()=>{const i=un(e);return mn(i)});return d.useEffect(()=>{var l;const i=un(e);if(o.language!==i){const c=mn(i);s(c),(l=t==null?void 0:t.info)==null||l.call(t,"Language changed",{from:o.language,to:c.language})}},[e,t]),a.createElement(zs,{value:{language:o.language,strings:Hs(o.strings,n),dateLocale:o.dateLocale,format:(i,l,c)=>Ee.format(i,l,{locale:o.dateLocale,...c})}},r)},{Provider:$s,useContext:Ye}=j("Modal");function Dn({children:e}){const[t,n]=d.useState([]),[r,o]=d.useState(null),s=d.useRef(0);d.useEffect(()=>{if(!r&&t.length>0){const[u,...m]=t;u&&(o(u),n(m))}},[r,t]);const i=d.useCallback(u=>new Promise(m=>{const g={id:`modal-${++s.current}`,render:u,resolve:m};n(_=>[..._,g])}),[]),l=d.useCallback((u,m)=>{o(h=>(h==null?void 0:h.id)===u?(h.resolve(m),null):h)},[]),c={openModal:i,currentModal:r};return a.createElement($s,{value:c},e,r&&a.createElement(f.Modal,{visible:!0,supportedOrientations:["landscape","portrait"],transparent:!0,animationType:"fade",onRequestClose:()=>l(r.id,null),style:{height:0}},r.render(u=>l(r.id,u??null))))}const{Provider:Us,useContext:z}=j("MessengerTheme"),qs=({children:e,...t})=>a.createElement(co,{...t,appearance:{theme:t.mode??"light"}},n=>{const r=Ws(n.theme);return a.createElement(Us,{value:{...n,themedColor:r}},e)});function Ws(e){const t=n=>n[e.selectedTheme];return{textHighEmphasis:t({light:e.palette.onlight.textHighEmphasis,dark:e.palette.ondark.textHighEmphasis}),textMidEmphasis:t({light:e.palette.onlight.textMidEmphasis,dark:e.palette.ondark.textMidEmphasis}),textLowEmphasis:t({light:e.palette.onlight.textLowEmphasis,dark:e.palette.ondark.textLowEmphasis}),textDisabled:t({light:e.palette.onlight.textDisabled,dark:e.palette.ondark.textDisabled}),textHighEmphasisInverse:t({light:e.palette.ondark.textHighEmphasis,dark:e.palette.onlight.textHighEmphasis}),textMidEmphasisInverse:t({light:e.palette.ondark.textMidEmphasis,dark:e.palette.onlight.textMidEmphasis}),textLowEmphasisInverse:t({light:e.palette.ondark.textLowEmphasis,dark:e.palette.onlight.textLowEmphasis}),textDisabledInverse:t({light:e.palette.ondark.textDisabled,dark:e.palette.onlight.textDisabled}),bg_50_600:t({light:e.palette.background50,dark:e.palette.background600}),bg_100_500:t({light:e.palette.background100,dark:e.palette.background500}),bg_200_400:t({light:e.palette.background200,dark:e.palette.background400}),primary:t({light:e.palette.primary.main,dark:e.palette.primary.light}),secondary:t({light:e.palette.secondary.main,dark:e.palette.secondary.light}),error:t({light:e.palette.error.main,dark:e.palette.error.light}),information:t({light:e.palette.information.light,dark:e.palette.information.light}),overlay:t({light:e.palette.overlay.light,dark:e.palette.overlay.dark})}}const R={create:e=>{const t=new WeakMap,n=r=>{const o=t.get(r.theme);if(o)return o;const s=e(r),i={},l={};for(const m in s)typeof s[m]=="function"?l[m]=s[m]:i[m]=s[m];const u={...f.StyleSheet.create(i),...l};return t.set(r.theme,u),u};return{use:()=>{const r=z(),o=fe.useSafeAreaInsets();return n({...r,edgeInsets:o,select:s=>s[r.theme.selectedTheme]})}}}},Vs={ltr:{left:"paddingStart",right:"paddingEnd",top:"paddingTop",bottom:"paddingBottom"},rtl:{left:"paddingEnd",right:"paddingStart",top:"paddingTop",bottom:"paddingBottom"}},Ie=(e,t=f.I18nManager.isRTL?"rtl":"ltr")=>{const n=fe.useSafeAreaInsets();return e.reduce((r,o)=>{const s=Vs[t][o];return r[s]=n[o],r},{})},Gs={send:require("./icons/icon-send.png"),close:require("./icons/icon-close.png"),menu:require("./icons/icon-menu.png"),chat:require("./icons/icon-chat.png"),message:require("./icons/icon-message.png"),spinner:require("./icons/icon-spinner.png"),error:require("./icons/icon-error.png"),refresh:require("./icons/icon-refresh.png"),"chevron-down":require("./icons/icon-chevron-down.png"),done:require("./icons/icon-done.png"),"done-all":require("./icons/icon-done-all.png"),user:require("./icons/icon-user.png"),"file-document":require("./icons/icon-file-document.png"),remove:require("./icons/icon-remove.png"),add:require("./icons/icon-add.png"),agent:require("./icons/icon-agent.png"),camera:require("./icons/icon-camera.png"),photo:require("./icons/icon-photo.png"),document:require("./icons/icon-document.png"),"bot-filled":require("./icons/icon-bot-filled.png"),copy:require("./icons/icon-copy.png"),source:require("./icons/icon-source.png"),"radio-on":require("./icons/icon-radio-on.png"),"radio-off":require("./icons/icon-radio-off.png"),good:require("./icons/icon-good.png"),bad:require("./icons/icon-bad.png"),"good-filled":require("./icons/icon-good-filled.png"),"bad-filled":require("./icons/icon-bad-filled.png"),delight:require("./icons/icon-delight.png"),"thumbnail-none":require("./icons/icon-thumbnail-none.png")},js={send:!0,chat:!0,message:!0,good:!0,bad:!0,"good-filled":!0,"bad-filled":!0},O=({customSource:e,type:t,color:n,size:r=24,style:o})=>{const s=Ks.use(),i=f.I18nManager.isRTL&&!!js[t];return a.createElement(y,{alignItems:"center",justifyContent:"center"},a.createElement(f.Image,{resizeMode:"contain",source:e??Gs[t],style:[s.icon({color:n,size:r,mirror:i}),o]}))},Ks=R.create(({theme:e,themedColor:t})=>({icon:n=>({tintColor:typeof n.color=="function"?n.color(t):n.color??e.colors.base.primary,width:n.size,height:n.size,transform:n.mirror?[{scaleX:-1}]:void 0})})),qt=(e,t)=>{if(!t||t.length===0)return!1;const n=t.trimStart();if(n.length===0)return!1;const r=e==="start"?Array.from(n)[0]:Array.from(n).pop(),o=r==null?void 0:r.codePointAt(0);return o===void 0?!1:Zs(o)},On=e=>qt("start",e),Ys=e=>qt("end",e),Xs=e=>{const{text:t,style:n,isTextInput:r}=e;return n!=null&&n.textAlign&&n.textAlign!=="left"&&n.textAlign!=="right"?n.textAlign:f.I18nManager.isRTL&&typeof t=="string"&&On(t)?r?"right":f.I18nManager.doLeftAndRightSwapInRTL?"left":"right":n==null?void 0:n.textAlign},Zs=e=>{for(const[t,n]of Js)if(e>=t&&e<=n)return!0;return!1},Js=[[1424,1535],[1536,1791],[1872,1919],[2208,2303],[64285,64335],[65136,65279],[126464,126719]],Wt={isStartsWithRTL:On,isEndsWithRTL:Ys,isRTLString:qt,useTextAlign:Xs},k=({variant:e="body1",color:t,style:n,...r})=>{const{theme:o,themedColor:s}=z(),i=d.useMemo(()=>{if(typeof t=="function")return t(s);if(typeof t=="string")return t;const u=f.StyleSheet.flatten(n);return u&&u.color?u.color:t??s.textHighEmphasis},[n,t,s.textHighEmphasis]),l=d.useMemo(()=>{const u=o.typography[e]??o.typography.body1;return f.StyleSheet.flatten([{includeFontPadding:!1,...u,color:i},n])},[e,i,o.typography,s.textHighEmphasis]),c=Wt.useTextAlign({text:r.children,style:l});return a.createElement(f.Text,{style:[l,{textAlign:c}],...r})},Bn=350,Qs=({children:e,...t})=>a.createElement(f.Pressable,{disabled:!t.onPress&&!t.onLongPress,delayLongPress:Bn,...t},n=>typeof e=="function"?e(n):e),ea=({children:e,style:t,...n})=>{const[r,o]=d.useState(!1),s={pressed:r};return a.createElement(f.TouchableOpacity,{disabled:!n.onPress&&!n.onLongPress,delayLongPress:Bn,style:typeof t=="function"?t(s):t,onPressIn:()=>o(!0),onPressOut:()=>o(!1),...n},typeof e=="function"?e(s):e)},P=e=>e.activeOpacity&&e.activeOpacity<1?a.createElement(ea,{...e}):a.createElement(Qs,{...e}),{Provider:ta,useContext:Nn}=j("BottomSheetAnimation");function na({onClose:e,children:t}){const n=d.useRef(new f.Animated.Value(500)).current;d.useEffect(()=>{f.Animated.timing(n,{toValue:0,duration:300,useNativeDriver:!0}).start()},[n]);const r=d.useCallback(s=>async()=>{f.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(async()=>{try{await(s==null?void 0:s())}catch{e==null||e()}})},[n]),o=d.useRef(f.PanResponder.create({onMoveShouldSetPanResponder:(s,i)=>i.dy>5,onPanResponderMove:(s,i)=>{i.dy>0&&n.setValue(i.dy)},onPanResponderRelease:(s,i)=>{i.dy>100||i.vy>.5?f.Animated.timing(n,{toValue:500,duration:200,useNativeDriver:!0}).start(()=>{e==null||e()}):f.Animated.timing(n,{toValue:0,duration:200,useNativeDriver:!0}).start()}})).current;return a.createElement(ta,{value:{wrapWithAnimation:r,translateY:n,panHandlers:o.panHandlers}},t)}const ra=({icon:e,label:t="",destructive:n=!1,onPress:r})=>{const o=Hn.use(),{themedColor:s}=z();return a.createElement(P,{onPress:r,style:o.actionItem,activeOpacity:.75},e&&a.createElement(O,{type:e,size:24,color:s.primary}),a.createElement(k,{variant:"body3",color:n?s.error:s.textHighEmphasis,numberOfLines:1},t))},oa=({onClose:e,children:t})=>{const n=Hn.use(),{translateY:r,panHandlers:o,wrapWithAnimation:s}=Nn(),i=Ie(["left","right"]);return a.createElement(P,{onPress:s(e),style:n.overlay},a.createElement(y.Animated,{style:[n.container,i,{transform:[{translateY:r}]}],...o},t))},Xe=oe({template:oa,components:{ActionItem:ra}}),ee=e=>{const{Template:t}=Xe.useContext();return a.createElement(na,{onClose:e.onClose},a.createElement(t,{...e}))};ee.ActionItem=e=>{const{components:t}=Xe.useContext(),{wrapWithAnimation:n}=Nn();return a.createElement(t.ActionItem,{...e,onPress:n(e.onPress)})};const Hn=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}})),sa=({date:e=Date.now(),style:t,...n})=>{const{format:r,strings:o}=H();return a.createElement(y,{flexDirection:"row",justifyContent:"center",alignItems:"center",style:t,...n},a.createElement(k,{variant:"caption4",color:s=>s.textMidEmphasis},r(e,o.date_format.date_separator)))},Vt=({iconSize:e=64,icon:t,style:n,label:r,children:o})=>{const{themedColor:s}=z();return a.createElement(y,{style:[zn.body,n]},t&&a.createElement(O,{type:t,size:e,color:s.textLowEmphasis}),r&&a.createElement(k,{variant:"body1",color:s.textMidEmphasis},r),o)},aa=({children:e})=>{const{theme:t}=z();return a.createElement(y,{backgroundColor:t.colors.base.background,style:zn.container},e)},zn=f.StyleSheet.create({container:{position:"relative",justifyContent:"center",alignItems:"center",flex:1},body:{flexDirection:"column",minHeight:104,alignItems:"center",gap:20}}),ia=({label:e,icon:t="error",action:n,...r})=>{const{strings:o}=H();return a.createElement(Vt,{icon:t,label:e??o.common.placeholder_something_went_wrong,...r},n&&a.createElement(la,{onPress:n.onPress,label:n.label??o.common.placeholder_something_went_wrong_retry_label}))},la=({label:e,onPress:t})=>{const{themedColor:n}=z();return a.createElement(P,{onPress:t},a.createElement(y,{style:ca.button},a.createElement(O,{type:"refresh",size:20}),a.createElement(k,{variant:"button",color:n.primary},e)))},ca=f.StyleSheet.create({button:{flexDirection:"row",gap:4,alignItems:"center",justifyContent:"center"}}),ua=({iconSize:e=48,style:t})=>{const n=d.useRef(new f.Animated.Value(0)).current;d.useEffect(()=>{const o=f.Animated.loop(f.Animated.timing(n,{toValue:1,duration:1e3,easing:f.Easing.linear,useNativeDriver:!0}));return o.start(),()=>{o.stop()}},[n]);const r=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(y.Animated,{style:[{transform:[{rotate:r}]},t]},a.createElement(O,{type:"spinner",size:e}))},da=({label:e,icon:t="chat",...n})=>{const{strings:r}=H();return a.createElement(Vt,{icon:t,label:e??r.common.placeholder_no_conversations,...n})},ma=({label:e,icon:t="message",...n})=>{const{strings:r}=H();return a.createElement(Vt,{icon:t,label:e??r.common.placeholder_no_messages,...n})},ga=e=>{const{components:t}=Gt.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(aa,null,n)},Gt=oe({template:ga,components:{Loading:ua,Error:ia,NoChannels:da,NoMessages:ma}}),ve=e=>{const{Template:t}=Gt.useContext();return a.createElement(t,{...e})},ha=({style:e,onPress:t})=>{const n=fa.use(),{theme:r}=z();return a.createElement(P,{style:[n.button,e],onPress:t},a.createElement(y,{alignItems:"center",justifyContent:"center"},a.createElement(O,{size:24,type:"chevron-down",color:r.colors.base.primary})))},fa=R.create(({select:e,theme:t})=>({button:{width:40,height:40,borderRadius:24,alignItems:"center",justifyContent:"center",backgroundColor:e({light:t.palette.background50,dark:t.palette.background400}),boxShadow:[{color:"rgba(0, 0, 0, 0.08)",offsetX:0,offsetY:2,blurRadius:8,spreadDistance:0},{color:"rgba(0, 0, 0, 0.12)",offsetX:0,offsetY:4,blurRadius:6,spreadDistance:0}]}})),pa=({loading:e,error:t,data:n,LoadingComponent:r,ErrorComponent:o,EmptyComponent:s,...i},l)=>t?o:e?r:!n||n.length===0?s:a.createElement(f.FlatList,{ref:l,data:n,...i}),Fn=d.memo(d.forwardRef(pa)),jt=({name:e,type:t="FILE",onPress:n})=>{const r=_a.use();return a.createElement(P,{onPress:n,style:r.container,activeOpacity:.75},a.createElement(y,{style:r.iconWrapper},a.createElement(O,{type:"file-document",size:24,color:r.icon.tintColor})),a.createElement(y,{flex:1,flexDirection:"column",gap:4,style:r.info},a.createElement(k,{variant:"button",color:o=>o.textHighEmphasis,numberOfLines:1,ellipsizeMode:"middle"},e),a.createElement(k,{variant:"caption3",color:o=>o.textMidEmphasis},t)))},_a=R.create(({theme:e,themedColor:t})=>({container:{width:220,borderRadius:12,gap:8,height:64,flexDirection:"row",alignItems:"center",padding:12,borderWidth:1,borderColor:t.textDisabled,backgroundColor:t.bg_50_600},iconWrapper:{borderRadius:8,width:40,height:40,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary},icon:{tintColor:e.colors.base.primaryContrastContent},info:{alignItems:"flex-start",minWidth:0}})),ya=({file:e,children:t,onClickFile:n=({url:r})=>f.Linking.openURL(r)})=>a.createElement(y,{gap:M.GAP_GROUPED,width:M.BODY_MAX_WIDTH,maxWidth:M.BODY_MAX_WIDTH},a.createElement(jt,{name:e.name,type:Ht(e.name,e.type),onPress:n?()=>n==null?void 0:n(e):void 0}),t),xe=({style:e,...t})=>a.createElement(f.Image,{style:[e,t],...t}),ba=({file:e,onClickMedia:t=({url:r})=>f.Linking.openURL(r),children:n})=>{const r=Ea.use();return a.createElement(y,{gap:M.GAP_GROUPED},a.createElement(P,{style:r.mediaContainer,onPress:()=>t==null?void 0:t(e)},a.createElement(xe,{source:{uri:e.url},style:r.media,resizeMode:"cover"})),n)},Ea=R.create(({select:e,theme:t})=>({mediaContainer:{width:M.BODY_MAX_WIDTH,height:160,borderRadius:12,overflow:"hidden",backgroundColor:e({light:t.palette.background100,dark:t.palette.background400})},media:{width:"100%",height:"100%"}})),$n=({code:e,language:t})=>{const[n,r]=d.useState(!1),o=async()=>{Sr.default.setString(e),r(!0),setTimeout(()=>r(!1),2e3)};return a.createElement(y,{style:He.container,flexDirection:"row"},a.createElement(f.Pressable,{style:He.copyButton,onPress:o},a.createElement(O,{type:n?"done":"copy",size:16,color:"#fff"})),a.createElement(y,null,a.createElement(Ar.default,{hljsStyle:br.atomOneDarkReasonable,scrollViewProps:{contentContainerStyle:He.codeContainer,bounces:!1},textStyle:He.codeText,language:t},e)))},He=f.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}}),Un=d.memo(({src:e,onPress:t})=>{const[n,r]=d.useState("1/1"),[o,s]=d.useState(!1),i=Ca.use();return d.useLayoutEffect(()=>{e&&Rn(e).then(({width:l,height:c})=>r(`${l}/${c}`))},[e]),a.createElement(f.Pressable,{style:{marginTop:8},onPress:t},a.createElement(y,{style:[i.container,{aspectRatio:n}]},o?a.createElement(O,{size:28,type:"thumbnail-none",color:l=>l.textHighEmphasisInverse}):a.createElement(f.Image,{source:{uri:e},style:f.StyleSheet.absoluteFillObject,onError:()=>s(!0)})))}),Ca=R.create(({themedColor:e})=>({container:{width:"100%",backgroundColor:e.textDisabled,borderRadius:4,overflow:"hidden",justifyContent:"center",alignItems:"center"}}));Un.displayName="MarkdownImage";const Le=e=>d.isValidElement(e)&&"children"in e.props,Ot=(e=.75)=>`rgba(0, 0, 0, ${e})`,va=({children:e})=>{var i;const t=f.useWindowDimensions(),n=Ot(.3),r=d.useMemo(()=>{try{if(!Array.isArray(e)||e.length<2)return null;const l=e[0],c=e[1],u=Le(c)?c.props.children:void 0;if(!u||!Array.isArray(u)||u.length===0)return null;const m=u,h=m[0],g=Le(h)?h.props.children:void 0;if(!g||!Array.isArray(g)||g.length===0)return null;const _=m.length,p=g.length,S=Array(p).fill(null).map(()=>[]);for(let C=0;C<_;C++){const x=m[C],T=Le(x)?x.props.children:void 0;if(!(!T||!Array.isArray(T)))for(let A=0;A<p;A++){const w=S[A];w&&A<T.length&&(w[C]=T[A])}}const b=Le(l)?l.props.children:void 0,E=Array.isArray(b)?b[0]:void 0,v=Le(E)?E.props.children:void 0;if(v&&Array.isArray(v))for(let C=0;C<p;C++){const x=S[C];x&&C<v.length&&x.unshift(v[C])}return S}catch{return null}},[e]),[o,s]=d.useState(Array(((i=r==null?void 0:r[0])==null?void 0:i.length)??0).fill(0));return r?a.createElement(f.View,{style:{flexDirection:"row"}},r.map((l,c)=>{const u=c===0,m=c===r.length-1;return a.createElement(f.View,{key:c,style:{flexDirection:"column",borderStartWidth:1,borderEndWidth:m?1:0,borderTopWidth:1,borderBottomWidth:1,borderColor:n,borderTopStartRadius:u?6:0,borderBottomStartRadius:u?6:0,borderTopEndRadius:m?6:0,borderBottomEndRadius:m?6:0}},l.map((h,g)=>{const _=g===0,p=g===l.length-1;return a.createElement(f.View,{key:g,onLayout:({nativeEvent:{layout:S}})=>{const b=S.height;(o[g]??0)<b&&(o[g]=b,s([...o]))},style:{borderBottomWidth:p?0:1,borderColor:n,backgroundColor:_?Ot(.15):"transparent",maxWidth:t.width*2/3,minHeight:(o[g]??0)>0?o[g]:void 0,padding:8}},h)}))})):a.createElement(f.View,null,e)},Kt=d.memo(({children:e,textStyle:t,linkStyle:n,onPressImage:r})=>{const{themedColor:o}=z(),s=f.StyleSheet.compose({fontSize:14,color:o.textHighEmphasis,textAlign:"left"},t),i=f.StyleSheet.flatten(s),l=i.fontSize||14,c=i.lineHeight||l*1.286,u=Ot(.3),m={color:i.color,textAlign:Wt.useTextAlign({text:e,style:i}),fontSize:l,lineHeight:c,fontWeight:i.fontWeight,fontFamily:i.fontFamily,fontStyle:i.fontStyle,letterSpacing:i.letterSpacing,textDecorationLine:i.textDecorationLine,textDecorationStyle:i.textDecorationStyle,textDecorationColor:i.textDecorationColor},h=d.useMemo(()=>({image:g=>{var p,S;const _=((p=g.attributes)==null?void 0:p.src)||((S=g.attributes)==null?void 0:S.href);return _?a.createElement(Un,{key:g.key,src:_,onPress:()=>r==null?void 0:r(_)}):null},code_block:g=>a.createElement($n,{code:g.content,language:"text"}),table:(g,_)=>a.createElement(f.View,{key:g.key,style:{marginTop:8}},a.createElement(f.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!0,nestedScrollEnabled:!0,persistentScrollbar:!0},a.createElement(va,null,_)))}),[r]);return a.createElement(y,{flexDirection:"row",marginTop:-8},a.createElement(xr.default,{style:{body:{...m,width:e.length>50?"100%":void 0,marginBottom:0},paragraph:{...m,marginTop:8,marginBottom:0},heading1:{...m,marginTop:8,marginBottom:0,fontSize:l*1.429,lineHeight:l*1.429*1.4,fontWeight:"700"},heading2:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.286,lineHeight:l*1.286*1.333},heading3:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading4:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading5:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},heading6:{...m,fontWeight:"600",marginTop:8,marginBottom:0,fontSize:l*1.143,lineHeight:l*1.143*1.375},link:f.StyleSheet.flatten(f.StyleSheet.compose({...m,fontWeight:"700",textDecorationLine:"underline"},n)),code_inline:{...m,fontSize:l*.929,lineHeight:l*.929*1.538,fontWeight:"600",backgroundColor:u},code_block:{...m,borderWidth:0,backgroundColor:u,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538},fence:{...m,borderRadius:4,padding:12,marginTop:8,marginBottom:0,fontSize:l*.929,lineHeight:l*.929*1.538,backgroundColor:o.textDisabled},bullet_list:{marginTop:4,marginBottom:0},bullet_list_icon:{marginLeft:0,marginRight:4,fontWeight:"900"},ordered_list:{marginTop:4,marginBottom:0},ordered_list_icon:{marginLeft:0,marginRight:4},list_item:{...m,marginTop:4,marginBottom:0},blockquote:{...m,paddingStart:8,marginTop:8,marginBottom:0,paddingVertical:4,borderStartWidth:4,borderStartColor:u,backgroundColor:"transparent",fontWeight:"500",fontSize:l,lineHeight:c},hr:{backgroundColor:u,height:1,marginTop:8,marginBottom:0},th:{...m,padding:4,fontSize:l,lineHeight:l*1.143,fontWeight:"700"},td:{...m,padding:2,fontSize:l,lineHeight:l*1.429},image:{maxHeight:300,maxWidth:"100%"}},rules:h},zr(e)))});Kt.displayName="MarkdownText";const gn=({maxBodyWidth:e,customStyle:t,message:n,children:r})=>{const o=Sa.use(),s=e??M.BODY_MAX_WIDTH,i=d.useMemo(()=>Or(n),[n]),l=d.useCallback(c=>f.Linking.openURL(c),[]);return i.length===0&&!r?null:a.createElement(y,{alignSelf:"flex-start",maxWidth:s,borderRadius:12,paddingVertical:12,style:[o.container,(t==null?void 0:t.bubbleBackgroundColor)&&{backgroundColor:t==null?void 0:t.bubbleBackgroundColor}]},i.map((c,u)=>c.type==="text"?a.createElement(y,{key:u,paddingHorizontal:12},a.createElement(Kt,{onPressImage:l,textStyle:o.text},c.value)):c.type==="code"?a.createElement($n,{key:u,code:c.value,language:c.language}):null),r)},Sa=R.create(({theme:e})=>({container:{backgroundColor:e.colors.messageIncoming.background},text:{color:e.colors.messageIncoming.text}})),Aa=e=>{const{strings:t}=H(),n=()=>{const r=An(e)?a.createElement(gn,{...e}):null;return e.messageType==="user"?r:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(ba,{...e},r):a.createElement(ya,{...e},r):a.createElement(gn,{...e,message:t.conversation.unknown_message_type})};return a.createElement(y,{style:e.containerStyle},n())};function qn({id:e,src:t,size:n=56,onClick:r,style:o}){const s=xa.use(),i=a.createElement(f.View,{style:[s.container(n),o],testID:e},t?a.createElement(f.Image,{source:{uri:t},style:s.image}):a.createElement(O,{type:"user",size:n}));return r?a.createElement(P,{onPress:r,activeOpacity:.75},i):i}const xa=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"}})),wa=({sender:e,isBotMessage:t})=>{const n=Ia.use();return t&&!e.profileUrl?a.createElement(y,{style:n.botContainer},a.createElement(O,{type:"delight",size:M.AVATAR_SIZE-8})):a.createElement(qn,{src:e.profileUrl,size:M.AVATAR_SIZE})},Ia=R.create(({theme:e})=>({botContainer:{width:M.AVATAR_SIZE,height:M.AVATAR_SIZE,borderRadius:M.AVATAR_SIZE/2,padding:4,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.base.primary}})),Ta=({sender:e})=>a.createElement(y,{flex:1,paddingVertical:5,paddingStart:0,paddingEnd:7,alignItems:"flex-start"},a.createElement(k,{variant:"caption1",color:t=>t.textMidEmphasis,numberOfLines:1},e.nickname)),ka=({createdAt:e,containerStyle:t})=>{const{strings:n,format:r}=H();return e?a.createElement(y,{alignItems:"flex-start",style:t},a.createElement(k,{variant:"caption4",color:o=>o.textLowEmphasis},r(e,n.date_format.message_timestamp))):null},Ma=({customStyle:e,containerStyle:t})=>{const{theme:n}=z(),r=d.useRef(new f.Animated.Value(0)).current,o=La.map(([s,i,l])=>[r.interpolate({inputRange:s,outputRange:i,extrapolate:"clamp"}),r.interpolate({inputRange:s,outputRange:l,extrapolate:"clamp"})]);return d.useEffect(()=>{const s=f.Animated.loop(f.Animated.timing(r,{toValue:1.4,duration:1400,easing:f.Easing.linear,useNativeDriver:!0}));return s.start(),()=>s.reset()},[]),a.createElement(y,{style:t},a.createElement(y,{width:60,flexDirection:"row",alignItems:"center",justifyContent:"center",borderRadius:16,paddingHorizontal:12,height:34,backgroundColor:(e==null?void 0:e.bubbleBackgroundColor)??n.colors.messageIncoming.background},o.map(([s,i],l)=>a.createElement(y.Animated,{key:l,style:[Ra.dot,{marginEnd:l===o.length-1?0:6,opacity:i,transform:[{scale:s}],backgroundColor:(e==null?void 0:e.bubbleContentColor)??n.colors.messageIncoming.text}]}))))},La=[[[.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]]],Ra=f.StyleSheet.create({dot:{width:8,height:8,borderRadius:4}}),Pa=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>f.Linking.openURL(n)})=>{const n=Da.use(),r=e==null?void 0:e.cta_button;return r?a.createElement(P,{onPress:()=>t(r),activeOpacity:.75,style:n.button},a.createElement(k,{variant:"button",color:o=>o.textHighEmphasis,numberOfLines:1},r.label)):null},Da=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})}})),Oa=({extendedMessagePayload:e,onClickCitation:t=n=>f.Linking.openURL(n.link)})=>{const{strings:n}=H(),{theme:r}=z(),o=e==null?void 0:e.citations;return!o||o.length===0?null:a.createElement(y,{gap:8,borderRadius:8,paddingHorizontal:12,paddingTop:8,paddingBottom:6},a.createElement(k,{variant:"caption1",color:r.colors.messageIncoming.text,style:hn.sourceLabel},n.conversation.citation_title),a.createElement(y,{gap:8},o.map(s=>a.createElement(P,{key:s.embedding_id,onPress:()=>t(s),activeOpacity:.5},a.createElement(y,{flexDirection:"row",alignItems:"center",gap:4},a.createElement(O,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(y,{flex:1},a.createElement(k,{variant:"body3",color:r.colors.messageIncoming.text,numberOfLines:1,style:hn.citationText},s.title)))))))},hn=f.StyleSheet.create({sourceLabel:{opacity:.5},citationText:{textDecorationLine:"underline"}}),Bt=e=>`${e}-filled`,Ba=e=>e==="good"?G.AIAgentMessageFeedbackRating.GOOD:G.AIAgentMessageFeedbackRating.BAD,fn=({onClose:e,isEdit:t,initialRating:n,initialComment:r="",isCommentEnabled:o=!1})=>{const{strings:s}=H(),{themedColor:i,theme:l}=z(),c=Na.use(),[u,m]=d.useState(r),[h,g]=d.useState(n),_=()=>{h&&e({rating:h,comment:u.trim()||void 0})},p=()=>{e()},S={good:i.secondary,bad:i.error};return a.createElement(f.KeyboardAvoidingView,{style:{flex:1},behavior:"padding"},a.createElement(P,{onPress:p,style:c.overlay},a.createElement(y,{width:280,backgroundColor:l.colors.base.modalContentBackground,borderRadius:12,overflow:"hidden",onStartShouldSetResponder:()=>!0},a.createElement(y,{padding:24},a.createElement(k,{variant:"h2",color:i.textHighEmphasis},s.feedback.title)),a.createElement(y,{paddingHorizontal:24,gap:24},a.createElement(y,{flexDirection:"row",gap:4},["good","bad"].map(b=>{const E=h===b,v=b==="good"?s.feedback.good:s.feedback.bad;return a.createElement(P,{key:b,onPress:()=>g(b),activeOpacity:.6,style:c.ratingButton(E)},a.createElement(O,{type:E?Bt(b):b,size:24,color:E?S[b]:i.textLowEmphasis}),a.createElement(k,{variant:"caption1",color:E?S[b]:i.textLowEmphasis},v))})),o&&a.createElement(y,{gap:6},a.createElement(k,{variant:"caption3",color:i.textHighEmphasis},s.feedback.comment_label),a.createElement(f.TextInput,{value:u,onChangeText:b=>m(b),placeholder:s.feedback.comment_placeholder,placeholderTextColor:i.textLowEmphasis,multiline:!0,maxLength:100,style:c.commentInput}))),a.createElement(y,{paddingHorizontal:24,paddingVertical:16,flexDirection:"row",justifyContent:"flex-end",gap:4},a.createElement(P,{onPress:p,activeOpacity:.6,style:c.cancelButton},a.createElement(k,{variant:"button",color:i.textHighEmphasis},s.feedback.cancel)),a.createElement(P,{onPress:_,disabled:!h,activeOpacity:.6,style:c.submitButton(!h)},a.createElement(k,{variant:"button",color:l.colors.base.primaryContrastContent},t?s.feedback.save:s.feedback.submit))))))},Na=R.create(({select:e,theme:t,themedColor:n})=>({overlay:{flex:1,backgroundColor:t.palette.overlay.dark,alignItems:"center",justifyContent:"center"},ratingButton:r=>({width:114,height:64,borderRadius:12,borderWidth:1,borderColor:n.textDisabled,alignItems:"center",justifyContent:"center",gap:0,backgroundColor:r?e({light:t.palette.background100,dark:t.palette.background600}):"transparent"}),commentInput:{width:"100%",maxHeight:118,borderRadius:4,borderWidth:1,borderColor:n.textDisabled,backgroundColor:n.textLowEmphasisInverse,color:n.textHighEmphasis,paddingHorizontal:12,paddingVertical:6,fontSize:12,lineHeight:16,textAlignVertical:"top"},cancelButton:{width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center"},submitButton:r=>({width:86,height:40,borderRadius:20,alignItems:"center",justifyContent:"center",backgroundColor:t.colors.base.primary,opacity:r?.4:1})})),Ha=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:o,extendedMessagePayload:s,onFeedbackUpdate:i,containerStyle:l})=>{const{strings:c}=H(),{themedColor:u}=z(),{openModal:m}=Ye(),h=za.use(),g=s==null?void 0:s.feedback,_=(g==null?void 0:g.rating)??"none";if(_!=="none"?!1:!!(n||!e||!r||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const S={good:u.secondary,bad:u.error},b=async C=>{const x=await m(T=>a.createElement(fn,{onClose:T,isEdit:!1,initialRating:C,initialComment:"",isCommentEnabled:o}));x&&(i==null||i(x))},E=async()=>{const C=await m(x=>a.createElement(ee,{onClose:()=>x()},a.createElement(ee.ActionItem,{onPress:()=>x("edit"),label:c.feedback.edit}),a.createElement(ee.ActionItem,{onPress:()=>x("remove"),label:c.feedback.remove,destructive:!0})));if(C==="edit"){const x=await m(T=>a.createElement(fn,{onClose:T,isEdit:!0,initialRating:g==null?void 0:g.rating,initialComment:g==null?void 0:g.comment,isCommentEnabled:o}));x&&(i==null||i(x))}else C==="remove"&&(i==null||i(null))},v=()=>t&&_!=="none"?a.createElement(y,{flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:M.BODY_MAX_WIDTH},a.createElement(y,{padding:2,flexShrink:0,alignItems:"center"},a.createElement(O,{type:Bt(_),size:12,color:S[_]})),(g==null?void 0:g.comment)&&a.createElement(k,{variant:"caption2",style:h.commentText},g.comment)):a.createElement(y,{gap:4,maxWidth:M.BODY_MAX_WIDTH},a.createElement(y,{flexDirection:"row",gap:2},["good","bad"].map(C=>{const x=_===C;return a.createElement(P,{key:C,onPress:()=>{_==="none"?b(C):E()},activeOpacity:.6,style:h.feedbackButton(x)},a.createElement(O,{type:x?Bt(C):C,size:14,color:x?S[C]:u.textMidEmphasis}))})),_!=="none"&&(g==null?void 0:g.comment)&&a.createElement(k,{variant:"caption2",style:h.commentText},g.comment));return a.createElement(y,{style:l},v())},za=R.create(({select:e,theme:t,themedColor:n})=>({feedbackButton:r=>({width:38,height:20,borderRadius:18,alignItems:"center",justifyContent:"center",borderWidth:1,borderColor:e({light:t.palette.background200,dark:t.palette.background400}),backgroundColor:r?e({light:t.palette.background100,dark:t.palette.background500}):"transparent"}),commentText:{lineHeight:16,color:e({light:n.textMidEmphasis,dark:n.textHighEmphasis})}})),Fa=e=>{var n;return(n=e.extendedMessagePayload)==null?void 0:n.form,null},$a=e=>null,Wn=({debug:e=!1,style:t,showsHorizontalScrollIndicator:n=!1,children:r,...o})=>a.createElement(f.ScrollView,{style:[t,o,e&&Ut],showsHorizontalScrollIndicator:n,...o},r),Ua=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const r=qa.use(),[o,s]=d.useState(!1),i=(e==null?void 0:e.suggested_replies)??[];if(i.length===0||o)return null;const l=n==="vertical",c=m=>{t==null||t({reply:m}),s(!0)},u=()=>i.map((m,h)=>a.createElement(P,{key:h,style:r.itemContainer,onPress:()=>c(m)},a.createElement(k,{variant:"body3",color:g=>g.primary},m)));return l?a.createElement(y,{alignItems:"flex-end",gap:8,marginVertical:16,paddingHorizontal:M.HORIZONTAL_PADDING},u()):a.createElement(Wn,{horizontal:!0,showsHorizontalScrollIndicator:!1,contentContainerStyle:r.horizontalContainer},u())},qa=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:M.HORIZONTAL_PADDING,paddingVertical:16}})),Wa=e=>{var _,p,S,b,E,v,C;const{components:t}=Ze.useContext(),{streamText:n,isAnimating:r}=Yo({text:e.message,enabled:e.isStreaming,onAnimationStart:e.onStreamAnimationStart,onAnimationComplete:e.onStreamAnimationComplete}),o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},s=!!o.isTyping,i=!!((_=o.extendedMessagePayload)!=null&&_.form)&&!((p=o.extendedMessagePayload)!=null&&p.form.canceled_at),l=!!((S=o.extendedMessagePayload)!=null&&S.message_template),c=!!((b=o.extendedMessagePayload)!=null&&b.cta_button),u=!!((E=o.extendedMessagePayload)!=null&&E.citations)&&o.extendedMessagePayload.citations.length>0,m=!!o.createdAt,h=o.groupType==="top"||o.groupType==="single",g=o.groupType==="bottom"||o.groupType==="single";return a.createElement(y,{marginBottom:s?0:zt(o.groupType)},h&&a.createElement(y,{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:M.HORIZONTAL_PADDING},a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(y,{gap:M.GAP_GROUPED},s?a.createElement(t.TypingIndicator,{...o,containerStyle:ge.middleArea}):a.createElement(t.MessageBody,{...o,containerStyle:ge.middleArea},c&&a.createElement(y,{marginTop:12,marginHorizontal:12},a.createElement(t.CTAButton,{...o})),u&&a.createElement(t.Citation,{...o})),l&&a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(t.MessageBody,{...o,messageType:"user",message:((C=(v=o.extendedMessagePayload)==null?void 0:v.message_template)==null?void 0:C.fallback_message)??"Cannot read this template.",containerStyle:ge.middleArea}),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??a.createElement(t.TypingIndicator,{...o,containerStyle:ge.middleArea})}),i&&a.createElement(t.Form,{...o,containerStyle:ge.middleArea})),g&&m&&a.createElement(t.SentTime,{...o,containerStyle:ge.bottomArea}),a.createElement(d.Fragment,null,!s&&a.createElement(t.Feedback,{...o,containerStyle:ge.feedbackArea}),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},Ze=oe({template:Wa,components:{SenderName:Ta,SenderAvatar:wa,SentTime:ka,MessageBody:Aa,TypingIndicator:Ma,SuggestedReplies:Ua,MessageTemplate:$a,CTAButton:Pa,Citation:Oa,Form:Fa,Feedback:Ha}}),ge=f.StyleSheet.create({middleArea:{paddingStart:M.HORIZONTAL_PADDING+M.AVATAR_SIZE,paddingEnd:M.HORIZONTAL_PADDING},bottomArea:{marginTop:M.BODY_TIME_GAP,paddingStart:M.HORIZONTAL_PADDING+M.AVATAR_SIZE+8,paddingEnd:M.HORIZONTAL_PADDING},feedbackArea:{marginTop:8,paddingStart:M.HORIZONTAL_PADDING+M.AVATAR_SIZE+8,paddingEnd:M.HORIZONTAL_PADDING}}),Va=({file:e,children:t,sendingStatus:n,onClickFile:r=({url:o})=>f.Linking.openURL(o)})=>{const o=(()=>{if(!(!r||n!=="succeeded"))return()=>r(e)})();return a.createElement(y,{flexDirection:"column",alignItems:"flex-end",gap:M.GAP_GROUPED,width:M.BODY_MAX_WIDTH,maxWidth:M.BODY_MAX_WIDTH},a.createElement(jt,{name:e.name,type:Ht(e.name,e.type),onPress:o}),t)},Vn=({size:e=26,children:t})=>{const n=d.useRef(new f.Animated.Value(0)).current;d.useEffect(()=>{const o=f.Animated.loop(f.Animated.timing(n,{toValue:1,duration:1e3,easing:f.Easing.linear,useNativeDriver:!0}));return o.start(),()=>{o.stop()}},[n]);const r=n.interpolate({inputRange:[0,1],outputRange:["0deg","360deg"]});return a.createElement(y.Animated,{style:{transform:[{rotate:r}],width:e,height:e,alignItems:"center",justifyContent:"center"}},t??a.createElement(O,{type:"spinner",size:e}))};function Ga(e){return typeof e=="object"&&e!==null&&"uri"in e}const ja=({file:e,metadata:t,sendingStatus:n,onClickMedia:r=({url:s})=>f.Linking.openURL(s),children:o})=>{const s=Ka.use(),{aspectRatio:i,localFile:l}=t,[c]=d.useState(()=>Ga(l)?l.uri:e.url),[u,m]=d.useState(!1),h=(()=>{if(!(!r||n!=="succeeded"))return()=>r(e)})();return a.createElement(y,{flexDirection:"column",alignItems:"flex-end",gap:M.GAP_GROUPED},a.createElement(P,{onPress:h,style:[s.imageContainer,{aspectRatio:i}],activeOpacity:.75},!u&&a.createElement(y,{alignItems:"center",justifyContent:"center"},a.createElement(Vn,{size:26},a.createElement(O,{type:"spinner",color:g=>g.textLowEmphasis,size:26}))),a.createElement(xe,{source:{uri:c},style:[s.image,{opacity:u?1:0}],resizeMode:"cover",onLoad:()=>m(!0)})),o)},Ka=R.create(({themedColor:e})=>({imageContainer:{width:M.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}})),pn=e=>{var n,r;const t=Ya.use();return a.createElement(y,{style:[t.container({maxWidth:e.maxBodyWidth??M.BODY_MAX_WIDTH}),((n=e.customStyle)==null?void 0:n.bubbleBackgroundColor)&&{backgroundColor:e.customStyle.bubbleBackgroundColor}]},a.createElement(k,{variant:"body3",style:[t.text,((r=e.customStyle)==null?void 0:r.bubbleContentColor)&&{color:e.customStyle.bubbleContentColor}]},e.message))},Ya=R.create(({theme:e})=>({container:t=>({flexDirection:"column",borderRadius:12,overflow:"hidden",maxWidth:t.maxWidth,backgroundColor:e.colors.messageOutgoing.background,paddingVertical:12}),text:{textAlign:"left",lineHeight:20,paddingHorizontal:12,color:e.colors.messageOutgoing.text}})),Xa=e=>{const{strings:t}=H(),n=()=>{const r=An(e)?a.createElement(pn,{...e}):null;return e.messageType==="user"?r:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(ja,{...e},r):a.createElement(Va,{...e},r):a.createElement(pn,{...e,message:t.unknown_message_type})};return a.createElement(P,{onPress:e.sendingStatus==="failed"?e.onClickFailedMessage:void 0,activeOpacity:.75},a.createElement(y,{style:e.containerStyle},n()))},Za=({sendingStatus:e,containerStyle:t})=>{const{themedColor:n}=z(),r=()=>{switch(e){case"pending":return a.createElement(y,{marginBottom:2},a.createElement(Vn,{size:16},a.createElement(O,{type:"spinner",color:n.primary,size:16})));case"failed":return a.createElement(y,{marginBottom:2},a.createElement(O,{type:"error",color:n.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement(y,{marginBottom:2},a.createElement(O,{type:"done",color:n.secondary,size:16}))}};return a.createElement(y,{style:t},r())},Ja=({createdAt:e,containerStyle:t})=>{const{format:n,strings:r}=H();return e?a.createElement(y,{style:t},a.createElement(k,{variant:"caption4",color:o=>o.textLowEmphasis},n(e,r.date_format.message_timestamp))):null},Qa=e=>{const{components:t}=Je.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(y,{flex:1,flexDirection:"column",alignItems:"flex-end",marginBottom:zt(e.groupType)},a.createElement(t.MessageBody,{...e,containerStyle:_t.middleArea}),r&&(n?a.createElement(t.SentTime,{...e,containerStyle:_t.bottomArea}):a.createElement(t.SendingStatus,{...e,containerStyle:_t.bottomArea})))},Je=oe({template:Qa,components:{SendingStatus:Za,SentTime:Ja,MessageBody:Xa}}),_t=f.StyleSheet.create({middleArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:M.HORIZONTAL_PADDING},bottomArea:{alignSelf:"stretch",flexDirection:"row",justifyContent:"flex-end",paddingStart:M.HORIZONTAL_PADDING,paddingEnd:M.HORIZONTAL_PADDING+8,marginTop:M.BODY_TIME_GAP}}),ei=e=>e.messageType!=="admin"?null:a.createElement(k,{variant:"caption2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},ti(e.message)),ti=e=>{try{const t=[];let n=e,r=0;for(;n;){const o=n.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),s=n.match(/\*\*([^*]+)\*\*/),i=[o&&{match:o,type:"link"},s&&{match:s,type:"bold"}].filter(h=>!!h);if(!i.length){t.push(n);break}const l=i.reduce((h,g)=>g.match.index<h.match.index?g:h),{match:c,type:u}=l,m=c.index;m>0&&t.push(n.slice(0,m)),u==="link"?t.push(a.createElement(f.Text,{key:r++,onPress:()=>f.Linking.openURL((c==null?void 0:c[2])??""),style:{textDecorationLine:"underline"}},c[1])):u==="bold"&&t.push(a.createElement(f.Text,{key:r++,style:{fontWeight:"bold"}},c[1])),n=n.slice(m+c[0].length)}return t.filter(o=>o!=="")}catch{return[e]}},ni=({children:e,style:t})=>a.createElement(k,{variant:"caption4",color:n=>n.error,style:t},e),ri=({children:e,style:t,required:n})=>{const{strings:r}=H();return a.createElement(k,{variant:"caption3",color:o=>o.textMidEmphasis,style:t},e,!n&&a.createElement(k,{variant:"caption3",color:o=>o.textLowEmphasis},` (${r.form.optional_label})`))},oi=({style:e})=>{const t=si.use();return a.createElement(y,{style:[t.separator,e]})},si=R.create(({themedColor:e})=>({separator:{width:"100%",height:1,backgroundColor:e.textDisabled}})),ai=({value:e="",onChange:t,placeholder:n,variant:r="single-line",error:o=!1,submitted:s=!1,style:i,disabled:l=!1,maxLength:c})=>{const[u,m]=d.useState(!1),h=ii.use(),{themedColor:g}=z(),_=p=>{c&&p.length>c||t==null||t(p)};return a.createElement(f.TextInput,{value:e,onChangeText:_,placeholder:n,editable:!l&&!s,maxLength:c,multiline:r==="multi-line",style:[h.input(r,o,s,u),i],placeholderTextColor:g.textLowEmphasis,onFocus:()=>m(!0),onBlur:()=>m(!1)})},ii=R.create(({select:e,theme:t,themedColor:n})=>({input:(r,o,s,i)=>{let l,c;s?(l="transparent",c=e({light:t.palette.ondark.textMidEmphasis,dark:t.palette.onlight.textLowEmphasis})):o?(l=n.error,c=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis})):(l=i?n.primary:n.textDisabled,c=e({light:t.palette.background50,dark:t.palette.onlight.textLowEmphasis}));const u={width:"100%",padding:8,paddingHorizontal:12,borderRadius:6,fontSize:14,fontWeight:"400",lineHeight:20,borderWidth:1,borderColor:l,backgroundColor:c,color:s?n.textLowEmphasis:n.textHighEmphasis};return r==="multi-line"?{...u,height:96,textAlignVertical:"top"}:{...u,height:36}}})),Pe={Label:ri,ErrorLabel:ni,TextInput:ai,Separator:oi},Gn=({onClick:e,checked:t,label:n,disabled:r,labelVariant:o="caption2"})=>{const{themedColor:s}=z(),i=li.use(),l=t?s.primary:r?s.textDisabled:s.textLowEmphasis;return a.createElement(P,{disabled:r||!e,onPress:e},a.createElement(y,{style:i.container},a.createElement(y,{style:i.iconContainer},a.createElement(O,{size:20,type:t?"radio-on":"radio-off",color:l})),a.createElement(k,{variant:o,style:i.label(t,r)},n)))},li=R.create(({themedColor:e})=>({container:{flexDirection:"row",alignItems:"flex-start",justifyContent:"flex-start",width:"100%",gap:2},iconContainer:{width:20,height:20},label:(t,n)=>{let r;return t?r=e.textHighEmphasis:n?r=e.textLowEmphasis:r=e.textHighEmphasis,{flex:1,color:r,lineHeight:20}}})),ci=({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?a.createElement(y,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(Pe.Label,{required:e.cre.required},e.cre.question),a.createElement(y,{flexDirection:"column",gap:8,width:"100%"},[{label:e.cre.positive_label,value:!0},{label:e.cre.negative_label,value:!1}].map(s=>a.createElement(Gn,{key:s.label,checked:r===s.value,label:s.label,disabled:t,onClick:()=>o==null?void 0:o(s.value)})))):null),ui=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{strings:s}=H();return a.createElement(y,{flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(Pe.Label,{required:e.required},e.question),e.response_type==="free_text"&&a.createElement(Pe.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:i=>r(i),error:o}),e.response_type==="single_choice"&&a.createElement(y,{flexDirection:"column",gap:8,width:"100%"},e.options.map(i=>a.createElement(Gn,{key:i,checked:n===i,label:i,disabled:t,onClick:()=>r==null?void 0:r(i),labelVariant:"body3"}))),o&&a.createElement(Pe.ErrorLabel,null,s.form.validation_required))},di=e=>null,mi=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",s=jn.use(),[i,l]=d.useState(16);return a.createElement(y,{onLayout:c=>{c.nativeEvent.layout.width<300&&l(0)},flexDirection:"column",gap:8,alignItems:"flex-start"},a.createElement(k,{variant:"caption3",color:c=>c.textMidEmphasis},e.csat_question),a.createElement(y,{style:[s.scoresContainer,{gap:i}]},e.csat_scores.map(({label:c,image_url:u},m)=>{const h=m+1,g=n===h;return a.createElement(P,{key:m,disabled:t,onPress:()=>r(h),style:s.scoreButton},a.createElement(gi,{value:h,selected:o||g,label:c,src:u}),!!c&&a.createElement(k,{style:{textAlign:"center"},variant:"caption3",color:_=>g?_.textHighEmphasis:_.textLowEmphasis,lineBreakStrategyIOS:"standard",textBreakStrategy:"simple"},c))})))},gi=({value:e,src:t,label:n,selected:r})=>{const[o,s]=d.useState(!1),i=jn.use();return o?a.createElement(di,{value:e,selected:r,label:n}):a.createElement(xe,{source:{uri:t},style:i.emojiImage(r),onError:()=>s(!0),accessibilityLabel:n})},jn=R.create(()=>({scoresContainer:{flexDirection:"row",justifyContent:"space-between",alignSelf:"center",width:"100%",maxWidth:400},scoreButton:{backgroundColor:"transparent",gap:4,flexDirection:"column",alignItems:"center",justifyContent:"flex-start",minWidth:48,maxWidth:68,flex:1},emojiImage:e=>({width:40,height:40,opacity:e?1:.38})})),hi=({csatPayload:e})=>a.createElement(k,{style:{textAlign:"left"},variant:"button",color:t=>t.textHighEmphasis},e.title),yt=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:s})=>{const{params:i,setParams:l,error:c,setError:u,followUpItem:m,state:h,validateParams:g,itemProps:_}=Go({csatPayload:e,type:t,initialCsat:r,initialCsatReason:o,initialIsResolved:s});return a.createElement(a.Fragment,null,a.createElement(y,{flexDirection:"column",gap:12},a.createElement(hi,{..._}),t===ie.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(ci,{..._,defaultValue:s,value:i.isResolved,onChange:p=>l({isResolved:p})}),a.createElement(mi,{..._,value:i.csat,onChange:p=>l({csat:p})}),m&&a.createElement(ui,{..._,followUpItem:m,value:i.csatReason,onChange:p=>{l({csatReason:p}),u({followUpItem:!1})},hasError:c.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Pe.Separator,null),n({state:h,params:i,validateParams:g})))},fi=e=>{const{strings:t}=H();return kr(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})},pi=()=>{const{strings:e}=H();return a.createElement(k,{variant:"body2",color:t=>t.textMidEmphasis,style:{textAlign:"center"}},e.csat.submission_expired)},_i=e=>{if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:t,onSubmitCSAT:n}=e,{csat:r,csatReason:o,csatExpireAt:s,isResolvedWhenDeterminedByUser:i}=e,[,l]=d.useState(0),c=fi(t==null?void 0:t.csat),u=yi.use();if(!c||!c.visibility||!ie[c.type])return null;const m=c.type===ie.AI_AGENT_CSAT_5||c.type===ie.AI_AGENT_CSAT_5_WITH_CRE||c.type===ie.HELPDESK_CSAT_5?yt:()=>null;return a.createElement(y,{style:u.container},!r&&Qt(s)?a.createElement(pi,null):a.createElement(m,{csatPayload:c,type:c.type,initialCsat:r,initialCsatReason:o,initialIsResolved:i,renderSubmitButton:({state:h,params:g,validateParams:_})=>a.createElement(P,{activeOpacity:.75,disabled:h==="submitted",onPress:async()=>{!Qt(s)&&_()?await n(g):l(p=>p+1)},style:u.submitButton(h)},a.createElement(k,{variant:"button",style:u.submitButtonText(h)},h==="submitted"?c.csat_submitted_label:c.csat_submit_label))}))},yi=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}}})),bi=e=>{const{components:t}=Qe.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(y,{paddingHorizontal:M.HORIZONTAL_PADDING,marginBottom:zt(e.groupType)},n)},Qe=oe({template:bi,components:{AdminMessage:ei,CSATMessage:_i}}),Ei=({style:e,...t})=>{const{strings:n}=H();if(!$t("powered-by"))return null;const o=()=>{f.Linking.openURL("https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby")};return a.createElement(y,{style:[Ci.container,e],...t},a.createElement(k,{variant:"caption2",color:s=>s.textLowEmphasis},n.conversation.powered_by+" "),a.createElement(P,{onPress:o},a.createElement(k,{variant:"caption2",color:s=>s.textLowEmphasis},"Sendbird")))},Ci=f.StyleSheet.create({container:{flexDirection:"row",justifyContent:"center",alignItems:"center"}}),vi=()=>{var l;const{strings:e}=H(),{channelSource:t,scrollSource:n,updateActiveChannel:r}=te(),o=Si.use(),s=we(t.channel),i=d.useRef(s);return d.useEffect(()=>{const c=i.current;i.current=s,!c&&s&&n.actions.scrollToBottom(!0)},[s,n]),!((l=t.channel)!=null&&l.isAIAgent)||!s?null:a.createElement(y,{justifyContent:"center",flexDirection:"row",style:o.wrapper},a.createElement(P,{activeOpacity:.75,onPress:()=>r(),style:o.button},a.createElement(k,{variant:"button",role:"button",color:c=>c.textHighEmphasis},e.conversation.start_new_conversation_label)))},Si=R.create(({themedColor:e})=>({wrapper:{marginBottom:16},button:{borderRadius:6,paddingVertical:10,paddingHorizontal:20,borderWidth:1,borderColor:e.textDisabled}})),Ai=()=>{const{aiAgentInfo:e}=J(),{channelSource:t}=te(),n=Mn(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}})()},xi=(e,t)=>!ar.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),wi=({messageStackDirection:e="top"})=>{var K,ne;const{Template:t}=Ze.useContext(),{Template:n}=Je.useContext(),{Template:r}=Qe.useContext(),{openModal:o}=Ye(),{strings:s}=H(),{config:i,cache:l,chatSDK:c}=U(),{aiAgentInfo:u,userSession:m,connectionError:h}=J(),{messageSource:g,channelSource:_,scrollSource:p,state:{input:S,streamAnimation:b}}=te(),E=Ai(),v=Ii.use(),C=Ie(["left","right"]),{state:x,props:T}=p,A=(K=_.channel)==null?void 0:K.conversation,w=(I,X=!1)=>{var de;return X?u??{nickname:"",profileUrl:""}:((de=_.channel)==null?void 0:de.members.find(ke=>ke.userId===I.sender.userId))??I.sender},L=I=>{if(I.sendingStatus==="failed"&&!S.disabled)return()=>{o(X=>a.createElement(ee,{onClose:()=>X()},a.createElement(ee.ActionItem,{label:s.conversation.failed_message_resend,onPress:async()=>{g.resendMessage(I),X()}}),a.createElement(ee.ActionItem,{destructive:!0,label:s.conversation.failed_message_remove,onPress:async()=>{g.deleteMessage(I),X()}})))}},$=({item:I,index:X})=>{const de=g.messages[X+1],ke=g.messages[X-1],Me=(()=>{var Zt,Jt;const B=!(u!=null&&u.isUserFeedbackEnabled&&Ae(I,u==null?void 0:u.userId)&&!Ue.isWelcomeMessage(I)),W=Pr(I,de,ke,B),Z={extendedMessagePayload:I.extendedMessagePayload,message:I.message,createdAt:I.createdAt,groupType:W};if(Oe.isAdmin(I))return Oe.isCSAT(I)?A?a.createElement(r,{...Z,...A,messageType:"admin.csat",isResolvedWhenDeterminedByUser:Ir(A),onSubmitCSAT:async({csat:ce,..._e})=>{var ue;ce&&await((ue=_.channel)==null?void 0:ue.submitCSAT({csat:ce,..._e}))}}):null:a.createElement(r,{...Z,messageType:"admin"});if(Oe.isOutgoing(I,(m==null?void 0:m.userId)??"")){const ce={...Z,sender:w(I),sendingStatus:I.sendingStatus,onClickFailedMessage:L(I)};if(I.isUserMessage())return a.createElement(n,{...ce,messageType:"user"});if(I.isFileMessage()){const[_e,ue]=((Zt=I.metaArrays.find(F=>F.key===vn))==null?void 0:Zt.value)??[];return a.createElement(n,{...ce,messageType:"file",file:I,metadata:{aspectRatio:_e&&ue?`${_e}/${ue}`:"1/1",localFile:(Jt=I.messageParams)==null?void 0:Jt.file}})}}if(Oe.isIncoming(I,(m==null?void 0:m.userId)??"")){const ce=I.sender.userId===(u==null?void 0:u.userId),_e=X===0,ue={...Z,sender:w(I,ce),suggestedRepliesVisible:_e,isBotMessage:ce,isStreaming:Ue.isStreaming(I),isHandedOff:Se(_.channel),isConversationClosed:we(_.channel),isFeedbackEnabled:u==null?void 0:u.isUserFeedbackEnabled,isFeedbackCommentEnabled:u==null?void 0:u.isUserFeedbackCommentOptionEnabled,onClickSuggestedReply:async({reply:F})=>{g.sendUserMessage({message:F})},onRequestMessageTemplate:async F=>{const{template:ae}=await c.aiAgent.getMessageTemplate(F);return l.template.set(F,ae),ae},onGetCachedMessageTemplate:F=>l.template.get(F),onHandleTemplateInternalAction:F=>{if(F.type==="internal"&&F.internalData){const{method:ae,payload:me}=F.internalData;ae==="message.send"&&(me!=null&&me.message)&&g.sendUserMessage({message:me.message})}},onFeedbackUpdate:F=>{const ae={messageId:I.messageId,channelUrl:I.channelUrl};if(!F)return c.aiAgent.deleteMessageFeedback(ae);const me={...ae,rating:Ba(F.rating),comment:F.comment};return Ue.hasFeedback(I)?c.aiAgent.updateMessageFeedback(me):c.aiAgent.createMessageFeedback(me)},onSubmitForm:({key:F,data:ae})=>c.aiAgent.submitForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:F,formData:ae}),onCancelForm:({key:F})=>c.aiAgent.cancelForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:F}),onStreamAnimationStart:()=>{b.start(I.messageId)},onStreamAnimationComplete:()=>{b.stop(I.messageId)}};if(I.isUserMessage())return a.createElement(t,{...ue,messageType:"user"});if(I.isFileMessage())return a.createElement(t,{...ue,messageType:"file",file:I})}return null})(),D=xi(I,de)&&a.createElement(sa,{date:I.createdAt,style:v.dateSeparator});return a.createElement(y,null,D,Me)},Y=()=>a.createElement(Ei,{style:v.poweredBy}),q=()=>{var I;return a.createElement(a.Fragment,null,E&&a.createElement(t,{isTyping:!0,isBotMessage:E.isBot,sender:E.user,messageType:"user",groupType:"single",message:""}),((I=i==null?void 0:i.conversation)==null?void 0:I.isTalkToAgentViewEnabled)&&a.createElement(vi,null),x.bottomSpace?a.createElement(y,{height:x.bottomSpace}):null)};return a.createElement(y,{flex:1},a.createElement(Fn,{ref:p.ref,style:v.list,contentContainerStyle:[v.listContent,C,e==="top"&&v.stackTop],data:g.messages,onEndReached:g.loadPrevious,keyExtractor:Rr,renderItem:$,loading:!g.initialized,error:!!(h||_.error),LoadingComponent:a.createElement(ve,{type:"loading"}),EmptyComponent:a.createElement(ve,{type:"noMessages",label:s.common.placeholder_no_messages}),ErrorComponent:a.createElement(ve,{type:"error",label:(h==null?void 0:h.message)??((ne=_.error)==null?void 0:ne.message),action:_.error?{label:s.common.placeholder_something_went_wrong_retry_label,onPress:()=>_.refetch()}:void 0}),ListFooterComponent:Y(),ListHeaderComponent:q(),inverted:!0,...T}),x.shouldShowScrollButton&&a.createElement(y,{style:v.scrollButtonContainer},a.createElement(ha,{onPress:()=>p.actions.scrollToBottom(!0)})))},Ii=R.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background},stackTop:{flexGrow:1,justifyContent:"flex-end"},dateSeparator:{marginVertical:16},poweredBy:{marginTop:16},scrollButtonContainer:{position:"absolute",bottom:20,end:20}})),le={CAMERA_PERMISSION_DENIED:"Camera permission is not granted",GALLERY_PERMISSION_DENIED:"Photo library permission is not granted",IMAGE_PICKER_NOT_CONFIGURED:"Image picker is not configured. Please provide imagePicker in NativeAdapterConfig to use camera or gallery features.",DOCUMENT_PICKER_NOT_CONFIGURED:"Document picker is not configured. Please provide documentPicker in NativeAdapterConfig to use file selection features."};function Ti(e){return{captureCamera:async()=>{if(e.requestCameraPermissionsAsync&&!(await e.requestCameraPermissionsAsync()).granted)throw new Error(le.CAMERA_PERMISSION_DENIED);const t=await e.launchCameraAsync({mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});return t.canceled||!t.assets||t.assets.length===0?null:t.assets.map(_n)},selectFromGallery:async t=>{if(e.requestMediaLibraryPermissionsAsync&&!(await e.requestMediaLibraryPermissionsAsync()).granted)throw new Error(le.GALLERY_PERMISSION_DENIED);const n=await e.launchImageLibraryAsync({selectionLimit:(t==null?void 0:t.selectionLimit)??1,allowsMultipleSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,mediaTypes:["images"],preferredAssetRepresentationMode:e.UIImagePickerPreferredAssetRepresentationMode.Compatible});return n.canceled||!n.assets||n.assets.length===0?null:n.assets.map(_n)}}}function ki(e,t){const n=async()=>{const o=f.Platform.select({ios:t.PERMISSIONS.IOS.CAMERA,android:t.PERMISSIONS.ANDROID.CAMERA});if(!o)return;const s=await t.request(o);if(s!=="granted"&&s!=="limited")throw new Error(le.CAMERA_PERMISSION_DENIED)},r=async()=>{const o=f.Platform.select({ios:[t.PERMISSIONS.IOS.PHOTO_LIBRARY],android:typeof f.Platform.Version=="number"&&f.Platform.Version>32?[]:typeof f.Platform.Version=="number"&&f.Platform.Version>28?[t.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]:[t.PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,t.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]});if(!o||o.length===0)return;const s=await t.requestMultiple(o);if(!Object.values(s).every(l=>l==="granted"||l==="limited"))throw new Error(le.GALLERY_PERMISSION_DENIED)};return{captureCamera:async()=>{await n();const o=await e.launchCamera({mediaType:"photo",assetRepresentationMode:"compatible"});if(o.didCancel)return null;if(o.errorCode)throw o.errorCode==="permission"?new Error(le.CAMERA_PERMISSION_DENIED):new Error(o.errorMessage||`Camera error: ${o.errorCode}`);return!o.assets||o.assets.length===0?null:o.assets.map(yn)},selectFromGallery:async o=>{await r();const s=await e.launchImageLibrary({mediaType:"photo",selectionLimit:(o==null?void 0:o.selectionLimit)??1,assetRepresentationMode:"compatible"});if(s.didCancel)return null;if(s.errorCode)throw s.errorCode==="permission"?new Error(le.GALLERY_PERMISSION_DENIED):new Error(s.errorMessage||`Gallery error: ${s.errorCode}`);return!s.assets||s.assets.length===0?null:s.assets.map(yn)}}}function Mi(e){return{selectFile:async t=>{const n=(t==null?void 0:t.mimeTypes)??["*/*"],r=await e.getDocumentAsync({multiple:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:n});return r.canceled||!r.assets||r.assets.length===0?null:r.assets.map(Ri)}}}function Li(e){return{selectFile:async t=>{try{const n=(t==null?void 0:t.mimeTypes)??["*/*"],r=f.Platform.select({android:n,ios:void 0}),o=await e.pick({mode:"open",allowMultiSelection:t!=null&&t.selectionLimit?t.selectionLimit>1:!1,type:r});return(Array.isArray(o)?o:[o]).map(Pi)}catch(n){if(n&&typeof n=="object"&&"message"in n){const r=String(n.message).toLowerCase();if(r.includes("cancel")||r.includes("user cancelled"))return null;throw new Error(String(n.message))}throw new Error("File selection failed")}}}}function _n(e){return{uri:e.uri,type:e.mimeType||"image/jpeg",size:e.fileSize||0,name:e.fileName||"image.jpg",width:e.width,height:e.height}}function Ri(e){return{uri:e.uri,type:e.mimeType||"application/octet-stream",size:e.size||0,name:e.name}}function yn(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 Pi(e){return{uri:e.uri,type:e.type||"application/octet-stream",size:e.size||0,name:e.name||"document"}}function Di(e){return{keyValueStorage:{get:t=>e.getString(t)??null,set:(t,n)=>e.set(t,n),delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}}function Oi(){return{captureCamera:async()=>{throw new Error(le.IMAGE_PICKER_NOT_CONFIGURED)},selectFromGallery:async()=>{throw new Error(le.IMAGE_PICKER_NOT_CONFIGURED)}}}function Bi(){return{selectFile:async()=>{throw new Error(le.DOCUMENT_PICKER_NOT_CONFIGURED)}}}const{Provider:Ni,useContext:Kn}=j("NativeAdapter"),Yn=({config:e,children:t})=>{const n=d.useMemo(()=>{const{imagePicker:r,documentPicker:o,mmkv:s}=e,i=r?(Hi(e),"launchCameraAsync"in r?Ti(r):ki(r,e.permissions)):Oi(),l=o?"getDocumentAsync"in o?Mi(o):Li(o):Bi(),c=Di(s);return{...i,...l,...c}},[e.imagePicker,e.documentPicker,e.mmkv,e.permissions]);return a.createElement(Ni,{value:n},t)};function Hi(e){if(!e.imagePicker)return;if(!("launchCameraAsync"in e.imagePicker)&&!e.permissions)throw new Error("react-native-permissions is required when using react-native-image-picker. Please install react-native-permissions and provide it in nativeModules.permissions")}const zi=({onPressAddAttachment:e,disabled:t})=>a.createElement(P,{disabled:t,style:Fi.container,activeOpacity:.75,onPress:e},a.createElement(O,{type:"add",size:24,color:n=>t?n.textDisabled:n.primary})),Fi=f.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),$i=({name:e,type:t,url:n,onRemove:r})=>{const o=Ui.use();return a.createElement(y,{style:o.wrapper},Dr(t)?a.createElement(xe,{source:{uri:n},style:o.image,resizeMode:"cover"}):a.createElement(jt,{name:e,type:Ht(e,t)}),r&&a.createElement(P,{onPress:r,style:o.removeButton},a.createElement(O,{type:"remove",size:20,color:o.removeIcon.tintColor})))},ze=7,Ui=R.create(({themedColor:e})=>({wrapper:{marginTop:ze,marginRight:ze,flexShrink:0},image:{borderRadius:8,width:64,height:64},removeButton:{position:"absolute",top:-ze,right:-ze,width:22,height:22,borderRadius:11,borderColor:e.bg_50_600,backgroundColor:e.bg_50_600,alignItems:"center",justifyContent:"center"},removeIcon:{tintColor:e.textMidEmphasis}})),qi=e=>{const{theme:t,themedColor:n}=z(),r=Wi.use(),o=Wt.useTextAlign({text:e.value??e.placeholder,style:r.input,isTextInput:!0});return a.createElement(y,{style:r.container},e.attachments&&a.createElement(Wn,{horizontal:!0,flexDirection:"row",gap:8},e.attachments),a.createElement(y,null,a.createElement(f.TextInput,{multiline:!0,style:[r.input,{textAlign:o}],placeholderTextColor:e.editable?t.colors.messageInput.placeholderText:n.textDisabled,...e})))},Wi=R.create(({theme:e})=>({container:{backgroundColor:e.colors.messageInput.background,gap:16,flex:1,paddingHorizontal:16,paddingVertical:8,justifyContent:"center",borderRadius:20,minHeight:36},input:{...Vi(e.typography.body3),color:e.colors.messageInput.text,includeFontPadding:!1,padding:0,margin:0,textAlignVertical:"center"}}));function Vi(e){const t={maxHeight:52};return e.fontFamily&&(t.fontFamily=e.fontFamily),typeof e.fontSize=="number"&&(t.fontSize=e.fontSize,t.maxHeight=e.fontSize*3.5),typeof e.lineHeight=="number"&&(t.lineHeight=e.lineHeight,t.maxHeight=e.lineHeight*3.5),e.fontWeight&&(t.fontWeight=e.fontWeight),t}const Gi=({onPressSend:e})=>a.createElement(P,{style:ji.container,activeOpacity:.75,onPress:e},a.createElement(O,{type:"send",size:24})),ji=f.StyleSheet.create({container:{width:32,height:32,justifyContent:"center",alignItems:"center"}}),Ki=()=>{const e=Yi.use(),{aiAgentInfo:t,userSession:n}=J(),{messageSource:r,channelSource:o}=te(),[s,i]=d.useState(null),l=$t("special-notice",o.channel),c=d.useCallback(()=>o.channel?l?r.messages.some(u=>Ae(u,(n==null?void 0:n.userId)??"")):!0:null,[o.channel,l,r.messages,n==null?void 0:n.userId]);return d.useEffect(()=>{s||i(c())},[c,s]),s||!(t!=null&&t.specialNotice)?null:a.createElement(y,{style:e.container},a.createElement(Kt,{textStyle:e.text,linkStyle:e.link},(t==null?void 0:t.specialNotice)??""))},Yi=R.create(({theme:e,themedColor:t,select:n})=>({container:{backgroundColor:e.colors.base.background,paddingVertical:8,paddingHorizontal:16,alignItems:"center"},text:{...e.typography.body3,color:t.textLowEmphasis,textAlign:"center"},link:{fontWeight:"700",textDecorationLine:"none",color:n({light:e.palette.information.light,dark:e.palette.information.main})}})),Xi=()=>{var S;const{chatSDK:e}=U(),{strings:t}=H(),{createAttachmentRules:n}=J(),{channelSource:r,state:o}=te(),[s,i]=d.useState(""),[l,c]=d.useState([]),u=n({channel:r.channel,uploadSizeLimit:(S=e.appInfo)==null?void 0:S.uploadSizeLimit}),m=(b,E)=>{const v=E.filter(A=>u.isSupportedMimeType(A.type));if(v.length===0&&E.length>0)return f.Alert.alert("",t.conversation.file_upload_not_supported_file),b;const C=A=>{const w=u.getUploadSizeLimit(A.type);return A.size&&A.size>w},x=v.find(A=>C(A));if(x){const A=u.getUploadSizeLimitInMB(x.type);return f.Alert.alert("",t.conversation.file_upload_notification_size_limit(A)),b}return b.length+v.length>u.maxAttachmentCount?(f.Alert.alert("",t.conversation.file_upload_notification_count_limit(u.maxAttachmentCount)),b):[...b,...v]},h=b=>{c(E=>m(E,b))},g=b=>{c(E=>E.filter((v,C)=>C!==b))},_=()=>{c([])},p=(()=>{if(!o.input.disabled)return t.conversation.input_placeholder;switch(o.input.disabledBy){case"form_active":return t.conversation.input_placeholder_active_form;case"ai_responding":return t.conversation.input_placeholder_wait_ai_agent_response;case"reconnecting":return t.conversation.input_placeholder_reconnecting;case"unavailable":case"conversation_closed":default:return t.conversation.input_placeholder_disabled}})();return d.useEffect(()=>{o.input.disabled&&(i(""),_())},[o.input.disabled]),{files:l,addFiles:h,removeFile:g,clearFiles:_,value:s,onChangeText:i,editable:!o.input.disabled,placeholder:p,sendButtonVisible:!o.input.disabled&&(!!s.trim()||l.length>0),addAttachmentButtonVisible:u.isEnabled(),addAttachmentButtonDisabled:o.input.disabled||l.length>=u.maxAttachmentCount,hasImageMimeTypes:()=>u.supportedMimeTypes.filter(E=>E.startsWith("image/")||E===Sn).length>0,hasFileMimeTypes:()=>u.supportedMimeTypes.length>0,acceptableMimeTypes:u.supportedMimeTypes,maxAttachmentCount:u.maxAttachmentCount}},Zi=()=>{const{config:e}=U(),t=Kn(),{strings:n}=H(),{messageSource:r}=te(),{openModal:o}=Ye(),s=Ie(["left","right","bottom"]),i=Ji.use(),{maxAttachmentCount:l,sendButtonVisible:c,addAttachmentButtonVisible:u,addAttachmentButtonDisabled:m,acceptableMimeTypes:h,hasImageMimeTypes:g,hasFileMimeTypes:_,...p}=Xi(),E={...p,onPressAddAttachment:async()=>{const v=await o(C=>{var x,T,A,w,L,$,Y,q;return a.createElement(ee,{onClose:()=>C()},((A=(T=(x=e==null?void 0:e.conversation)==null?void 0:x.input)==null?void 0:T.camera)==null?void 0:A.photoEnabled)&&a.createElement(ee.ActionItem,{icon:"camera",label:n.conversation.attachment_camera,onPress:async()=>{if(!g())return f.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const K=await t.captureCamera();C(K)}}),(($=(L=(w=e==null?void 0:e.conversation)==null?void 0:w.input)==null?void 0:L.gallery)==null?void 0:$.photoEnabled)&&a.createElement(ee.ActionItem,{icon:"photo",label:n.conversation.attachment_photo,onPress:async()=>{if(!g())return f.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const K=await t.selectFromGallery({selectionLimit:l-p.files.length});C(K)}}),((q=(Y=e==null?void 0:e.conversation)==null?void 0:Y.input)==null?void 0:q.fileEnabled)&&a.createElement(ee.ActionItem,{icon:"document",label:n.conversation.attachment_document,onPress:async()=>{if(!_())return f.Alert.alert("",n.conversation.file_upload_no_supported_files),C(null);const K=await t.selectFile({selectionLimit:l-p.files.length,mimeTypes:h});C(K)}}))});v&&p.addFiles(v)},onPressSend:()=>{p.files.length>0?r.sendFileMessage({message:p.value.trim(),file:p.files[0]}):r.sendUserMessage({message:p.value}),p.clearFiles(),p.onChangeText("")}};return a.createElement(f.KeyboardAvoidingView,{behavior:"padding",keyboardVerticalOffset:-s.paddingBottom},a.createElement(Ki,null),a.createElement(y,{style:i.container(s)},u&&a.createElement(zi,{...E,disabled:m}),a.createElement(qi,{...E,value:E.editable?E.value:"",attachments:E.files.length===0?null:E.files.map((v,C)=>a.createElement($i,{key:C,name:v.name,type:v.type,url:v.uri,onRemove:()=>E.removeFile(C)}))}),c&&a.createElement(Gi,{...E})))},Ji=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})})),Xn=({start:e,title:t,titleAlign:n="start",end:r})=>{const o=Ie(["left","right","top"]),[s,i]=d.useState(0),[l,c]=d.useState(0),u=g=>{i(g.nativeEvent.layout.width)},m=g=>{c(g.nativeEvent.layout.width)},h=Qi.use();return a.createElement(y,{style:h.container},a.createElement(y,{height:o.paddingTop}),a.createElement(y,{style:h.contentContainer(o)},n==="center"&&t&&a.createElement(y,{style:h.centerTitleContainer(Math.max(s,l))},a.createElement(y,{style:h.centerTitle},t)),a.createElement(y,{style:h.rowContainer},a.createElement(y,{style:h.startSide,onLayout:u},e),(n==="start"||n==="end")&&t&&a.createElement(y,{style:h.titleSide(n,e,r)},t),a.createElement(y,{style:h.endSide,onLayout:m},r))))},Qi=R.create(({theme:e,themedColor:t})=>({container:{width:"100%",backgroundColor:e.colors.base.headerBackground,borderBottomWidth:1,borderBottomColor:t.textDisabled},contentContainer:n=>({position:"relative",height:56,paddingStart:n.paddingStart+12,paddingEnd:n.paddingEnd+12}),centerTitleContainer:n=>({position:"absolute",left:n,right:n,top:0,bottom:0,alignItems:"center",justifyContent:"center"}),centerTitle:{maxWidth:"100%",overflow:"hidden"},rowContainer:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",height:"100%",zIndex:1},startSide:{flexShrink:0},endSide:{flexShrink:0},titleSide:(n,r,o)=>({flex:1,overflow:"hidden",alignItems:`flex-${n}`,marginStart:r?8:0,marginEnd:o?8:0})})),el=()=>{const{themedColor:e}=z(),{onClose:t}=te();return t?a.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(O,{color:e.textHighEmphasis,type:"close",size:24})):null},tl=()=>{const{themedColor:e}=z(),{channelSource:{channel:t}}=te(),n=$t("handoff-button",t),r=!Cn(t)||Se(t);return n?a.createElement(P,{hitSlop:4,disabled:r,onPress:()=>t==null?void 0:t.markConversationAsHandoff(),activeOpacity:.75},a.createElement(O,{color:r?e.textDisabled:e.textHighEmphasis,type:"agent",size:24})):null},nl=()=>{const{themedColor:e}=z(),{onNavigateToConversationList:t}=te();return t?a.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(O,{color:e.textHighEmphasis,type:"menu",size:24})):null},Zn=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=J(),{fallbackIcon:o,url:s}=Ln({channel:e,aiAgentInfo:r,userSession:n}),{theme:i}=z();return s?a.createElement(qn,{src:s,size:t}):a.createElement(y,{width:t,height:t,borderRadius:t/2,alignItems:"center",justifyContent:"center",flexShrink:0,style:{backgroundColor:i.colors.base.primary}},a.createElement(O,{type:o,size:t*.55,color:i.colors.base.primaryContrastContent}))},rl=()=>{const{channelSource:{channel:e}}=te(),{userSession:t,aiAgentInfo:n}=J(),r=Ln({channel:e,userSession:t,aiAgentInfo:n});return a.createElement(y,{gap:6,flexDirection:"row",alignItems:"center",maxWidth:"100%"},a.createElement(Zn,{channel:e,size:34}),a.createElement(y,{flexShrink:1},a.createElement(k,{numberOfLines:1,variant:"h1"},r.title)))},ol=e=>{const{components:t}=pe.useContext();return a.createElement(Xn,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},sl=()=>{const{components:e}=pe.useContext();return a.createElement(e.MenuButton,null)},al=()=>{const{components:e}=pe.useContext();return a.createElement(e.Title,null)},il=()=>{const{components:e}=pe.useContext();return a.createElement(y,{flexDirection:"row",alignItems:"center",gap:10},a.createElement(e.HandoffButton,null),a.createElement(e.CloseButton,null))},pe=oe({template:ol,components:{StartArea:sl,TitleArea:al,EndArea:il,MenuButton:nl,Title:rl,HandoffButton:tl,CloseButton:el}}),ll=()=>{const{Template:e}=pe.useContext();return a.createElement(e,{titleAlign:"start"})},cl=e=>{const{components:t}=et.useContext();return a.createElement(y,{flex:1},a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},et=oe({template:cl,components:{Header:ll,Body:wi,Footer:Zi}}),Jn=({children:e,...t})=>{const{Template:n}=et.useContext();return a.createElement(Pn,{...t},a.createElement(n,null),e)},{Provider:ul,Context:dl,useContext:tt}=j("ConversationList"),Qn=({conversationListLimit:e,conversationListFilter:t,onNavigateToConversation:n,onClose:r,children:o})=>{const{sdkUser:s,authenticate:i}=J();return d.useEffect(()=>{s||i()},[]),a.createElement(Fo,{conversationListLimit:e,conversationListFilter:t},l=>a.createElement(ul,{value:{...l,onClose:r,onNavigateToConversation:n}},o))},bt=99,ml=d.memo(function(t){const{channel:n,onClick:r}=t,{strings:o,format:s}=H(),{themedColor:i}=z(),l=hl.use(),c=Mr(n),u=Lr(n,s,{justNow:o.date_format.just_now,minutesAgo:o.date_format.minutes_ago,hoursAgo:o.date_format.hours_ago,dateShortFormat:o.date_format.date_short}),m=n.unreadMessageCount;return a.createElement(P,{onPress:r,activeOpacity:.75},a.createElement(y,{flexDirection:"row",alignItems:"center",width:"100%",height:72,gap:16},a.createElement(y,{marginStart:16,alignItems:"center",justifyContent:"center"},a.createElement(Zn,{channel:n})),a.createElement(y,{flexDirection:"row",alignItems:"center",flex:1,paddingEnd:16,height:"100%",gap:8,style:l.rightContainer},a.createElement(y,{flexDirection:"column",justifyContent:"center",flex:1,gap:4},a.createElement(k,{variant:"subtitle1",color:i.textHighEmphasis,numberOfLines:1},c),a.createElement(y,{flexDirection:"row",alignItems:"center",gap:6},we(n)&&a.createElement(a.Fragment,null,a.createElement(k,{variant:"caption1",color:i.textMidEmphasis,numberOfLines:1},o.conversation_list.ended),a.createElement(y,{width:2,height:2,borderRadius:1,backgroundColor:i.textLowEmphasis})),a.createElement(k,{variant:"caption2",color:i.textLowEmphasis,numberOfLines:1},u))),m>0&&a.createElement(y,{alignItems:"center",justifyContent:"center",height:20,width:m<=bt?20:void 0,padding:4,borderRadius:10,backgroundColor:i.error},a.createElement(k,{variant:"caption3",color:i.textHighEmphasisInverse,style:{lineHeight:12}},m<=bt?m:`${bt}+`)))))}),gl=oe({template:ml,components:{}}),hl=R.create(({themedColor:e})=>({rightContainer:{borderBottomWidth:1,borderBottomColor:e.textDisabled}})),fl=()=>{var l;const{Template:e}=gl.useContext(),{strings:t}=H(),{connectionError:n}=J(),{listSource:r,onNavigateToConversation:o}=tt(),s=Ie(["left","right"]),i=pl.use();return a.createElement(Fn,{style:i.list,contentContainerStyle:[i.listContent,s],data:r.channels,onEndReached:r.loadMore,keyExtractor:d.useCallback(c=>c.url,[]),renderItem:d.useCallback(({item:c})=>a.createElement(e,{channel:c,onClick:()=>o==null?void 0:o(c.url,we(c)?"closed":"open")}),[e,o]),loading:!r.initialized,error:!!(n||r.error),LoadingComponent:a.createElement(ve,{type:"loading"}),EmptyComponent:a.createElement(ve,{type:"noChannels",label:t.common.placeholder_no_conversations}),ErrorComponent:a.createElement(ve,{type:"error",label:(n==null?void 0:n.message)??((l=r.error)==null?void 0:l.message)})})},pl=R.create(({theme:e})=>({list:{flex:1,backgroundColor:e.colors.base.background},listContent:{backgroundColor:e.colors.base.background}})),_l=()=>{const{strings:e}=H(),{language:t,countryCode:n,context:r}=U(),{aiAgentInfo:o,refreshActiveChannel:s,createConversation:i,setActiveChannel:l,sdkUser:c}=J(),{onNavigateToConversation:u}=tt(),m=Ie(["left","right","bottom"]),h=yl.use();return a.createElement(P,{activeOpacity:.75,disabled:!c,onPress:async()=>{if(o!=null&&o.isMultipleActiveConversationsEnabled){const g=await i({aiAgentId:o.userId,language:t,country:n,context:r});l({url:g,status:G.ConversationStatus.OPEN}),u==null||u(g,G.ConversationStatus.OPEN)}else{const g=await s();u==null||u(g,G.ConversationStatus.OPEN)}}},a.createElement(y,{alignItems:"center",justifyContent:"center",paddingHorizontal:16,height:64+m.paddingBottom,style:[h.container,m]},a.createElement(k,{variant:"h1",color:g=>g.textHighEmphasisInverse,numberOfLines:1},e.conversation_list.footer_title)))},yl=R.create(({themedColor:e})=>({container:{backgroundColor:e.primary}})),bl=()=>{const{aiAgentInfo:e}=J();return e?a.createElement(_l,null):null},El=()=>{const{themedColor:e}=z(),{onClose:t}=tt();return t?a.createElement(P,{hitSlop:4,onPress:t,activeOpacity:.75},a.createElement(O,{color:e.textHighEmphasis,type:"close",size:24})):null},Cl=()=>{const{strings:e}=H();return a.createElement(k,{numberOfLines:1,variant:"h1"},e.conversation_list.header_title)},vl=e=>{const{components:t}=Te.useContext();return a.createElement(Xn,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null)})},Sl=()=>null,Al=()=>{const{components:e}=Te.useContext();return a.createElement(e.Title,null)},xl=()=>{const{components:e}=Te.useContext();return a.createElement(e.CloseButton,null)},Te=oe({template:vl,components:{StartArea:Sl,TitleArea:Al,EndArea:xl,Title:Cl,CloseButton:El}}),wl=()=>{const{Template:e}=Te.useContext();return a.createElement(e,{titleAlign:"start"})},Il=()=>{const{components:e}=nt.useContext();return a.createElement(y,{flex:1},a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},nt=oe({template:Il,components:{Header:wl,Body:fl,Footer:bl}}),er=({children:e,...t})=>{const{Template:n}=nt.useContext();return a.createElement(Qn,{...t},a.createElement(n,null),e)},Tl="1.0.1",kl=Tl,Ml=d.forwardRef(function({logLevel:t=V.LogLevel.WARN,language:n=Ke,userSessionInfo:r,children:o,strings:s,...i},l){const[c]=d.useState(()=>new wn(t));c.level!==t&&(c.level=t);const{nativeModules:u,chatParams:m={},...h}=i;return a.createElement(Yn,{config:u},({keyValueStorage:g})=>a.createElement(Rl,{logger:c,theme:h.theme,language:n,strings:s},a.createElement(Kr,{language:n,logger:c,chatSDK:h.customChatSDK,keyValueStorage:g,chatParams:{...m,useMMKVStorageStore:u.mmkv},messengerVersion:kl,extensions:{platform:V.SendbirdPlatform.REACT_NATIVE,deviceOSPlatform:f.Platform.select({web:V.DeviceOsPlatform.WEB,ios:V.DeviceOsPlatform.IOS,default:V.DeviceOsPlatform.ANDROID})},...h},a.createElement(is,{ref:l,userSessionInfo:r},o))))}),Ll=wr(et,pe,nt,Te,Gt,Xe,Ze,Je,Qe),Rl=({children:e,logger:t,theme:n,language:r,strings:o})=>a.createElement(fe.SafeAreaProvider,null,a.createElement(qs,{logger:t,...n},a.createElement(Fs,{language:r,logger:t,strings:o},a.createElement(Dn,null,a.createElement(qo,null,a.createElement(Ll,null,e)))))),{Provider:Pl,useContext:Yt}=j("FixedMessengerStyle"),Dl={useNativeDriver:!0},Fe={OPEN_START:"0deg",OPEN_END:"-180deg",CLOSE_START:"180deg",CLOSE_END:"0deg"},$e={VISIBLE:1,HIDDEN:0},Ol=({isOpened:e})=>{const t=d.useRef(new f.Animated.Value(e?1:0)).current;d.useEffect(()=>{const o=e?1:0;f.Animated.spring(t,{toValue:o,...Dl}).start()},[e,t]);const n={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[Fe.OPEN_START,Fe.OPEN_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[$e.VISIBLE,$e.HIDDEN]})}]},r={transform:[{rotate:t.interpolate({inputRange:[0,1],outputRange:[Fe.CLOSE_START,Fe.CLOSE_END]})},{scale:t.interpolate({inputRange:[0,1],outputRange:[$e.HIDDEN,$e.VISIBLE]})}]};return{openIconStyle:n,closeIconStyle:r}},Bl=2/3,Nl=({isOpened:e,onPress:t})=>{const n=Fl.use(),{launcherInfo:r}=J(),{theme:o}=z(),{launcherSize:s,horizontal:i}=Yt(),l=Math.round(s*Bl),c=o.colors.base.primary,u=o.colors.base.primaryContrastContent,{openIconStyle:m,closeIconStyle:h}=Ol({isOpened:e});return a.createElement(y,{alignSelf:i==="start"?"flex-start":"flex-end"},a.createElement(P,{onPress:t,activeOpacity:.8},({pressed:g})=>a.createElement(y,{style:[n.container({backgroundColor:c,size:s}),g&&n.pressed]},a.createElement(y.Animated,{style:[n.iconWrapper,m]},a.createElement(Hl,{url:(r==null?void 0:r.imageUrl)??"",isDefaultIcon:(r==null?void 0:r.type)==="default_icon",size:l,fillColor:u})),a.createElement(y.Animated,{style:[n.iconWrapper,h]},a.createElement(zl,{size:l,fillColor:u})))))},Hl=({url:e,isDefaultIcon:t,size:n,fillColor:r})=>e?t?a.createElement(xe,{source:{uri:e},width:n,height:n,tintColor:r,resizeMode:"contain"}):a.createElement(xe,{source:{uri:e},width:n,height:n,resizeMode:"cover"}):a.createElement(O,{type:"delight",size:n,color:r}),zl=({size:e,fillColor:t})=>a.createElement(O,{type:"chevron-down",size:e,color:t}),Fl=R.create(()=>({container:e=>({position:"relative",width:e.size,height:e.size,backgroundColor:e.backgroundColor,borderRadius:e.size/2,justifyContent:"center",alignItems:"center",boxShadow:"0px 8px 16px 0px rgba(33, 33, 33, 0.3)"}),pressed:{transform:[{scale:.9}]},iconWrapper:{position:"absolute",width:"100%",height:"100%",justifyContent:"center",alignItems:"center"}})),Q={TRANSLATE_OFFSET:40,DURATION:300,OPACITY_DURATION:83,EASING:f.Easing.out(f.Easing.ease)},$l=e=>e==="entered"?0:Q.TRANSLATE_OFFSET,Ul=e=>e==="entered"?1:0,ql=({transitionState:e,isActive:t})=>{const[n,r]=d.useState(!1),o=d.useRef(new f.Animated.Value($l(e))).current,s=d.useRef(new f.Animated.Value(Ul(e))).current;return d.useEffect(()=>{if(!n){e==="entered"?(o.setValue(0),s.setValue(1)):e==="exited"&&(o.setValue(Q.TRANSLATE_OFFSET),s.setValue(0)),r(!0);return}e==="entering"?(o.setValue(Q.TRANSLATE_OFFSET),s.setValue(0),f.Animated.parallel([f.Animated.timing(o,{toValue:0,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),f.Animated.timing(s,{toValue:1,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()):e==="exiting"&&f.Animated.parallel([f.Animated.timing(o,{toValue:Q.TRANSLATE_OFFSET,duration:Q.DURATION,easing:Q.EASING,useNativeDriver:!0}),f.Animated.timing(s,{toValue:0,duration:Q.OPACITY_DURATION,easing:Q.EASING,useNativeDriver:!0})]).start()},[e,o,s,n]),d.useMemo(()=>({position:"absolute",top:0,left:0,width:"100%",height:"100%",transform:[{translateY:o}],opacity:s,zIndex:t?999:1,pointerEvents:t?"auto":"none",display:e==="exited"?"none":"flex"}),[o,s,t,e])},tr=d.createContext(null),Wl=()=>{const e=d.useContext(tr);if(!e)throw new Error("useNavigatorContext() must be used within <Navigator />");return e},nr=({children:e})=>{const t=Wl();return typeof e=="function"?a.createElement(a.Fragment,null,e(t)):a.createElement(a.Fragment,null,e)},Vl=d.memo(({transitionState:e,isActive:t,children:n})=>{const r=ql({transitionState:e,isActive:t});return a.createElement(f.Animated.View,{style:r},n)}),bn=300,qe=({initialId:e,children:t})=>{const[n,r]=d.useState([e]),o=n[n.length-1],s=d.useCallback((b,E)=>{r(v=>[...v,b]),h(v=>({...v,[b]:!0})),E!=null&&E.reset&&S(v=>({...v,[b]:(v[b]||0)+1})),_(v=>({...v,[b]:"entering"})),setTimeout(()=>{_(v=>({...v,[b]:"entered"}))},bn)},[]),i=d.useCallback(()=>{r(b=>{if(b.length<=1)return b;const E=b[b.length-1];return _(v=>({...v,[E]:"exiting"})),setTimeout(()=>{_(v=>({...v,[E]:"exited"})),r(v=>v.slice(0,-1))},bn),b})},[]),l=d.useMemo(()=>({navigation:{navigate:s,pop:i},activeScreenId:o}),[s,i,o]),c=d.useMemo(()=>d.Children.toArray(t).filter(b=>b.type===nr),[t]),u=d.useMemo(()=>{const b={};return c.forEach(E=>{const{id:v,lazy:C,children:x}=E.props;b[v]={lazy:C,element:typeof x=="function"?x(l):x}}),b},[c,l]),[m,h]=d.useState(()=>{const b={};return Object.entries(u).forEach(([E,{lazy:v}])=>{v===!1&&(b[E]=!0)}),b[e]=!0,b}),[g,_]=d.useState(()=>{const b={};return Object.keys(u).forEach(E=>{b[E]=E===e?"entered":"exited"}),b}),[p,S]=d.useState({});return a.createElement(tr.Provider,{value:l},a.createElement(y,{style:{position:"relative",width:"100%",height:"100%"}},Object.keys(u).map(b=>{var x;if(!m[b])return null;const E=g[b]||"exited",v=b===o,C=`${b}-${p[b]||0}`;return a.createElement(Vl,{key:C,transitionState:E,isActive:v},(x=u[b])==null?void 0:x.element)})))};qe.Screen=nr;const{Provider:Gl,useContext:Xt}=j("PageChildren"),jl=({children:e})=>{const[t,n]=d.useState(null),[r,o]=d.useState(null);return a.createElement(Gl,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:o}},e)},he={conv:"conv",convList:"conv-list"},Kl=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onClose:o})=>{const{conversationChildren:s,conversationListChildren:i}=Xt(),l=t==="ConversationList"?he.convList:he.conv;return a.createElement(qe,{initialId:l},a.createElement(qe.Screen,{id:he.conv},({navigation:c,activeScreenId:u})=>a.createElement(Jn,{channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>c.navigate(he.convList),onClose:o,shouldMarkAsRead:e&&u===he.conv},s)),a.createElement(qe.Screen,{id:he.convList,lazy:!0},({navigation:c})=>a.createElement(er,{onNavigateToConversation:u=>{r(u),c.navigate(he.conv,{reset:!0})},onClose:o},i)))},De=.15,Yl=150,En=(e,t)=>e.interpolate({inputRange:[De,1],outputRange:[t,0],extrapolate:"clamp"}),Xl=(e,t)=>{if(e<=0)return 0;const n=(1-De)*e/2,r=t==="start"?-1:1,o=f.I18nManager.isRTL?-1:1;return n*r*o},Zl=(e,t)=>e<=0?0:(1-De)*e/2*(t==="top"?-1:1),Jl=({isOpened:e,horizontal:t,vertical:n})=>{const[r,o]=d.useState({width:0,height:0}),s=d.useRef(new f.Animated.Value(e?1:De)).current,i=d.useRef(new f.Animated.Value(e?1:0)).current,l=d.useMemo(()=>Xl(r.width,t),[r.width,t]),c=d.useMemo(()=>Zl(r.height,n),[r.height,n]),{translateXInterpolation:u,translateYInterpolation:m}=d.useMemo(()=>({translateXInterpolation:En(s,l),translateYInterpolation:En(s,c)}),[s,l,c]);d.useEffect(()=>{const _=e?"open":"close",p=_==="open"?1:De,S=_==="open"?1:0,b=_==="open"?f.Easing.out(f.Easing.quad):f.Easing.in(f.Easing.quad),E={duration:Yl,useNativeDriver:!0,easing:b};_==="close"&&f.Keyboard.dismiss(),f.Animated.parallel([f.Animated.timing(s,{toValue:p,...E}),f.Animated.timing(i,{toValue:S,...E})]).start()},[e,s,i]);const h=d.useMemo(()=>({opacity:i,transform:[{translateX:u},{translateY:m},{scale:s}]}),[i,u,m,s]),g=d.useMemo(()=>_=>{const{width:p,height:S}=_.nativeEvent.layout;o(b=>b.width===p&&b.height===S?b:{width:p,height:S})},[]);return{animatedStyle:h,handleLayout:g,pointerEvents:e?"auto":"none"}},Ql={top:0,left:0,right:0,bottom:0},ec=({children:e,isOpened:t})=>{const n=tc.use(),{horizontal:r,vertical:o}=Yt(),{animatedStyle:s,handleLayout:i,pointerEvents:l}=Jl({isOpened:t,horizontal:r,vertical:o});return a.createElement(fe.SafeAreaInsetsContext.Provider,{value:Ql},a.createElement(y,{flex:1},a.createElement(y.Animated,{pointerEvents:l,onLayout:i,style:s},a.createElement(y,{style:n.windowContainer},e))))},tc=R.create(({theme:e})=>({windowContainer:{width:"100%",height:"100%",borderRadius:16,overflow:"hidden",zIndex:999,backgroundColor:e.colors.base.background,boxShadow:"0px 4px 24px 0px rgba(0, 0, 0, 0.12)"}})),rr=()=>{const[e,t]=d.useState(0);return d.useEffect(()=>{const n=f.Platform.OS==="ios"?"keyboardWillShow":"keyboardDidShow",r=f.Platform.OS==="ios"?"keyboardWillHide":"keyboardDidHide",o=f.Keyboard.addListener(n,i=>{const{endCoordinates:l}=i,c=(l==null?void 0:l.height)||0;t(c)}),s=f.Keyboard.addListener(r,()=>{t(0)});return()=>{o.remove(),s.remove()}},[]),e},nc=e=>{const t=d.useRef(new f.Animated.Value(0)).current,[n,r]=d.useState(!1);return d.useEffect(()=>{const s=e?"open":"close",i={toValue:s==="open"?1:0,useNativeDriver:!0,duration:300};s==="open"&&r(!0),f.Animated.timing(t,i).start(()=>{s==="close"&&(r(!1),f.Keyboard.dismiss())})},[e,t]),{windowAnimatedStyle:{opacity:t,display:n?"flex":"none"},pointerEvents:e?"auto":"none"}},rc=({children:e,insets:t,isOpened:n})=>{const r=oc.use(),s={...fe.useSafeAreaInsets(),...t},i=rr(),{windowAnimatedStyle:l,pointerEvents:c}=nc(n);return a.createElement(fe.SafeAreaInsetsContext.Provider,{value:s},a.createElement(y.Animated,{flex:1,style:[r.bg,l],pointerEvents:c},a.createElement(y,{flex:1},e),a.createElement(y,{height:Math.max(0,i-f.Platform.select({android:0,default:s.bottom})),style:r.bg})))},oc=R.create(({theme:e})=>({bg:{backgroundColor:e.colors.base.background}})),sc="end-bottom",Re={top:24,bottom:24,start:24,end:24},ac=({mode:e,edgeToEdgeEnabled:t})=>{const n=e==="floating"?ec:rc,[r,o]=At({position:sc,margin:Re,launcherSize:48,spacing:12}),{bottom:s}=fe.useSafeAreaInsets(),i=rr(),[l,c]=r.position.split("-"),u=(()=>{const g=f.Platform.select({android:t?s:0,default:0}),_=c==="top"?r.spacing:-r.launcherSize,p=i>0?i+_+g:0;return p>0?p:r.margin.bottom})(),m={position:"absolute",zIndex:1e3,...c==="top"?{top:r.margin.top}:{bottom:r.margin.bottom},...l==="start"?{left:r.margin.start}:{right:r.margin.end}},h=(()=>{if(e==="floating"){const g=r.launcherSize+r.spacing;return{position:"absolute",top:r.margin.top+(c==="top"?g:0),bottom:u+(c==="bottom"?g:0),left:r.margin.start,right:r.margin.end,zIndex:999}}return{position:"absolute",top:0,bottom:0,left:0,right:0,zIndex:1001}})();return{Window:n,windowContainerStyle:h,launcherContainerStyle:m,styleContext:{...r,horizontal:l,vertical:c,setPosition:g=>o({position:g}),setMargin:({top:g=Re.top,bottom:_=Re.bottom,start:p=Re.start,end:S=Re.end})=>o({margin:{top:g,bottom:_,start:p,end:S}}),setLauncherSize:g=>o({launcherSize:g}),setSpacing:g=>o({spacing:g})}}},ic=e=>{var s,i,l,c;const{setPosition:t,setMargin:n,setLauncherSize:r,setSpacing:o}=Yt();return d.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n(e.margin),e.launcherSize!==void 0&&r(e.launcherSize),e.spacing!==void 0&&o(e.spacing)},[e.position,(s=e.margin)==null?void 0:s.top,(i=e.margin)==null?void 0:i.bottom,(l=e.margin)==null?void 0:l.start,(c=e.margin)==null?void 0:c.end,e.launcherSize,e.spacing]),null},lc=({children:e})=>{const{setConversationChildren:t}=Xt();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},cc=({children:e})=>{const{setConversationListChildren:t}=Xt();return d.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},uc=({entryPoint:e="Conversation",edgeToEdgeEnabled:t=!0,windowMode:n="floating",fullscreenInsets:r,initialChannelUrl:o,windowContainerProps:s,children:i})=>{const[l,c]=d.useState(!1),[u,m]=d.useState(o),{Window:h,windowContainerStyle:g,launcherContainerStyle:_,styleContext:p}=ac({mode:n,edgeToEdgeEnabled:t});return d.useEffect(()=>{const S=f.BackHandler.addEventListener("hardwareBackPress",()=>l?(c(!1),!0):!1);return()=>S.remove()},[l]),a.createElement(Pl,{value:p},a.createElement(jl,null,a.createElement(y,{style:g,backgroundColor:"transparent",pointerEvents:l?"auto":"box-none",...s},a.createElement(h,{isOpened:l,insets:r},a.createElement(Kl,{isOpened:l,entryPoint:e,selectedChannelUrl:u,setSelectedChannelUrl:m,onClose:()=>c(!1)}))),a.createElement(y,{style:_,backgroundColor:"transparent",pointerEvents:"box-none"},a.createElement(Nl,{isOpened:l,onPress:()=>c(!l)})),i))},dc=Object.assign(uc,{Style:ic,ConversationChildren:lc,ConversationListChildren:cc});exports.AIAgentProviderContainer=Ml;exports.AnonymousSessionInfo=Ve;exports.BottomSheet=ee;exports.BottomSheetLayout=Xe;exports.Conversation=Jn;exports.ConversationContext=ps;exports.ConversationContextProvider=Pn;exports.ConversationHeaderLayout=pe;exports.ConversationLayout=et;exports.ConversationList=er;exports.ConversationListContext=dl;exports.ConversationListContextProvider=Qn;exports.ConversationListHeaderLayout=Te;exports.ConversationListLayout=nt;exports.FixedMessenger=dc;exports.IncomingMessageLayout=Ze;exports.ManualSessionInfo=Ft;exports.ModalProvider=Dn;exports.NativeAdapterProvider=Yn;exports.OutgoingMessageLayout=Je;exports.SystemMessageLayout=Qe;exports.useConversationContext=te;exports.useConversationListContext=tt;exports.useMessengerSessionContext=J;exports.useModalContext=Ye;exports.useNativeAdapterContext=Kn;
|
package/dist/index.d.ts
CHANGED
|
@@ -336,6 +336,10 @@ declare interface AIAgentStringSet {
|
|
|
336
336
|
failed_message_remove: string;
|
|
337
337
|
|
|
338
338
|
file_upload_no_supported_files: string;
|
|
339
|
+
|
|
340
|
+
// Accessibility
|
|
341
|
+
a11y_message_list: string;
|
|
342
|
+
a11y_scroll_to_bottom: string;
|
|
339
343
|
};
|
|
340
344
|
|
|
341
345
|
conversation_list: {
|
|
@@ -1803,7 +1807,7 @@ declare type SystemMessageUnion =
|
|
|
1803
1807
|
csatReason?: string;
|
|
1804
1808
|
csatExpireAt?: number;
|
|
1805
1809
|
isResolvedWhenDeterminedByUser?: boolean;
|
|
1806
|
-
onSubmitCSAT: (params: CSATSubmitParams) => void
|
|
1810
|
+
onSubmitCSAT: (params: CSATSubmitParams) => Promise<void>;
|
|
1807
1811
|
}>;
|
|
1808
1812
|
|
|
1809
1813
|
declare type TextField = {
|
package/dist/index.js
CHANGED
|
@@ -1950,7 +1950,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
1950
1950
|
start_new_conversation_label: "Start a conversation",
|
|
1951
1951
|
failed_message_resend: "Retry",
|
|
1952
1952
|
failed_message_remove: "Remove",
|
|
1953
|
-
file_upload_no_supported_files: "No supported file types available."
|
|
1953
|
+
file_upload_no_supported_files: "No supported file types available.",
|
|
1954
|
+
// Accessibility
|
|
1955
|
+
a11y_message_list: "Chat messages",
|
|
1956
|
+
a11y_scroll_to_bottom: "Scroll to bottom"
|
|
1954
1957
|
},
|
|
1955
1958
|
conversation_list: {
|
|
1956
1959
|
header_title: "Conversations",
|
|
@@ -2015,7 +2018,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2015
2018
|
start_new_conversation_label: "대화 시작",
|
|
2016
2019
|
failed_message_resend: "다시 시도",
|
|
2017
2020
|
failed_message_remove: "삭제",
|
|
2018
|
-
file_upload_no_supported_files: "사용 가능한 지원 파일 형식이 없습니다."
|
|
2021
|
+
file_upload_no_supported_files: "사용 가능한 지원 파일 형식이 없습니다.",
|
|
2022
|
+
// Accessibility
|
|
2023
|
+
a11y_message_list: "채팅 메시지",
|
|
2024
|
+
a11y_scroll_to_bottom: "맨 아래로 스크롤"
|
|
2019
2025
|
},
|
|
2020
2026
|
conversation_list: {
|
|
2021
2027
|
header_title: "대화",
|
|
@@ -2080,7 +2086,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2080
2086
|
start_new_conversation_label: "会話を始める",
|
|
2081
2087
|
failed_message_resend: "再試行",
|
|
2082
2088
|
failed_message_remove: "削除",
|
|
2083
|
-
file_upload_no_supported_files: "サポートされているファイルタイプがありません。"
|
|
2089
|
+
file_upload_no_supported_files: "サポートされているファイルタイプがありません。",
|
|
2090
|
+
// Accessibility
|
|
2091
|
+
a11y_message_list: "チャットメッセージ",
|
|
2092
|
+
a11y_scroll_to_bottom: "一番下にスクロール"
|
|
2084
2093
|
},
|
|
2085
2094
|
conversation_list: {
|
|
2086
2095
|
header_title: "会話",
|
|
@@ -2145,7 +2154,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2145
2154
|
start_new_conversation_label: "Iniciar una conversación",
|
|
2146
2155
|
failed_message_resend: "Reintentar",
|
|
2147
2156
|
failed_message_remove: "Eliminar",
|
|
2148
|
-
file_upload_no_supported_files: "No hay tipos de archivo compatibles disponibles."
|
|
2157
|
+
file_upload_no_supported_files: "No hay tipos de archivo compatibles disponibles.",
|
|
2158
|
+
// Accessibility
|
|
2159
|
+
a11y_message_list: "Mensajes del chat",
|
|
2160
|
+
a11y_scroll_to_bottom: "Desplazarse hacia abajo"
|
|
2149
2161
|
},
|
|
2150
2162
|
conversation_list: {
|
|
2151
2163
|
header_title: "Conversaciones",
|
|
@@ -2210,7 +2222,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2210
2222
|
start_new_conversation_label: "Iniciar uma conversa",
|
|
2211
2223
|
failed_message_resend: "Tentar novamente",
|
|
2212
2224
|
failed_message_remove: "Remover",
|
|
2213
|
-
file_upload_no_supported_files: "Nenhum tipo de arquivo suportado disponível."
|
|
2225
|
+
file_upload_no_supported_files: "Nenhum tipo de arquivo suportado disponível.",
|
|
2226
|
+
// Accessibility
|
|
2227
|
+
a11y_message_list: "Mensagens do chat",
|
|
2228
|
+
a11y_scroll_to_bottom: "Rolar para baixo"
|
|
2214
2229
|
},
|
|
2215
2230
|
conversation_list: {
|
|
2216
2231
|
header_title: "Conversas",
|
|
@@ -2275,7 +2290,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2275
2290
|
start_new_conversation_label: "Démarrer une conversation",
|
|
2276
2291
|
failed_message_resend: "Réessayer",
|
|
2277
2292
|
failed_message_remove: "Supprimer",
|
|
2278
|
-
file_upload_no_supported_files: "Aucun type de fichier pris en charge disponible."
|
|
2293
|
+
file_upload_no_supported_files: "Aucun type de fichier pris en charge disponible.",
|
|
2294
|
+
// Accessibility
|
|
2295
|
+
a11y_message_list: "Messages du chat",
|
|
2296
|
+
a11y_scroll_to_bottom: "Faire défiler vers le bas"
|
|
2279
2297
|
},
|
|
2280
2298
|
conversation_list: {
|
|
2281
2299
|
header_title: "Conversations",
|
|
@@ -2340,7 +2358,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2340
2358
|
start_new_conversation_label: "एक बातचीत शुरू करें",
|
|
2341
2359
|
failed_message_resend: "पुनः प्रयास करें",
|
|
2342
2360
|
failed_message_remove: "हटाएं",
|
|
2343
|
-
file_upload_no_supported_files: "कोई समर्थित फ़ाइल प्रकार उपलब्ध नहीं हैं।"
|
|
2361
|
+
file_upload_no_supported_files: "कोई समर्थित फ़ाइल प्रकार उपलब्ध नहीं हैं।",
|
|
2362
|
+
// Accessibility
|
|
2363
|
+
a11y_message_list: "चैट संदेश",
|
|
2364
|
+
a11y_scroll_to_bottom: "नीचे स्क्रॉल करें"
|
|
2344
2365
|
},
|
|
2345
2366
|
conversation_list: {
|
|
2346
2367
|
header_title: "बातचीत",
|
|
@@ -2405,7 +2426,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2405
2426
|
start_new_conversation_label: "Inizia una conversazione",
|
|
2406
2427
|
failed_message_resend: "Riprova",
|
|
2407
2428
|
failed_message_remove: "Rimuovi",
|
|
2408
|
-
file_upload_no_supported_files: "Nessun tipo di file supportato disponibile."
|
|
2429
|
+
file_upload_no_supported_files: "Nessun tipo di file supportato disponibile.",
|
|
2430
|
+
// Accessibility
|
|
2431
|
+
a11y_message_list: "Messaggi della chat",
|
|
2432
|
+
a11y_scroll_to_bottom: "Scorri in basso"
|
|
2409
2433
|
},
|
|
2410
2434
|
conversation_list: {
|
|
2411
2435
|
header_title: "Conversazioni",
|
|
@@ -2470,7 +2494,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2470
2494
|
start_new_conversation_label: "Ein Gespräch starten",
|
|
2471
2495
|
failed_message_resend: "Erneut versuchen",
|
|
2472
2496
|
failed_message_remove: "Entfernen",
|
|
2473
|
-
file_upload_no_supported_files: "Keine unterstützten Dateitypen verfügbar."
|
|
2497
|
+
file_upload_no_supported_files: "Keine unterstützten Dateitypen verfügbar.",
|
|
2498
|
+
// Accessibility
|
|
2499
|
+
a11y_message_list: "Chat-Nachrichten",
|
|
2500
|
+
a11y_scroll_to_bottom: "Nach unten scrollen"
|
|
2474
2501
|
},
|
|
2475
2502
|
conversation_list: {
|
|
2476
2503
|
header_title: "Gespräche",
|
|
@@ -2535,7 +2562,10 @@ const Ps = /* @__PURE__ */ new Set(["free_text", "single_choice"]), Os = ({ csat
|
|
|
2535
2562
|
start_new_conversation_label: "Bir sohbet başlat",
|
|
2536
2563
|
failed_message_resend: "Tekrar dene",
|
|
2537
2564
|
failed_message_remove: "Kaldır",
|
|
2538
|
-
file_upload_no_supported_files: "Desteklenen dosya türü mevcut değil."
|
|
2565
|
+
file_upload_no_supported_files: "Desteklenen dosya türü mevcut değil.",
|
|
2566
|
+
// Accessibility
|
|
2567
|
+
a11y_message_list: "Sohbet mesajları",
|
|
2568
|
+
a11y_scroll_to_bottom: "Aşağı kaydır"
|
|
2539
2569
|
},
|
|
2540
2570
|
conversation_list: {
|
|
2541
2571
|
header_title: "Görüşmeler",
|
|
@@ -4911,8 +4941,8 @@ const Ni = ({
|
|
|
4911
4941
|
{
|
|
4912
4942
|
activeOpacity: 0.75,
|
|
4913
4943
|
disabled: g === "submitted",
|
|
4914
|
-
onPress: () => {
|
|
4915
|
-
!En(s) && p() ? n(m) : l((h) => h + 1);
|
|
4944
|
+
onPress: async () => {
|
|
4945
|
+
!En(s) && p() ? await n(m) : l((h) => h + 1);
|
|
4916
4946
|
},
|
|
4917
4947
|
style: u.submitButton(g)
|
|
4918
4948
|
},
|
|
@@ -5044,9 +5074,9 @@ const Ni = ({
|
|
|
5044
5074
|
...C,
|
|
5045
5075
|
messageType: "admin.csat",
|
|
5046
5076
|
isResolvedWhenDeterminedByUser: _o(C),
|
|
5047
|
-
onSubmitCSAT: ({ csat: fe, ...Ae }) => {
|
|
5077
|
+
onSubmitCSAT: async ({ csat: fe, ...Ae }) => {
|
|
5048
5078
|
var _e;
|
|
5049
|
-
fe && ((_e = p.channel) == null
|
|
5079
|
+
fe && await ((_e = p.channel) == null ? void 0 : _e.submitCSAT({ csat: fe, ...Ae }));
|
|
5050
5080
|
}
|
|
5051
5081
|
}
|
|
5052
5082
|
) : null : /* @__PURE__ */ a.createElement(r, { ...te, messageType: "admin" });
|
|
@@ -6013,7 +6043,7 @@ const Hl = ({ onPressSend: e }) => /* @__PURE__ */ a.createElement(O, { style: z
|
|
|
6013
6043
|
}), vc = ({ children: e, ...t }) => {
|
|
6014
6044
|
const { Template: n } = gn.useContext();
|
|
6015
6045
|
return /* @__PURE__ */ a.createElement(oc, { ...t }, /* @__PURE__ */ a.createElement(n, null), e);
|
|
6016
|
-
}, Cc = "1.0.
|
|
6046
|
+
}, Cc = "1.0.1", Sc = Cc, Lu = ot(
|
|
6017
6047
|
function({
|
|
6018
6048
|
logLevel: t = Wr.WARN,
|
|
6019
6049
|
language: n = lt,
|
|
@@ -6392,15 +6422,7 @@ const {
|
|
|
6392
6422
|
horizontal: r,
|
|
6393
6423
|
vertical: o
|
|
6394
6424
|
});
|
|
6395
|
-
return /* @__PURE__ */ a.createElement(Wn.Provider, { value: qc }, /* @__PURE__ */ a.createElement(f, { flex: 1 }, /* @__PURE__ */ a.createElement(
|
|
6396
|
-
f.Animated,
|
|
6397
|
-
{
|
|
6398
|
-
pointerEvents: l,
|
|
6399
|
-
onLayout: i,
|
|
6400
|
-
style: [n.windowContainer, s]
|
|
6401
|
-
},
|
|
6402
|
-
e
|
|
6403
|
-
)));
|
|
6425
|
+
return /* @__PURE__ */ a.createElement(Wn.Provider, { value: qc }, /* @__PURE__ */ a.createElement(f, { flex: 1 }, /* @__PURE__ */ a.createElement(f.Animated, { pointerEvents: l, onLayout: i, style: s }, /* @__PURE__ */ a.createElement(f, { style: n.windowContainer }, e))));
|
|
6404
6426
|
}, Kc = P.create(({ theme: e }) => ({
|
|
6405
6427
|
windowContainer: {
|
|
6406
6428
|
width: "100%",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sendbird/ai-agent-messenger-react-native",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "Delight AI Agent Messenger for React Native",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"react-native-safe-area-context": "^5.6.1",
|
|
68
68
|
"typescript": "^5.9.2",
|
|
69
69
|
"vite-plugin-static-copy": "^3.1.4",
|
|
70
|
-
"@sendbird/ai-agent-core": "1.10.
|
|
70
|
+
"@sendbird/ai-agent-core": "1.10.3",
|
|
71
71
|
"@sendbird/vite-tools": "0.0.1"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|