@sendbird/ai-agent-messenger-react 1.42.0 → 1.43.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 CHANGED
@@ -1,20 +1,20 @@
1
- "use strict";var Jc=Object.defineProperty;var Qc=(e,t,n)=>t in e?Jc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var C=(e,t,n)=>Qc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=require("@sendbird/chat"),l=require("react"),F=require("styled-components"),ft=require("date-fns"),el=require("date-fns/locale/en-US"),we=require("@sendbird/chat/message"),Ce=require("@sendbird/chat/aiAgent"),tl=require("react-dom"),rt=require("@sendbird/chat/groupChannel"),nl=require("date-fns/isSameDay"),_i=e=>e&&e.__esModule?e:{default:e};function rl(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 sl=_i(_e),a=rl(l),S=_i(F),Ci=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Si=e=>{const t=Ci(e);return typeof t=="object"&&t!==null?t:{}},vi=e=>typeof e=="string"?Si(e):e??{},ol=e=>!!vi(e).stream,Fs=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},Zr=e=>{const t=vi(e),n=Fs(t.user_message_id)??Fs(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},wt="sb-agent",bi="KEY_IMG_ASPECT_RATIO",xr="*/*",re={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var wn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(wn||{}),Qt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Qt||{});const il=e=>!!(e!=null&&e.cta_button),al=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},yi=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,cl=e=>{var t;return yi(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},ll=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Je=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},sn=e=>Object.defineProperties({},{hasMessageTemplate:Je(()=>!!(e!=null&&e.message_template)),hasCTAButton:Je(()=>il(e)),hasChallenge:Je(()=>!!(e!=null&&e.challenge)),isThinking:Je(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Je(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Je(()=>ll(e)),hasCustomMessageTemplates:Je(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Je(()=>yi(e)),hasActiveForm:Je(()=>cl(e)),hasSteward:Je(()=>!!(e!=null&&e.steward)),hasCitations:Je(()=>al(e))}),ul=e=>{const t=sn(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Ai=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},dl=e=>e===Qt.COMPLETED||e===Qt.CANCELED?e:Qt.IN_PROGRESS,ir=e=>Xe(e)&&!Ai(e),Xe=e=>!!e&&"sender"in e,ml=(e,{aiAgentInfo:t,members:n})=>t&&Ue(e,t.userId)?t:(n==null?void 0:n.find(r=>r.userId===e.sender.userId))??e.sender,hl=e=>Xe(e)&&e.reqId?e.reqId:String(e.messageId),gl=(e,t,n,r=!0)=>{if(!r||!ir(e))return"single";const s=()=>{if(!ir(t))return!1;const u=t.sender.userId===e.sender.userId,d=ft.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!ir(n))return!1;const u=n.sender.userId===e.sender.userId,d=ft.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},Ue=(e,t)=>(()=>{var r;return Xe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Le={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Ai(e),isIncoming:(e,t)=>Xe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Xe(e)&&(e.sender.userId===t||e.sendingStatus===we.SendingStatus.PENDING)},Ve=e=>e.startsWith("image/"),on=e=>e.startsWith("video/"),fl=e=>e.startsWith("audio/"),Ti=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Jr=(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"},Ii=(e,t)=>t.map(r=>r.trim()).filter(Boolean).sort((r,s)=>s.length-r.length).reduce((r,s)=>r.replace(s,""),e.trim()).replace(/[\s,]/g,"").length===0,xi=e=>{if(e.message.length===0)return!1;if(e.messageType==="file"||e.messageType==="multipleFiles"){const t=e.messageType==="file"?[e.file.name]:e.files.map(n=>n.name);return!Ii(e.message,t)}return!0},pl=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return ul(t)},Vn=e=>{switch(e){case"top":case"middle":return re.GAP_GROUPED;default:return re.GAP_UNGROUPED}},El=e=>{const t=/```(\w+)?\n([\s\S]*?)```/g,n=[];let r=0;return e.replace(t,(s,...o)=>{const[i,c,u]=o;return r<u&&n.push({type:"text",value:e.slice(r,u).trim()}),n.push({type:"code",value:c.trim(),language:i?i.trim():"plaintext"}),r=u+s.length,s}),r<e.length&&n.push({type:"text",value:e.slice(r).trim()}),n},Qr=e=>{const t=[],n=(c,u)=>{u&&t.push({kind:c,value:u})},r=c=>{var g;const u=[],d=/`+/g;let m;for(;(m=d.exec(c))!==null;)u.push({start:m.index,end:m.index+m[0].length,length:m[0].length});let h=0;for(let f=0;f<u.length;f++){const p=u[f];if(!p)continue;let v=0;for(;c[p.start-1-v]==="\\";)v+=1;if(v%2===1)continue;let _=f+1;for(;_<u.length&&((g=u[_])==null?void 0:g.length)!==p.length;)_+=1;const E=u[_];E&&(n("text",c.slice(h,p.start)),n("span",c.slice(p.start,E.end)),h=E.end,f=_)}n("text",c.slice(h))},s=/(?:^|\n)[ \t]{0,3}((`|~)\2{2,})[\s\S]*?(?:\n[ \t]{0,3}\1\2*[ \t]*(?=\n|$)|$)/g;let o=0,i;for(;(i=s.exec(e))!==null;){const c=i[0].startsWith(`
2
- `)?i.index+1:i.index;r(e.slice(o,c)),n("fence",e.slice(c,i.index+i[0].length)),o=i.index+i[0].length}return r(e.slice(o)),t},Us=(e,{anchorsLineEnd:t=!1}={})=>(n,{atLineStart:r,atLineEnd:s}={atLineStart:!0,atLineEnd:!0})=>{const o=n.indexOf(`
1
+ "use strict";var el=Object.defineProperty;var tl=(e,t,n)=>t in e?el(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>tl(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=require("@sendbird/chat"),l=require("react"),F=require("styled-components"),pt=require("date-fns"),nl=require("date-fns/locale/en-US"),we=require("@sendbird/chat/message"),Ce=require("@sendbird/chat/aiAgent"),rl=require("react-dom"),rt=require("@sendbird/chat/groupChannel"),sl=require("date-fns/isSameDay"),_i=e=>e&&e.__esModule?e:{default:e};function ol(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 il=_i(_e),a=ol(l),v=_i(F),Ci=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Si=e=>{const t=Ci(e);return typeof t=="object"&&t!==null?t:{}},vi=e=>typeof e=="string"?Si(e):e??{},al=e=>!!vi(e).stream,$s=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},Xr=e=>{const t=vi(e),n=$s(t.user_message_id)??$s(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},wt="sb-agent",bi="KEY_IMG_ASPECT_RATIO",Ir="*/*",re={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var wn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(wn||{}),Qt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Qt||{});const cl=e=>!!(e!=null&&e.cta_button),ll=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},yi=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,ul=e=>{var t;return yi(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},dl=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Je=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},sn=e=>Object.defineProperties({},{hasMessageTemplate:Je(()=>!!(e!=null&&e.message_template)),hasCTAButton:Je(()=>cl(e)),hasChallenge:Je(()=>!!(e!=null&&e.challenge)),isThinking:Je(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Je(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Je(()=>dl(e)),hasCustomMessageTemplates:Je(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Je(()=>yi(e)),hasActiveForm:Je(()=>ul(e)),hasSteward:Je(()=>!!(e!=null&&e.steward)),hasCitations:Je(()=>ll(e))}),ml=e=>{const t=sn(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Ai=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},hl=e=>e===Qt.COMPLETED||e===Qt.CANCELED?e:Qt.IN_PROGRESS,ir=e=>Xe(e)&&!Ai(e),Xe=e=>!!e&&"sender"in e,gl=(e,{aiAgentInfo:t,members:n})=>t&&Ue(e,t.userId)?t:(n==null?void 0:n.find(r=>r.userId===e.sender.userId))??e.sender,fl=e=>Xe(e)&&e.reqId?e.reqId:String(e.messageId),pl=(e,t,n,r=!0)=>{if(!r||!ir(e))return"single";const s=()=>{if(!ir(t))return!1;const u=t.sender.userId===e.sender.userId,d=pt.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!ir(n))return!1;const u=n.sender.userId===e.sender.userId,d=pt.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},Ue=(e,t)=>(()=>{var r;return Xe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Le={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Ai(e),isIncoming:(e,t)=>Xe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Xe(e)&&(e.sender.userId===t||e.sendingStatus===we.SendingStatus.PENDING)},Ve=e=>e.startsWith("image/"),on=e=>e.startsWith("video/"),El=e=>e.startsWith("audio/"),Ti=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Zr=(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"},Ii=(e,t)=>t.map(r=>r.trim()).filter(Boolean).sort((r,s)=>s.length-r.length).reduce((r,s)=>r.replace(s,""),e.trim()).replace(/[\s,]/g,"").length===0,xi=e=>{if(e.message.length===0)return!1;if(e.messageType==="file"||e.messageType==="multipleFiles"){const t=e.messageType==="file"?[e.file.name]:e.files.map(n=>n.name);return!Ii(e.message,t)}return!0},_l=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return ml(t)},Vn=e=>{switch(e){case"top":case"middle":return re.GAP_GROUPED;default:return re.GAP_UNGROUPED}},Cl=e=>{const t=/```(\w+)?\n([\s\S]*?)```/g,n=[];let r=0;return e.replace(t,(s,...o)=>{const[i,c,u]=o;return r<u&&n.push({type:"text",value:e.slice(r,u).trim()}),n.push({type:"code",value:c.trim(),language:i?i.trim():"plaintext"}),r=u+s.length,s}),r<e.length&&n.push({type:"text",value:e.slice(r).trim()}),n},Jr=e=>{const t=[],n=(c,u)=>{u&&t.push({kind:c,value:u})},r=c=>{var g;const u=[],d=/`+/g;let m;for(;(m=d.exec(c))!==null;)u.push({start:m.index,end:m.index+m[0].length,length:m[0].length});let h=0;for(let f=0;f<u.length;f++){const p=u[f];if(!p)continue;let C=0;for(;c[p.start-1-C]==="\\";)C+=1;if(C%2===1)continue;let _=f+1;for(;_<u.length&&((g=u[_])==null?void 0:g.length)!==p.length;)_+=1;const E=u[_];E&&(n("text",c.slice(h,p.start)),n("span",c.slice(p.start,E.end)),h=E.end,f=_)}n("text",c.slice(h))},s=/(?:^|\n)[ \t]{0,3}((`|~)\2{2,})[\s\S]*?(?:\n[ \t]{0,3}\1\2*[ \t]*(?=\n|$)|$)/g;let o=0,i;for(;(i=s.exec(e))!==null;){const c=i[0].startsWith(`
2
+ `)?i.index+1:i.index;r(e.slice(o,c)),n("fence",e.slice(c,i.index+i[0].length)),o=i.index+i[0].length}return r(e.slice(o)),t},Fs=(e,{anchorsLineEnd:t=!1}={})=>(n,{atLineStart:r,atLineEnd:s}={atLineStart:!0,atLineEnd:!0})=>{const o=n.indexOf(`
3
3
  `),i=r?0:o===-1?n.length:o+1,c=!t||s?n.length:n.lastIndexOf(`
4
- `)+1;return i>=c?n:n.slice(0,i)+e(n.slice(i,c))+n.slice(c)},_l=e=>t=>{const n=Qr(t);return n.map((r,s)=>r.kind==="text"?e(r.value,{atLineStart:s===0,atLineEnd:s===n.length-1}):r.kind==="span"?r.value.replace(/\n/g," "):r.value).join("")},Cl=e=>e.replace(/\[([^\]]+)\](?!\(\s*[^\s)])/g,"\\[$1\\]"),Sl=e=>e.replace(/^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)\[( |x|X)\]/gm,"$1\\[$2\\]"),vl=/[\p{P}$+<=>^`|~]/u,pn=e=>e===void 0||/\s/.test(e),Rt=e=>e!==void 0&&vl.test(e),bl=e=>{const t=[];let n=0;for(const _ of Qr(e))_.kind!=="text"&&t.push([n,n+_.value.length]),n+=_.value.length;const r=[],s=/^[ \t]{0,3}(?:_[ \t]*){3,}$/gm;let o;for(;(o=s.exec(e))!==null;)r.push([o.index,o.index+o[0].length]);const i=(_,E,A)=>{for(;E.index<_.length&&_[E.index][1]<=A;)E.index+=1;return E.index<_.length&&A>=_[E.index][0]},c={index:0},u={index:0},d=[],m=/_+/g;let h;for(;(h=m.exec(e))!==null;){const _=h.index,E=_+h[0].length;if(i(t,c,_)||i(r,u,_))continue;let A=0;for(;e[_-1-A]==="\\";)A+=1;if(A%2===1)continue;const y=e[_-1],T=e[E],I=!pn(T)&&(!Rt(T)||pn(y)||Rt(y)),k=!pn(y)&&(!Rt(y)||pn(T)||Rt(T));d.push({start:_,end:E,canOpen:I&&(!k||Rt(y)),canClose:k&&(!I||Rt(T)),paired:!1})}const g=[];let f=0;for(const _ of d){/\n[ \t]*\n/.test(e.slice(f,_.start))&&(g.length=0),f=_.end;const E=_.canClose?g.pop():void 0;E?(E.paired=!0,_.paired=!0):_.canOpen&&g.push(_)}let p="",v=0;for(const _ of d)_.paired||(p+=e.slice(v,_.start)+"\\_".repeat(_.end-_.start),v=_.end);return p+e.slice(v)},yl=e=>e.replace(/(^|\n)([ \t]{0,3}(?:\*[ \t]*){3,})(?=\n|$)/g,`$1
4
+ `)+1;return i>=c?n:n.slice(0,i)+e(n.slice(i,c))+n.slice(c)},Sl=e=>t=>{const n=Jr(t);return n.map((r,s)=>r.kind==="text"?e(r.value,{atLineStart:s===0,atLineEnd:s===n.length-1}):r.kind==="span"?r.value.replace(/\n/g," "):r.value).join("")},vl=e=>e.replace(/\[([^\]]+)\](?!\(\s*[^\s)])/g,"\\[$1\\]"),bl=e=>e.replace(/^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)\[( |x|X)\]/gm,"$1\\[$2\\]"),yl=/[\p{P}$+<=>^`|~]/u,pn=e=>e===void 0||/\s/.test(e),Rt=e=>e!==void 0&&yl.test(e),Al=e=>{const t=[];let n=0;for(const _ of Jr(e))_.kind!=="text"&&t.push([n,n+_.value.length]),n+=_.value.length;const r=[],s=/^[ \t]{0,3}(?:_[ \t]*){3,}$/gm;let o;for(;(o=s.exec(e))!==null;)r.push([o.index,o.index+o[0].length]);const i=(_,E,A)=>{for(;E.index<_.length&&_[E.index][1]<=A;)E.index+=1;return E.index<_.length&&A>=_[E.index][0]},c={index:0},u={index:0},d=[],m=/_+/g;let h;for(;(h=m.exec(e))!==null;){const _=h.index,E=_+h[0].length;if(i(t,c,_)||i(r,u,_))continue;let A=0;for(;e[_-1-A]==="\\";)A+=1;if(A%2===1)continue;const y=e[_-1],T=e[E],I=!pn(T)&&(!Rt(T)||pn(y)||Rt(y)),k=!pn(y)&&(!Rt(y)||pn(T)||Rt(T));d.push({start:_,end:E,canOpen:I&&(!k||Rt(y)),canClose:k&&(!I||Rt(T)),paired:!1})}const g=[];let f=0;for(const _ of d){/\n[ \t]*\n/.test(e.slice(f,_.start))&&(g.length=0),f=_.end;const E=_.canClose?g.pop():void 0;E?(E.paired=!0,_.paired=!0):_.canOpen&&g.push(_)}let p="",C=0;for(const _ of d)_.paired||(p+=e.slice(C,_.start)+"\\_".repeat(_.end-_.start),C=_.end);return p+e.slice(C)},Tl=e=>e.replace(/(^|\n)([ \t]{0,3}(?:\*[ \t]*){3,})(?=\n|$)/g,`$1
5
5
  $2
6
6
  `).replace(/(^|\n)([ \t]{0,3}(?:_[ \t]*){3,})(?=\n|$)/g,`$1
7
7
  $2
8
- `),Al=e=>e.replace(/~~/g,"\\~\\~"),Tl=e=>{const t=e.replace(/\r\n?/g,`
8
+ `),Il=e=>e.replace(/~~/g,"\\~\\~"),xl=e=>{const t=e.replace(/\r\n?/g,`
9
9
  `),n=s=>s.replace(/(\S[ \t]*)\n(?![ \t]*\n)/g,`$1
10
- `),r=Qr(t);return r.map((s,o)=>{var c;if(s.kind!=="text")return s.value;const i=n(s.value);return((c=r[o-1])==null?void 0:c.kind)!=="span"?i:i.replace(/^([ \t]*)\n(?![ \t]*\n)/,`$1
11
- `)}).join("")},Mr=(...e)=>(t,n)=>e.reduce((r,s)=>s(r,n),t),Bs=Mr(_l(Mr(Us(yl,{anchorsLineEnd:!0}),Cl,Us(Sl),Al)),bl),Il=({convertSoftBreaks:e=!1}={})=>e?Mr(Tl,Bs):Bs,Mi=typeof navigator<"u"&&navigator.product==="ReactNative",xl=(e,t)=>{for(let n=0;n<e.length;n++){const r=Mi?n:e.length-1-n,s=e[r];if(s&&t(s)==="stop")return}},Rr=(e,t)=>{const n=r=>!t||t.length===0?!0:Xe(r)&&t.includes(r.sendingStatus);return Mi?e.find(n):e.findLast(n)},Ml=(e,t)=>{const n=Rr(e,[we.SendingStatus.SUCCEEDED]);return n&&Le.isIncoming(n,t)?n:void 0},Re=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function Ee(){}function Rl(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function kl(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 Te={isStreaming(e){return ol(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(Te.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!Ue(e,t))return!1;const n=Zr(e.data);return!n.isStreaming&&!n.hasResponseMetadata},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)}},ar=`@${wt}`,wl=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${ar}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=kl(`${e}/${t}/${s}`);return`${ar}-udata/${o}`},anonUserSession:()=>`${ar}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Ri=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},Ll=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class Ol{constructor(t){C(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??Ce.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[Ce.ConversationStatus.OPEN,Ce.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??Ce.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===Ce.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==Ce.DeskChannelFilter.EXCLUDE:!1}}class ki extends rt.BaseChannelCollection{constructor(n,r){const s=new Ol(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=rt.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,g,f)=>i.getMyGroupChannels(m,h.params,f),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:g,deskChannelFilter:f,pinnedChannelUrls:p,copilotConversationOnly:v,copilotSupportChannelUrl:_}=s.params,E={aiAgentChannelFilter:h,aiAgentIds:g,deskChannelFilter:f,pinnedChannelUrls:p,copilotConversationOnly:v,copilotSupportChannelUrl:_};return i.getMyGroupChannelChangeLogs(m,E,rt.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});C(this,"_params");C(this,"_sdk");C(this,"_throttledOnChannelChanged");C(this,"_key");C(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Ll()}`,this._throttledOnChannelChanged=Ri(()=>{var f;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:p,context:v}of m)h.delete(p.url),h.set(p.url,{channel:p,context:v});const g=new Map;for(const{channel:p,context:v}of h.values())g.has(v)||g.set(v,new Map),g.get(v).set(p.url,p);for(const[p,v]of g){const _=Array.from(v.values()),E=(f=this._sdk.currentUser)==null?void 0:f.userId,A=_.filter(T=>this.filter.match(T,E)),y=_.filter(T=>!this.filter.match(T,E)).map(T=>T.url);A.length>0&&this._base._addChannelsToView(A,p,!1),y.length>0&&this._removeChannels(y,p)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const g of m)this._pendingChannels.push({channel:g,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class wi{constructor(t){C(this,"subscribers",{});this.logger=t}async send(t){const n=Nl(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Nl=()=>{let e=Ee,t=Ee;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var ze=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e.NudgeMessageReceived="nudge.message.received",e))(ze||{});class Ut{constructor(t={}){C(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const ut={CloseConversation:e=>new Dl(e),MessengerSettingsUpdated:e=>new Pl(e),ActiveChannelUpdated:e=>new $l(e),AnonymousSessionTokenExpired:()=>new Fl,AuthTokenRefreshed:()=>new Ul,NudgeMessageReceived:e=>new Bl(e)};class Dl extends Ut{constructor(){super(...arguments);C(this,"type","conv.close")}}class Pl extends Ut{constructor(){super(...arguments);C(this,"type","messenger.settings.updated")}}class $l extends Ut{constructor(){super(...arguments);C(this,"type","active.channel.updated")}}class Fl extends Ut{constructor(){super(...arguments);C(this,"type","anon.token.expired")}}class Ul extends Ut{constructor(){super(...arguments);C(this,"type","auth.token.refreshed")}}class Bl extends Ut{constructor(){super(...arguments);C(this,"type","nudge.message.received")}}const Bt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class an{constructor(t){C(this,"category","connection");this.userId=t}get data(){return Bt({user_id:this.userId})}}class Hl extends an{constructor(){super(...arguments);C(this,"metricKey","connection_connected")}}class Gl extends an{constructor(){super(...arguments);C(this,"metricKey","connection_reconnect_started")}}class zl extends an{constructor(){super(...arguments);C(this,"metricKey","connection_reconnect_succeeded")}}class Vl extends an{constructor(){super(...arguments);C(this,"metricKey","connection_reconnect_failed")}}class Kl extends an{constructor(){super(...arguments);C(this,"metricKey","connection_disconnected")}}class ql{constructor(t){C(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new Hl(n):t==="reconnectStarted"?new Gl(n):t==="reconnectSucceeded"?new zl(n):t==="reconnectFailed"?new Vl(n):new Kl(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class es{constructor(t,n){C(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return Bt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Wl extends es{constructor(){super(...arguments);C(this,"metricKey","conversation_initialized")}}class Yl extends es{constructor(){super(...arguments);C(this,"metricKey","conversation_open")}}class jl extends es{constructor(){super(...arguments);C(this,"metricKey","conversation_closed")}}class Xl{constructor(t){C(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===Ce.ConversationStatus.INITIALIZED?new Wl(t.url,n.id):s===Ce.ConversationStatus.OPEN?new Yl(t.url,n.id):new jl(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===Ce.ConversationStatus.INITIALIZED?t===void 0:n===Ce.ConversationStatus.OPEN?t===Ce.ConversationStatus.INITIALIZED:t===Ce.ConversationStatus.OPEN}}const Li=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},$e=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ce.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},ts=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ce.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function dt(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function Zl(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!dt(e):!1}function Jl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Oi(e){return!!e&&e<=Date.now()}function Ql(e){return!e.title}function eu(e,t){var n;if(e)return Ql(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question,always_visible:!1}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}class ns{constructor(t,n){C(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return Bt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class tu extends ns{constructor(){super(...arguments);C(this,"metricKey","handoff_started")}}class nu extends ns{constructor(){super(...arguments);C(this,"metricKey","handoff_succeeded")}}class ru extends ns{constructor(){super(...arguments);C(this,"metricKey","handoff_failed")}}class su{constructor(t){C(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new tu(t.url,r.id):o==="succeeded"?new nu(t.url,r.id):new ru(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if($e(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class ou{constructor(t){C(this,"category","message");C(this,"metricKey","incoming_message_received");C(this,"channelUrl");C(this,"messageId");C(this,"senderType");C(this,"createdAt");C(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return Bt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const iu=(e,t)=>{const n=Xe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class au{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new ou({channelUrl:t.url,messageId:n.messageId,senderType:iu(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!Ue(t,this.getCurrentUserId())&&n!==null}}class rs{constructor(t){C(this,"category","memory");C(this,"action");C(this,"deleteOnOff");C(this,"userId");this.action=t.action,this.deleteOnOff=t.deleteOnOff,this.userId=t.userId}get data(){return Bt({action:this.action,delete_on_off:this.deleteOnOff,user_id:this.userId})}}class cu extends rs{constructor(){super(...arguments);C(this,"metricKey","memory_consent")}}class lu extends rs{constructor(){super(...arguments);C(this,"metricKey","memory_on")}}class uu extends rs{constructor(){super(...arguments);C(this,"metricKey","memory_off")}}const du={consent:{Metric:cu,actions:{shown:"shown",confirm:"enable",cancel:"disable"}},on:{Metric:lu,actions:{shown:"shown",confirm:"keep",cancel:"disable",dismiss:"dismiss"}},off:{Metric:uu,actions:{shown:"shown",confirm:"keep",cancel:"enable",dismiss:"dismiss"}}};class mu{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({variant:t,action:n,deleteOnOff:r}){if(t==="readonly")return;const{Metric:s,actions:o}=du[t],i=o[n];i&&this.dispatch(new s({action:i,deleteOnOff:t==="on"?r:void 0,userId:this.getCurrentUserId()}))}}class hu{constructor(t){C(this,"category","message");C(this,"metricKey");C(this,"channelUrl");C(this,"requestId");C(this,"messageId");C(this,"target");C(this,"sendingStatus");C(this,"createdAt");C(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return Bt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const gu=e=>{switch(e){case we.SendingStatus.PENDING:return"pending";case we.SendingStatus.SUCCEEDED:return"succeeded";case we.SendingStatus.FAILED:return"failed";case we.SendingStatus.SCHEDULED:return"scheduled";default:return}};class fu{constructor(t,n){C(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!Ue(n,this.getCurrentUserId()))return;const r=gu(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new hu({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:dt(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class pu{constructor(t){C(this,"id","aiagent_livemetric");C(this,"dispatch");C(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});C(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new ql(this.emit),conversation:new Xl(this.emit),handoff:new su(this.emit),incomingMessage:new au(this.emit,n),outgoingMessage:new fu(this.emit,n),memory:new mu(this.emit,n)}}start(){const t=new _e.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new rt.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var ss=(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))(ss||{});class Ni{constructor(t){C(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${wt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${wt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${wt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${wt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${wt}/error]`,...t)}}class Di{constructor({userId:t,authToken:n,sessionHandler:r}){C(this,"userId");C(this,"authToken");C(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class kr{constructor(){C(this,"userId");C(this,"authToken");C(this,"sessionHandler")}}const Eu=e=>({onSessionTokenRequired:t=>{t(null),e.send(ut.AnonymousSessionTokenExpired())}}),os=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),_u="ai_agent:stats",is="ai_agent:assertion",Cu="conversation_initial_render",Su="conversation_not_interactive_timeout",vu="recovery_not_interactive_timeout",bu="conversation_list_initial_render",yu="message_pending_stuck",Au="aiev_auth_expired_unhandled",Tu="user_perceived_response_time",Iu="stream_stalled",xu="ai_typing_indicator_absent_timeout",Mu="rendered_content_unusable",Ru="streaming_message_validation",ku="duplicate_message_response",wu="message_lifecycle_event",Lu=800220;var X=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(X||{});const wr=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),Pi=e=>typeof e=="object"&&e!==null,Ou=e=>{if(Pi(e))return typeof e.code=="number"?e.code:void 0},Nu=e=>e instanceof Error?e.message:typeof e=="string"?e:Pi(e)&&typeof e.message=="string"?e.message:"";class qe{constructor(){C(this,"timers",new Map);C(this,"committed",!1);C(this,"commitCallback",null);C(this,"conversationId",null);C(this,"errorCode",null);C(this,"errorDescription",null);C(this,"extraData",{})}getStatType(){return _u}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=Ou(t)??Lu,this.errorDescription=Nu(t),this)}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:performance.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=os({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(this.getStatType(),t)):!1}}class Hs extends qe{constructor(){super(...arguments);C(this,"reason");C(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return Au}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Ht{constructor(t){C(this,"commitCallback");this.commitCallback=t}}class Tt extends Ht{constructor(){super(...arguments);C(this,"records",new Map)}}class $i extends Ht{constructor(){super(...arguments);C(this,"activeSpan",null);C(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class as{constructor(t,n){C(this,"stats");C(this,"visible");C(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const yt=(e,t)=>!(e&&t&&e!==t),Lr=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&yt(n.measure.channelUrl,t))return!0;return!1},cn=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class Du extends Ht{onPayloadParseFailed(t){new Hs().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new Hs().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Pu extends qe{constructor(){super(...arguments);C(this,"channelUrl",null);C(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(X.PAGE_RENDER),this.timers.delete(X.PAGE_RENDER_FROM_CACHE),this.timers.delete(X.GET_CHANNEL),this.timers.delete(X.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Cu}buildPayload(){const n=this.getTimer(X.AUTH),r=this.getTimer(X.PAGE_RENDER),s=this.getTimer(X.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-wr(n,r),i=s.duration===null?null:s.duration-wr(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[X.AUTH]:n.duration,[X.GET_CHANNEL]:this.getTimer(X.GET_CHANNEL).duration,[X.GET_MESSAGES]:this.getTimer(X.GET_MESSAGES).duration,[X.PAGE_RENDER_FROM_CACHE]:i}})}}class $u extends as{constructor(n,r,s){var o;super(n,s);C(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(X.PAGE_RENDER).startTimer(X.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(X.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(X.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(X.GET_CHANNEL).setError(r).stopTimer(X.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(X.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(X.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(X.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(X.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(X.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(X.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Fu extends $i{constructor(){super(...arguments);C(this,"stats",null);C(this,"authState","idle");C(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Pu().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(X.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(X.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(X.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new $u(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Uu extends qe{constructor(){super(...arguments);C(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(X.PAGE_RENDER),this.timers.delete(X.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return bu}buildPayload(){const n=this.getTimer(X.AUTH),r=this.getTimer(X.PAGE_RENDER),s=this.getTimer(X.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-wr(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[X.AUTH]:n.duration,[X.GET_LIST]:s}})}}class Bu extends as{constructor(n,r){var s;super(n,r);C(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(X.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(X.PAGE_RENDER),this.stats.startTimer(X.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(X.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(X.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(X.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(X.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class Hu extends $i{constructor(){super(...arguments);C(this,"stats",null);C(this,"authState","idle");C(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Uu().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(X.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(X.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(X.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(X.AUTH),this.activeSpan=new Bu(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Gu extends qe{constructor(){super(...arguments);C(this,"phaseReached","auth");C(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return Su}buildPayload(){const n=this.getTimer(X.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class zu extends Tt{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new Gu().setCommitCallback(this.commitCallback).startTimer(X.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(X.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Vu extends qe{constructor(){super(...arguments);C(this,"previousMessageId");C(this,"nextMessageId")}setDuplicatePair(n){return this.previousMessageId=n.previousMessageId,this.nextMessageId=n.nextMessageId,this}getStatType(){return is}getMetricKey(){return ku}buildPayload(){return this.previousMessageId===void 0||this.nextMessageId===void 0?null:this.createPayload("",{extra:{prev_message_id:String(this.previousMessageId),next_message_id:String(this.nextMessageId)}})}}const Ku=500,qu=(e,t)=>Ue(e,t)&&!Te.isStreaming(e)&&!!e.message;class Wu extends Ht{constructor(){super(...arguments);C(this,"emittedMessageChannels",new Map)}onMessagesChanged(n){const r=this.findLastTwoReplies(n.messages,n.aiAgentUserId);r&&r.previous.message===r.latest.message&&(this.emittedMessageChannels.has(r.latest.messageId)||this.emit(r.latest,r.previous,n))}clear(){this.emittedMessageChannels.clear()}findLastTwoReplies(n,r){let s=null,o=null;return xl(n,i=>{if(!(Xe(i)&&i.sendingStatus!==we.SendingStatus.SUCCEEDED)&&Ue(i,r)){if(!qu(i,r))return"stop";if(!s)s=i;else return o=i,"stop"}}),s&&o?{latest:s,previous:o}:null}emit(n,r,s){cn(this.emittedMessageChannels,Ku),this.emittedMessageChannels.set(n.messageId,s.channelUrl),new Vu().setDuplicatePair({previousMessageId:r.messageId,nextMessageId:n.messageId}).setConversationId(s.conversationId).setCommitCallback(this.commitCallback).commit()}}const Yu=-1;class ju extends qe{constructor(){super(...arguments);C(this,"timestamps")}setTimestamps(n){return this.timestamps=n,this}setFailure(n){return this.setError(n),this}getStatType(){return is}getMetricKey(){return wu}buildPayload(){const n=this.timestamps;if(!n)return null;const r=n.messageSentAt??n.streamStartAt,s=n.animationEndAt,o=s===void 0||r===void 0?Yu:s-r;return this.createPayload(o,{extra:{message_id:n.messageId===void 0?void 0:String(n.messageId),message_sent_at:n.messageSentAt,typing_start_at:n.typingStartAt,typing_end_at:n.typingEndAt,stream_start_at:n.streamStartAt,stream_failed_at:n.streamFailedAt,last_stream_at:n.lastStreamAt,stream_end_at:n.streamEndAt,animation_start_at:n.animationStartAt,animation_end_at:n.animationEndAt}})}}const Xu=3e4,Zu=1e4,Ju=e=>{var t;return((t=e.extendedMessagePayload)==null?void 0:t.is_last_in_turn)===!0};class Qu extends as{constructor(n,r){super(n,!0);C(this,"measure");this.measure={messageSentAt:r.messageSentAt,startTimeoutTimer:null,stallTimer:null,stopBackgroundWatch:r.stopBackgroundWatch}}armStartTimeout(){this.measure.startTimeoutTimer=setTimeout(()=>this.failWith("sent_timeout"),Xu)}setConversationId(n){var r;(r=this.stats)==null||r.setConversationId(n)}onTypingChanged(n){if(this.stats){if(n){this.measure.typingStartAt===void 0&&(this.measure.typingStartAt=Date.now());return}this.measure.typingStartAt!==void 0&&this.measure.typingEndAt===void 0&&(this.measure.typingEndAt=Date.now())}}onStreamStart(n){this.stats&&(this.measure.streamMessageId=n.messageId,this.measure.streamStartAt=Date.now(),this.clearStartTimeout(),this.armStall())}onStreamFrame(n,r){if(!this.stats)return;const s=Date.now();if(r&&(this.measure.lastStreamAt=s),Te.isStreaming(n))return this.armStall();this.measure.streamEndAt=s,this.clearStall(),this.measure.animationStartAt===void 0&&this.failWith("animation_not_started")}onAnimationStart(){this.stats&&this.measure.animationStartAt===void 0&&(this.measure.animationStartAt=Date.now())}onAnimationComplete(n){if(this.stats){if(!n)return this.cancel();this.settle({animationEndAt:Date.now()})}}cancel(){var n,r;this.clearTimers(),(r=(n=this.measure).stopBackgroundWatch)==null||r.call(n),super.cancel()}failWith(n){if(this.stats){if(this.stats.setFailure(n),n!=="stream_failed")return this.settle({});this.settle(this.measure.lastStreamAt===void 0?{streamFailedAt:Date.now(),streamStartAt:void 0}:{streamFailedAt:Date.now(),lastStreamAt:this.measure.lastStreamAt})}}settle(n){var r,s;if(this.stats){if(this.clearTimers(),(s=(r=this.measure).stopBackgroundWatch)!=null&&s.call(r))return super.cancel();this.stats.setTimestamps({messageId:this.measure.streamMessageId,messageSentAt:this.measure.messageSentAt,typingStartAt:this.measure.typingStartAt,typingEndAt:this.measure.typingEndAt,streamStartAt:this.measure.streamStartAt,streamEndAt:this.measure.streamEndAt,animationStartAt:this.measure.animationStartAt,...n}),this.commitOrDefer()}}armStall(){this.clearStall(),this.measure.stallTimer=setTimeout(()=>this.failWith("stream_failed"),Zu)}clearTimers(){this.clearStartTimeout(),this.clearStall()}clearStartTimeout(){this.measure.startTimeoutTimer!==null&&clearTimeout(this.measure.startTimeoutTimer),this.measure.startTimeoutTimer=null}clearStall(){this.measure.stallTimer!==null&&clearTimeout(this.measure.stallTimer),this.measure.stallTimer=null}}class ed extends Ht{constructor(){super(...arguments);C(this,"block",null);C(this,"watchBackgrounded")}setBackgroundedWatcher(n){this.watchBackgrounded=n}onUserMessageSent(n){this.discardBlock();const r=this.createSpan(n.conversationId,{messageSentAt:Date.now()});r.armStartTimeout(),this.block={channelUrl:n.channelUrl,userMessageId:n.messageId,conversationId:n.conversationId,first:r,firstAnnounced:!1,spans:new Map,closed:!1}}onConversationIdResolved(n){const r=this.blockFor(n.channelUrl);r&&(r.conversationId??(r.conversationId=n.conversationId),r.first.setConversationId(n.conversationId),r.spans.forEach(s=>s.setConversationId(n.conversationId)))}onTypingChanged(n){var r;(r=this.blockFor(n.channelUrl))==null||r.first.onTypingChanged(n.isAgentTyping)}onCollectionEvent(n){const r=this.blockFor(n.channelUrl),s=n.event;if(!r||s.channelUrl!==n.channelUrl)return;if(s.kind==="messagesDeleted"){s.messages.forEach(i=>{var c;return(c=r.spans.get(i.messageId))==null?void 0:c.cancel()});return}if(s.kind==="initialized")return;const o=s.source===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED;s.messages.forEach(i=>{Ue(i,n.aiAgentUserId)&&Zr(i.data).userMessageId===r.userMessageId&&this.observeReply(r,i,o)})}onAnimationStart(n){var r,s;(s=(r=this.block)==null?void 0:r.spans.get(n.messageId))==null||s.onAnimationStart()}onAnimationComplete(n){var r,s;(s=(r=this.block)==null?void 0:r.spans.get(n.messageId))==null||s.onAnimationComplete(n.completed)}clearChannel(n){!n||!this.blockFor(n)||this.discardBlock()}clear(){this.discardBlock()}observeReply(n,r,s){const o=Te.isStreaming(r);Ju(r)&&(n.lastMessageId=r.messageId);const i=n.lastMessageId===r.messageId&&!o,c=n.spans.get(r.messageId);if(c){c.onStreamFrame(r,s),i&&(n.closed=!0);return}if(n.closed)return;if(!o){n.firstAnnounced||n.first.cancel(),n.firstAnnounced=!0,i&&(n.closed=!0);return}const u=n.firstAnnounced?this.createSpan(n.conversationId,{}):n.first;n.firstAnnounced=!0,u.onStreamStart(r),n.spans.set(r.messageId,u)}createSpan(n,r){var o;const s=new ju().setConversationId(n).setCommitCallback(this.commitCallback);return new Qu(s,{messageSentAt:r.messageSentAt,stopBackgroundWatch:((o=this.watchBackgrounded)==null?void 0:o.call(this))??null})}discardBlock(){const n=this.block;n&&(n.first.cancel(),n.spans.forEach(r=>r.cancel()),this.block=null)}blockFor(n){const r=this.block;if(!(!r||r.channelUrl!==n))return r}}class td extends qe{constructor(){super(...arguments);C(this,"requestId");C(this,"messageType");C(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return yu}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const nd=5e3,Gs=1e4;class rd extends Tt{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new td().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?Gs:nd;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),Gs))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class cr extends qe{constructor(){super(...arguments);C(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return vu}buildPayload(){const n=this.getTimer(X.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class sd extends Tt{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new cr().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(X.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(X.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new cr().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new cr().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class od extends qe{constructor(){super(...arguments);C(this,"messageId");C(this,"contentKind");C(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return Mu}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const id=500;class ad extends Ht{constructor(){super(...arguments);C(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;cn(this.measure.committed,id),this.measure.committed.add(r),new od().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class cd extends qe{constructor(){super(...arguments);C(this,"durationMs");C(this,"messageId");C(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return Iu}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const zs=1e4,kt=5e3,ld=500;class ud extends Tt{constructor(){super(...arguments);C(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,kt))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,kt)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,kt))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<kt){this.scheduleRenderStallCheck(n,r,kt-o);return}const i=performance.now()-s.lastRawAt;if(i>=kt&&s.deliveryTimer!==null){const c=zs-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),zs))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new cd().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||cn(this.emittedMessageChannels,ld),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class dd extends qe{constructor(){super(...arguments);C(this,"durationMs");C(this,"messageId");C(this,"chunkIntervalsMs",[]);C(this,"regenerated",!1)}setMessageId(n){return this.messageId=n,this}setStream(n){return this.durationMs=n.durationMs,this.chunkIntervalsMs=n.chunkIntervalsMs,this.regenerated=n.regenerated,this}getStatType(){return is}getMetricKey(){return Ru}buildPayload(){return this.durationMs===void 0||this.messageId===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),chunk_intervals_ms:this.chunkIntervalsMs,regenerated:this.regenerated}})}}const md=-1,hd=e=>e===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED;class gd extends Tt{constructor(){super(...arguments);C(this,"watchBackgrounded")}setBackgroundedWatcher(n){this.watchBackgrounded=n}onCollectionEvent(n){const r=n.event;if(r.channelUrl!==n.channelUrl)return;if(r.kind==="messagesDeleted"){r.messages.forEach(o=>{const i=this.records.get(o.messageId);i&&this.drop(o.messageId,i)});return}if(r.kind==="initialized"||!hd(r.source))return;const s=r.source===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED;r.messages.forEach(o=>{const i=this.records.get(o.messageId);if(!i){s&&Ue(o,n.aiAgentUserId)&&Te.isStreaming(o)&&this.start(o,n.channelUrl,n.conversationId);return}i.measure.channelUrl===n.channelUrl&&(i.stats.setConversationId(n.conversationId),this.advance(i,o),Te.isStreaming(o)||this.finish(o.messageId,i))})}clearChannel(n){n&&this.records.forEach((r,s)=>{r.measure.channelUrl===n&&this.drop(s,r)})}clear(){this.records.forEach((n,r)=>this.drop(r,n))}start(n,r,s){var i;this.clearChannel(r);const o=performance.now();this.records.set(n.messageId,{stats:new dd().setMessageId(n.messageId).setConversationId(s).setCommitCallback(this.commitCallback),measure:{channelUrl:r,startedAt:o,lastAt:o,lastText:n.message,chunkIntervalsMs:[],regenerated:!1,stopBackgroundWatch:((i=this.watchBackgrounded)==null?void 0:i.call(this))??null}})}advance(n,r){const s=n.measure,o=r.message;if(o===s.lastText)return;o.startsWith(s.lastText)||(s.regenerated=!0,s.chunkIntervalsMs.push(md));const i=performance.now();s.chunkIntervalsMs.push(Math.round(i-s.lastAt)),s.lastText=o,s.lastAt=i}finish(n,r){var o;const s=r.measure;this.records.delete(n),!((o=s.stopBackgroundWatch)!=null&&o.call(s))&&r.stats.setStream({durationMs:Math.round(performance.now()-s.startedAt),chunkIntervalsMs:s.chunkIntervalsMs,regenerated:s.regenerated}).commit()}drop(n,r){var s,o;(o=(s=r.measure).stopBackgroundWatch)==null||o.call(s),this.records.delete(n)}}class fd extends qe{constructor(){super(...arguments);C(this,"beforeTpstAbsentMs");C(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return xu}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[X.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[X.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const Vs=3e3,pd=3e4;class Ed extends Tt{constructor(){super(...arguments);C(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new fd().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),pd),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{yt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{yt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!Lr(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(cn(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{yt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{yt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=Vs&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=Vs&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class _d extends qe{constructor(){super(...arguments);C(this,"ackToFirstChunkMs");C(this,"firstChunkToRenderMs");C(this,"isStreaming");C(this,"sendToAckMs");C(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return Tu}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[X.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[X.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[X.SEND_TO_ACK]:this.sendToAckMs}})}}const Cd=.15,Sd=10,vd=e=>e<=0?!1:e>=1?!0:Math.random()<e;class bd extends Tt{constructor(n,r){super(n);C(this,"samplingRate");C(this,"pendingAIResponseByUserMessageId",new Map);C(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??Cd}startTurn(n){if(this.collectedCount>=Sd||!vd(this.samplingRate))return;this.collectedCount+=1;const r={stats:new _d().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&Lr(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!Lr(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&yt(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&yt(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||(cn(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function yd(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const Ks={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},cs={conversation:{...Ks,messageAlertSoundEnabled:!1,list:{...Ks,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},qs=e=>e?{conversation:Id(e.conversation),launcher:Ad(e.launcher)}:cs,Ad=e=>Lt(cs.launcher,e),Td=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},Id=e=>{const t=cs.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...Lt(t.list,c,n),deferredMarkdownElements:Td(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:Lt(t.header,r),input:{camera:Lt(t.input.camera,u),gallery:Lt(t.input.gallery,d),fileEnabled:m},fileViewer:Lt(t.fileViewer,o)}},Lt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,os(r));return n},xd=(e,t)=>Or(e,t),Or=(e,t)=>{if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>Or(r,t[s]));if(!Ws(e)||!Ws(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>Or(e[r],t[r]))},Ws=e=>typeof e=="object"&&e!==null,Md=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),Rd=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Nr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class kd{constructor(){C(this,"_channelHandlerId",null);C(this,"_connectionHandlerId",null);C(this,"_initConversationRequests",new Map);C(this,"_handleActiveChannelChangedThrottled",null);C(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Ri(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:$e(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new rt.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new _e.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});C(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});C(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:$e(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});C(this,"_initConversationIfNeeded",(t,n)=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const r=this._initConversationRequests.get(t.url);if(r)return r;const s=t.initConversation({aiAgentId:this.aiAgentId,initialUserMessage:n==null?void 0:n.initialUserMessage}).then(()=>{}).catch(o=>{this._logger.warn("AIAgentEventManager: initConversation failed",o)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,s),s});C(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(ze.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(ze.MessengerSettingsUpdated,t)}));C(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(ze.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(ze.ActiveChannelUpdated,t)}));C(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(ze.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(ze.AuthTokenRefreshed,t)}));C(this,"onNudgeMessageReceived",t=>(this._dispatcher.subscribe(ze.NudgeMessageReceived,t),()=>{this._dispatcher.unsubscribe(ze.NudgeMessageReceived,t)}))}}class wd{constructor(t){C(this,"_sdkUser");C(this,"_userSession");C(this,"_dispatcher");C(this,"_activeChannel");C(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(ut.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});C(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(ut.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const Fi=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},Ui=e=>JSON.parse(e),Ld=e=>JSON.parse(e);function Od(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Nd(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function Dd({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,Fi(c))},e)}async function Pd({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,Fi(c)),e)}var ls=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(ls||{});const Bi=e=>typeof e=="object"&&e!==null,lr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",$d=e=>!Bi(e)||!lr(e,"channel_url")||!lr(e,"ai_agent_id")||!lr(e,"cpa_key")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id,cpaKey:e.cpa_key},Fd={1:$d};function Ud(e){if(!Bi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Fd[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Bd(e,t,n,r){const s=sl.default.init({appId:e,modules:[new rt.GroupChannelModule,new Ce.AIAgentModule],localCacheEnabled:!0,options:new _e.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:_e.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Hd(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 Gd=[400300,400301,400302,400310],zd=ls.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Vd=e=>`${zd}:${e}`;class us{constructor(t,n,r,s,o){C(this,"chatSDK");C(this,"_aiAgentId");C(this,"_externalAuthTokenExpiredEventHandlerKey");C(this,"_logger");C(this,"_cache");C(this,"_statsTrackers");C(this,"_sessionHandler");C(this,"_aiEventHandlerRegistered",!1);C(this,"connect",async(t,n,r,s,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const i=new _e.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(i)}this._registerAIEventHandler();try{await this.chatSDK.connect(t.userId,t.authToken);const[,i]=await Promise.allSettled([this._syncTemplatesIfNeeded(),o?this.submitCPAAuthorizationCodes(o):Promise.resolve()]);return o&&(i.status==="fulfilled"?this._logger.debug("ChatClient.connect: CPA authorization codes submitted",i.value):this._logger.error("ChatClient.connect: CPA authorization code submission failed",i.reason)),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(i){const c=i;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(c))this._logger.warn("ChatClient.connect","offline connect restricted",c.message,c.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(u=>this._logger.warn("ChatClient.connect","clear cached-data failure",u));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",c.message,c.code),this.dispose(),c}});C(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});C(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=Ud(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==ls.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});C(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});C(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});C(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));C(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));C(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));C(this,"requestNudgeMessage",async t=>this.chatSDK.aiAgent.requestNudgeMessage(t));C(this,"submitCPAAuthorizationCodes",async({aiAgentId:t,authCodes:n})=>this.chatSDK.aiAgent.submitCustomerProvidedAuthCodes({aiAgentId:t,authorizationCodes:n}));C(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});C(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});C(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});C(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});C(this,"_isCacheRestrictedError",t=>Gd.some(n=>t.code===n));C(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=Ui(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=Vd(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Hd(t.chatSDK),n=t.chatSDK):n=Bd(t.appId,t.extensions,t.messengerVersion,t.chatParams),new us(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Kd=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},qd=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},En=new Map,Hi={set:(e,t)=>{En.set(e,t)},get:e=>{if(En.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=En.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=En.entries().next().value;return{platform:t[0],...t[1]}}},Gi="SENDBIRD_DESK_INQUIRE_TICKET_CLOSURE";var Ln=(e=>(e.WAITING="WAITING",e.CONFIRMED="CONFIRMED",e.DECLINED="DECLINED",e))(Ln||{});const Wd=e=>{if(!e)return null;const t=Si(e);if(t.type!==Gi)return null;const{state:n,ticketId:r}=t.body??{};return n==null||r==null?null:{state:n,ticketId:r}};class Ys extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);C(this,"status");C(this,"code");C(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var ds=(e=>(e.INITIALIZED="INITIALIZED",e.PROACTIVE="PROACTIVE",e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.CLOSED="CLOSED",e.WORK_IN_PROGRESS="WORK_IN_PROGRESS",e.IDLE="IDLE",e))(ds||{}),ms=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(ms||{}),zi=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(zi||{});const Yd=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class jd{constructor(t){C(this,"_appId");C(this,"_apiHost");C(this,"_logger");C(this,"_credential",null);C(this,"_authRefreshPromise",null);C(this,"_onDeskTokenRefreshRequired",async()=>!1);C(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});C(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});C(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});C(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Yd(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});C(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});C(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));C(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));C(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));C(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));C(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Ys(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Ys(t.status,{})}});C(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class On{constructor(t,n){C(this,"id");C(this,"title");C(this,"status");C(this,"agent");C(this,"priority");C(this,"group");C(this,"firstResponseTime");C(this,"issuedAt");C(this,"customFields");C(this,"_client");C(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new On({id:t.id,title:t.channelName??null,status:t.status2??ds.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??ms.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class hs{constructor(t){C(this,"_logger");C(this,"_apiClient");C(this,"_onDeskTokenRefreshRequired");C(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);C(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});C(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});C(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});C(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return On._fromResponse(n,this)});C(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:os({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return On._fromResponse(n,this)});C(this,"confirmEndOfChat",async({messageId:t,ticketId:n,confirmed:r})=>{this._assertAuthenticated(this._apiClient),await this._apiClient.request(`/tickets/${encodeURIComponent(n)}/edit_message/`,{method:"PATCH",body:{messageId:t,messageData:JSON.stringify({type:Gi,body:{state:r?Ln.CONFIRMED:Ln.DECLINED,ticketId:n}})}})});this._logger=t.logger,this._apiClient=new jd(t)}static init(t){return new hs(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class gs{constructor(){C(this,"authenticate",async t=>!1);C(this,"deauthenticate",()=>{});C(this,"refreshDeskAuthToken",async()=>!1);C(this,"setCustomerLanguage",async()=>{});C(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")});C(this,"confirmEndOfChat",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new gs}}function Xd(e){return{get:t=>e.getString(t)??null,set:(t,n)=>{e.set(t,n)},delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}const Zd=1440*60*1e3,Jd=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function We(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Qd(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const em=e=>{const t={conversationInitialRender:new Fu(e),conversationNotInteractiveTimeout:new zu(e),recoveryNotInteractiveTimeout:new sd(e),conversationListInitialRender:new Hu(e),aievAuthExpiredUnhandled:new Du(e),messagePendingStuck:new rd(e),userPerceivedResponseTime:new bd(e),streamStalled:new ud(e),typingIndicatorAbsentTimeout:new Ed(e),renderedContentUnusable:new ad(e),streamingMessageValidation:new gd(e),duplicateMessageResponse:new Wu(e),messageLifecycleEvent:new ed(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class Nn extends kd{constructor(n){super();C(this,"appId");C(this,"aiAgentId");C(this,"_chatClient");C(this,"_deskClient");C(this,"_cache");C(this,"_logger");C(this,"_dispatcher");C(this,"_session",null);C(this,"language");C(this,"countryCode");C(this,"context");C(this,"cpaAuthorizationCodes");C(this,"queryParams");C(this,"_config",qs());C(this,"_networkStateAdapter");C(this,"_scheduleForegroundTask");C(this,"_watchBackgrounded");C(this,"_forceCreateChannel");C(this,"_agentVersion");C(this,"_statsTrackers");C(this,"_liveMetricManager");C(this,"_operationQueue",yd());C(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});C(this,"initConversationIfNeeded",(n,r)=>this._initConversationIfNeeded(n,r));C(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(ut.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let g;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),g={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:v,session_token:_,expire_at:E}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:_,expireAt:E}),g={userId:v,authToken:_},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else g={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,h),this._dispatcher.send(ut.MessengerSettingsUpdated({settings:h,source:"server"}));const f=(()=>{var v;return s.type==="anonymous"?Eu(this._dispatcher):(v=s.userSessionCandidate)==null?void 0:v.sessionHandler})(),p=await this._chatClient.connect(g,f,v=>{var _;this._logger.debug("AIAgent: session token refreshed"),(_=this._session)==null||_._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()},this.cpaAuthorizationCodes?{aiAgentId:this.aiAgentId,authCodes:this.cpaAuthorizationCodes}:void 0);return await this._deskClient.authenticate({userId:g.userId,accessToken:g.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var _;if(v===zi.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const E=(_=this._session)==null?void 0:_.userSession.authToken;return E?await this._deskClient.refreshDeskAuthToken(E):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new wd({sdkUser:p,userSession:g,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:g.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});C(this,"submitCPAAuthorizationCodes",async n=>{We(this._session),this._logger.debug("AIAgent.submitCPAAuthorizationCodes: start");const r=await this._chatClient.submitCPAAuthorizationCodes({aiAgentId:this.aiAgentId,authCodes:n});return this._logger.debug("AIAgent.submitCPAAuthorizationCodes: end",r),r});C(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));C(this,"createConversation",async n=>{We(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});C(this,"searchConversation",async n=>{if(We(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:Ce.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)Qd(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});C(this,"closeConversation",async n=>{var s;We(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===Ce.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Ce.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});C(this,"createConversationListCollection",n=>new ki(this.chatSDK,n??{}));C(this,"patchContext",async(n,r)=>{We(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});C(this,"updateContext",async(n,r)=>{We(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});C(this,"getContextObject",async n=>{We(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});C(this,"requestNudgeMessage",async n=>{We(this._session);const r=this._session;this._logger.debug("AIAgent.requestNudgeMessage: start",n);const s=await this._chatClient.requestNudgeMessage({aiAgentId:this.aiAgentId,key:n.key,context:n.context,language:this.language});if(this._logger.debug("AIAgent.requestNudgeMessage: end",s),this._session!==r){this._logger.debug("AIAgent.requestNudgeMessage: session changed during request, discarding stale nudge");return}s.status!=="ok"||!s.payload.message||this._dispatcher.send(ut.NudgeMessageReceived({message:s.payload.message,callbackUserMessage:s.payload.callback_user_message??void 0}))});C(this,"clearUserMemories",async(n={})=>{We(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});C(this,"confirmEndOfChat",async n=>{We(this._session),this._logger.debug("AIAgent.confirmEndOfChat: start",n),await this._deskClient.confirmEndOfChat(n),this._logger.debug("AIAgent.confirmEndOfChat: end")});C(this,"setUserMemoryState",async n=>{We(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Nr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(ut.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),Nr(i)});C(this,"refreshActiveChannel",async n=>{var c,u,d;We(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});C(this,"_getSessionCandidate",n=>n instanceof Di?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof kr?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});C(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Zd<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});C(this,"_getManualSessionInfo",n=>{if(!n||n instanceof kr)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this.cpaAuthorizationCodes=n.cpaAuthorizationCodes,this.config=n.config,this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=Kd(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&qd(n.foregroundStateAdapter),this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new pu(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var f;const r=Hi.get(n.platform),s=n.logger??new Ni(n.logLevel??ss.WARN),o=n.dispatcher??new wi(s),i=n.useMMKVStorage?Xd(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=wl({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=em((p,v)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,v)});d=us.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion,customData:n._sourceService?{source_service:n._sourceService}:void 0},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const g=Jd?hs.init({appId:n.appId,logger:s,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):gs.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Nn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,cpaAuthorizationCodes:n.cpaAuthorizationCodes,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:g,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){const r=qs(n);xd(r,this._config)||(this._config=r)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}get watchBackgrounded(){return this._watchBackgrounded}}const ye=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.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`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function Qe(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m=l.useCallback(f=>c(()=>f),[]),h=l.useCallback((f,p)=>d(v=>v[f]===p?v:{...v,[f]:p}),[]),g=l.useMemo(()=>({Template:i,updateTemplate:m,components:u,updateComponent:h}),[i,u,m,h]);return a.createElement(t.Provider,{value:g},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function tm(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function nm(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":rm(e,t)}function rm(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function sm(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ft.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):ft.isToday(s)?n.hoursAgo(ft.differenceInHours(r,s)):t(s,n.dateShortFormat)}const om=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__,im=({data:e,extendedMessagePayload:t,ticketClosureLabels:n})=>{if(om){const r=Wd(e);if(r)return r.state!==Ln.WAITING?[]:[{action:"confirmTicketClosure",label:n.confirm,confirmed:!0,ticketId:r.ticketId},{action:"confirmTicketClosure",label:n.decline,confirmed:!1,ticketId:r.ticketId}]}return((t==null?void 0:t.suggested_replies)??[]).map(r=>({action:"sendMessage",label:r}))},am=e=>{const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},_n=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),js=(e,t)=>{const n=_n(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=am(e);return r?`#${_n(r[0])}${_n(r[1])}${_n(r[2])}${n}`:e},cm=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},lm=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",um=e=>e.length>0,dm=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ve(s.type)),r=e.some(s=>!Ve(s.type));return n&&r?Ve(t.type)?e.filter(s=>Ve(s.type)):[t]:r?[t]:e},Xs=e=>e.length===0?"empty":e.every(t=>Ve(t.type))?"images":"non_images",mm=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=dm(t),s=Xs(e),o=Xs(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},Dt=3,Vi=6,hm=e=>e%Dt===0?Dt:Vi,gm=({index:e,itemCount:t})=>{const n=t%Dt,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:Dt,c=o?e-s:e%Dt,u=!r&&e>=t-Dt;return{columnSpan:r?Vi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},Ki=ye("AIAgent"),fm=Ki.Provider,Ie=Ki.useContext;function pm(e){const t=Em(e),n=l.useMemo(()=>({_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,cpaAuthorizationCodes:t.cpaAuthorizationCodes,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}),[t,t.chatSDK,t.deskClient,t.appId,t.aiAgentId,t.language,t.countryCode,t.context,t.cpaAuthorizationCodes,t.logger,t.dispatcher,t.cache,t.networkStateAdapter,t.queryParams,t.config,e.handlers]);return a.createElement(fm,{value:n},e.children)}function Em(e){var o,i;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=Nn.init(e);else{const c=_m(n.current,e);(c.appId||c.aiAgentId||c.chatSDK)&&(t.current.dispose(),t.current=Nn.init({...e,chatParams:c.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var c;(c=t.current)==null||c.dispose()},[]);const r=t.current;r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.cpaAuthorizationCodes=e.cpaAuthorizationCodes,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(o=e.handlers)==null?void 0:o.onLiveMetric;const s=(i=e.handlers)==null?void 0:i.onNudgeMessageReceived;return l.useEffect(()=>{if(s)return r.onNudgeMessageReceived(async c=>s(c))},[r,s]),r}function _m(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Kn=()=>{const[e,t]=l.useState(0),n=l.useCallback(()=>t(r=>r+1),[]);return n.revision=e,n};let Cm=0;function Sm(){return l.useState(()=>`${Cm++}`)[0]}const Ct=(e,t,n)=>{const r=l.useRef(t),o=Sm();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...g)=>{var p;const f=r.current;(p=f[h])==null||p.call(f,...g)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new rt.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function vm(e,t){return!e||!t?!0:e.url!==t.url}function je(e){return e!=null&&"sendingStatus"in e}function bm(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return je(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function ym(e,t){return bm(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Zs(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const Dn={collection:{groupChannel:{defaultOrder:rt.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Js(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Qs(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Am=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=Tm(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=je(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];Im(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{je(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{je(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>ym(s,n));return t.value.clearBeforeAction?e.newMessageMap=Qs(r,Zs):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Qs(r,Zs)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(je(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(je(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Tm=e=>e.reduce((t,n)=>(je(n)?(t[n.reqId]=n,n.sendingStatus===we.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Im=(e,t,n=!1)=>{var r,s;if(!je(e)||!je(t))return!0;if(n&&e&&Te.isStreaming(e)&&Te.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===we.SendingStatus.SUCCEEDED?t.sendingStatus===we.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},xm=(e=Mm)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Am,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(_,E,A,y)=>{i({type:"update_messages",value:{messages:_,clearBeforeAction:E,currentUserId:A,strictStreamingOrder:y}})},u=(_,E)=>{i({type:"delete_messages",value:{messageIds:_,reqIds:E}})},d=(_,E,A)=>{i({type:"update_new_messages",value:{messages:_,clearBeforeAction:E,currentUserId:A}})},m=(_,E)=>{i({type:"delete_new_messages",value:{messageIds:_,reqIds:E}})},h=_=>{i({type:"update_initialized",value:{status:_}})},g=_=>{i({type:"update_loading",value:{status:_}})},f=_=>{i({type:"update_refreshing",value:{status:_}})},p=l.useMemo(()=>Object.values(o),[o]),v=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:g,updateRefreshing:f,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:v,newMessages:p,updateNewMessages:d,deleteNewMessages:m}},eo=Math.floor(Number.MAX_SAFE_INTEGER/10);function Mm(e,t){let n=0,r=0;return je(e)&&e.sendingStatus!=="succeeded"&&(n=eo),je(t)&&t.sendingStatus!=="succeeded"&&(r=eo),e.createdAt+n-(t.createdAt+r)}const Rm=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new rt.MessageFilter(r)})};function to(e){return e<Date.now()?Dn.collection.message.searchLimit:Dn.collection.message.defaultLimit}const km=(e,t,n={})=>{var xe,Oe;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=to(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Kn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:g,loading:f,refreshing:p,messages:v,newMessages:_,updateMessages:E,updateNewMessages:A,deleteNewMessages:y,deleteMessages:T,updateInitialized:I,updateLoading:k,updateRefreshing:L}=xm(n==null?void 0:n.sortComparator),R=ce(x=>{var w,D,U,Z;if(!s.current||!s.current.url)return(w=o==null?void 0:o.error)==null?void 0:w.call(o,"[useGroupChannelMessages] channel is required");try{switch(x){case _e.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case _e.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case _e.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(U=(D=r.current).markAsRead)==null||U.call(D,[s.current]);break}}catch(oe){(Z=o==null?void 0:o.warn)==null||Z.call(o,"[useGroupChannelMessages/markAsReadBySource]",oe)}}),M=ce((x,w)=>{var D,U,Z,oe,Q;if(w.length>0)switch(x){case _e.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case _e.CollectionEventSource.SYNC_MESSAGE_FILL:{(U=(D=r.current).shouldCountNewMessages)!=null&&U.call(D)&&A(w,!1,(Z=e.currentUser)==null?void 0:Z.userId),(Q=(oe=r.current).onMessagesReceived)==null||Q.call(oe,w);break}}}),$=ce(x=>{var w,D;(D=(w=r.current).onCollectionEvent)==null||D.call(w,x)}),N=ce(async(x,w,D)=>new Promise((U,Z)=>{var z,he,ge;h.current.instance&&h.current.instance.dispose(),R(),A([],!0,(z=e.currentUser)==null?void 0:z.userId);const oe=()=>{var de,ve;const{pendingMessages:ie,failedMessages:pe}=h.current.instance??{};Js(ie)&&E(ie,!1,(de=e.currentUser)==null?void 0:de.userId),Js(pe)&&E(pe,!1,(ve=e.currentUser)==null?void 0:ve.userId)},Q=Rm(x,D,{...r.current,startingPoint:w});h.current={apiInitialized:!1,initialized:!1,instance:Q},Q.setMessageCollectionHandler({onMessagesAdded:(ie,pe,de)=>{var ve;R(ie.source),M(ie.source,de),E(de,!1,(ve=e.currentUser)==null?void 0:ve.userId,u),$({kind:"messagesAdded",source:ie.source,channelUrl:x.url,messages:de})},onMessagesUpdated:(ie,pe,de)=>{var ve,Be,He;R(ie.source),M(ie.source,de),E(de,!1,(ve=e.currentUser)==null?void 0:ve.userId,u),ie.source===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((He=(Be=r.current).onMessagesUpdated)==null||He.call(Be,de)),$({kind:"messagesUpdated",source:ie.source,channelUrl:x.url,messages:de})},onMessagesDeleted:(ie,pe,de,ve)=>{const Be=ve.map(Ze=>Ze.messageId),He=ve.filter(je).map(Ze=>Ze.reqId);T(Be,He),y(Be,He),$({kind:"messagesDeleted",source:ie.source,channelUrl:x.url,messages:ve})},onChannelDeleted:(ie,pe)=>{var de,ve;(ve=(de=r.current).onChannelDeleted)==null||ve.call(de,pe)},onChannelUpdated:(ie,pe)=>{var de,ve;m(),(ve=(de=r.current).onChannelUpdated)==null||ve.call(de,pe,ie)},onHugeGapDetected:()=>{N(x,Number.MAX_SAFE_INTEGER,Dn.collection.message.defaultLimit)}});let Se=!1;(ge=(he=r.current).onCollectionInitializeStart)==null||ge.call(he),Q.initialize(rt.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ie,pe)=>{var de,ve,Be,He,Ze;(ve=(de=r.current).onCacheResult)==null||ve.call(de,ie,pe??[],x.url),ie?(e.isCacheEnabled&&((Be=o==null?void 0:o.error)==null||Be.call(o,"[useGroupChannelMessages/onCacheResult]",ie)),Se=!0):pe&&((He=o==null?void 0:o.debug)==null||He.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",pe.length),E(Q.succeededMessages,!0,(Ze=e.currentUser)==null?void 0:Ze.userId),oe(),pe.length>0&&(h.current.initialized=!0,U())),$({kind:"initialized",source:"cache",channelUrl:x.url,messages:pe??[],error:ie})}).onApiResult((ie,pe)=>{var de,ve,Be,He,Ze,Pe,tt;(ve=(de=r.current).onApiResult)==null||ve.call(de,ie,pe??[],x.url),h.current.initialized=!0,h.current.apiInitialized=!0,ie?((Be=o==null?void 0:o.warn)==null||Be.call(o,"[useGroupChannelMessages/onApiResult]",ie),Se?Z(ie):U()):pe&&((He=o==null?void 0:o.debug)==null||He.call(o,"[useGroupChannelMessages/onApiResult]","message length:",pe.length),E(Q.succeededMessages,!0,(Ze=e.currentUser)==null?void 0:Ze.userId),r.current.startingPoint||(tt=(Pe=r.current).onMessagesReceived)==null||tt.call(Pe,pe),e.isCacheEnabled&&oe(),U()),$({kind:"initialized",source:"api",channelUrl:x.url,messages:pe??[],error:ie})})}));Ct(e,{onUserBanned(x,w){var D,U,Z;x.isGroupChannel()&&!vm(x,s.current)&&(w.userId===((D=e.currentUser)==null?void 0:D.userId)?(Z=(U=r.current).onCurrentUserBanned)==null||Z.call(U):m())}}),l.useLayoutEffect(()=>{const x=setTimeout(async()=>{e.currentUser&&s.current&&(I(!1),k(!0),await N(s.current,i,c),k(!1),I(!0))});return()=>clearTimeout(x)},[e,(xe=e.currentUser)==null?void 0:xe.userId,(Oe=s.current)==null?void 0:Oe.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const J=ce(async()=>{e.currentUser&&s.current&&(L(!0),await N(s.current,Number.MAX_SAFE_INTEGER,Dn.collection.message.defaultLimit),L(!1))}),se=ce(async()=>{var w;const x=h.current.instance;if(x!=null&&x.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const D=await x.loadPrevious();E(D,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.prev=!1}}),Y=ce(()=>{const{initialized:x,instance:w}=h.current;return x&&w?w.hasPrevious:!1}),j=ce(async()=>{var w;const x=h.current.instance;if(x!=null&&x.hasNext&&!d.current.next)try{d.current.next=!0;const D=await x.loadNext();E(D,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.next=!1}}),P=ce(()=>{const{initialized:x,apiInitialized:w,instance:D}=h.current;return w&&x&&D?D.hasNext:!1}),K=x=>{var w,D,U,Z;!x||x.channelUrl!==((w=s.current)==null?void 0:w.url)||(E([x],!1,(D=e.currentUser)==null?void 0:D.userId),(Z=(U=r.current).onOutgoingMessageStatusChanged)==null||Z.call(U,x))},q=ce((x,w)=>{var D;if(!s.current||!s.current.url)throw(D=o==null?void 0:o.error)==null||D.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((U,Z)=>{s.current.sendUserMessage(x).onPending(oe=>{K(oe),w==null||w(oe)}).onSucceeded(oe=>{K(oe),U(oe)}).onFailed((oe,Q)=>{K(Q),Z(oe)})})}),W=ce((x,w)=>{var D;if(!s.current||!s.current.url)throw(D=o==null?void 0:o.error)==null||D.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((U,Z)=>{s.current.sendFileMessage(x).onPending(oe=>{K(oe),w==null||w(oe)}).onSucceeded(oe=>{K(oe),U(oe)}).onFailed((oe,Q)=>{K(Q),Z(oe)})})}),H=ce((x,w,D)=>{var U;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((Z,oe)=>{s.current.sendMultipleFilesMessage(x).onPending(Q=>{K(Q),w==null||w(Q)}).onFileUploaded(Q=>{D==null||D(Q),m()}).onSucceeded(Q=>{K(Q),Z(Q)}).onFailed((Q,Se)=>{K(Se),oe(Q)})})}),G=ce(async(x,w)=>{var U,Z;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const D=await s.current.updateUserMessage(x,w);return D.channelUrl===s.current.url&&E([D],!1,(Z=e.currentUser)==null?void 0:Z.userId),D}),V=ce(async(x,w)=>{var U,Z;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const D=await s.current.updateFileMessage(x,w);return D.channelUrl===s.current.url&&E([D],!1,(Z=e.currentUser)==null?void 0:Z.userId),D}),ee=ce(async(x,w,D)=>{var U;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((Z,oe)=>{let Q;x.isUserMessage()&&(Q=s.current.resendMessage(x)),x.isFileMessage()&&(Q=s.current.resendMessage(x)),x.isMultipleFilesMessage()&&(Q=s.current.resendMessage(x)),Q&&("onPending"in Q&&Q.onPending(Se=>{K(Se),w==null||w(Se)}),"onFileUploaded"in Q&&Q.onFileUploaded(Se=>{D==null||D(Se),m()}),"onSucceeded"in Q&&Q.onSucceeded(Se=>{K(Se),Z(Se)}),"onFailed"in Q&&Q.onFailed((Se,z)=>{K(z),oe(Se)}))})}),ae=ce(async x=>{var w,D,U,Z;if(!s.current||!s.current.url)throw(w=o==null?void 0:o.error)==null||w.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(x.sendingStatus==="succeeded")x.isUserMessage()&&await s.current.deleteMessage(x),x.isFileMessage()&&await s.current.deleteMessage(x),x.isMultipleFilesMessage()&&await s.current.deleteMessage(x);else try{await((D=h.current.instance)==null?void 0:D.removeFailedMessage(x.reqId))}finally{T([],[x.reqId]),(Z=(U=r.current).onLocalMessageDeleted)==null||Z.call(U,x)}}),O=ce(()=>{var x;A([],!0,(x=e.currentUser)==null?void 0:x.userId)}),be=ce(async x=>{var w;if(e.currentUser&&s.current){const D=to(x);k(!0),E([],!0,(w=e.currentUser)==null?void 0:w.userId),await N(s.current,x,D),k(!1)}});return{initialized:g,loading:f,refreshing:p,collectionRevision:m.revision,messages:v,newMessages:_,resetNewMessages:O,refresh:J,loadPrevious:se,hasPrevious:Y,loadNext:j,hasNext:P,sendUserMessage:q,sendFileMessage:W,sendMultipleFilesMessage:H,updateUserMessage:G,updateFileMessage:V,resendMessage:ee,deleteMessage:ae,resetWithStartingPoint:be,_dangerous_reducer_updateMessages:E,_dangerous_reducer_deleteMessages:T}},wm=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,Lm=(e,t,n)=>{const r=km(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!wm(o)),[r.messages]);return{...r,messages:s}},Om=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{try{n(t)}catch{}})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},qn=Om(),Nm=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(p=>r.current===p,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(p=>{c(p)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:p,conversationId:v})=>{i.current=!0,n.markChannelJoined(v,p)},[n]),h=l.useCallback(({channelUrl:p})=>{n.clearChannel(p),i.current=!1},[n]),g=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,m(p)}},[c,m]),f=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,h(p)}},[c,h]);return l.useEffect(()=>{if(t){const p=o.current;if(!p||(o.current=null,p.channelUrl!==e))return;"error"in p?h(p):m(p);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:g,onFetchError:f}},Dm=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var f;(f=o.current)==null||f.call(o),o.current=null;const g=u.current;h&&(u.current=null),h&&g&&r.clearChannel(g)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const g=c.current,f=()=>{if(!i.current||g!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(f))??null,n||f()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},nn={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function qi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Pm(e){const t=qi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function $m(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Fm(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function Um(e,t,n){let r,s,o;if(t===0)r=s=o=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},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function Cn(e,t,n){const[r,s,o]=Pm(e),[i,c,u]=Fm(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,g,f]=Um(i,m,d);return $m([Math.round(h),Math.round(g),Math.round(f)])}function Bm(e,t="light"){return{extraDark:Cn(e,.6,1.2),dark:Cn(e,.85,1.1),main:e,light:Cn(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Cn(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Dr(e){const t=qi(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?nn.BLACK:nn.WHITE}function Hm(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100},conversation:{headerProfileSkeleton:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const Gm=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400},conversation:{headerProfileSkeleton:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),Sn={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, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},ur={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 no(e){const t=zm(e),n=Vm(e,t),r=qm(n,e.colors,e.selectedTheme),s=Ym(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function zm({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Sn.primary.main?Sn.primary:Bm(n,e):Sn.primary;return{...Sn,primary:r,...t}}function Vm({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??Dr(o),c=n??nn.DEFAULT_BOT_MSG_BG,u=r??Dr(c);return(e==="light"?Hm:Gm)(s,o,i,c,u)}function Km(e,t,n){return typeof e=="string"?e:e[t]??n}function qm(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=Km(m,n,h)}}}return r}function Wm(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Ym({typography:e}){if(!e)return ur;const t={...ur};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=ur[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Wm(s,r,o)}}),t}const{Provider:jm,useContext:Wn}=ye("AIAgentTheme");function Xm({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>no({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((h,g)=>{g&&(i.current=g);const f=(s==null?void 0:s.theme)??h,p=i.current?i.current.themes[f]:null,v={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!v.primary&&(p!=null&&p.primary_color)&&(v.primary=p.primary_color,v.primaryContrast=p.primary_contrast_color),!v.botMessageBackground&&(p!=null&&p.bot_message_bg_color)&&(v.botMessageBackground=p.bot_message_bg_color,v.botMessageBackgroundContrast=p.bot_message_bg_contrast_color);const _=no({selectedTheme:f,palette:t,typography:n,colors:r,...v});u(_),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]);const m=l.useMemo(()=>({theme:c,updateTheme:d}),[c,d]);return a.createElement(jm,{value:m},o)}const dr=25*1024*1024,ro=1,so=new Set(["image/png","image/jpeg","image/jpg"]),oo=new Set(["application/pdf"]),Zm={off:"off",always:"always",handed_off_only:"handed_off_only"},Jm=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:ro,attachmentMode:"handed_off_only",defaultUploadSizeLimit:dr,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:so,supportedFileMimeTypes:oo})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??ro,attachmentMode:Zm[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??dr,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??so),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??oo)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=dr}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?dt(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return dt(o);default:return!0}},get supportedMimeTypes(){return c()?[xr]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},io=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},Wt=e=>({...e,context:e.context??{}}),{Provider:Qm,useContext:et}=ye("AIAgentMessengerSession"),eh=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=Ie(),{updateTheme:c}=Wn(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[g,f]=l.useState(null),[p,v]=l.useState(null),[_,E]=l.useState(null),[A,y]=l.useState(null),[T,I]=l.useState(null),{updateBaseAttachmentRules:k,createAttachmentRules:L}=Jm();l.useEffect(()=>{const N=r.onMessengerSettingsUpdated(({settings:Y})=>{const{appearance:j,bot:P,launcher:K,memory:q}=Y;c(j.selected_theme,j),E(Md(P)),y(Rd(K)),I(q?Nr(q):null),k(Y)}),J=r.onActiveChannelUpdated(({channelUrl:Y,status:j,conversationStatus:P})=>{h({url:Y,status:j,conversationStatus:P})}),se=r.onAuthTokenRefreshed(()=>{var j;const Y=(j=r.session)==null?void 0:j.userSession.authToken;Y&&v(P=>P?{...P,authToken:Y}:null)});return()=>{N(),J(),se()}},[r,c,k]);const R=l.useCallback(async()=>{try{const N=await r.authenticate(e),J=r.session;return f(J.sdkUser),v(J.userSession),h(J.activeChannel),d(void 0),N}catch(N){throw f(null),v(null),h(void 0),d(N),N}},[r,e]),M=l.useCallback(async()=>{await r.deauthenticate(),f(null),h(void 0),v(null),E(null),y(null),I(null)},[r]),$=l.useCallback(async()=>{if(!r.session){if(p)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(p==null?void 0:p.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,p]);return l.useImperativeHandle(n,()=>{const N=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:R,deauthenticate:M,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,updateContext:async(...J)=>{const se=io(...J);if(se.type==="active"){const P=await(await N()).updateContext(o,se.context);return Wt(P)}const Y=await s.aiAgent.updateContext(se.aiAgentId,se.channelUrl,se.context);return Wt(Y)},patchContext:async(...J)=>{const se=io(...J);if(se.type==="active"){const P=await(await N()).patchContext(o,se.context);return Wt(P)}const Y=await s.aiAgent.patchContext(se.aiAgentId,se.channelUrl,se.context);return Wt(Y)},getContextObject:async()=>{const se=await(await N()).getContextObject(o);return Wt(se)},requestNudgeMessage:J=>r.requestNudgeMessage(J)}},[R,M,m,s,o,i,r]),a.createElement(Qm,{value:{sdkUser:g,userSessionInfo:e,userSession:p,activeChannel:m,setActiveChannel:h,refreshActiveChannel:$,createConversation:r.createConversation,searchConversation:r.searchConversation,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,connectionError:u,aiAgentInfo:_,launcherInfo:A,memoryInfo:T,authenticate:R,deauthenticate:M,createAttachmentRules:L}},t)}),th={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},nh=e=>e.disabled?th[e.disabledBy]==="ready":!0,rh=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ve(t)?"file_image":t&&on(t)?"file_video":t&&fl(t)?"file_audio":"file_document"};let ao=0;const sh=e=>(ao+=1,`${e??"unknown"}:${ao}`),Ot=(e,t)=>e===void 0||t===e,Wi=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Yi=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},oh=(e,t)=>{Wi(e,t)},ih=(e,t)=>{Yi(e,t)},ah=(e,t,n)=>{var o;if(!Ue(e,n))return;const{hasResponseMetadata:r,...s}=Zr(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},co=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Xe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},mr=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},ch=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=Ie(),{aiAgentInfo:r}=et(),s=l.useRef(!1),o=r==null?void 0:r.userId;Ct(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},lh=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(mr(n,s),r.current=void 0);return}s&&s!==t&&(mr(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(mr(n,s),r.current=void 0)},[n])},uh=({aiAgentUserId:e,statsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(f=>i.current&&c.current===f,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const f=d.current;d.current=t,!(f||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const g=l.useCallback(f=>f.lifecycleGeneration===u.current&&Ot(n,f.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const f=s.current;f&&g(f)&&(f.tracked||(Wi(r,f),f.tracked=!0));const p=o.current;p&&g(p)&&(p.tracked||(Yi(r,p),p.tracked=!0))},[t,g,r]),l.useMemo(()=>({onCollectionEvent:f=>{if(h(m)&&Ot(n,f.channelUrl)){if(f.kind==="messagesDeleted"){f.messages.forEach(p=>co(p,r));return}t&&f.messages.forEach(p=>ah(p,r,e))}},onCacheResult:(f,p,v)=>{if(!h(m)||!Ot(n,v))return;const _={error:f,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=_,t&&(oh(r,_),_.tracked=!0)},onApiResult:(f,p,v)=>{if(!h(m)||!Ot(n,v))return;const _={error:f,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=_,t&&(ih(r,_),_.tracked=!0)},onLocalMessageDeleted:f=>{h(m)&&Ot(n,f.channelUrl)&&co(f,r)}}),[e,m,t,h,n,r])},dh=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},mh=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(v=>u==null?void 0:u(v),()=>{});let m;const h=i.current,g=s.current,f=()=>r.current&&o.current&&i.current===h&&s.current===g,p=v=>f()&&Ot(g,v);try{const v=await c(_=>{if(!p(_.channelUrl)){u==null||u(_);return}m=_.reqId,n.messagePendingStuck.start({requestId:_.reqId,channelUrl:_.channelUrl,messageType:rh(_),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(_)},_=>{!f()||m!==_||n.messagePendingStuck.markUploadProgress(_)});return m&&(f()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}catch(v){throw m&&(f()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}},[n])},hh=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=sh(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const g=await c(f=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,f),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,f),h=f)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:g.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:g.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),g}catch(g){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),g}},[e,n])},gh=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=et();ch({activeChannelUrl:t,statsTrackers:r}),lh({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=uh({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=mh({channelUrl:t,enabled:n,statsTrackers:r}),c=hh({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},mt=()=>Ie()._aiAgentSDK.statsTrackers,fh=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=mt(),{watchBackgrounded:r}=Ie()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();Re(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},ph=({enabled:e=!0,channelUrl:t,conversationId:n,messages:r})=>{const{duplicateMessageResponse:s}=mt(),{aiAgentInfo:o}=et(),i=o==null?void 0:o.userId;l.useEffect(()=>{!e||!t||!i||s.onMessagesChanged({channelUrl:t,conversationId:n,aiAgentUserId:i,messages:r})},[i,t,n,e,r,s])},Eh=({enabled:e=!0,channelUrl:t,conversationId:n}={})=>{const{messageLifecycleEvent:r}=mt(),{chatSDK:s,_aiAgentSDK:o}=Ie(),{watchBackgrounded:i}=o,{aiAgentInfo:c}=et(),u=c==null?void 0:c.userId,d=e&&!!t&&!!u;l.useEffect(()=>{r.setBackgroundedWatcher(i)},[r,i]),Ct(d?s:void 0,{onTypingStatusUpdated(f){f.url===t&&r.onTypingChanged({channelUrl:f.url,isAgentTyping:f.getTypingUsers().some(p=>p.userId===u)})}}),l.useEffect(()=>{if(!d||!t||!u)return;const f=qn.subscribe(p=>{r.onCollectionEvent({event:p,channelUrl:t,aiAgentUserId:u})});return()=>{f(),r.clearChannel(t)}},[u,t,d,r]),l.useEffect(()=>{!d||!t||r.onConversationIdResolved({channelUrl:t,conversationId:n})},[t,n,d,r]);const m=l.useCallback(f=>{!d||!t||!Xe(f)||f.sendingStatus!==we.SendingStatus.SUCCEEDED||r.onUserMessageSent({channelUrl:t,conversationId:n,messageId:f.messageId})},[t,n,d,r]),h=l.useCallback(f=>{d&&r.onAnimationStart({messageId:f})},[d,r]),g=l.useCallback((f,p)=>{d&&r.onAnimationComplete({messageId:f,completed:p})},[d,r]);return{onOutgoingMessageStatusChanged:m,onAnimationStart:h,onAnimationComplete:g}},_h=({enabled:e=!0,channelUrl:t,conversationId:n}={})=>{const{streamingMessageValidation:r}=mt(),{watchBackgrounded:s}=Ie()._aiAgentSDK,{aiAgentInfo:o}=et(),i=o==null?void 0:o.userId,c=l.useRef(n);c.current=n,l.useEffect(()=>{r.setBackgroundedWatcher(s)},[r,s]),l.useEffect(()=>{if(!e||!t||!i)return;const u=qn.subscribe(d=>{r.onCollectionEvent({event:d,channelUrl:t,conversationId:c.current,aiAgentUserId:i})});return()=>{u(),r.clearChannel(t)}},[i,t,e,r])},vt=e=>{e&&e.catch(()=>{})},ln=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new _e.ConnectionHandler({onDisconnected:o=>{var i,c;return vt((c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o))},onConnected:o=>{var i,c;return vt((c=(i=r.current).onConnected)==null?void 0:c.call(i,o))},onReconnectStarted:()=>{var o,i;return vt((i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o))},onReconnectSucceeded:()=>{var o,i;return vt((i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o))},onReconnectFailed:()=>{var o,i;return vt((i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o))},onConnectionLost:()=>{var o,i;return vt((i=(o=r.current).onConnectionLost)==null?void 0:i.call(o))},onConnectionDelayed:o=>{var i,c;return vt((c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o))}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},lo=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function Ch(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=Ie(),{sdkUser:u}=et(),d=lo(),m=lo(),[h,g]=l.useState(void 0),f=Kn(),[p,v]=l.useState(void 0),[_,E]=l.useState(!1),A=ce(T=>{if(n&&T.isAIAgent&&!T.conversation){const I=m.next();E(!0),c.initConversationIfNeeded(T,{initialUserMessage:r}).finally(()=>{m.isCurrent(I)&&E(!1)})}});async function y(){var I,k,L,R,M,$;const T=d.next();if(!u){o.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(o.debug("useChannel.getChannel: start"),g(void 0),v(void 0),m.invalidate(),E(!1),e){(I=t.onFetchStart)==null||I.call(t,e);try{o.debug("useChannel.getChannel: get channel",e);const N=await s.groupChannel.getChannel(e);if(!d.isCurrent(T))return;A(N),g(N),(L=t.onFetchSuccess)==null||L.call(t,{channelUrl:N.url,conversationId:(k=N.conversation)==null?void 0:k.id}),N.url===((R=c.session)==null?void 0:R.activeChannel.url)&&c.session._updateActiveChannel({url:N.url,status:$e(N)?"closed":"open",conversationStatus:(M=N.conversation)==null?void 0:M.status}),o.debug("useChannel.getChannel: fetched channel",N)}catch(N){if(!d.isCurrent(T))return;($=t.onFetchError)==null||$.call(t,{channelUrl:e,error:N}),N instanceof _e.SendbirdError&&v(N),o.error("useChannel.getChannel: error",N)}}}return l.useEffect(()=>(y(),()=>{d.invalidate()}),[s,u,e,i]),l.useEffect(()=>{n&&h&&A(h)},[n]),ln(s,{async onReconnectSucceeded(){var T;try{if(!h){p&&await y();return}const I=d.current(),k=await h.refresh();if(!d.isCurrent(I)||h.url!==e)return;(T=t.onReconnectSucceeded)==null||T.call(t,h.url),A(k),g(k)}catch(I){o.error("useChannel.onReconnectSucceeded: failed to sync the channel",I)}}}),Ct(s,{onChannelChanged:T=>{T.isGroupChannel()&&T.url===e&&(o.debug("useChannel.onChannelChanged: channel changed",T.url),g(T),f())}}),{channel:h,channelRevision:f.revision,channelFetchError:p,getChannel:y,isInitializingConversation:_}}const Sh=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!r)return;const s=sn(n);switch(r){case"suggested_replies":return s.hasSuggestedReplies?r:void 0;case"steward":return s.hasSteward?r:void 0;case"system":return r;default:return}},vh=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=sn(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},bh=()=>{const{chatSDK:e,networkStateAdapter:t}=Ie(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return ln(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===_e.ConnectionState.OPEN?"connected":o)})},[t,e]),n},yh=3e4,Ah=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&Ue(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=g=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},g)},m=Date.now()-c,h=yh-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},ji=e=>{const{chatSDK:t}=Ie(),[n,r]=l.useState([]);return Ct(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Th=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=ji(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=Ue(t,n)&&(Te.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},Ih=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=et(),i=bh(),c=Th({channel:e,lastMessage:Rr(t,[we.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Ah({shouldApply:!!(e!=null&&e.isAIAgent)&&!dt(e),isBlockedWhileAIResponding:c,lastMessage:Rr(t,[we.SendingStatus.PENDING,we.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""});if(!e||i==="disconnected")return bt.unavailable;if(i==="reconnecting")return bt.reconnecting;if($e(e))return bt.conversation_closed;if(Zl(e))return bt.handoff_pending;if(vh(e))return bt.form_active;const d=Sh(e);return d?bt[d]:c||u||r?bt.ai_responding:xh},lt=e=>Object.freeze(e==="ai_responding"?{disabled:!0,disabledBy:e,focusPolicy:"preserve"}:{disabled:!0,disabledBy:e,focusPolicy:"release"}),xh=Object.freeze({disabled:!1,disabledBy:"",focusPolicy:"auto"}),bt=Object.freeze({ai_responding:lt("ai_responding"),unavailable:lt("unavailable"),form_active:lt("form_active"),conversation_closed:lt("conversation_closed"),suggested_replies:lt("suggested_replies"),steward:lt("steward"),system:lt("system"),reconnecting:lt("reconnecting"),handoff_pending:lt("handoff_pending")}),Mh=()=>{const[e,t]=l.useState(new Set),[n,r]=l.useState(new Map),s=l.useCallback(h=>{t(g=>{if(g.has(h))return g;const f=new Set(g);return f.add(h),f})},[]),o=l.useCallback(h=>{t(g=>{if(!g.has(h))return g;const f=new Set(g);return f.delete(h),f})},[]),i=l.useCallback((h,g)=>{r(f=>{const p=new Map(f);return p.set(h,g),p})},[]),c=l.useCallback(h=>{r(g=>{if(!g.has(h))return g;const f=new Map(g);return f.delete(h),f})},[]),u=l.useCallback(h=>n.has(h),[n]),d=n.values().next().value,m=e.size>0;return l.useMemo(()=>({isAnimating:m,start:s,stop:o,isHolding:u,heldTypingInfo:d,holdStart:i,holdStop:c}),[m,s,o,u,d,i,c])},{Provider:Rh}=ye("AIAgentConversation");function kh({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=Ee,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,initialUserMessage:g,shouldCountNewMessages:f=()=>!1,sortComparator:p}){var U,Z,oe,Q,Se;const{_aiAgentSDK:v,chatSDK:_,logger:E,dispatcher:A}=Ie(),y=()=>{d&&(M==null||M.markAsRead().catch(z=>E.warn("AIAgentConversationContext: markAsRead failed",z)))},T=mt(),I={channelUrl:t,enabled:m},k=Nm({...I,statsTracker:T.conversationNotInteractiveTimeout}),L=Dm({...I,scheduleForegroundTask:v.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),R=fh(I),{channel:M,channelRevision:$,channelFetchError:N,getChannel:J,isInitializingConversation:se}=Ch(t,{shouldInitializeConversation:h,initialUserMessage:g,onFetchStart:z=>{k.onFetchStart(z),R.onGetChannelStart(z)},onFetchSuccess:z=>{k.onFetchSuccess(z),R.onGetChannelComplete(z)},onFetchError:z=>{k.onFetchError(z),R.onGetChannelError(z)},onReconnectSucceeded:L.onReconnectSucceeded}),Y=M==null?void 0:M.url,j=Eh({enabled:m&&!!(M!=null&&M.isAIAgent)&&M.hasAiBot,channelUrl:Y,conversationId:(U=M==null?void 0:M.conversation)==null?void 0:U.id}),P=gh({requestedChannelUrl:t,activeChannelUrl:Y,statsEnabled:m,statsTrackers:T}),K=Lm(_,M,{replyType:we.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:f,logger:E,markAsRead:y,sortComparator:p,onChannelDeleted:n,onMessagesReceived:z=>r==null?void 0:r(z),onMessagesUpdated:z=>s==null?void 0:s(z),onCollectionInitializeStart:()=>{R.onCollectionInitializeStart()},onApiResult:(z,he,ge)=>{R.onCollectionApiResult(z,ge),P.messageCallbacks.onApiResult(z,he,ge)},onCacheResult:(z,he,ge)=>{R.onCollectionCacheResult(z,ge),P.messageCallbacks.onCacheResult(z,he,ge)},onCollectionEvent:z=>{P.messageCallbacks.onCollectionEvent(z),qn.publish(z)},onLocalMessageDeleted:z=>{P.messageCallbacks.onLocalMessageDeleted(z)},onOutgoingMessageStatusChanged:z=>{j.onOutgoingMessageStatusChanged(z),M&&v.liveMetricManager.track({type:"outgoingMessage",channel:M,message:z})}}),q=Mh(),W=Ih({channel:M,messages:K.messages,isStreamAnimating:q.isAnimating,isInitializingConversation:se});_h({enabled:m,channelUrl:Y,conversationId:(Z=M==null?void 0:M.conversation)==null?void 0:Z.id}),ph({enabled:m,channelUrl:Y,conversationId:(oe=M==null?void 0:M.conversation)==null?void 0:oe.id,messages:K.messages}),dh({enabled:m,channelUrl:Y,initialized:K.initialized,inputReady:nh(W),renderedSignal:K.messages,statsTrackers:T}),l.useEffect(()=>{y()},[d,M]);const H=(Q=M==null?void 0:M.conversation)==null?void 0:Q.status;l.useEffect(()=>{H&&(o==null||o(H))},[H,o]),l.useEffect(()=>{const z=async he=>{const ge=typeof(he==null?void 0:he.channelUrl)=="string";M&&ge&&he.channelUrl!==M.url||(E.debug("conversation.dispatcher: try to close conversation",M),M!=null&&M.conversation&&M.conversation.status===Ce.ConversationStatus.OPEN&&(await M.closeConversation(),i==null||i()))};return A.subscribe(ze.ConversationClose,z),()=>{A.unsubscribe(ze.ConversationClose,z)}},[A,M,E,(Se=M==null?void 0:M.conversation)==null?void 0:Se.status,i]);const G=ce(()=>K.loadPrevious()),V=ce(()=>K.loadNext()),ee=ce(async z=>{try{await K.deleteMessage(z)}finally{z.sendingStatus!=="succeeded"&&P.messageCallbacks.onLocalMessageDeleted(z)}}),ae=ce(z=>z.isUserMessage()?P.runWithUserTurnStats(he=>P.runWithPendingStuckStats(ge=>K.resendMessage(z,ie=>{he(ie.reqId),ge(ie)}),void 0)):P.runWithPendingStuckStats((he,ge)=>K.resendMessage(z,he,ge),void 0,{tracksUploadProgress:z.isMultipleFilesMessage()})),O=ce(()=>K.resetNewMessages()),be=ce(async z=>{var ge;if(((ge=M==null?void 0:M.conversation)==null?void 0:ge.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(z=await c(z));const he=await P.runWithUserTurnStats(ie=>P.runWithPendingStuckStats(pe=>K.sendUserMessage(z,de=>{ie(de.reqId),pe(de)}),u));return u==null||u(he),he}),xe=ce(async z=>{var ge;if(((ge=M==null?void 0:M.conversation)==null?void 0:ge.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(z=await c(z));const he=await P.runWithPendingStuckStats(ie=>K.sendFileMessage(z,ie),u);return u==null||u(he),he}),Oe=ce(async z=>{var ge;if(((ge=M==null?void 0:M.conversation)==null?void 0:ge.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(z=await c(z));const he=await P.runWithPendingStuckStats((ie,pe)=>K.sendMultipleFilesMessage(z,ie,pe),u,{tracksUploadProgress:!0});return u==null||u(he),he}),x=ce(J),w=ce(async()=>{$e(M)||await(M==null?void 0:M.closeConversation())}),D=l.useMemo(()=>({_statsEnabled:m,_stats:{onMessageLifecycleAnimationStart:j.onAnimationStart,onMessageLifecycleAnimationComplete:j.onAnimationComplete},conversation:(M==null?void 0:M.conversation)??void 0,actions:{setUserMemoryState:v.setUserMemoryState},channelSource:{channel:M,error:N,refetch:x,closeConversation:w},messageSource:{messages:K.messages,newMessages:K.newMessages,initialized:K.initialized,loadPrevious:G,loadNext:V,deleteMessage:ee,resendMessage:ae,resetNewMessages:O,sendUserMessage:be,sendFileMessage:xe,sendMultipleFilesMessage:Oe},state:{streamAnimation:q,input:W}}),[m,j.onAnimationStart,j.onAnimationComplete,M,$,v,N,x,w,K.messages,K.newMessages,K.initialized,K.collectionRevision,G,V,ee,ae,O,be,xe,Oe,q,W]);return a.createElement(Rh,{value:D},e)}function wh(e,t,n){var E,A,y,T,I,k,L,R,M,$;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),g=ce(()=>{var N;return(N=n==null?void 0:n.onListRequestStart)==null?void 0:N.call(n)}),f=ce(N=>{var J;return(J=n==null?void 0:n.onListRequestComplete)==null?void 0:J.call(n,N)}),p=l.useCallback(async N=>{g();try{await N.loadMore(),f()}catch(J){throw f(J),J}},[g,f]),v=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const N=new ki(e,t);N.setConversationListCollectionHandler({onChannelsAdded:()=>{u(N.channels)},onChannelsUpdated:()=>{u(N.channels)},onChannelsDeleted:()=>{u(N.channels)}}),await p(N),u(N.channels),m(N),i(null)}catch(N){m(null),i(N)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(E=t.filter)==null?void 0:E.aiAgentChannelFilter,(y=(A=t.filter)==null?void 0:A.aiAgentConversationStatusFilter)==null?void 0:y.join(),(I=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:I.join(),(k=t.filter)==null?void 0:k.deskChannelFilter,(R=(L=t.filter)==null?void 0:L.pinnedChannelUrls)==null?void 0:R.join(),(M=t.filter)==null?void 0:M.copilotConversationOnly,($=t.filter)==null?void 0:$.copilotSupportChannelUrl,t.limit,p]),_=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(N){i(N)}},[d]);return ln(e,{onConnected:()=>v()}),l.useEffect(()=>{v()},[v]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:_}}const Xi=e=>{var s;const{aiAgentId:t,queryParams:n}=Ie(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[Ce.ConversationStatus.CLOSED,Ce.ConversationStatus.OPEN],...r,...e}},Lh=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=mt(),{watchBackgrounded:n}=Ie()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();Re(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:Oh}=ye("AIAgentConversationList");function Nh({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=Ie(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=Xi(t),u=Lh({enabled:n}),d=wh(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:g=>{u.onListRequestComplete(g)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(Oh,{value:m},r)}function Dh(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:Ph,useContext:$h}=ye("MessageTemplateFetching");function Fh({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const f=m(h);if(f)return f;const p=r.current[h];if(p)return p;g||i(h,{fetching:!0});const v=d(h).catch(_=>{throw g||i(h,{error:!0}),_}).finally(()=>{g||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Dh(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(Ph,{value:u},e)}const Uh="remove_powered_by",fs=(e,t)=>{var s,o;const{chatSDK:n}=Ie(),{aiAgentInfo:r}=et();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&ts(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(Uh)),[i])}throw new Error("Unsupported feature")},Bh={required:"This question is required",minLength:e=>`Minimum ${e} characters required`,maxLength:e=>`Maximum ${e} characters allowed`,min:e=>`Minimum value is ${e}`,max:e=>`Maximum value is ${e}`,minSelect:e=>`Select at least ${e} options`,maxSelect:e=>`Select at most ${e} options`,regex:"Invalid format",invalidSelection:"Invalid selection"},Hh={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Gh={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},zh={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;return e.required&&!r?{isValid:!1,error:n.required}:r&&!e.options.includes(r)?{isValid:!1,error:n.invalidSelection}:{isValid:!0}}},Vh={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},Kh={text:Hh,number:Gh,"single-select":zh,"multi-select":Vh},qh={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Zi(e){return Kh[e.type]||qh}function uo(e){return Zi(e).getValueOrDefault(e)}function Wh(e,t,n={}){const r={...Bh,...n};return Zi(e).validate(e,t,r)}const Yh=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const v={};return e.fields.forEach(_=>{v[_.key]=uo(_)}),v}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const v={};let _=!1;e.fields.forEach(E=>{const A=uo(E);JSON.stringify(c[E.key])!==JSON.stringify(A)&&(_=!0),v[E.key]=A}),_&&u(v)}},[d]);const m=(v,_)=>{u(E=>({...E,[v]:_})),i(E=>({...E,[v]:void 0}))},h=e.fields.map(v=>{var A,y,T;const _=c[v.key]??null,E={key:v.key,label:v.label,error:o[v.key],required:v.required};return v.type==="text"?{...E,type:"text",layout:v.layout,value:_,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...E,type:"number",layout:v.layout,value:_,...v.placeholder&&{placeholder:v.placeholder},...((y=v.rules)==null?void 0:y.max)&&{max:v.rules.max}}:v.type==="single-select"?{...E,type:"single-select",layout:v.layout,value:_,options:v.options}:v.type==="multi-select"?{...E,type:"multi-select",layout:v.layout,value:_,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{...E,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(_=>_.key===v),updateFieldValue:m,submit:async()=>{const v={};let _=!1;for(const E of e.fields){const A=c[E.key]??null,y=Wh(E,A,n);y.isValid||(v[E.key]=y.error,_=!0)}if(i(v),!_&&r){const E={};e.fields.forEach(A=>{E[A.key]=c[A.key]??null}),await r(E)}},cancel:async()=>{await(s==null?void 0:s())}}},hr=e=>e.response===null?e:{...e,response:null},Ji=({isMessengerOpened:e,onConversationStarted:t})=>{const{_aiAgentSDK:n,aiAgentId:r,language:s,countryCode:o,context:i}=Ie(),{createConversation:c,userSession:u}=et(),[d,m]=l.useState({seq:0,response:null}),h=u==null?void 0:u.userId;l.useEffect(()=>{if(m(hr),!(e||!h))return n.onNudgeMessageReceived(v=>m(_=>({seq:_.seq+1,response:v})))},[n,e,h]);const g=()=>m(hr),f=l.useRef(!1),p=async()=>{var _;if(!d.response||f.current)return;f.current=!0,m(hr);const v=n.session;try{const E=await c({aiAgentId:r,language:s,country:o,context:i});if(n.session!==v)return;(_=n.session)==null||_._updateActiveChannel({url:E,status:"open"}),t({channelUrl:E,initialUserMessage:d.response.callbackUserMessage})}finally{f.current=!1}};return{nudgeMessage:e?null:d.response,nudgeMessageKey:d.seq,dismissNudgeMessage:g,startNudgeConversation:p}},jh=e=>{const{chatSDK:t,handlers:n,logger:r}=Ie(),{aiAgentInfo:s}=et(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!Ue(m,s.userId))return;const g=m.messageId;if(Te.isStreaming(m)){i.current.add(g);return}h==="updated"&&!i.current.has(g)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(g))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=Ci(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,g)=>{m.url===e&&(c(h,g),u(h))};return Ct(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},Xh=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},Qi=e=>{const{aiAgentInfo:t}=et(),n=ji(e);if($e(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Xh(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Zh=250,Jh=(e,t)=>{var i;const[n,r]=l.useState(!1),s=l.useRef(e),o=l.useRef(void 0);return e!==null?(s.current=e,n||(o.current=t==null?void 0:t.messageId,r(!0))):n&&t!==void 0&&t.sender.userId===((i=s.current)==null?void 0:i.user.userId)&&t.messageId!==o.current&&r(!1),l.useEffect(()=>{if(!n||e!==null)return;const c=setTimeout(()=>r(!1),Zh);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},Qh=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},eg=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},tg=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=eg(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},ng=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},ps=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:void 0,url:void 0,title:""};const r=Li(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?dt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},mo=e=>l.useReducer((t,n)=>({...t,...n}),e);var st=(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))(st||{});const rg=new Set(["free_text","single_choice"]),sg=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=mo({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=mo({followUpItem:!1}),d=l.useMemo(()=>{var _;const f=o.csat,p=typeof f=="number",v=(_=e.follow_up)==null?void 0:_.find(E=>p?E.scores.includes(f):E.always_visible??!1);if(rg.has(v==null?void 0:v.response_type))return v},[o.csat,e.follow_up]),m=(()=>{var f;if(typeof n=="number")return"submitted";if((t===st.AI_AGENT_CSAT_5||t===st.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===st.AI_AGENT_CSAT_5_WITH_CRE){const p=typeof o.csat=="number",v=!((f=e.cre)!=null&&f.required)||typeof o.isResolved=="boolean";if(p&&v)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},og=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!st[n.type],o=!r&&typeof e!="number"&&Oi(t),i=Kn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},gr=5,Xt=250,ea=50,ig=1500,fr=e=>Math.max(0,e-ea),xn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,ag=(e,t)=>{const n=e&&t.length<=ea,r=l.useRef(n&&t.length>0?t:null),[s,o]=l.useState(()=>!n),i=r.current!==null&&t!==r.current,c=!n||i;return l.useEffect(()=>{if(s)return;const u=()=>{r.current=null,o(!0)};if(c){u();return}if(r.current===null&&t.length>0&&(r.current=t),r.current===null)return;const d=setTimeout(u,ig);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},cg=e=>e<1e3?{speed:gr*.5,chunkSize:2}:e<2e3?{speed:gr*.8,chunkSize:2}:{speed:gr*.6,chunkSize:3},Mn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},ho=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(Mn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},ta=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!Mn(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!Mn(e,s),c=e[s]==="["&&!Mn(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=ho(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=ho(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},lg=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(A=>{var y;(y=r.current)==null||y.call(r,A)},[]),m=l.useCallback(A=>{const y=e.initialEnabled&&(e.enabled||A<e.textLength),T=y&&e.deferImages,I=y&&e.deferLinks;return!T&&!I?A:ta(e.text.slice(0,A),{hideImages:T,hideLinks:I}).length},[e]),h=l.useCallback((A,y,T=!1)=>{r.current&&(A<=c.lastLength||!T&&y-c.lastReportedAt<Xt||(c.lastLength=A,c.lastReportedAt=y,d(A)))},[d,c]),g=l.useCallback((A,y,T=!1)=>{if(!r.current)return;const I=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&y-I<Xt||(c.lastCheckedAt=y,h(m(A),y,!0))},[m,h,c]),f=l.useCallback((A,y,T=!1)=>{s.current&&(A<=i.lastLength||!T&&y-i.lastReportedAt<Xt||(i.lastLength=A,i.lastReportedAt=y,s.current(A)))},[i]),p=l.useCallback((A,y,T)=>{const I=A>=y,k=T-i.lastReportedAt>=Xt;if(!I&&!k)return;const L=m(A);f(L,T,I)},[m,i,f]),v=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),_=l.useCallback(A=>{r.current&&(o.current!==null&&A<=o.current||(o.current=A,d(A)))},[d]),E=l.useCallback(({displayedLength:A,streamTextLength:y})=>{const T=u.current;if(u.current={displayedLength:A,streamTextLength:y},!e.initialEnabled||!T||A>T.displayedLength||y<=T.streamTextLength)return;const I=xn();h(y,I,!0),f(y,I,!0)},[u,f,h,e]);return{resetProgress:v,reportVisibleTextProgress:g,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:_,reportMarkdownRevealProgress:E}},ug=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onAnimationHoldChange:u,onVisibleTextProgress:d,onRenderedTextProgress:m}=e,h=ag(n,t),g=s.includes("image"),f=s.includes("link"),[p,v]=l.useState(()=>n?h?0:fr(t.length):t.length),_=l.useRef(null),E=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,A=l.useRef({startCalled:!1,completeCalled:!1}).current,y=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:g,deferLinks:f,snapOnDisable:r,isGatingStreamingStart:h}).current,T=ce(()=>o==null?void 0:o()),I=ce(()=>i==null?void 0:i()),k=ce(q=>c==null?void 0:c(q)),L=ce(q=>u==null?void 0:u(q)),{resetProgress:R,reportVisibleTextProgress:M,reportRenderedTextProgress:$,reportNonStreamingVisibleTextProgress:N,reportMarkdownRevealProgress:J}=lg({trackedRef:y,onVisibleTextProgress:d,onRenderedTextProgress:m}),se=n,Y=p<t.length,j=y.initialEnabled&&(se||Y);l.useLayoutEffect(()=>{y.textLength=t.length,y.enabled=n,y.text=t,y.deferImages=g,y.deferLinks=f,y.snapOnDisable=r,y.isGatingStreamingStart=h}),l.useLayoutEffect(()=>{if(y.initialEnabled){if(A.startCalled||(A.startCalled=!0,T()),!y.enabled&&y.snapOnDisable){v(t.length);const q=xn();M(t.length,q,!0),$(t.length,t.length,q);return}v(q=>t.length<q?t.length:q)}},[T,$,M,t]),l.useEffect(()=>{if(!y.initialEnabled)return;let q=h?0:fr(t.length),W=h;E.lastUpdate=0,E.startTime=0,E.lastProgressCall=0,R();const H=G=>{E.lastUpdate===0&&(E.lastUpdate=G,E.startTime=G,E.lastProgressCall=G,q>0&&M(q,G,!0));const V=y.textLength;W&&!y.isGatingStreamingStart&&(q=fr(V),v(q),q>0&&M(q,G,!0),E.lastUpdate=G,W=!1),!y.enabled&&y.snapOnDisable&&q<V&&(q=V,v(q),M(q,G,!0),$(q,V,G));const ee=G-E.lastUpdate,ae=G-E.startTime,{speed:O,chunkSize:be}=cg(ae),xe=O*be;!y.isGatingStreamingStart&&ee>=xe&&q<V&&(q=Math.min(q+be,V),v(q),M(q,G,q>=V),$(q,V,G),E.lastUpdate=G),G-E.lastProgressCall>=Xt&&(E.lastProgressCall=G,I()),(q<V||y.enabled)&&(_.current=requestAnimationFrame(H))};return _.current=requestAnimationFrame(H),()=>{_.current&&cancelAnimationFrame(_.current),A.startCalled&&!A.completeCalled&&(A.completeCalled=!0,k({completed:!1}))}},[k,I,$,M,R]),l.useEffect(()=>{y.initialEnabled&&(n||t.length>0)||(N(t.length),$(t.length,t.length,xn()))},[n,m,d,N,$,t.length,y]),l.useEffect(()=>{const q=y.initialEnabled&&A.startCalled,W=!n,H=p>=t.length;q&&W&&H&&!A.completeCalled&&(A.completeCalled=!0,k({completed:!0}))},[n,p,k,t.length]);const P=l.useMemo(()=>{let q=t;y.initialEnabled&&(q=h?"":t.slice(0,p));const W=j&&g,H=j&&f;return!W&&!H?q:ta(q,{hideImages:W,hideLinks:H})},[t,p,g,f,j,h]);l.useEffect(()=>{!y.initialEnabled||j||M(p,xn(),!0)},[p,j,M]),l.useEffect(()=>{J({displayedLength:p,streamTextLength:P.length})},[p,J,P.length]);const K=P.length===0&&j;return l.useLayoutEffect(()=>(L(K),()=>L(!1)),[L,K]),{streamText:P,isAnimating:j,isHolding:K}},go={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},dg=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),mg=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},hg=()=>{const{chatSDK:e}=Ie(),[t,n]=l.useState(go),r=()=>n(go);return ln(e,{onConnectionDelayed:s=>{s>0?n(dg(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>mg(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},gg=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},fg=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},pg=({enabled:e=!0}={})=>{const t=mt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=Te.isStreaming(n),c=sn(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!pl(n)&&!Te.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),g=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!g&&!m&&!u&&!d)return;let f=!1,p=!1;const v={};return(g||m)&&(v.onVisibleTextProgress=()=>{g&&!f&&(f=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!p&&(p=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(v.onRenderedTextProgress=_=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:_})}),u&&(v.onMessageTemplateError=_=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:_})}),d&&(v.onFormRenderError=_=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:_})}),v},[e,t])},Eg=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},pr=5e3,_g=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=mt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-pr:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(performance.now()-u.current<pr){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=performance.now()-pr):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Cg=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=mt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Sg=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(g=>{h===i.current&&o(g.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===_e.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),ln(e,{onConnected:c,onReconnectSucceeded:c}),s},$t=e=>e.replace(/\s+/g," ").trim(),vg="Code block",na=e=>`A11Y_INLINE_CODE_${e}`,ra=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},sa=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},bg=e=>{const{blockquotePrefix:t,content:n}=ra(e),{content:r}=sa(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},yg=(e,t)=>{const{blockquotePrefix:n,content:r}=ra(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=sa(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},Ag=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},Tg=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},Ig=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},xg=e=>{let t=0,n="";for(;t<e.length;){const r=Ag(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Tg(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Pn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!Pn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=Ig(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},oa=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Mg=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return oa(n,r,i)?t:`${n}${r}`}),Rg=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),kg=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),wg=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return oa(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Lg=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Og=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},fo=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},po=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},Ng=e=>{const t=e.split(`
10
+ `),r=Jr(t);return r.map((s,o)=>{var c;if(s.kind!=="text")return s.value;const i=n(s.value);return((c=r[o-1])==null?void 0:c.kind)!=="span"?i:i.replace(/^([ \t]*)\n(?![ \t]*\n)/,`$1
11
+ `)}).join("")},xr=(...e)=>(t,n)=>e.reduce((r,s)=>s(r,n),t),Us=xr(Sl(xr(Fs(Tl,{anchorsLineEnd:!0}),vl,Fs(bl),Il)),Al),Ml=({convertSoftBreaks:e=!1}={})=>e?xr(xl,Us):Us,Mi=typeof navigator<"u"&&navigator.product==="ReactNative",Rl=(e,t)=>{for(let n=0;n<e.length;n++){const r=Mi?n:e.length-1-n,s=e[r];if(s&&t(s)==="stop")return}},Mr=(e,t)=>{const n=r=>!t||t.length===0?!0:Xe(r)&&t.includes(r.sendingStatus);return Mi?e.find(n):e.findLast(n)},kl=(e,t)=>{const n=Mr(e,[we.SendingStatus.SUCCEEDED]);return n&&Le.isIncoming(n,t)?n:void 0},Re=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function Ee(){}function wl(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Ll(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 Ie={isStreaming(e){return al(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(Ie.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!Ue(e,t))return!1;const n=Xr(e.data);return!n.isStreaming&&!n.hasResponseMetadata},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)}},ar=`@${wt}`,Ol=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${ar}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Ll(`${e}/${t}/${s}`);return`${ar}-udata/${o}`},anonUserSession:()=>`${ar}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Ri=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},Nl=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class Dl{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??Ce.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[Ce.ConversationStatus.OPEN,Ce.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??Ce.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===Ce.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==Ce.DeskChannelFilter.EXCLUDE:!1}}class ki extends rt.BaseChannelCollection{constructor(n,r){const s=new Dl(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=rt.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,g,f)=>i.getMyGroupChannels(m,h.params,f),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:g,deskChannelFilter:f,pinnedChannelUrls:p,copilotConversationOnly:C,copilotSupportChannelUrl:_}=s.params,E={aiAgentChannelFilter:h,aiAgentIds:g,deskChannelFilter:f,pinnedChannelUrls:p,copilotConversationOnly:C,copilotSupportChannelUrl:_};return i.getMyGroupChannelChangeLogs(m,E,rt.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});S(this,"_params");S(this,"_sdk");S(this,"_throttledOnChannelChanged");S(this,"_key");S(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Nl()}`,this._throttledOnChannelChanged=Ri(()=>{var f;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:p,context:C}of m)h.delete(p.url),h.set(p.url,{channel:p,context:C});const g=new Map;for(const{channel:p,context:C}of h.values())g.has(C)||g.set(C,new Map),g.get(C).set(p.url,p);for(const[p,C]of g){const _=Array.from(C.values()),E=(f=this._sdk.currentUser)==null?void 0:f.userId,A=_.filter(T=>this.filter.match(T,E)),y=_.filter(T=>!this.filter.match(T,E)).map(T=>T.url);A.length>0&&this._base._addChannelsToView(A,p,!1),y.length>0&&this._removeChannels(y,p)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const g of m)this._pendingChannels.push({channel:g,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class wi{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=Pl(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Pl=()=>{let e=Ee,t=Ee;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var ze=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e.NudgeMessageReceived="nudge.message.received",e))(ze||{});class Ut{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const ut={CloseConversation:e=>new $l(e),MessengerSettingsUpdated:e=>new Fl(e),ActiveChannelUpdated:e=>new Ul(e),AnonymousSessionTokenExpired:()=>new Bl,AuthTokenRefreshed:()=>new Hl,NudgeMessageReceived:e=>new Gl(e)};class $l extends Ut{constructor(){super(...arguments);S(this,"type","conv.close")}}class Fl extends Ut{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class Ul extends Ut{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Bl extends Ut{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Hl extends Ut{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}class Gl extends Ut{constructor(){super(...arguments);S(this,"type","nudge.message.received")}}const Bt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class an{constructor(t){S(this,"category","connection");this.userId=t}get data(){return Bt({user_id:this.userId})}}class zl extends an{constructor(){super(...arguments);S(this,"metricKey","connection_connected")}}class Vl extends an{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_started")}}class Kl extends an{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_succeeded")}}class ql extends an{constructor(){super(...arguments);S(this,"metricKey","connection_reconnect_failed")}}class Wl extends an{constructor(){super(...arguments);S(this,"metricKey","connection_disconnected")}}class Yl{constructor(t){S(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new zl(n):t==="reconnectStarted"?new Vl(n):t==="reconnectSucceeded"?new Kl(n):t==="reconnectFailed"?new ql(n):new Wl(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Qr{constructor(t,n){S(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return Bt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class jl extends Qr{constructor(){super(...arguments);S(this,"metricKey","conversation_initialized")}}class Xl extends Qr{constructor(){super(...arguments);S(this,"metricKey","conversation_open")}}class Zl extends Qr{constructor(){super(...arguments);S(this,"metricKey","conversation_closed")}}class Jl{constructor(t){S(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===Ce.ConversationStatus.INITIALIZED?new jl(t.url,n.id):s===Ce.ConversationStatus.OPEN?new Xl(t.url,n.id):new Zl(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===Ce.ConversationStatus.INITIALIZED?t===void 0:n===Ce.ConversationStatus.OPEN?t===Ce.ConversationStatus.INITIALIZED:t===Ce.ConversationStatus.OPEN}}const Ql=(e,t)=>{if(e)return e.members.find(n=>n.userId!==t)},eu=e=>{var r,s,o;const t=(s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.assignedAgent;if(!t)return;const n=e==null?void 0:e.members.find(({userId:i})=>i===t.userId);return{nickname:((o=n==null?void 0:n.nickname)==null?void 0:o.trim())||t.name,profileUrl:n==null?void 0:n.profileUrl}},Li=(e,t)=>e!=null&&e.isAIAgent?eu(e):Ql(e,t),$e=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ce.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},es=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ce.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function dt(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function tu(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!dt(e):!1}function nu(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Oi(e){return!!e&&e<=Date.now()}function ru(e){return!e.title}function su(e,t){var n;if(e)return ru(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question,always_visible:!1}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}class ts{constructor(t,n){S(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return Bt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class ou extends ts{constructor(){super(...arguments);S(this,"metricKey","handoff_started")}}class iu extends ts{constructor(){super(...arguments);S(this,"metricKey","handoff_succeeded")}}class au extends ts{constructor(){super(...arguments);S(this,"metricKey","handoff_failed")}}class cu{constructor(t){S(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new ou(t.url,r.id):o==="succeeded"?new iu(t.url,r.id):new au(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if($e(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class lu{constructor(t){S(this,"category","message");S(this,"metricKey","incoming_message_received");S(this,"channelUrl");S(this,"messageId");S(this,"senderType");S(this,"createdAt");S(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return Bt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const uu=(e,t)=>{const n=Xe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class du{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new lu({channelUrl:t.url,messageId:n.messageId,senderType:uu(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!Ue(t,this.getCurrentUserId())&&n!==null}}class ns{constructor(t){S(this,"category","memory");S(this,"action");S(this,"deleteOnOff");S(this,"userId");this.action=t.action,this.deleteOnOff=t.deleteOnOff,this.userId=t.userId}get data(){return Bt({action:this.action,delete_on_off:this.deleteOnOff,user_id:this.userId})}}class mu extends ns{constructor(){super(...arguments);S(this,"metricKey","memory_consent")}}class hu extends ns{constructor(){super(...arguments);S(this,"metricKey","memory_on")}}class gu extends ns{constructor(){super(...arguments);S(this,"metricKey","memory_off")}}const fu={consent:{Metric:mu,actions:{shown:"shown",confirm:"enable",cancel:"disable"}},on:{Metric:hu,actions:{shown:"shown",confirm:"keep",cancel:"disable",dismiss:"dismiss"}},off:{Metric:gu,actions:{shown:"shown",confirm:"keep",cancel:"enable",dismiss:"dismiss"}}};class pu{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({variant:t,action:n,deleteOnOff:r}){if(t==="readonly")return;const{Metric:s,actions:o}=fu[t],i=o[n];i&&this.dispatch(new s({action:i,deleteOnOff:t==="on"?r:void 0,userId:this.getCurrentUserId()}))}}class Eu{constructor(t){S(this,"category","message");S(this,"metricKey");S(this,"channelUrl");S(this,"requestId");S(this,"messageId");S(this,"target");S(this,"sendingStatus");S(this,"createdAt");S(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return Bt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const _u=e=>{switch(e){case we.SendingStatus.PENDING:return"pending";case we.SendingStatus.SUCCEEDED:return"succeeded";case we.SendingStatus.FAILED:return"failed";case we.SendingStatus.SCHEDULED:return"scheduled";default:return}};class Cu{constructor(t,n){S(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!Ue(n,this.getCurrentUserId()))return;const r=_u(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new Eu({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:dt(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class Su{constructor(t){S(this,"id","aiagent_livemetric");S(this,"dispatch");S(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});S(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new Yl(this.emit),conversation:new Jl(this.emit),handoff:new cu(this.emit),incomingMessage:new du(this.emit,n),outgoingMessage:new Cu(this.emit,n),memory:new pu(this.emit,n)}}start(){const t=new _e.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new rt.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var rs=(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))(rs||{});class Ni{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${wt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${wt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${wt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${wt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${wt}/error]`,...t)}}class Di{constructor({userId:t,authToken:n,sessionHandler:r}){S(this,"userId");S(this,"authToken");S(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class Rr{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const vu=e=>({onSessionTokenRequired:t=>{t(null),e.send(ut.AnonymousSessionTokenExpired())}}),ss=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),bu="ai_agent:stats",os="ai_agent:assertion",yu="conversation_initial_render",Au="conversation_not_interactive_timeout",Tu="recovery_not_interactive_timeout",Iu="conversation_list_initial_render",xu="message_pending_stuck",Mu="aiev_auth_expired_unhandled",Ru="user_perceived_response_time",ku="stream_stalled",wu="ai_typing_indicator_absent_timeout",Lu="rendered_content_unusable",Ou="streaming_message_validation",Nu="duplicate_message_response",Du="message_lifecycle_event",Pu=800220;var X=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(X||{});const kr=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),Pi=e=>typeof e=="object"&&e!==null,$u=e=>{if(Pi(e))return typeof e.code=="number"?e.code:void 0},Fu=e=>e instanceof Error?e.message:typeof e=="string"?e:Pi(e)&&typeof e.message=="string"?e.message:"";class qe{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}getStatType(){return bu}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=$u(t)??Pu,this.errorDescription=Fu(t),this)}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:performance.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=ss({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(this.getStatType(),t)):!1}}class Bs extends qe{constructor(){super(...arguments);S(this,"reason");S(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return Mu}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Ht{constructor(t){S(this,"commitCallback");this.commitCallback=t}}class Tt extends Ht{constructor(){super(...arguments);S(this,"records",new Map)}}class $i extends Ht{constructor(){super(...arguments);S(this,"activeSpan",null);S(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class is{constructor(t,n){S(this,"stats");S(this,"visible");S(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const yt=(e,t)=>!(e&&t&&e!==t),wr=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&yt(n.measure.channelUrl,t))return!0;return!1},cn=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class Uu extends Ht{onPayloadParseFailed(t){new Bs().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new Bs().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Bu extends qe{constructor(){super(...arguments);S(this,"channelUrl",null);S(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(X.PAGE_RENDER),this.timers.delete(X.PAGE_RENDER_FROM_CACHE),this.timers.delete(X.GET_CHANNEL),this.timers.delete(X.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return yu}buildPayload(){const n=this.getTimer(X.AUTH),r=this.getTimer(X.PAGE_RENDER),s=this.getTimer(X.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-kr(n,r),i=s.duration===null?null:s.duration-kr(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[X.AUTH]:n.duration,[X.GET_CHANNEL]:this.getTimer(X.GET_CHANNEL).duration,[X.GET_MESSAGES]:this.getTimer(X.GET_MESSAGES).duration,[X.PAGE_RENDER_FROM_CACHE]:i}})}}class Hu extends is{constructor(n,r,s){var o;super(n,s);S(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(X.PAGE_RENDER).startTimer(X.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(X.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(X.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(X.GET_CHANNEL).setError(r).stopTimer(X.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(X.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(X.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(X.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(X.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(X.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(X.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Gu extends $i{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Bu().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(X.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(X.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(X.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new Hu(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class zu extends qe{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(X.PAGE_RENDER),this.timers.delete(X.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Iu}buildPayload(){const n=this.getTimer(X.AUTH),r=this.getTimer(X.PAGE_RENDER),s=this.getTimer(X.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-kr(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[X.AUTH]:n.duration,[X.GET_LIST]:s}})}}class Vu extends is{constructor(n,r){var s;super(n,r);S(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(X.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(X.PAGE_RENDER),this.stats.startTimer(X.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(X.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(X.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(X.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(X.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class Ku extends $i{constructor(){super(...arguments);S(this,"stats",null);S(this,"authState","idle");S(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new zu().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(X.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(X.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(X.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(X.AUTH),this.activeSpan=new Vu(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class qu extends qe{constructor(){super(...arguments);S(this,"phaseReached","auth");S(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return Au}buildPayload(){const n=this.getTimer(X.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class Wu extends Tt{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new qu().setCommitCallback(this.commitCallback).startTimer(X.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(X.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Yu extends qe{constructor(){super(...arguments);S(this,"previousMessageId");S(this,"nextMessageId")}setDuplicatePair(n){return this.previousMessageId=n.previousMessageId,this.nextMessageId=n.nextMessageId,this}getStatType(){return os}getMetricKey(){return Nu}buildPayload(){return this.previousMessageId===void 0||this.nextMessageId===void 0?null:this.createPayload("",{extra:{prev_message_id:String(this.previousMessageId),next_message_id:String(this.nextMessageId)}})}}const ju=500,Xu=(e,t)=>Ue(e,t)&&!Ie.isStreaming(e)&&!!e.message;class Zu extends Ht{constructor(){super(...arguments);S(this,"emittedMessageChannels",new Map)}onMessagesChanged(n){const r=this.findLastTwoReplies(n.messages,n.aiAgentUserId);r&&r.previous.message===r.latest.message&&(this.emittedMessageChannels.has(r.latest.messageId)||this.emit(r.latest,r.previous,n))}clear(){this.emittedMessageChannels.clear()}findLastTwoReplies(n,r){let s=null,o=null;return Rl(n,i=>{if(!(Xe(i)&&i.sendingStatus!==we.SendingStatus.SUCCEEDED)&&Ue(i,r)){if(!Xu(i,r))return"stop";if(!s)s=i;else return o=i,"stop"}}),s&&o?{latest:s,previous:o}:null}emit(n,r,s){cn(this.emittedMessageChannels,ju),this.emittedMessageChannels.set(n.messageId,s.channelUrl),new Yu().setDuplicatePair({previousMessageId:r.messageId,nextMessageId:n.messageId}).setConversationId(s.conversationId).setCommitCallback(this.commitCallback).commit()}}const Ju=-1;class Qu extends qe{constructor(){super(...arguments);S(this,"timestamps")}setTimestamps(n){return this.timestamps=n,this}setFailure(n){return this.setError(n),this}getStatType(){return os}getMetricKey(){return Du}buildPayload(){const n=this.timestamps;if(!n)return null;const r=n.messageSentAt??n.streamStartAt,s=n.animationEndAt,o=s===void 0||r===void 0?Ju:s-r;return this.createPayload(o,{extra:{message_id:n.messageId===void 0?void 0:String(n.messageId),message_sent_at:n.messageSentAt,typing_start_at:n.typingStartAt,typing_end_at:n.typingEndAt,stream_start_at:n.streamStartAt,stream_failed_at:n.streamFailedAt,last_stream_at:n.lastStreamAt,stream_end_at:n.streamEndAt,animation_start_at:n.animationStartAt,animation_end_at:n.animationEndAt}})}}const ed=3e4,td=1e4,nd=e=>{var t;return((t=e.extendedMessagePayload)==null?void 0:t.is_last_in_turn)===!0};class rd extends is{constructor(n,r){super(n,!0);S(this,"measure");this.measure={messageSentAt:r.messageSentAt,startTimeoutTimer:null,stallTimer:null,stopBackgroundWatch:r.stopBackgroundWatch}}armStartTimeout(){this.measure.startTimeoutTimer=setTimeout(()=>this.failWith("sent_timeout"),ed)}setConversationId(n){var r;(r=this.stats)==null||r.setConversationId(n)}onTypingChanged(n){if(this.stats){if(n){this.measure.typingStartAt===void 0&&(this.measure.typingStartAt=Date.now());return}this.measure.typingStartAt!==void 0&&this.measure.typingEndAt===void 0&&(this.measure.typingEndAt=Date.now())}}onStreamStart(n){this.stats&&(this.measure.streamMessageId=n.messageId,this.measure.streamStartAt=Date.now(),this.clearStartTimeout(),this.armStall())}onStreamFrame(n,r){if(!this.stats)return;const s=Date.now();if(r&&(this.measure.lastStreamAt=s),Ie.isStreaming(n))return this.armStall();this.measure.streamEndAt=s,this.clearStall(),this.measure.animationStartAt===void 0&&this.failWith("animation_not_started")}onAnimationStart(){this.stats&&this.measure.animationStartAt===void 0&&(this.measure.animationStartAt=Date.now())}onAnimationComplete(n){if(this.stats){if(!n)return this.cancel();this.settle({animationEndAt:Date.now()})}}cancel(){var n,r;this.clearTimers(),(r=(n=this.measure).stopBackgroundWatch)==null||r.call(n),super.cancel()}failWith(n){if(this.stats){if(this.stats.setFailure(n),n!=="stream_failed")return this.settle({});this.settle(this.measure.lastStreamAt===void 0?{streamFailedAt:Date.now(),streamStartAt:void 0}:{streamFailedAt:Date.now(),lastStreamAt:this.measure.lastStreamAt})}}settle(n){var r,s;if(this.stats){if(this.clearTimers(),(s=(r=this.measure).stopBackgroundWatch)!=null&&s.call(r))return super.cancel();this.stats.setTimestamps({messageId:this.measure.streamMessageId,messageSentAt:this.measure.messageSentAt,typingStartAt:this.measure.typingStartAt,typingEndAt:this.measure.typingEndAt,streamStartAt:this.measure.streamStartAt,streamEndAt:this.measure.streamEndAt,animationStartAt:this.measure.animationStartAt,...n}),this.commitOrDefer()}}armStall(){this.clearStall(),this.measure.stallTimer=setTimeout(()=>this.failWith("stream_failed"),td)}clearTimers(){this.clearStartTimeout(),this.clearStall()}clearStartTimeout(){this.measure.startTimeoutTimer!==null&&clearTimeout(this.measure.startTimeoutTimer),this.measure.startTimeoutTimer=null}clearStall(){this.measure.stallTimer!==null&&clearTimeout(this.measure.stallTimer),this.measure.stallTimer=null}}class sd extends Ht{constructor(){super(...arguments);S(this,"block",null);S(this,"watchBackgrounded")}setBackgroundedWatcher(n){this.watchBackgrounded=n}onUserMessageSent(n){this.discardBlock();const r=this.createSpan(n.conversationId,{messageSentAt:Date.now()});r.armStartTimeout(),this.block={channelUrl:n.channelUrl,userMessageId:n.messageId,conversationId:n.conversationId,first:r,firstAnnounced:!1,spans:new Map,closed:!1}}onConversationIdResolved(n){const r=this.blockFor(n.channelUrl);r&&(r.conversationId??(r.conversationId=n.conversationId),r.first.setConversationId(n.conversationId),r.spans.forEach(s=>s.setConversationId(n.conversationId)))}onTypingChanged(n){var r;(r=this.blockFor(n.channelUrl))==null||r.first.onTypingChanged(n.isAgentTyping)}onCollectionEvent(n){const r=this.blockFor(n.channelUrl),s=n.event;if(!r||s.channelUrl!==n.channelUrl)return;if(s.kind==="messagesDeleted"){s.messages.forEach(i=>{var c;return(c=r.spans.get(i.messageId))==null?void 0:c.cancel()});return}if(s.kind==="initialized")return;const o=s.source===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED;s.messages.forEach(i=>{Ue(i,n.aiAgentUserId)&&Xr(i.data).userMessageId===r.userMessageId&&this.observeReply(r,i,o)})}onAnimationStart(n){var r,s;(s=(r=this.block)==null?void 0:r.spans.get(n.messageId))==null||s.onAnimationStart()}onAnimationComplete(n){var r,s;(s=(r=this.block)==null?void 0:r.spans.get(n.messageId))==null||s.onAnimationComplete(n.completed)}clearChannel(n){!n||!this.blockFor(n)||this.discardBlock()}clear(){this.discardBlock()}observeReply(n,r,s){const o=Ie.isStreaming(r);nd(r)&&(n.lastMessageId=r.messageId);const i=n.lastMessageId===r.messageId&&!o,c=n.spans.get(r.messageId);if(c){c.onStreamFrame(r,s),i&&(n.closed=!0);return}if(n.closed)return;if(!o){n.firstAnnounced||n.first.cancel(),n.firstAnnounced=!0,i&&(n.closed=!0);return}const u=n.firstAnnounced?this.createSpan(n.conversationId,{}):n.first;n.firstAnnounced=!0,u.onStreamStart(r),n.spans.set(r.messageId,u)}createSpan(n,r){var o;const s=new Qu().setConversationId(n).setCommitCallback(this.commitCallback);return new rd(s,{messageSentAt:r.messageSentAt,stopBackgroundWatch:((o=this.watchBackgrounded)==null?void 0:o.call(this))??null})}discardBlock(){const n=this.block;n&&(n.first.cancel(),n.spans.forEach(r=>r.cancel()),this.block=null)}blockFor(n){const r=this.block;if(!(!r||r.channelUrl!==n))return r}}class od extends qe{constructor(){super(...arguments);S(this,"requestId");S(this,"messageType");S(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return xu}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const id=5e3,Hs=1e4;class ad extends Tt{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new od().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?Hs:id;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),Hs))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class cr extends qe{constructor(){super(...arguments);S(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return Tu}buildPayload(){const n=this.getTimer(X.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class cd extends Tt{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new cr().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(X.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(X.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new cr().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new cr().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class ld extends qe{constructor(){super(...arguments);S(this,"messageId");S(this,"contentKind");S(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return Lu}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const ud=500;class dd extends Ht{constructor(){super(...arguments);S(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;cn(this.measure.committed,ud),this.measure.committed.add(r),new ld().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class md extends qe{constructor(){super(...arguments);S(this,"durationMs");S(this,"messageId");S(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return ku}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const Gs=1e4,kt=5e3,hd=500;class gd extends Tt{constructor(){super(...arguments);S(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,kt))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,kt)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,kt))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<kt){this.scheduleRenderStallCheck(n,r,kt-o);return}const i=performance.now()-s.lastRawAt;if(i>=kt&&s.deliveryTimer!==null){const c=Gs-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),Gs))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new md().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||cn(this.emittedMessageChannels,hd),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class fd extends qe{constructor(){super(...arguments);S(this,"durationMs");S(this,"messageId");S(this,"chunkIntervalsMs",[]);S(this,"regenerated",!1)}setMessageId(n){return this.messageId=n,this}setStream(n){return this.durationMs=n.durationMs,this.chunkIntervalsMs=n.chunkIntervalsMs,this.regenerated=n.regenerated,this}getStatType(){return os}getMetricKey(){return Ou}buildPayload(){return this.durationMs===void 0||this.messageId===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),chunk_intervals_ms:this.chunkIntervalsMs,regenerated:this.regenerated}})}}const pd=-1,Ed=e=>e===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED;class _d extends Tt{constructor(){super(...arguments);S(this,"watchBackgrounded")}setBackgroundedWatcher(n){this.watchBackgrounded=n}onCollectionEvent(n){const r=n.event;if(r.channelUrl!==n.channelUrl)return;if(r.kind==="messagesDeleted"){r.messages.forEach(o=>{const i=this.records.get(o.messageId);i&&this.drop(o.messageId,i)});return}if(r.kind==="initialized"||!Ed(r.source))return;const s=r.source===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED;r.messages.forEach(o=>{const i=this.records.get(o.messageId);if(!i){s&&Ue(o,n.aiAgentUserId)&&Ie.isStreaming(o)&&this.start(o,n.channelUrl,n.conversationId);return}i.measure.channelUrl===n.channelUrl&&(i.stats.setConversationId(n.conversationId),this.advance(i,o),Ie.isStreaming(o)||this.finish(o.messageId,i))})}clearChannel(n){n&&this.records.forEach((r,s)=>{r.measure.channelUrl===n&&this.drop(s,r)})}clear(){this.records.forEach((n,r)=>this.drop(r,n))}start(n,r,s){var i;this.clearChannel(r);const o=performance.now();this.records.set(n.messageId,{stats:new fd().setMessageId(n.messageId).setConversationId(s).setCommitCallback(this.commitCallback),measure:{channelUrl:r,startedAt:o,lastAt:o,lastText:n.message,chunkIntervalsMs:[],regenerated:!1,stopBackgroundWatch:((i=this.watchBackgrounded)==null?void 0:i.call(this))??null}})}advance(n,r){const s=n.measure,o=r.message;if(o===s.lastText)return;o.startsWith(s.lastText)||(s.regenerated=!0,s.chunkIntervalsMs.push(pd));const i=performance.now();s.chunkIntervalsMs.push(Math.round(i-s.lastAt)),s.lastText=o,s.lastAt=i}finish(n,r){var o;const s=r.measure;this.records.delete(n),!((o=s.stopBackgroundWatch)!=null&&o.call(s))&&r.stats.setStream({durationMs:Math.round(performance.now()-s.startedAt),chunkIntervalsMs:s.chunkIntervalsMs,regenerated:s.regenerated}).commit()}drop(n,r){var s,o;(o=(s=r.measure).stopBackgroundWatch)==null||o.call(s),this.records.delete(n)}}class Cd extends qe{constructor(){super(...arguments);S(this,"beforeTpstAbsentMs");S(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return wu}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[X.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[X.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const zs=3e3,Sd=3e4;class vd extends Tt{constructor(){super(...arguments);S(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new Cd().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),Sd),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{yt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{yt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!wr(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(cn(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{yt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{yt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=zs&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=zs&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class bd extends qe{constructor(){super(...arguments);S(this,"ackToFirstChunkMs");S(this,"firstChunkToRenderMs");S(this,"isStreaming");S(this,"sendToAckMs");S(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return Ru}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[X.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[X.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[X.SEND_TO_ACK]:this.sendToAckMs}})}}const yd=.15,Ad=10,Td=e=>e<=0?!1:e>=1?!0:Math.random()<e;class Id extends Tt{constructor(n,r){super(n);S(this,"samplingRate");S(this,"pendingAIResponseByUserMessageId",new Map);S(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??yd}startTurn(n){if(this.collectedCount>=Ad||!Td(this.samplingRate))return;this.collectedCount+=1;const r={stats:new bd().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&wr(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!wr(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&yt(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&yt(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||(cn(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function xd(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const Vs={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},as={conversation:{...Vs,messageAlertSoundEnabled:!1,list:{...Vs,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Ks=e=>e?{conversation:kd(e.conversation),launcher:Md(e.launcher)}:as,Md=e=>Lt(as.launcher,e),Rd=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},kd=e=>{const t=as.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...Lt(t.list,c,n),deferredMarkdownElements:Rd(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:Lt(t.header,r),input:{camera:Lt(t.input.camera,u),gallery:Lt(t.input.gallery,d),fileEnabled:m},fileViewer:Lt(t.fileViewer,o)}},Lt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,ss(r));return n},wd=(e,t)=>Lr(e,t),Lr=(e,t)=>{if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>Lr(r,t[s]));if(!qs(e)||!qs(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>Lr(e[r],t[r]))},qs=e=>typeof e=="object"&&e!==null,Ld=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),Od=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Or=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Nd{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_initConversationRequests",new Map);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Ri(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:$e(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new rt.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new _e.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});S(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});S(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:$e(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});S(this,"_initConversationIfNeeded",(t,n)=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const r=this._initConversationRequests.get(t.url);if(r)return r;const s=t.initConversation({aiAgentId:this.aiAgentId,initialUserMessage:n==null?void 0:n.initialUserMessage}).then(()=>{}).catch(o=>{this._logger.warn("AIAgentEventManager: initConversation failed",o)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,s),s});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(ze.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(ze.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(ze.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(ze.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(ze.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(ze.AuthTokenRefreshed,t)}));S(this,"onNudgeMessageReceived",t=>(this._dispatcher.subscribe(ze.NudgeMessageReceived,t),()=>{this._dispatcher.unsubscribe(ze.NudgeMessageReceived,t)}))}}class Dd{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(ut.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(ut.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const Fi=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},Ui=e=>JSON.parse(e),Pd=e=>JSON.parse(e);function $d(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Fd(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function Ud({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,Fi(c))},e)}async function Bd({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,Fi(c)),e)}var cs=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(cs||{});const Bi=e=>typeof e=="object"&&e!==null,lr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Hd=e=>!Bi(e)||!lr(e,"channel_url")||!lr(e,"ai_agent_id")||!lr(e,"cpa_key")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id,cpaKey:e.cpa_key},Gd={1:Hd};function zd(e){if(!Bi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Gd[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Vd(e,t,n,r){const s=il.default.init({appId:e,modules:[new rt.GroupChannelModule,new Ce.AIAgentModule],localCacheEnabled:!0,options:new _e.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:_e.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Kd(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 qd=[400300,400301,400302,400310],Wd=cs.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Yd=e=>`${Wd}:${e}`;class ls{constructor(t,n,r,s,o){S(this,"chatSDK");S(this,"_aiAgentId");S(this,"_externalAuthTokenExpiredEventHandlerKey");S(this,"_logger");S(this,"_cache");S(this,"_statsTrackers");S(this,"_sessionHandler");S(this,"_aiEventHandlerRegistered",!1);S(this,"connect",async(t,n,r,s,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const i=new _e.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(i)}this._registerAIEventHandler();try{await this.chatSDK.connect(t.userId,t.authToken);const[,i]=await Promise.allSettled([this._syncTemplatesIfNeeded(),o?this.submitCPAAuthorizationCodes(o):Promise.resolve()]);return o&&(i.status==="fulfilled"?this._logger.debug("ChatClient.connect: CPA authorization codes submitted",i.value):this._logger.error("ChatClient.connect: CPA authorization code submission failed",i.reason)),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(i){const c=i;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(c))this._logger.warn("ChatClient.connect","offline connect restricted",c.message,c.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(u=>this._logger.warn("ChatClient.connect","clear cached-data failure",u));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",c.message,c.code),this.dispose(),c}});S(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});S(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=zd(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==cs.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});S(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});S(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});S(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));S(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));S(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));S(this,"requestNudgeMessage",async t=>this.chatSDK.aiAgent.requestNudgeMessage(t));S(this,"submitCPAAuthorizationCodes",async({aiAgentId:t,authCodes:n})=>this.chatSDK.aiAgent.submitCustomerProvidedAuthCodes({aiAgentId:t,authorizationCodes:n}));S(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});S(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});S(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});S(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});S(this,"_isCacheRestrictedError",t=>qd.some(n=>t.code===n));S(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=Ui(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=Yd(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Kd(t.chatSDK),n=t.chatSDK):n=Vd(t.appId,t.extensions,t.messengerVersion,t.chatParams),new ls(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const jd=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},Xd=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},En=new Map,Hi={set:(e,t)=>{En.set(e,t)},get:e=>{if(En.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=En.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=En.entries().next().value;return{platform:t[0],...t[1]}}},Gi="SENDBIRD_DESK_INQUIRE_TICKET_CLOSURE";var Ln=(e=>(e.WAITING="WAITING",e.CONFIRMED="CONFIRMED",e.DECLINED="DECLINED",e))(Ln||{});const Zd=e=>{if(!e)return null;const t=Si(e);if(t.type!==Gi)return null;const{state:n,ticketId:r}=t.body??{};return n==null||r==null?null:{state:n,ticketId:r}};class Ws extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);S(this,"status");S(this,"code");S(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var us=(e=>(e.INITIALIZED="INITIALIZED",e.PROACTIVE="PROACTIVE",e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.CLOSED="CLOSED",e.WORK_IN_PROGRESS="WORK_IN_PROGRESS",e.IDLE="IDLE",e))(us||{}),ds=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(ds||{}),zi=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(zi||{});const Jd=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Qd{constructor(t){S(this,"_appId");S(this,"_apiHost");S(this,"_logger");S(this,"_credential",null);S(this,"_authRefreshPromise",null);S(this,"_onDeskTokenRefreshRequired",async()=>!1);S(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});S(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});S(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});S(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Jd(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});S(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});S(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));S(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));S(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));S(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));S(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Ws(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Ws(t.status,{})}});S(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class On{constructor(t,n){S(this,"id");S(this,"title");S(this,"status");S(this,"agent");S(this,"priority");S(this,"group");S(this,"firstResponseTime");S(this,"issuedAt");S(this,"customFields");S(this,"_client");S(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new On({id:t.id,title:t.channelName??null,status:t.status2??us.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??ds.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class ms{constructor(t){S(this,"_logger");S(this,"_apiClient");S(this,"_onDeskTokenRefreshRequired");S(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);S(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});S(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});S(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});S(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return On._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:ss({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return On._fromResponse(n,this)});S(this,"confirmEndOfChat",async({messageId:t,ticketId:n,confirmed:r})=>{this._assertAuthenticated(this._apiClient),await this._apiClient.request(`/tickets/${encodeURIComponent(n)}/edit_message/`,{method:"PATCH",body:{messageId:t,messageData:JSON.stringify({type:Gi,body:{state:r?Ln.CONFIRMED:Ln.DECLINED,ticketId:n}})}})});this._logger=t.logger,this._apiClient=new Qd(t)}static init(t){return new ms(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class hs{constructor(){S(this,"authenticate",async t=>!1);S(this,"deauthenticate",()=>{});S(this,"refreshDeskAuthToken",async()=>!1);S(this,"setCustomerLanguage",async()=>{});S(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")});S(this,"confirmEndOfChat",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new hs}}function em(e){return{get:t=>e.getString(t)??null,set:(t,n)=>{e.set(t,n)},delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}const tm=1440*60*1e3,nm=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function We(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function rm(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const sm=e=>{const t={conversationInitialRender:new Gu(e),conversationNotInteractiveTimeout:new Wu(e),recoveryNotInteractiveTimeout:new cd(e),conversationListInitialRender:new Ku(e),aievAuthExpiredUnhandled:new Uu(e),messagePendingStuck:new ad(e),userPerceivedResponseTime:new Id(e),streamStalled:new gd(e),typingIndicatorAbsentTimeout:new vd(e),renderedContentUnusable:new dd(e),streamingMessageValidation:new _d(e),duplicateMessageResponse:new Zu(e),messageLifecycleEvent:new sd(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class Nn extends Nd{constructor(n){super();S(this,"appId");S(this,"aiAgentId");S(this,"_chatClient");S(this,"_deskClient");S(this,"_cache");S(this,"_logger");S(this,"_dispatcher");S(this,"_session",null);S(this,"language");S(this,"countryCode");S(this,"context");S(this,"cpaAuthorizationCodes");S(this,"queryParams");S(this,"_config",Ks());S(this,"_networkStateAdapter");S(this,"_scheduleForegroundTask");S(this,"_watchBackgrounded");S(this,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_liveMetricManager");S(this,"_operationQueue",xd());S(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});S(this,"initConversationIfNeeded",(n,r)=>this._initConversationIfNeeded(n,r));S(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(ut.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let g;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),g={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:C,session_token:_,expire_at:E}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:C,authToken:_,expireAt:E}),g={userId:C,authToken:_},this._logger.debug("AIAgent.authenticate: anonymous user created",C)}else g={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,h),this._dispatcher.send(ut.MessengerSettingsUpdated({settings:h,source:"server"}));const f=(()=>{var C;return s.type==="anonymous"?vu(this._dispatcher):(C=s.userSessionCandidate)==null?void 0:C.sessionHandler})(),p=await this._chatClient.connect(g,f,C=>{var _;this._logger.debug("AIAgent: session token refreshed"),(_=this._session)==null||_._updateAuthToken(C),this._deskClient.refreshDeskAuthToken(C)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()},this.cpaAuthorizationCodes?{aiAgentId:this.aiAgentId,authCodes:this.cpaAuthorizationCodes}:void 0);return await this._deskClient.authenticate({userId:g.userId,accessToken:g.authToken,onDeskTokenRefreshRequired:async({reason:C})=>{var _;if(C===zi.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const E=(_=this._session)==null?void 0:_.userSession.authToken;return E?await this._deskClient.refreshDeskAuthToken(E):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new Dd({sdkUser:p,userSession:g,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:g.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});S(this,"submitCPAAuthorizationCodes",async n=>{We(this._session),this._logger.debug("AIAgent.submitCPAAuthorizationCodes: start");const r=await this._chatClient.submitCPAAuthorizationCodes({aiAgentId:this.aiAgentId,authCodes:n});return this._logger.debug("AIAgent.submitCPAAuthorizationCodes: end",r),r});S(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));S(this,"createConversation",async n=>{We(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});S(this,"searchConversation",async n=>{if(We(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:Ce.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)rm(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});S(this,"closeConversation",async n=>{var s;We(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===Ce.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Ce.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});S(this,"createConversationListCollection",n=>new ki(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{We(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});S(this,"updateContext",async(n,r)=>{We(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});S(this,"getContextObject",async n=>{We(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});S(this,"requestNudgeMessage",async n=>{We(this._session);const r=this._session;this._logger.debug("AIAgent.requestNudgeMessage: start",n);const s=await this._chatClient.requestNudgeMessage({aiAgentId:this.aiAgentId,key:n.key,context:n.context,language:this.language});if(this._logger.debug("AIAgent.requestNudgeMessage: end",s),this._session!==r){this._logger.debug("AIAgent.requestNudgeMessage: session changed during request, discarding stale nudge");return}s.status!=="ok"||!s.payload.message||this._dispatcher.send(ut.NudgeMessageReceived({message:s.payload.message,callbackUserMessage:s.payload.callback_user_message??void 0}))});S(this,"clearUserMemories",async(n={})=>{We(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});S(this,"confirmEndOfChat",async n=>{We(this._session),this._logger.debug("AIAgent.confirmEndOfChat: start",n),await this._deskClient.confirmEndOfChat(n),this._logger.debug("AIAgent.confirmEndOfChat: end")});S(this,"setUserMemoryState",async n=>{We(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Or(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(ut.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),Or(i)});S(this,"refreshActiveChannel",async n=>{var c,u,d;We(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});S(this,"_getSessionCandidate",n=>n instanceof Di?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Rr?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});S(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-tm<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});S(this,"_getManualSessionInfo",n=>{if(!n||n instanceof Rr)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this.cpaAuthorizationCodes=n.cpaAuthorizationCodes,this.config=n.config,this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=jd(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&Xd(n.foregroundStateAdapter),this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new Su(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var f;const r=Hi.get(n.platform),s=n.logger??new Ni(n.logLevel??rs.WARN),o=n.dispatcher??new wi(s),i=n.useMMKVStorage?em(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=Ol({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=sm((p,C)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,C)});d=ls.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion,customData:n._sourceService?{source_service:n._sourceService}:void 0},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const g=nm?ms.init({appId:n.appId,logger:s,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):hs.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Nn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,cpaAuthorizationCodes:n.cpaAuthorizationCodes,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:g,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){const r=Ks(n);wd(r,this._config)||(this._config=r)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}get watchBackgrounded(){return this._watchBackgrounded}}const ye=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.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`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function Qe(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m=l.useCallback(f=>c(()=>f),[]),h=l.useCallback((f,p)=>d(C=>C[f]===p?C:{...C,[f]:p}),[]),g=l.useMemo(()=>({Template:i,updateTemplate:m,components:u,updateComponent:h}),[i,u,m,h]);return a.createElement(t.Provider,{value:g},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function om(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function im(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":am(e,t)}function am(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function cm(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=pt.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):pt.isToday(s)?n.hoursAgo(pt.differenceInHours(r,s)):t(s,n.dateShortFormat)}const lm=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__,um=({data:e,extendedMessagePayload:t,ticketClosureLabels:n})=>{if(lm){const r=Zd(e);if(r)return r.state!==Ln.WAITING?[]:[{action:"confirmTicketClosure",label:n.confirm,confirmed:!0,ticketId:r.ticketId},{action:"confirmTicketClosure",label:n.decline,confirmed:!1,ticketId:r.ticketId}]}return((t==null?void 0:t.suggested_replies)??[]).map(r=>({action:"sendMessage",label:r}))},dm=e=>{const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},_n=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ys=(e,t)=>{const n=_n(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=dm(e);return r?`#${_n(r[0])}${_n(r[1])}${_n(r[2])}${n}`:e},mm=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},hm=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",gm=e=>e.length>0,fm=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ve(s.type)),r=e.some(s=>!Ve(s.type));return n&&r?Ve(t.type)?e.filter(s=>Ve(s.type)):[t]:r?[t]:e},js=e=>e.length===0?"empty":e.every(t=>Ve(t.type))?"images":"non_images",pm=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=fm(t),s=js(e),o=js(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},Dt=3,Vi=6,Em=e=>e%Dt===0?Dt:Vi,_m=({index:e,itemCount:t})=>{const n=t%Dt,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:Dt,c=o?e-s:e%Dt,u=!r&&e>=t-Dt;return{columnSpan:r?Vi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},Ki=ye("AIAgent"),Cm=Ki.Provider,Te=Ki.useContext;function Sm(e){const t=vm(e),n=l.useMemo(()=>({_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,cpaAuthorizationCodes:t.cpaAuthorizationCodes,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}),[t,t.chatSDK,t.deskClient,t.appId,t.aiAgentId,t.language,t.countryCode,t.context,t.cpaAuthorizationCodes,t.logger,t.dispatcher,t.cache,t.networkStateAdapter,t.queryParams,t.config,e.handlers]);return a.createElement(Cm,{value:n},e.children)}function vm(e){var o,i;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=Nn.init(e);else{const c=bm(n.current,e);(c.appId||c.aiAgentId||c.chatSDK)&&(t.current.dispose(),t.current=Nn.init({...e,chatParams:c.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var c;(c=t.current)==null||c.dispose()},[]);const r=t.current;r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.cpaAuthorizationCodes=e.cpaAuthorizationCodes,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(o=e.handlers)==null?void 0:o.onLiveMetric;const s=(i=e.handlers)==null?void 0:i.onNudgeMessageReceived;return l.useEffect(()=>{if(s)return r.onNudgeMessageReceived(async c=>s(c))},[r,s]),r}function bm(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Kn=()=>{const[e,t]=l.useState(0),n=l.useCallback(()=>t(r=>r+1),[]);return n.revision=e,n};let ym=0;function Am(){return l.useState(()=>`${ym++}`)[0]}const mt=(e,t,n)=>{const r=l.useRef(t),o=Am();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...g)=>{var p;const f=r.current;(p=f[h])==null||p.call(f,...g)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new rt.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Tm(e,t){return!e||!t?!0:e.url!==t.url}function je(e){return e!=null&&"sendingStatus"in e}function Im(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return je(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function xm(e,t){return Im(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Xs(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const Dn={collection:{groupChannel:{defaultOrder:rt.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Zs(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Js(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Mm=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=Rm(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=je(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];km(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{je(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{je(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>xm(s,n));return t.value.clearBeforeAction?e.newMessageMap=Js(r,Xs):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Js(r,Xs)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(je(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(je(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},Rm=e=>e.reduce((t,n)=>(je(n)?(t[n.reqId]=n,n.sendingStatus===we.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),km=(e,t,n=!1)=>{if(!je(e)||!je(t))return!0;if(n&&e&&Ie.isStreaming(t)){if(!Ie.isStreaming(e))return!1;const r=e.message??"",s=t.message??"";if(s.length<r.length&&r.startsWith(s))return!1}return e.sendingStatus===we.SendingStatus.SUCCEEDED?t.sendingStatus===we.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},wm=(e=Lm)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Mm,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(_,E,A,y)=>{i({type:"update_messages",value:{messages:_,clearBeforeAction:E,currentUserId:A,strictStreamingOrder:y}})},u=(_,E)=>{i({type:"delete_messages",value:{messageIds:_,reqIds:E}})},d=(_,E,A)=>{i({type:"update_new_messages",value:{messages:_,clearBeforeAction:E,currentUserId:A}})},m=(_,E)=>{i({type:"delete_new_messages",value:{messageIds:_,reqIds:E}})},h=_=>{i({type:"update_initialized",value:{status:_}})},g=_=>{i({type:"update_loading",value:{status:_}})},f=_=>{i({type:"update_refreshing",value:{status:_}})},p=l.useMemo(()=>Object.values(o),[o]),C=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:g,updateRefreshing:f,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:C,newMessages:p,updateNewMessages:d,deleteNewMessages:m}},Qs=Math.floor(Number.MAX_SAFE_INTEGER/10);function Lm(e,t){let n=0,r=0;return je(e)&&e.sendingStatus!=="succeeded"&&(n=Qs),je(t)&&t.sendingStatus!=="succeeded"&&(r=Qs),e.createdAt+n-(t.createdAt+r)}const Om=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new rt.MessageFilter(r)})};function eo(e){return e<Date.now()?Dn.collection.message.searchLimit:Dn.collection.message.defaultLimit}const Nm=(e,t,n={})=>{var xe,Oe;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=eo(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Kn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:g,loading:f,refreshing:p,messages:C,newMessages:_,updateMessages:E,updateNewMessages:A,deleteNewMessages:y,deleteMessages:T,updateInitialized:I,updateLoading:k,updateRefreshing:L}=wm(n==null?void 0:n.sortComparator),R=ce(x=>{var w,D,U,J;if(!s.current||!s.current.url)return(w=o==null?void 0:o.error)==null?void 0:w.call(o,"[useGroupChannelMessages] channel is required");try{switch(x){case _e.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case _e.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case _e.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(U=(D=r.current).markAsRead)==null||U.call(D,[s.current]);break}}catch(oe){(J=o==null?void 0:o.warn)==null||J.call(o,"[useGroupChannelMessages/markAsReadBySource]",oe)}}),M=ce((x,w)=>{var D,U,J,oe,ee;if(w.length>0)switch(x){case _e.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case _e.CollectionEventSource.SYNC_MESSAGE_FILL:{(U=(D=r.current).shouldCountNewMessages)!=null&&U.call(D)&&A(w,!1,(J=e.currentUser)==null?void 0:J.userId),(ee=(oe=r.current).onMessagesReceived)==null||ee.call(oe,w);break}}}),$=ce(x=>{var w,D;(D=(w=r.current).onCollectionEvent)==null||D.call(w,x)}),N=ce(async(x,w,D)=>new Promise((U,J)=>{var K,he,ge;h.current.instance&&h.current.instance.dispose(),R(),A([],!0,(K=e.currentUser)==null?void 0:K.userId);const oe=()=>{var de,ve;const{pendingMessages:ie,failedMessages:pe}=h.current.instance??{};Zs(ie)&&E(ie,!1,(de=e.currentUser)==null?void 0:de.userId),Zs(pe)&&E(pe,!1,(ve=e.currentUser)==null?void 0:ve.userId)},ee=Om(x,D,{...r.current,startingPoint:w});h.current={apiInitialized:!1,initialized:!1,instance:ee},ee.setMessageCollectionHandler({onMessagesAdded:(ie,pe,de)=>{var ve;R(ie.source),M(ie.source,de),E(de,!1,(ve=e.currentUser)==null?void 0:ve.userId,u),$({kind:"messagesAdded",source:ie.source,channelUrl:x.url,messages:de})},onMessagesUpdated:(ie,pe,de)=>{var ve,Be,He;R(ie.source),M(ie.source,de),E(de,!1,(ve=e.currentUser)==null?void 0:ve.userId,u),ie.source===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((He=(Be=r.current).onMessagesUpdated)==null||He.call(Be,de)),$({kind:"messagesUpdated",source:ie.source,channelUrl:x.url,messages:de})},onMessagesDeleted:(ie,pe,de,ve)=>{const Be=ve.map(Ze=>Ze.messageId),He=ve.filter(je).map(Ze=>Ze.reqId);T(Be,He),y(Be,He),$({kind:"messagesDeleted",source:ie.source,channelUrl:x.url,messages:ve})},onChannelDeleted:(ie,pe)=>{var de,ve;(ve=(de=r.current).onChannelDeleted)==null||ve.call(de,pe)},onChannelUpdated:(ie,pe)=>{var de,ve;m(),(ve=(de=r.current).onChannelUpdated)==null||ve.call(de,pe,ie)},onHugeGapDetected:()=>{N(x,Number.MAX_SAFE_INTEGER,Dn.collection.message.defaultLimit)}});let Se=!1;(ge=(he=r.current).onCollectionInitializeStart)==null||ge.call(he),ee.initialize(rt.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ie,pe)=>{var de,ve,Be,He,Ze;(ve=(de=r.current).onCacheResult)==null||ve.call(de,ie,pe??[],x.url),ie?(e.isCacheEnabled&&((Be=o==null?void 0:o.error)==null||Be.call(o,"[useGroupChannelMessages/onCacheResult]",ie)),Se=!0):pe&&((He=o==null?void 0:o.debug)==null||He.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",pe.length),E(ee.succeededMessages,!0,(Ze=e.currentUser)==null?void 0:Ze.userId),oe(),pe.length>0&&(h.current.initialized=!0,U())),$({kind:"initialized",source:"cache",channelUrl:x.url,messages:pe??[],error:ie})}).onApiResult((ie,pe)=>{var de,ve,Be,He,Ze,Pe,tt;(ve=(de=r.current).onApiResult)==null||ve.call(de,ie,pe??[],x.url),h.current.initialized=!0,h.current.apiInitialized=!0,ie?((Be=o==null?void 0:o.warn)==null||Be.call(o,"[useGroupChannelMessages/onApiResult]",ie),Se?J(ie):U()):pe&&((He=o==null?void 0:o.debug)==null||He.call(o,"[useGroupChannelMessages/onApiResult]","message length:",pe.length),E(ee.succeededMessages,!0,(Ze=e.currentUser)==null?void 0:Ze.userId),r.current.startingPoint||(tt=(Pe=r.current).onMessagesReceived)==null||tt.call(Pe,pe),e.isCacheEnabled&&oe(),U()),$({kind:"initialized",source:"api",channelUrl:x.url,messages:pe??[],error:ie})})}));mt(e,{onUserBanned(x,w){var D,U,J;x.isGroupChannel()&&!Tm(x,s.current)&&(w.userId===((D=e.currentUser)==null?void 0:D.userId)?(J=(U=r.current).onCurrentUserBanned)==null||J.call(U):m())}}),l.useLayoutEffect(()=>{const x=setTimeout(async()=>{e.currentUser&&s.current&&(I(!1),k(!0),await N(s.current,i,c),k(!1),I(!0))});return()=>clearTimeout(x)},[e,(xe=e.currentUser)==null?void 0:xe.userId,(Oe=s.current)==null?void 0:Oe.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const Q=ce(async()=>{e.currentUser&&s.current&&(L(!0),await N(s.current,Number.MAX_SAFE_INTEGER,Dn.collection.message.defaultLimit),L(!1))}),se=ce(async()=>{var w;const x=h.current.instance;if(x!=null&&x.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const D=await x.loadPrevious();E(D,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.prev=!1}}),Y=ce(()=>{const{initialized:x,instance:w}=h.current;return x&&w?w.hasPrevious:!1}),j=ce(async()=>{var w;const x=h.current.instance;if(x!=null&&x.hasNext&&!d.current.next)try{d.current.next=!0;const D=await x.loadNext();E(D,!1,(w=e.currentUser)==null?void 0:w.userId)}catch{}finally{d.current.next=!1}}),P=ce(()=>{const{initialized:x,apiInitialized:w,instance:D}=h.current;return w&&x&&D?D.hasNext:!1}),q=x=>{var w,D,U,J;!x||x.channelUrl!==((w=s.current)==null?void 0:w.url)||(E([x],!1,(D=e.currentUser)==null?void 0:D.userId),(J=(U=r.current).onOutgoingMessageStatusChanged)==null||J.call(U,x))},W=ce((x,w)=>{var D;if(!s.current||!s.current.url)throw(D=o==null?void 0:o.error)==null||D.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((U,J)=>{s.current.sendUserMessage(x).onPending(oe=>{q(oe),w==null||w(oe)}).onSucceeded(oe=>{q(oe),U(oe)}).onFailed((oe,ee)=>{q(ee),J(oe)})})}),G=ce((x,w)=>{var D;if(!s.current||!s.current.url)throw(D=o==null?void 0:o.error)==null||D.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((U,J)=>{s.current.sendFileMessage(x).onPending(oe=>{q(oe),w==null||w(oe)}).onSucceeded(oe=>{q(oe),U(oe)}).onFailed((oe,ee)=>{q(ee),J(oe)})})}),H=ce((x,w,D)=>{var U;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((J,oe)=>{s.current.sendMultipleFilesMessage(x).onPending(ee=>{q(ee),w==null||w(ee)}).onFileUploaded(ee=>{D==null||D(ee),m()}).onSucceeded(ee=>{q(ee),J(ee)}).onFailed((ee,Se)=>{q(Se),oe(ee)})})}),V=ce(async(x,w)=>{var U,J;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const D=await s.current.updateUserMessage(x,w);return D.channelUrl===s.current.url&&E([D],!1,(J=e.currentUser)==null?void 0:J.userId),D}),z=ce(async(x,w)=>{var U,J;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const D=await s.current.updateFileMessage(x,w);return D.channelUrl===s.current.url&&E([D],!1,(J=e.currentUser)==null?void 0:J.userId),D}),Z=ce(async(x,w,D)=>{var U;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((J,oe)=>{let ee;x.isUserMessage()&&(ee=s.current.resendMessage(x)),x.isFileMessage()&&(ee=s.current.resendMessage(x)),x.isMultipleFilesMessage()&&(ee=s.current.resendMessage(x)),ee&&("onPending"in ee&&ee.onPending(Se=>{q(Se),w==null||w(Se)}),"onFileUploaded"in ee&&ee.onFileUploaded(Se=>{D==null||D(Se),m()}),"onSucceeded"in ee&&ee.onSucceeded(Se=>{q(Se),J(Se)}),"onFailed"in ee&&ee.onFailed((Se,K)=>{q(K),oe(Se)}))})}),ae=ce(async x=>{var w,D,U,J;if(!s.current||!s.current.url)throw(w=o==null?void 0:o.error)==null||w.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(x.sendingStatus==="succeeded")x.isUserMessage()&&await s.current.deleteMessage(x),x.isFileMessage()&&await s.current.deleteMessage(x),x.isMultipleFilesMessage()&&await s.current.deleteMessage(x);else try{await((D=h.current.instance)==null?void 0:D.removeFailedMessage(x.reqId))}finally{T([],[x.reqId]),(J=(U=r.current).onLocalMessageDeleted)==null||J.call(U,x)}}),O=ce(()=>{var x;A([],!0,(x=e.currentUser)==null?void 0:x.userId)}),be=ce(async x=>{var w;if(e.currentUser&&s.current){const D=eo(x);k(!0),E([],!0,(w=e.currentUser)==null?void 0:w.userId),await N(s.current,x,D),k(!1)}});return{initialized:g,loading:f,refreshing:p,collectionRevision:m.revision,messages:C,newMessages:_,resetNewMessages:O,refresh:Q,loadPrevious:se,hasPrevious:Y,loadNext:j,hasNext:P,sendUserMessage:W,sendFileMessage:G,sendMultipleFilesMessage:H,updateUserMessage:V,updateFileMessage:z,resendMessage:Z,deleteMessage:ae,resetWithStartingPoint:be,_dangerous_reducer_updateMessages:E,_dangerous_reducer_deleteMessages:T}},Dm=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,Pm=(e,t,n)=>{const r=Nm(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!Dm(o)),[r.messages]);return{...r,messages:s}},$m=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{try{n(t)}catch{}})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},qn=$m(),Fm=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(p=>r.current===p,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(p=>{c(p)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:p,conversationId:C})=>{i.current=!0,n.markChannelJoined(C,p)},[n]),h=l.useCallback(({channelUrl:p})=>{n.clearChannel(p),i.current=!1},[n]),g=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,m(p)}},[c,m]),f=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,h(p)}},[c,h]);return l.useEffect(()=>{if(t){const p=o.current;if(!p||(o.current=null,p.channelUrl!==e))return;"error"in p?h(p):m(p);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:g,onFetchError:f}},Um=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var f;(f=o.current)==null||f.call(o),o.current=null;const g=u.current;h&&(u.current=null),h&&g&&r.clearChannel(g)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const g=c.current,f=()=>{if(!i.current||g!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(f))??null,n||f()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},nn={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function qi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Bm(e){const t=qi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Hm(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Gm(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function zm(e,t,n){let r,s,o;if(t===0)r=s=o=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},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function Cn(e,t,n){const[r,s,o]=Bm(e),[i,c,u]=Gm(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,g,f]=zm(i,m,d);return Hm([Math.round(h),Math.round(g),Math.round(f)])}function Vm(e,t="light"){return{extraDark:Cn(e,.6,1.2),dark:Cn(e,.85,1.1),main:e,light:Cn(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Cn(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Nr(e){const t=qi(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?nn.BLACK:nn.WHITE}function Km(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100},conversation:{headerProfileSkeleton:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const qm=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400},conversation:{headerProfileSkeleton:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),Sn={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, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},ur={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 to(e){const t=Wm(e),n=Ym(e,t),r=Xm(n,e.colors,e.selectedTheme),s=Jm(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function Wm({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Sn.primary.main?Sn.primary:Vm(n,e):Sn.primary;return{...Sn,primary:r,...t}}function Ym({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??Nr(o),c=n??nn.DEFAULT_BOT_MSG_BG,u=r??Nr(c);return(e==="light"?Km:qm)(s,o,i,c,u)}function jm(e,t,n){return typeof e=="string"?e:e[t]??n}function Xm(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=jm(m,n,h)}}}return r}function Zm(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Jm({typography:e}){if(!e)return ur;const t={...ur};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=ur[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Zm(s,r,o)}}),t}const{Provider:Qm,useContext:Wn}=ye("AIAgentTheme");function eh({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>to({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((h,g)=>{g&&(i.current=g);const f=(s==null?void 0:s.theme)??h,p=i.current?i.current.themes[f]:null,C={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!C.primary&&(p!=null&&p.primary_color)&&(C.primary=p.primary_color,C.primaryContrast=p.primary_contrast_color),!C.botMessageBackground&&(p!=null&&p.bot_message_bg_color)&&(C.botMessageBackground=p.bot_message_bg_color,C.botMessageBackgroundContrast=p.bot_message_bg_contrast_color);const _=to({selectedTheme:f,palette:t,typography:n,colors:r,...C});u(_),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]);const m=l.useMemo(()=>({theme:c,updateTheme:d}),[c,d]);return a.createElement(Qm,{value:m},o)}const th=25*1024*1024,no=1,ro=new Set(["image/png","image/jpeg","image/jpg"]),so=new Set(["application/pdf"]),nh={off:"off",always:"always",handed_off_only:"handed_off_only"},rh=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:no,attachmentMode:"handed_off_only",defaultUploadSizeLimit:void 0,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:ro,supportedFileMimeTypes:so})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??no,attachmentMode:nh[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:o==null?void 0:o.default_upload_size_limit,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??ro),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??so)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i}=s,c=e.defaultUploadSizeLimit??i??th,u=(m=!0)=>o!=null&&o.isAIAgent?m?dt(o):!1:!0,d=m=>{if(u())return c;const h=e.uploadSizeLimitPerType.get(m)??c;return Math.min(h,c)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(u(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return dt(o);default:return!0}},get supportedMimeTypes(){return u()?[Ir]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:m=>u()?!0:e.supportedImageMimeTypes.has(m)||e.supportedFileMimeTypes.has(m),getUploadSizeLimit:d,getUploadSizeLimitInMB:m=>d(m)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},oo=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},Wt=e=>({...e,context:e.context??{}}),{Provider:sh,useContext:et}=ye("AIAgentMessengerSession"),oh=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=Te(),{updateTheme:c}=Wn(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[g,f]=l.useState(null),[p,C]=l.useState(null),[_,E]=l.useState(null),[A,y]=l.useState(null),[T,I]=l.useState(null),{updateBaseAttachmentRules:k,createAttachmentRules:L}=rh();l.useEffect(()=>{const N=r.onMessengerSettingsUpdated(({settings:Y})=>{const{appearance:j,bot:P,launcher:q,memory:W}=Y;c(j.selected_theme,j),E(Ld(P)),y(Od(q)),I(W?Or(W):null),k(Y)}),Q=r.onActiveChannelUpdated(({channelUrl:Y,status:j,conversationStatus:P})=>{h({url:Y,status:j,conversationStatus:P})}),se=r.onAuthTokenRefreshed(()=>{var j;const Y=(j=r.session)==null?void 0:j.userSession.authToken;Y&&C(P=>P?{...P,authToken:Y}:null)});return()=>{N(),Q(),se()}},[r,c,k]);const R=l.useCallback(async()=>{try{const N=await r.authenticate(e),Q=r.session;return f(Q.sdkUser),C(Q.userSession),h(Q.activeChannel),d(void 0),N}catch(N){throw f(null),C(null),h(void 0),d(N),N}},[r,e]),M=l.useCallback(async()=>{await r.deauthenticate(),f(null),h(void 0),C(null),E(null),y(null),I(null)},[r]),$=l.useCallback(async()=>{if(!r.session){if(p)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(p==null?void 0:p.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,p]);return l.useImperativeHandle(n,()=>{const N=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:R,deauthenticate:M,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,updateContext:async(...Q)=>{const se=oo(...Q);if(se.type==="active"){const P=await(await N()).updateContext(o,se.context);return Wt(P)}const Y=await s.aiAgent.updateContext(se.aiAgentId,se.channelUrl,se.context);return Wt(Y)},patchContext:async(...Q)=>{const se=oo(...Q);if(se.type==="active"){const P=await(await N()).patchContext(o,se.context);return Wt(P)}const Y=await s.aiAgent.patchContext(se.aiAgentId,se.channelUrl,se.context);return Wt(Y)},getContextObject:async()=>{const se=await(await N()).getContextObject(o);return Wt(se)},requestNudgeMessage:Q=>r.requestNudgeMessage(Q)}},[R,M,m,s,o,i,r]),a.createElement(sh,{value:{sdkUser:g,userSessionInfo:e,userSession:p,activeChannel:m,setActiveChannel:h,refreshActiveChannel:$,createConversation:r.createConversation,searchConversation:r.searchConversation,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,connectionError:u,aiAgentInfo:_,launcherInfo:A,memoryInfo:T,authenticate:R,deauthenticate:M,createAttachmentRules:L}},t)}),ih={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},ah=e=>e.disabled?ih[e.disabledBy]==="ready":!0,ch=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ve(t)?"file_image":t&&on(t)?"file_video":t&&El(t)?"file_audio":"file_document"};let io=0;const lh=e=>(io+=1,`${e??"unknown"}:${io}`),Ot=(e,t)=>e===void 0||t===e,Wi=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Yi=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},uh=(e,t)=>{Wi(e,t)},dh=(e,t)=>{Yi(e,t)},mh=(e,t,n)=>{var o;if(!Ue(e,n))return;const{hasResponseMetadata:r,...s}=Xr(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},ao=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Xe(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},dr=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},hh=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=Te(),{aiAgentInfo:r}=et(),s=l.useRef(!1),o=r==null?void 0:r.userId;mt(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},gh=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(dr(n,s),r.current=void 0);return}s&&s!==t&&(dr(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(dr(n,s),r.current=void 0)},[n])},fh=({aiAgentUserId:e,statsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(f=>i.current&&c.current===f,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const f=d.current;d.current=t,!(f||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const g=l.useCallback(f=>f.lifecycleGeneration===u.current&&Ot(n,f.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const f=s.current;f&&g(f)&&(f.tracked||(Wi(r,f),f.tracked=!0));const p=o.current;p&&g(p)&&(p.tracked||(Yi(r,p),p.tracked=!0))},[t,g,r]),l.useMemo(()=>({onCollectionEvent:f=>{if(h(m)&&Ot(n,f.channelUrl)){if(f.kind==="messagesDeleted"){f.messages.forEach(p=>ao(p,r));return}t&&f.messages.forEach(p=>mh(p,r,e))}},onCacheResult:(f,p,C)=>{if(!h(m)||!Ot(n,C))return;const _={error:f,messages:p,channelUrl:C,lifecycleGeneration:u.current,tracked:!1};s.current=_,t&&(uh(r,_),_.tracked=!0)},onApiResult:(f,p,C)=>{if(!h(m)||!Ot(n,C))return;const _={error:f,messages:p,channelUrl:C,lifecycleGeneration:u.current,tracked:!1};o.current=_,t&&(dh(r,_),_.tracked=!0)},onLocalMessageDeleted:f=>{h(m)&&Ot(n,f.channelUrl)&&ao(f,r)}}),[e,m,t,h,n,r])},ph=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},Eh=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(C=>u==null?void 0:u(C),()=>{});let m;const h=i.current,g=s.current,f=()=>r.current&&o.current&&i.current===h&&s.current===g,p=C=>f()&&Ot(g,C);try{const C=await c(_=>{if(!p(_.channelUrl)){u==null||u(_);return}m=_.reqId,n.messagePendingStuck.start({requestId:_.reqId,channelUrl:_.channelUrl,messageType:ch(_),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(_)},_=>{!f()||m!==_||n.messagePendingStuck.markUploadProgress(_)});return m&&(f()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),C}catch(C){throw m&&(f()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),C}},[n])},_h=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=lh(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const g=await c(f=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,f),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,f),h=f)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:g.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:g.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),g}catch(g){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),g}},[e,n])},Ch=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=et();hh({activeChannelUrl:t,statsTrackers:r}),gh({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=fh({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Eh({channelUrl:t,enabled:n,statsTrackers:r}),c=_h({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},ht=()=>Te()._aiAgentSDK.statsTrackers,Sh=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=ht(),{watchBackgrounded:r}=Te()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();Re(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},vh=({enabled:e=!0,channelUrl:t,conversationId:n,messages:r})=>{const{duplicateMessageResponse:s}=ht(),{aiAgentInfo:o}=et(),i=o==null?void 0:o.userId;l.useEffect(()=>{!e||!t||!i||s.onMessagesChanged({channelUrl:t,conversationId:n,aiAgentUserId:i,messages:r})},[i,t,n,e,r,s])},bh=({enabled:e=!0,channelUrl:t,conversationId:n}={})=>{const{messageLifecycleEvent:r}=ht(),{chatSDK:s,_aiAgentSDK:o}=Te(),{watchBackgrounded:i}=o,{aiAgentInfo:c}=et(),u=c==null?void 0:c.userId,d=e&&!!t&&!!u;l.useEffect(()=>{r.setBackgroundedWatcher(i)},[r,i]),mt(d?s:void 0,{onTypingStatusUpdated(f){f.url===t&&r.onTypingChanged({channelUrl:f.url,isAgentTyping:f.getTypingUsers().some(p=>p.userId===u)})}}),l.useEffect(()=>{if(!d||!t||!u)return;const f=qn.subscribe(p=>{r.onCollectionEvent({event:p,channelUrl:t,aiAgentUserId:u})});return()=>{f(),r.clearChannel(t)}},[u,t,d,r]),l.useEffect(()=>{!d||!t||r.onConversationIdResolved({channelUrl:t,conversationId:n})},[t,n,d,r]);const m=l.useCallback(f=>{!d||!t||!Xe(f)||f.sendingStatus!==we.SendingStatus.SUCCEEDED||r.onUserMessageSent({channelUrl:t,conversationId:n,messageId:f.messageId})},[t,n,d,r]),h=l.useCallback(f=>{d&&r.onAnimationStart({messageId:f})},[d,r]),g=l.useCallback((f,p)=>{d&&r.onAnimationComplete({messageId:f,completed:p})},[d,r]);return{onOutgoingMessageStatusChanged:m,onAnimationStart:h,onAnimationComplete:g}},yh=({enabled:e=!0,channelUrl:t,conversationId:n}={})=>{const{streamingMessageValidation:r}=ht(),{watchBackgrounded:s}=Te()._aiAgentSDK,{aiAgentInfo:o}=et(),i=o==null?void 0:o.userId,c=l.useRef(n);c.current=n,l.useEffect(()=>{r.setBackgroundedWatcher(s)},[r,s]),l.useEffect(()=>{if(!e||!t||!i)return;const u=qn.subscribe(d=>{r.onCollectionEvent({event:d,channelUrl:t,conversationId:c.current,aiAgentUserId:i})});return()=>{u(),r.clearChannel(t)}},[i,t,e,r])},vt=e=>{e&&e.catch(()=>{})},ln=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new _e.ConnectionHandler({onDisconnected:o=>{var i,c;return vt((c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o))},onConnected:o=>{var i,c;return vt((c=(i=r.current).onConnected)==null?void 0:c.call(i,o))},onReconnectStarted:()=>{var o,i;return vt((i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o))},onReconnectSucceeded:()=>{var o,i;return vt((i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o))},onReconnectFailed:()=>{var o,i;return vt((i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o))},onConnectionLost:()=>{var o,i;return vt((i=(o=r.current).onConnectionLost)==null?void 0:i.call(o))},onConnectionDelayed:o=>{var i,c;return vt((c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o))}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},co=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function Ah(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=Te(),{sdkUser:u}=et(),d=co(),m=co(),[h,g]=l.useState(void 0),f=Kn(),[p,C]=l.useState(void 0),[_,E]=l.useState(!1),A=ce(T=>{if(n&&T.isAIAgent&&!T.conversation){const I=m.next();E(!0),c.initConversationIfNeeded(T,{initialUserMessage:r}).finally(()=>{m.isCurrent(I)&&E(!1)})}});async function y(){var I,k,L,R,M,$;const T=d.next();if(!u){o.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(o.debug("useChannel.getChannel: start"),g(void 0),C(void 0),m.invalidate(),E(!1),e){(I=t.onFetchStart)==null||I.call(t,e);try{o.debug("useChannel.getChannel: get channel",e);const N=await s.groupChannel.getChannel(e);if(!d.isCurrent(T))return;A(N),g(N),(L=t.onFetchSuccess)==null||L.call(t,{channelUrl:N.url,conversationId:(k=N.conversation)==null?void 0:k.id}),N.url===((R=c.session)==null?void 0:R.activeChannel.url)&&c.session._updateActiveChannel({url:N.url,status:$e(N)?"closed":"open",conversationStatus:(M=N.conversation)==null?void 0:M.status}),o.debug("useChannel.getChannel: fetched channel",N)}catch(N){if(!d.isCurrent(T))return;($=t.onFetchError)==null||$.call(t,{channelUrl:e,error:N}),N instanceof _e.SendbirdError&&C(N),o.error("useChannel.getChannel: error",N)}}}return l.useEffect(()=>(y(),()=>{d.invalidate()}),[s,u,e,i]),l.useEffect(()=>{n&&h&&A(h)},[n]),ln(s,{async onReconnectSucceeded(){var T;try{if(!h){p&&await y();return}const I=d.current(),k=await h.refresh();if(!d.isCurrent(I)||h.url!==e)return;(T=t.onReconnectSucceeded)==null||T.call(t,h.url),A(k),g(k)}catch(I){o.error("useChannel.onReconnectSucceeded: failed to sync the channel",I)}}}),mt(s,{onChannelChanged:T=>{T.isGroupChannel()&&T.url===e&&(o.debug("useChannel.onChannelChanged: channel changed",T.url),g(T),f())}}),{channel:h,channelRevision:f.revision,channelFetchError:p,getChannel:y,isInitializingConversation:_}}const Th=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!r)return;const s=sn(n);switch(r){case"suggested_replies":return s.hasSuggestedReplies?r:void 0;case"steward":return s.hasSteward?r:void 0;case"system":return r;default:return}},Ih=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=sn(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},xh=()=>{const{chatSDK:e,networkStateAdapter:t}=Te(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return ln(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===_e.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Mh=3e4,Rh=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&Ue(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=g=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},g)},m=Date.now()-c,h=Mh-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},ji=e=>{const{chatSDK:t}=Te(),[n,r]=l.useState([]);return mt(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},kh=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=ji(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=Ue(t,n)&&(Ie.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},wh=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=et(),i=xh(),c=kh({channel:e,lastMessage:Mr(t,[we.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Rh({shouldApply:!!(e!=null&&e.isAIAgent)&&!dt(e),isBlockedWhileAIResponding:c,lastMessage:Mr(t,[we.SendingStatus.PENDING,we.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""});if(!e||i==="disconnected")return bt.unavailable;if(i==="reconnecting")return bt.reconnecting;if($e(e))return bt.conversation_closed;if(tu(e))return bt.handoff_pending;if(Ih(e))return bt.form_active;const d=Th(e);return d?bt[d]:c||u||r?bt.ai_responding:Lh},lt=e=>Object.freeze(e==="ai_responding"?{disabled:!0,disabledBy:e,focusPolicy:"preserve"}:{disabled:!0,disabledBy:e,focusPolicy:"release"}),Lh=Object.freeze({disabled:!1,disabledBy:"",focusPolicy:"auto"}),bt=Object.freeze({ai_responding:lt("ai_responding"),unavailable:lt("unavailable"),form_active:lt("form_active"),conversation_closed:lt("conversation_closed"),suggested_replies:lt("suggested_replies"),steward:lt("steward"),system:lt("system"),reconnecting:lt("reconnecting"),handoff_pending:lt("handoff_pending")}),Oh=()=>{const[e,t]=l.useState(new Set),[n,r]=l.useState(new Map),s=l.useCallback(h=>{t(g=>{if(g.has(h))return g;const f=new Set(g);return f.add(h),f})},[]),o=l.useCallback(h=>{t(g=>{if(!g.has(h))return g;const f=new Set(g);return f.delete(h),f})},[]),i=l.useCallback((h,g)=>{r(f=>{const p=new Map(f);return p.set(h,g),p})},[]),c=l.useCallback(h=>{r(g=>{if(!g.has(h))return g;const f=new Map(g);return f.delete(h),f})},[]),u=l.useCallback(h=>n.has(h),[n]),d=n.values().next().value,m=e.size>0;return l.useMemo(()=>({isAnimating:m,start:s,stop:o,isHolding:u,heldTypingInfo:d,holdStart:i,holdStop:c}),[m,s,o,u,d,i,c])},{Provider:Nh}=ye("AIAgentConversation");function Dh({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=Ee,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,initialUserMessage:g,shouldCountNewMessages:f=()=>!1,sortComparator:p}){var U,J,oe,ee,Se;const{_aiAgentSDK:C,chatSDK:_,logger:E,dispatcher:A}=Te(),y=()=>{d&&(M==null||M.markAsRead().catch(K=>E.warn("AIAgentConversationContext: markAsRead failed",K)))},T=ht(),I={channelUrl:t,enabled:m},k=Fm({...I,statsTracker:T.conversationNotInteractiveTimeout}),L=Um({...I,scheduleForegroundTask:C.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),R=Sh(I),{channel:M,channelRevision:$,channelFetchError:N,getChannel:Q,isInitializingConversation:se}=Ah(t,{shouldInitializeConversation:h,initialUserMessage:g,onFetchStart:K=>{k.onFetchStart(K),R.onGetChannelStart(K)},onFetchSuccess:K=>{k.onFetchSuccess(K),R.onGetChannelComplete(K)},onFetchError:K=>{k.onFetchError(K),R.onGetChannelError(K)},onReconnectSucceeded:L.onReconnectSucceeded}),Y=M==null?void 0:M.url,j=bh({enabled:m&&!!(M!=null&&M.isAIAgent)&&M.hasAiBot,channelUrl:Y,conversationId:(U=M==null?void 0:M.conversation)==null?void 0:U.id}),P=Ch({requestedChannelUrl:t,activeChannelUrl:Y,statsEnabled:m,statsTrackers:T}),q=Pm(_,M,{replyType:we.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:f,logger:E,markAsRead:y,sortComparator:p,onChannelDeleted:n,onMessagesReceived:K=>r==null?void 0:r(K),onMessagesUpdated:K=>s==null?void 0:s(K),onCollectionInitializeStart:()=>{R.onCollectionInitializeStart()},onApiResult:(K,he,ge)=>{R.onCollectionApiResult(K,ge),P.messageCallbacks.onApiResult(K,he,ge)},onCacheResult:(K,he,ge)=>{R.onCollectionCacheResult(K,ge),P.messageCallbacks.onCacheResult(K,he,ge)},onCollectionEvent:K=>{P.messageCallbacks.onCollectionEvent(K),qn.publish(K)},onLocalMessageDeleted:K=>{P.messageCallbacks.onLocalMessageDeleted(K)},onOutgoingMessageStatusChanged:K=>{j.onOutgoingMessageStatusChanged(K),M&&C.liveMetricManager.track({type:"outgoingMessage",channel:M,message:K})}}),W=Oh(),G=wh({channel:M,messages:q.messages,isStreamAnimating:W.isAnimating,isInitializingConversation:se});yh({enabled:m,channelUrl:Y,conversationId:(J=M==null?void 0:M.conversation)==null?void 0:J.id}),vh({enabled:m,channelUrl:Y,conversationId:(oe=M==null?void 0:M.conversation)==null?void 0:oe.id,messages:q.messages}),ph({enabled:m,channelUrl:Y,initialized:q.initialized,inputReady:ah(G),renderedSignal:q.messages,statsTrackers:T}),l.useEffect(()=>{y()},[d,M]);const H=(ee=M==null?void 0:M.conversation)==null?void 0:ee.status;l.useEffect(()=>{H&&(o==null||o(H))},[H,o]),l.useEffect(()=>{const K=async he=>{const ge=typeof(he==null?void 0:he.channelUrl)=="string";M&&ge&&he.channelUrl!==M.url||(E.debug("conversation.dispatcher: try to close conversation",M),M!=null&&M.conversation&&M.conversation.status===Ce.ConversationStatus.OPEN&&(await M.closeConversation(),i==null||i()))};return A.subscribe(ze.ConversationClose,K),()=>{A.unsubscribe(ze.ConversationClose,K)}},[A,M,E,(Se=M==null?void 0:M.conversation)==null?void 0:Se.status,i]);const V=ce(()=>q.loadPrevious()),z=ce(()=>q.loadNext()),Z=ce(async K=>{try{await q.deleteMessage(K)}finally{K.sendingStatus!=="succeeded"&&P.messageCallbacks.onLocalMessageDeleted(K)}}),ae=ce(K=>K.isUserMessage()?P.runWithUserTurnStats(he=>P.runWithPendingStuckStats(ge=>q.resendMessage(K,ie=>{he(ie.reqId),ge(ie)}),void 0)):P.runWithPendingStuckStats((he,ge)=>q.resendMessage(K,he,ge),void 0,{tracksUploadProgress:K.isMultipleFilesMessage()})),O=ce(()=>q.resetNewMessages()),be=ce(async K=>{var ge;if(((ge=M==null?void 0:M.conversation)==null?void 0:ge.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(K=await c(K));const he=await P.runWithUserTurnStats(ie=>P.runWithPendingStuckStats(pe=>q.sendUserMessage(K,de=>{ie(de.reqId),pe(de)}),u));return u==null||u(he),he}),xe=ce(async K=>{var ge;if(((ge=M==null?void 0:M.conversation)==null?void 0:ge.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(K=await c(K));const he=await P.runWithPendingStuckStats(ie=>q.sendFileMessage(K,ie),u);return u==null||u(he),he}),Oe=ce(async K=>{var ge;if(((ge=M==null?void 0:M.conversation)==null?void 0:ge.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(K=await c(K));const he=await P.runWithPendingStuckStats((ie,pe)=>q.sendMultipleFilesMessage(K,ie,pe),u,{tracksUploadProgress:!0});return u==null||u(he),he}),x=ce(Q),w=ce(async()=>{$e(M)||await(M==null?void 0:M.closeConversation())}),D=l.useMemo(()=>({_statsEnabled:m,_stats:{onMessageLifecycleAnimationStart:j.onAnimationStart,onMessageLifecycleAnimationComplete:j.onAnimationComplete},conversation:(M==null?void 0:M.conversation)??void 0,actions:{setUserMemoryState:C.setUserMemoryState},channelSource:{channel:M,error:N,refetch:x,closeConversation:w},messageSource:{messages:q.messages,newMessages:q.newMessages,initialized:q.initialized,loadPrevious:V,loadNext:z,deleteMessage:Z,resendMessage:ae,resetNewMessages:O,sendUserMessage:be,sendFileMessage:xe,sendMultipleFilesMessage:Oe},state:{streamAnimation:W,input:G}}),[m,j.onAnimationStart,j.onAnimationComplete,M,$,C,N,x,w,q.messages,q.newMessages,q.initialized,q.collectionRevision,V,z,Z,ae,O,be,xe,Oe,W,G]);return a.createElement(Nh,{value:D},e)}function Ph(e,t,n){var E,A,y,T,I,k,L,R,M,$;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),g=ce(()=>{var N;return(N=n==null?void 0:n.onListRequestStart)==null?void 0:N.call(n)}),f=ce(N=>{var Q;return(Q=n==null?void 0:n.onListRequestComplete)==null?void 0:Q.call(n,N)}),p=l.useCallback(async N=>{g();try{await N.loadMore(),f()}catch(Q){throw f(Q),Q}},[g,f]),C=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const N=new ki(e,t);N.setConversationListCollectionHandler({onChannelsAdded:()=>{u(N.channels)},onChannelsUpdated:()=>{u(N.channels)},onChannelsDeleted:()=>{u(N.channels)}}),await p(N),u(N.channels),m(N),i(null)}catch(N){m(null),i(N)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(E=t.filter)==null?void 0:E.aiAgentChannelFilter,(y=(A=t.filter)==null?void 0:A.aiAgentConversationStatusFilter)==null?void 0:y.join(),(I=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:I.join(),(k=t.filter)==null?void 0:k.deskChannelFilter,(R=(L=t.filter)==null?void 0:L.pinnedChannelUrls)==null?void 0:R.join(),(M=t.filter)==null?void 0:M.copilotConversationOnly,($=t.filter)==null?void 0:$.copilotSupportChannelUrl,t.limit,p]),_=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(N){i(N)}},[d]);return ln(e,{onConnected:()=>C()}),l.useEffect(()=>{C()},[C]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:_}}const Xi=e=>{var s;const{aiAgentId:t,queryParams:n}=Te(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[Ce.ConversationStatus.CLOSED,Ce.ConversationStatus.OPEN],...r,...e}},$h=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=ht(),{watchBackgrounded:n}=Te()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();Re(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:Fh}=ye("AIAgentConversationList");function Uh({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=Te(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=Xi(t),u=$h({enabled:n}),d=Ph(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:g=>{u.onListRequestComplete(g)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(Fh,{value:m},r)}function Bh(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:Hh,useContext:Gh}=ye("MessageTemplateFetching");function zh({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:g=!1})=>{const f=m(h);if(f)return f;const p=r.current[h];if(p)return p;g||i(h,{fetching:!0});const C=d(h).catch(_=>{throw g||i(h,{error:!0}),_}).finally(()=>{g||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=C,C},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Bh(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(Hh,{value:u},e)}const Vh="remove_powered_by",gs=(e,t)=>{var s,o;const{chatSDK:n}=Te(),{aiAgentInfo:r}=et();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&es(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(Vh)),[i])}throw new Error("Unsupported feature")},Kh={required:"This question is required",minLength:e=>`Minimum ${e} characters required`,maxLength:e=>`Maximum ${e} characters allowed`,min:e=>`Minimum value is ${e}`,max:e=>`Maximum value is ${e}`,minSelect:e=>`Select at least ${e} options`,maxSelect:e=>`Select at most ${e} options`,regex:"Invalid format",invalidSelection:"Invalid selection"},qh={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Wh={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Yh={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;return e.required&&!r?{isValid:!1,error:n.required}:r&&!e.options.includes(r)?{isValid:!1,error:n.invalidSelection}:{isValid:!0}}},jh={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},Xh={text:qh,number:Wh,"single-select":Yh,"multi-select":jh},Zh={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Zi(e){return Xh[e.type]||Zh}function lo(e){return Zi(e).getValueOrDefault(e)}function Jh(e,t,n={}){const r={...Kh,...n};return Zi(e).validate(e,t,r)}const Qh=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const C={};return e.fields.forEach(_=>{C[_.key]=lo(_)}),C}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const C={};let _=!1;e.fields.forEach(E=>{const A=lo(E);JSON.stringify(c[E.key])!==JSON.stringify(A)&&(_=!0),C[E.key]=A}),_&&u(C)}},[d]);const m=(C,_)=>{u(E=>({...E,[C]:_})),i(E=>({...E,[C]:void 0}))},h=e.fields.map(C=>{var A,y,T;const _=c[C.key]??null,E={key:C.key,label:C.label,error:o[C.key],required:C.required};return C.type==="text"?{...E,type:"text",layout:C.layout,value:_,...C.placeholder&&{placeholder:C.placeholder},...((A=C.rules)==null?void 0:A.max_length)&&{maxLength:C.rules.max_length}}:C.type==="number"?{...E,type:"number",layout:C.layout,value:_,...C.placeholder&&{placeholder:C.placeholder},...((y=C.rules)==null?void 0:y.max)&&{max:C.rules.max}}:C.type==="single-select"?{...E,type:"single-select",layout:C.layout,value:_,options:C.options}:C.type==="multi-select"?{...E,type:"multi-select",layout:C.layout,value:_,options:C.options,...((T=C.rules)==null?void 0:T.max_select)&&{maxSelect:C.rules.max_select}}:{...E,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:C=>h.find(_=>_.key===C),updateFieldValue:m,submit:async()=>{const C={};let _=!1;for(const E of e.fields){const A=c[E.key]??null,y=Jh(E,A,n);y.isValid||(C[E.key]=y.error,_=!0)}if(i(C),!_&&r){const E={};e.fields.forEach(A=>{E[A.key]=c[A.key]??null}),await r(E)}},cancel:async()=>{await(s==null?void 0:s())}}},mr=e=>e.response===null?e:{...e,response:null},Ji=({isMessengerOpened:e,onConversationStarted:t})=>{const{_aiAgentSDK:n,aiAgentId:r,language:s,countryCode:o,context:i}=Te(),{createConversation:c,userSession:u}=et(),[d,m]=l.useState({seq:0,response:null}),h=u==null?void 0:u.userId;l.useEffect(()=>{if(m(mr),!(e||!h))return n.onNudgeMessageReceived(C=>m(_=>({seq:_.seq+1,response:C})))},[n,e,h]);const g=()=>m(mr),f=l.useRef(!1),p=async()=>{var _;if(!d.response||f.current)return;f.current=!0,m(mr);const C=n.session;try{const E=await c({aiAgentId:r,language:s,country:o,context:i});if(n.session!==C)return;(_=n.session)==null||_._updateActiveChannel({url:E,status:"open"}),t({channelUrl:E,initialUserMessage:d.response.callbackUserMessage})}finally{f.current=!1}};return{nudgeMessage:e?null:d.response,nudgeMessageKey:d.seq,dismissNudgeMessage:g,startNudgeConversation:p}},Qi="sb_handoff_external_service_type",ea="sb_handoff_ended_at",eg=e=>Qi in e||ea in e,tg=e=>{const{chatSDK:t,handlers:n,logger:r}=Te(),s=l.useRef(void 0),o=(i,c)=>{if(i.url!==e||!(n!=null&&n.onCustomEvent)||!eg(c))return;const u=i.cachedMetaData,d=Reflect.get(u,Qi),m=Reflect.get(u,ea),h={externalServiceType:typeof d=="string"?d:null,endedAt:typeof m=="string"?Number(m):null},g=JSON.stringify([i.url,h]);s.current!==g&&(s.current=g,r.debug("useCustomEventForHandoff: external-handoff-changed",h),n.onCustomEvent({type:"external-handoff-changed",data:h}))};mt(t,{onMetaDataCreated:o,onMetaDataUpdated:o})},ng=e=>{const{chatSDK:t,handlers:n,logger:r}=Te(),{aiAgentInfo:s}=et(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!Ue(m,s.userId))return;const g=m.messageId;if(Ie.isStreaming(m)){i.current.add(g);return}h==="updated"&&!i.current.has(g)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(g))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=Ci(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,g)=>{m.url===e&&(c(h,g),u(h))};return mt(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},uo=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},ta=e=>{const{aiAgentInfo:t}=et(),n=ji(e);if($e(e))return null;const r=n.find(i=>uo(i.metaData)!==void 0)??n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?uo(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},rg=250,sg=(e,t)=>{var i;const[n,r]=l.useState(!1),s=l.useRef(e),o=l.useRef(void 0);return e!==null?(s.current=e,n||(o.current=t==null?void 0:t.messageId,r(!0))):n&&t!==void 0&&t.sender.userId===((i=s.current)==null?void 0:i.user.userId)&&t.messageId!==o.current&&r(!1),l.useEffect(()=>{if(!n||e!==null)return;const c=setTimeout(()=>r(!1),rg);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},og=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},ig=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},ag=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=ig(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},cg=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},fs=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:void 0,url:void 0,title:""};const r=Li(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?dt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},mo=e=>l.useReducer((t,n)=>({...t,...n}),e);var st=(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))(st||{});const lg=new Set(["free_text","single_choice"]),ug=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=mo({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=mo({followUpItem:!1}),d=l.useMemo(()=>{var _;const f=o.csat,p=typeof f=="number",C=(_=e.follow_up)==null?void 0:_.find(E=>p?E.scores.includes(f):E.always_visible??!1);if(lg.has(C==null?void 0:C.response_type))return C},[o.csat,e.follow_up]),m=(()=>{var f;if(typeof n=="number")return"submitted";if((t===st.AI_AGENT_CSAT_5||t===st.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===st.AI_AGENT_CSAT_5_WITH_CRE){const p=typeof o.csat=="number",C=!((f=e.cre)!=null&&f.required)||typeof o.isResolved=="boolean";if(p&&C)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},dg=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!st[n.type],o=!r&&typeof e!="number"&&Oi(t),i=Kn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},hr=5,Xt=250,na=50,mg=1500,gr=e=>Math.max(0,e-na),hg=(e,t)=>{const n=Math.min(e.length,t.length);let r=0;for(;r<n&&e[r]===t[r];)r++;return r},xn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,gg=(e,t)=>{const n=e&&t.length<=na,r=l.useRef(n&&t.length>0?t:null),[s,o]=l.useState(()=>!n),i=r.current!==null&&t!==r.current,c=!n||i;return l.useEffect(()=>{if(s)return;const u=()=>{r.current=null,o(!0)};if(c){u();return}if(r.current===null&&t.length>0&&(r.current=t),r.current===null)return;const d=setTimeout(u,mg);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},fg=e=>e<1e3?{speed:hr*.5,chunkSize:2}:e<2e3?{speed:hr*.8,chunkSize:2}:{speed:hr*.6,chunkSize:3},Mn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},ho=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(Mn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},ra=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!Mn(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!Mn(e,s),c=e[s]==="["&&!Mn(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=ho(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=ho(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},pg=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(A=>{var y;(y=r.current)==null||y.call(r,A)},[]),m=l.useCallback(A=>{const y=e.initialEnabled&&(e.enabled||A<e.textLength),T=y&&e.deferImages,I=y&&e.deferLinks;return!T&&!I?A:ra(e.text.slice(0,A),{hideImages:T,hideLinks:I}).length},[e]),h=l.useCallback((A,y,T=!1)=>{r.current&&(A<=c.lastLength||!T&&y-c.lastReportedAt<Xt||(c.lastLength=A,c.lastReportedAt=y,d(A)))},[d,c]),g=l.useCallback((A,y,T=!1)=>{if(!r.current)return;const I=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&y-I<Xt||(c.lastCheckedAt=y,h(m(A),y,!0))},[m,h,c]),f=l.useCallback((A,y,T=!1)=>{s.current&&(A<=i.lastLength||!T&&y-i.lastReportedAt<Xt||(i.lastLength=A,i.lastReportedAt=y,s.current(A)))},[i]),p=l.useCallback((A,y,T)=>{const I=A>=y,k=T-i.lastReportedAt>=Xt;if(!I&&!k)return;const L=m(A);f(L,T,I)},[m,i,f]),C=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),_=l.useCallback(A=>{r.current&&(o.current!==null&&A<=o.current||(o.current=A,d(A)))},[d]),E=l.useCallback(({displayedLength:A,streamTextLength:y})=>{const T=u.current;if(u.current={displayedLength:A,streamTextLength:y},!e.initialEnabled||!T||A>T.displayedLength||y<=T.streamTextLength)return;const I=xn();h(y,I,!0),f(y,I,!0)},[u,f,h,e]);return{resetProgress:C,reportVisibleTextProgress:g,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:_,reportMarkdownRevealProgress:E}},Eg=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onAnimationHoldChange:u,onVisibleTextProgress:d,onRenderedTextProgress:m}=e,h=gg(n,t),g=s.includes("image"),f=s.includes("link"),[p,C]=l.useState(()=>n?h?0:gr(t.length):t.length),_=l.useRef(null),E=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,A=l.useRef({startCalled:!1,completeCalled:!1}).current,y=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:g,deferLinks:f,snapOnDisable:r,isGatingStreamingStart:h,prevText:t,prevEnabled:n,resyncLength:null,hasRevealed:!1}).current,T=ce(()=>o==null?void 0:o()),I=ce(()=>i==null?void 0:i()),k=ce(W=>c==null?void 0:c(W)),L=ce(W=>u==null?void 0:u(W)),{resetProgress:R,reportVisibleTextProgress:M,reportRenderedTextProgress:$,reportNonStreamingVisibleTextProgress:N,reportMarkdownRevealProgress:Q}=pg({trackedRef:y,onVisibleTextProgress:d,onRenderedTextProgress:m}),se=n,Y=p<t.length,j=y.initialEnabled&&(se||Y);l.useLayoutEffect(()=>{y.prevText=y.text,y.prevEnabled=y.enabled,y.textLength=t.length,y.enabled=n,y.text=t,y.deferImages=g,y.deferLinks=f,y.snapOnDisable=r,y.isGatingStreamingStart=h}),l.useLayoutEffect(()=>{if(!y.initialEnabled)return;A.startCalled||(A.startCalled=!0,T());const W=()=>{C(t.length);const Z=xn();M(t.length,Z,!0),$(t.length,t.length,Z)};if(!y.enabled&&y.snapOnDisable){W();return}const{prevText:G,prevEnabled:H}=y;if(!H){y.resyncLength=t.length,R(),W();return}if(t.length>=G.length?t.startsWith(G):G.startsWith(t)){C(Z=>t.length<Z?t.length:Z);return}const z=Math.max(1,Math.min(p,hg(G,t)));y.resyncLength=z,C(z)},[T,$,M,R,t]),l.useEffect(()=>{if(!y.initialEnabled)return;let W=h?0:gr(t.length),G=h;E.lastUpdate=0,E.startTime=0,E.lastProgressCall=0,R();const H=V=>{y.resyncLength!==null&&(W=y.resyncLength,y.resyncLength=null,E.lastUpdate=0,R(),G=!1),E.lastUpdate===0&&(E.lastUpdate=V,E.startTime=V,E.lastProgressCall=V,W>0&&M(W,V,!0));const z=y.textLength;G&&!y.isGatingStreamingStart&&(W=gr(z),C(W),W>0&&M(W,V,!0),E.lastUpdate=V,G=!1),!y.enabled&&y.snapOnDisable&&W<z&&(W=z,C(W),M(W,V,!0),$(W,z,V));const Z=V-E.lastUpdate,ae=V-E.startTime,{speed:O,chunkSize:be}=fg(ae),xe=O*be;!y.isGatingStreamingStart&&Z>=xe&&W<z&&(W=Math.min(W+be,z),C(W),M(W,V,W>=z),$(W,z,V),E.lastUpdate=V),V-E.lastProgressCall>=Xt&&(E.lastProgressCall=V,I()),(W<z||y.enabled)&&(_.current=requestAnimationFrame(H))};return _.current=requestAnimationFrame(H),()=>{_.current&&cancelAnimationFrame(_.current),A.startCalled&&!A.completeCalled&&(A.completeCalled=!0,k({completed:!1}))}},[k,I,$,M,R]),l.useEffect(()=>{y.initialEnabled&&(n||t.length>0)||(N(t.length),$(t.length,t.length,xn()))},[n,m,d,N,$,t.length,y]),l.useEffect(()=>{const W=y.initialEnabled&&A.startCalled,G=!n,H=(y.resyncLength??p)>=t.length;W&&G&&H&&!A.completeCalled&&(A.completeCalled=!0,k({completed:!0}))},[n,p,k,t.length]);const P=l.useMemo(()=>{let W=t;y.initialEnabled&&(W=h?"":t.slice(0,p));const G=j&&g,H=j&&f;return!G&&!H?W:ra(W,{hideImages:G,hideLinks:H})},[t,p,g,f,j,h]);l.useEffect(()=>{!y.initialEnabled||j||M(p,xn(),!0)},[p,j,M]),l.useEffect(()=>{Q({displayedLength:p,streamTextLength:P.length})},[p,Q,P.length]);const q=P.length===0&&j&&!y.hasRevealed;return l.useLayoutEffect(()=>{!(y.resyncLength!==null&&y.resyncLength!==p)&&P.length>0&&(y.hasRevealed=!0)}),l.useLayoutEffect(()=>(L(q),()=>L(!1)),[L,q]),{streamText:P,isAnimating:j,isHolding:q}},go={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},_g=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Cg=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},Sg=()=>{const{chatSDK:e}=Te(),[t,n]=l.useState(go),r=()=>n(go);return ln(e,{onConnectionDelayed:s=>{s>0?n(_g(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Cg(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},vg=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},bg=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},yg=({enabled:e=!0}={})=>{const t=ht();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=Ie.isStreaming(n),c=sn(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!_l(n)&&!Ie.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),g=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!g&&!m&&!u&&!d)return;let f=!1,p=!1;const C={};return(g||m)&&(C.onVisibleTextProgress=()=>{g&&!f&&(f=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!p&&(p=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(C.onRenderedTextProgress=_=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:_})}),u&&(C.onMessageTemplateError=_=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:_})}),d&&(C.onFormRenderError=_=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:_})}),C},[e,t])},Ag=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},fr=5e3,Tg=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=ht(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-fr:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(performance.now()-u.current<fr){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=performance.now()-fr):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},Ig=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=ht();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},xg=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(g=>{h===i.current&&o(g.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===_e.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),ln(e,{onConnected:c,onReconnectSucceeded:c}),s},$t=e=>e.replace(/\s+/g," ").trim(),Mg="Code block",sa=e=>`A11Y_INLINE_CODE_${e}`,oa=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},ia=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},Rg=e=>{const{blockquotePrefix:t,content:n}=oa(e),{content:r}=ia(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},kg=(e,t)=>{const{blockquotePrefix:n,content:r}=oa(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=ia(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},wg=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},Lg=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},Og=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},Ng=e=>{let t=0,n="";for(;t<e.length;){const r=wg(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Lg(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Pn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!Pn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=Og(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},aa=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},Dg=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return aa(n,r,i)?t:`${n}${r}`}),Pg=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),$g=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Fg=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return aa(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Ug=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Bg=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},fo=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},po=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},Hg=e=>{const t=e.split(`
12
12
  `),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=po(s);if(i.length>0&&o&&fo(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=po(c);if(u.length===0||fo(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
13
- `)},Dg=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Pg=(e,t)=>{const n=e.split(`
14
- `),r=[];let s=0;for(;s<n.length;){const o=n[s],i=bg(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(yg(n[u],i)){c=u;break}if(c===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=c+1}return r.join(`
15
- `)},Pn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},$g=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||Pn(e,n)){r+=s,n+=1;continue}let o=n;for(;o<e.length&&e[o]==="`";)o+=1;const i=e.slice(n,o);let c=o,u=!1;for(;c<e.length&&e[c]!==`
16
- `;){if(e[c]==="`"&&!Pn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=na(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},ia=(e,{codeBlockPlaceholder:t=vg}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
17
- `);if(!n)return;const r=[];let s=n;s=Pg(s,t),s=Og(s);const o=$g(s);s=o.text,r.push(...o.inlineCodes),s=xg(s),s=Mg(s),s=Rg(s),s=kg(s),s=wg(s),s=Ng(s),s=Dg(s),s=Lg(s);for(let c=0;c<r.length;c++)s=s.replaceAll(na(c),r[c]);return $t(s)||void 0},Fg=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ve(r)?t.image:on(r)?t.video:Ti({name:n,mimeType:r})?t.pdf(n):t.document(n)},$n=e=>(e==null?void 0:e.trim())||"",Ug=e=>(e?$t(e):void 0)||void 0,Eo=30,Bg=e=>e.length>Eo?`${e.slice(0,Eo)}…`:e,Hg=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=Bg($t(n)),c=[t,i].filter(Boolean).join(", ");return o($t(e),$t(c),r,s)},Pr=e=>({text:$n(e),format:"plain"}),Gg=e=>({text:$n(e),format:"markdown"}),zg=({markdownText:e,plainText:t,comparisonText:n})=>{const r=$n(e);return r&&r!==$n(n)?Gg(r):Pr(t)},en=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?ia(t,{codeBlockPlaceholder:s}):Ug(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},aa=(e,t)=>ia(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Vg=(...e)=>$t(e.filter(Boolean).join(", "))||void 0,_o=(e,t,n,r)=>{if(!t||Ii(t,n))return e;const s=aa(t,r);return s?Vg(e,s):e},ca=(e,t)=>{var r,s;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const o=((s=e.name)==null?void 0:s.trim())||"",i=Fg({name:o,mimeType:e.type},t);return _o(i,n,[o],t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const o=e.fileInfoList??[],i=o.length;if(i===0)return;const c=o.map(m=>{var h;return((h=m.fileName)==null?void 0:h.trim())||""}),d=o.every(m=>{var h;return(h=m.mimeType)==null?void 0:h.startsWith("image")})?t.receivedFilesImageCount(i):t.multipleFilesCount(i);return _o(d,n,c,t.codeBlockPlaceholder)}return aa(n,t.codeBlockPlaceholder)},Kg=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,g=0;const f=(R,M,$)=>({text:R,ignoreSuppression:M,queueOrder:g++,dedupeKey:$}),p=()=>{const R=c[0]??null,M=i;return R&&M?M.queueOrder<R.queueOrder?(i=null,M):c.shift()??null:R?c.shift()??null:M!==null?(i=null,M):null},v=()=>{for(;;){const R=p();if(!R)return null;if(!(!R.ignoreSuppression&&(r!=null&&r())))return R}},_=R=>{u=R.text,d=R.dedupeKey??null,h=!0,e(R.text),m=setTimeout(()=>{m=null,h=!1;const M=v();M&&_(M)},n)},E=R=>{u=R.text,d=R.dedupeKey??null,e(R.text)},A=(R,M,$,N)=>M!=null&&N!=null?M===N:M==null&&N==null?R!=null&&R===$:!1,y=(R,M,$)=>{if(!R||!M&&(r!=null&&r()))return;const N=$==null?void 0:$.dedupeKey;if(!(h&&A(R,N,u,d)))if(h){if((($==null?void 0:$.mode)??"latestOnly")==="ordered"){const se=c[c.length-1];if(se&&A(R,N,se.text,se.dedupeKey))return;c.push(f(R,M,N)),c.length>o&&c.shift();return}i=f(R,M,N)}else i=null,_(f(R,M,N))};return{announce:(R,M)=>{y(R,!1,M)},announceIgnoringSuppression:(R,M)=>{y(R,!0,M)},flush:()=>{const R=[];let M=p();for(;M!==null;)R.push(M),M=p();if(m!==null&&(clearTimeout(m),m=null),h=!1,R.length!==0)for(const $ of R)E($)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},qg=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Wg=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),Yg=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},jg=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},Xg=(e,t)=>!t||!Xe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Zg=(e,t)=>Le.isAdmin(e)?Le.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Jg=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Qg=e=>e===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED,ef=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",tf=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},nf=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},rf=({intent:e,strings:t})=>({label:tf(e,t),hint:nf(e,t)}),sf="1.42.0",Fe="sb-agent",Ae={ENTRY:`${Fe}-entry`,MODAL_ROOT:`${Fe}-modal-root`,WINDOW:`${Fe}-window`,LAUNCHER:`${Fe}-launcher`,NUDGE_MESSAGE:`${Fe}-nudge-message`,WINDOW_TITLE:`${Fe}-window-title`},la="data-sb-initial-focus",ua="true",of=`[${la}="${ua}"]`,da={[la]:ua},Es="data-sb-focus-trap-sentinel",af="true",ma="data-sb-initial-focus-header",ha="true",cf=`[${ma}="${ha}"]`,ga={[ma]:ha},fa="data-sb-message-input",pa="true",lf=`textarea[${fa}="${pa}"]:not(:disabled)`,uf={[fa]:pa},Ea=1e3,vn=2147483647,It={MODAL:vn-1,TOOLTIP:vn-2,WINDOW:vn-3,LAUNCHER:vn-4},_a=36,df=100,mf=sf,Ca="noopener noreferrer nofollow",hf=()=>typeof document>"u"||document.visibilityState==="visible",$r=()=>typeof document<"u"&&document.visibilityState==="hidden",Co=()=>$r()?"backgrounded":"foregrounded",gf={getState:Co,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(Co());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function ff(){return{isOnline:()=>navigator.onLine,subscribe:e=>{const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}const bn={};function pf(){return{get:e=>{try{return localStorage.getItem(e)}catch{return bn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{bn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete bn[e]}},getKeys:e=>{try{const t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r&&r.startsWith(e)&&t.push(r)}return t}catch{return Object.keys(bn).filter(t=>t.startsWith(e))}}}}const Ef={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_dismiss_nudge_message:"Dismiss message",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},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.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},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",button_ok:"OK",button_cancel:"Cancel"},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"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`},desk:{ticket_closure_confirm:"Yes, it's resolved",ticket_closure_decline:"No, I still need help",ticket_closure_error_message:"Failed to update the resolution status. Please try again."}},Fr={language:"en",strings:Ef,dateLocale:el.enUS},Sa=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,DESK__TICKET_CLOSURE_CONFIRM:e.desk.ticket_closure_confirm,DESK__TICKET_CLOSURE_DECLINE:e.desk.ticket_closure_decline,DESK__TICKET_CLOSURE_ERROR_MESSAGE:e.desk.ticket_closure_error_message,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_DISMISS_NUDGE_MESSAGE:e.conversation.a11y_dismiss_nudge_message,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),va=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??un},un="en",ba=new Set([un,"ko","es","pt","fr","hi","it","de","tr","ja"]),_f='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:Cf,useContext:_s}=ye("AgentUIElementResolver"),Sf=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===Ae.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(Cf,{value:s},r)};function Et(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const So=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:vf,useContext:Cs}=ye("EscapeDismissStack"),vo=e=>{e.stopPropagation(),e.stopImmediatePropagation()},bf=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=So()),s.current||(s.current=So());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??Et(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){vo(m);return}i.dismissTopmost()&&vo(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(vf,{value:c},n)},ya=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},yf=(e,t)=>{const{register:n}=Cs();ya(e,t,n)},Af=(e,t)=>{const{registerShellDismissHandler:n}=Cs();ya(e,t,n)},Aa=()=>{const{subscribe:e,getOpenCount:t}=Cs();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},Tf=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},bo=Sa(Fr.strings),If={...bo,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:bo.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},Fn={language:Fr.language,dateLocale:Fr.dateLocale,stringSet:If},xf=Object.freeze(Object.defineProperty({__proto__:null,default:Fn},Symbol.toStringTag,{value:"Module"})),Ur=new Map([[un,Fn]]);async function Mf(e){const t=Ur.get(e);if(t)return t;try{if(ba.has(e)){const{default:n}=await Tf(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/qr4Ghr48.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>xf),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/fdHbDI5i.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/DsrX4pE_.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BoXkkKL_.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/De9EY1XB.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/DoR1M7Tp.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/s8NcCXAz.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/D3Aoub0b.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/D-lytti9.cjs"))}),`./languages/${e}.ts`,3);return Ur.set(e,n),n}return Fn}catch{return Fn}}const{Provider:Rf,useContext:le}=ye("Localization"),kf=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(Ur.get(un));return l.useEffect(()=>{const c=t??va(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Mf(c).then(i))},[e,t,n]),a.createElement(Rf,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>ft.format(c,u,{locale:o.dateLocale,...d})}},s)},Un="data-sb-agent-theme",yo=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Un}='${e}'] & { ${r} }`},ne={light:yo("light"),dark:yo("dark")},wf=F.css(({theme:e})=>{const{palette:t}=e;return`
13
+ `)},Gg=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),zg=(e,t)=>{const n=e.split(`
14
+ `),r=[];let s=0;for(;s<n.length;){const o=n[s],i=Rg(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(kg(n[u],i)){c=u;break}if(c===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=c+1}return r.join(`
15
+ `)},Pn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},Vg=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||Pn(e,n)){r+=s,n+=1;continue}let o=n;for(;o<e.length&&e[o]==="`";)o+=1;const i=e.slice(n,o);let c=o,u=!1;for(;c<e.length&&e[c]!==`
16
+ `;){if(e[c]==="`"&&!Pn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=sa(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},ca=(e,{codeBlockPlaceholder:t=Mg}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
17
+ `);if(!n)return;const r=[];let s=n;s=zg(s,t),s=Bg(s);const o=Vg(s);s=o.text,r.push(...o.inlineCodes),s=Ng(s),s=Dg(s),s=Pg(s),s=$g(s),s=Fg(s),s=Hg(s),s=Gg(s),s=Ug(s);for(let c=0;c<r.length;c++)s=s.replaceAll(sa(c),r[c]);return $t(s)||void 0},Kg=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ve(r)?t.image:on(r)?t.video:Ti({name:n,mimeType:r})?t.pdf(n):t.document(n)},$n=e=>(e==null?void 0:e.trim())||"",qg=e=>(e?$t(e):void 0)||void 0,Eo=30,Wg=e=>e.length>Eo?`${e.slice(0,Eo)}…`:e,Yg=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=Wg($t(n)),c=[t,i].filter(Boolean).join(", ");return o($t(e),$t(c),r,s)},Dr=e=>({text:$n(e),format:"plain"}),jg=e=>({text:$n(e),format:"markdown"}),Xg=({markdownText:e,plainText:t,comparisonText:n})=>{const r=$n(e);return r&&r!==$n(n)?jg(r):Dr(t)},en=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?ca(t,{codeBlockPlaceholder:s}):qg(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},la=(e,t)=>ca(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Zg=(...e)=>$t(e.filter(Boolean).join(", "))||void 0,_o=(e,t,n,r)=>{if(!t||Ii(t,n))return e;const s=la(t,r);return s?Zg(e,s):e},ua=(e,t)=>{var r,s;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const o=((s=e.name)==null?void 0:s.trim())||"",i=Kg({name:o,mimeType:e.type},t);return _o(i,n,[o],t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const o=e.fileInfoList??[],i=o.length;if(i===0)return;const c=o.map(m=>{var h;return((h=m.fileName)==null?void 0:h.trim())||""}),d=o.every(m=>{var h;return(h=m.mimeType)==null?void 0:h.startsWith("image")})?t.receivedFilesImageCount(i):t.multipleFilesCount(i);return _o(d,n,c,t.codeBlockPlaceholder)}return la(n,t.codeBlockPlaceholder)},Jg=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,g=0;const f=(R,M,$)=>({text:R,ignoreSuppression:M,queueOrder:g++,dedupeKey:$}),p=()=>{const R=c[0]??null,M=i;return R&&M?M.queueOrder<R.queueOrder?(i=null,M):c.shift()??null:R?c.shift()??null:M!==null?(i=null,M):null},C=()=>{for(;;){const R=p();if(!R)return null;if(!(!R.ignoreSuppression&&(r!=null&&r())))return R}},_=R=>{u=R.text,d=R.dedupeKey??null,h=!0,e(R.text),m=setTimeout(()=>{m=null,h=!1;const M=C();M&&_(M)},n)},E=R=>{u=R.text,d=R.dedupeKey??null,e(R.text)},A=(R,M,$,N)=>M!=null&&N!=null?M===N:M==null&&N==null?R!=null&&R===$:!1,y=(R,M,$)=>{if(!R||!M&&(r!=null&&r()))return;const N=$==null?void 0:$.dedupeKey;if(!(h&&A(R,N,u,d)))if(h){if((($==null?void 0:$.mode)??"latestOnly")==="ordered"){const se=c[c.length-1];if(se&&A(R,N,se.text,se.dedupeKey))return;c.push(f(R,M,N)),c.length>o&&c.shift();return}i=f(R,M,N)}else i=null,_(f(R,M,N))};return{announce:(R,M)=>{y(R,!1,M)},announceIgnoringSuppression:(R,M)=>{y(R,!0,M)},flush:()=>{const R=[];let M=p();for(;M!==null;)R.push(M),M=p();if(m!==null&&(clearTimeout(m),m=null),h=!1,R.length!==0)for(const $ of R)E($)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Qg=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},ef=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),tf=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},nf=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},rf=(e,t)=>!t||!Xe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),sf=(e,t)=>Le.isAdmin(e)?Le.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,of=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,af=e=>e===_e.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===_e.CollectionEventSource.EVENT_MESSAGE_UPDATED,cf=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",lf=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},uf=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},df=({intent:e,strings:t})=>({label:lf(e,t),hint:uf(e,t)}),mf="1.43.1",Fe="sb-agent",Ae={ENTRY:`${Fe}-entry`,MODAL_ROOT:`${Fe}-modal-root`,WINDOW:`${Fe}-window`,LAUNCHER:`${Fe}-launcher`,NUDGE_MESSAGE:`${Fe}-nudge-message`,WINDOW_TITLE:`${Fe}-window-title`},da="data-sb-initial-focus",ma="true",hf=`[${da}="${ma}"]`,ha={[da]:ma},ps="data-sb-focus-trap-sentinel",gf="true",ga="data-sb-initial-focus-header",fa="true",ff=`[${ga}="${fa}"]`,pa={[ga]:fa},Ea="data-sb-message-input",_a="true",pf=`textarea[${Ea}="${_a}"]:not(:disabled)`,Ef={[Ea]:_a},Ca=1e3,vn=2147483647,It={MODAL:vn-1,TOOLTIP:vn-2,WINDOW:vn-3,LAUNCHER:vn-4},Sa=36,_f=100,Cf=mf,va="noopener noreferrer nofollow",Sf=()=>typeof document>"u"||document.visibilityState==="visible",Pr=()=>typeof document<"u"&&document.visibilityState==="hidden",Co=()=>Pr()?"backgrounded":"foregrounded",vf={getState:Co,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(Co());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function bf(){return{isOnline:()=>navigator.onLine,subscribe:e=>{const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}const bn={};function yf(){return{get:e=>{try{return localStorage.getItem(e)}catch{return bn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{bn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete bn[e]}},getKeys:e=>{try{const t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r&&r.startsWith(e)&&t.push(r)}return t}catch{return Object.keys(bn).filter(t=>t.startsWith(e))}}}}const Af={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_dismiss_nudge_message:"Dismiss message",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},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.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},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",button_ok:"OK",button_cancel:"Cancel"},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"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`},desk:{ticket_closure_confirm:"Yes, it's resolved",ticket_closure_decline:"No, I still need help",ticket_closure_error_message:"Failed to update the resolution status. Please try again."}},$r={language:"en",strings:Af,dateLocale:nl.enUS},ba=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,DESK__TICKET_CLOSURE_CONFIRM:e.desk.ticket_closure_confirm,DESK__TICKET_CLOSURE_DECLINE:e.desk.ticket_closure_decline,DESK__TICKET_CLOSURE_ERROR_MESSAGE:e.desk.ticket_closure_error_message,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_DISMISS_NUDGE_MESSAGE:e.conversation.a11y_dismiss_nudge_message,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),ya=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??un},un="en",Aa=new Set([un,"ko","es","pt","fr","hi","it","de","tr","ja"]),Tf='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:If,useContext:Es}=ye("AgentUIElementResolver"),xf=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===Ae.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(If,{value:s},r)};function _t(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const So=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:Mf,useContext:_s}=ye("EscapeDismissStack"),vo=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Rf=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=So()),s.current||(s.current=So());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??_t(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){vo(m);return}i.dismissTopmost()&&vo(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(Mf,{value:c},n)},Ta=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},kf=(e,t)=>{const{register:n}=_s();Ta(e,t,n)},wf=(e,t)=>{const{registerShellDismissHandler:n}=_s();Ta(e,t,n)},Ia=()=>{const{subscribe:e,getOpenCount:t}=_s();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},Lf=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},bo=ba($r.strings),Of={...bo,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:bo.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},Fn={language:$r.language,dateLocale:$r.dateLocale,stringSet:Of},Nf=Object.freeze(Object.defineProperty({__proto__:null,default:Fn},Symbol.toStringTag,{value:"Module"})),Fr=new Map([[un,Fn]]);async function Df(e){const t=Fr.get(e);if(t)return t;try{if(Aa.has(e)){const{default:n}=await Lf(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/qr4Ghr48.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Nf),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/fdHbDI5i.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/DsrX4pE_.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BoXkkKL_.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/De9EY1XB.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/DoR1M7Tp.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/s8NcCXAz.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/D3Aoub0b.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/D-lytti9.cjs"))}),`./languages/${e}.ts`,3);return Fr.set(e,n),n}return Fn}catch{return Fn}}const{Provider:Pf,useContext:le}=ye("Localization"),$f=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(Fr.get(un));return l.useEffect(()=>{const c=t??ya(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Df(c).then(i))},[e,t,n]),a.createElement(Pf,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>pt.format(c,u,{locale:o.dateLocale,...d})}},s)},Un="data-sb-agent-theme",yo=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Un}='${e}'] & { ${r} }`},ne={light:yo("light"),dark:yo("dark")},Ff=F.css(({theme:e})=>{const{palette:t}=e;return`
18
18
  :root,
19
19
  :host {
20
20
  --sendbird-primary-extra-dark: ${t.primary.extraDark};
@@ -63,7 +63,7 @@ $2
63
63
  --sendbird-overlay-dark: ${t.overlay.dark};
64
64
  --sendbird-overlay-light: ${t.overlay.light};
65
65
  }
66
- `}),Lf=F.css`[${Un}='light'] &{--sb-text-high-emphasis:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled:var(--sendbird-onlight-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-ondark-text-disabled);--sb-bg-50-600:var(--sendbird-background-50);--sb-bg-100-500:var(--sendbird-background-100);--sb-bg-300-500:var(--sendbird-background-300);--sb-bg-200-400:var(--sendbird-background-200);--sb-primary:var(--sendbird-primary-main);--sb-secondary:var(--sendbird-secondary-main);--sb-error:var(--sendbird-error-main);--sb-information:var(--sendbird-information-light);}[${Un}='dark'] &{--sb-text-high-emphasis:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled:var(--sendbird-ondark-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-onlight-text-disabled);--sb-bg-50-600:var(--sendbird-background-600);--sb-bg-100-500:var(--sendbird-background-500);--sb-bg-300-500:var(--sendbird-background-500);--sb-bg-200-400:var(--sendbird-background-400);--sb-primary:var(--sendbird-primary-light);--sb-secondary:var(--sendbird-secondary-light);--sb-error:var(--sendbird-error-light);--sb-information:var(--sendbird-information-light);}`,b={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},secondary:{dark:"var(--sendbird-secondary-dark)",light:"var(--sendbird-secondary-light)"},error:{dark:"var(--sendbird-error-dark)",light:"var(--sendbird-error-light)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background300:"var(--sendbird-background-300)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)",textDisabled:"var(--sendbird-onlight-text-disabled)"},ondark:{textHighEmphasis:"var(--sendbird-ondark-text-high-emphasis)",textMidEmphasis:"var(--sendbird-ondark-text-mid-emphasis)",textLowEmphasis:"var(--sendbird-ondark-text-low-emphasis)",textDisabled:"var(--sendbird-ondark-text-disabled)"},overlay:{dark:"var(--sendbird-overlay-dark)"}},themedColor:{textHighEmphasis:"var(--sb-text-high-emphasis)",textMidEmphasis:"var(--sb-text-mid-emphasis)",textLowEmphasis:"var(--sb-text-low-emphasis)",textDisabled:"var(--sb-text-disabled)",textHighEmphasisInverse:"var(--sb-text-high-emphasis-inverse)",textLowEmphasisInverse:"var(--sb-text-low-emphasis-inverse)",bg_50_600:"var(--sb-bg-50-600)",bg_100_500:"var(--sb-bg-100-500)",bg_300_500:"var(--sb-bg-300-500)",bg_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}};class At extends l.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){var n,r;(r=(n=this.props).onError)==null||r.call(n,t)}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:s}=this.props;return this.state.hasError?n:a.createElement(l.Suspense,{fallback:r},s)}}const nt=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Of=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{className:"fill",d:"M52.552 11.448a2.666 2.666 0 0 1 .222 3.52l-.222.251-16.781 16.78 16.781 16.782a2.665 2.665 0 0 1 0 3.771 2.666 2.666 0 0 1-3.52.222l-.251-.222L32 35.771 15.219 52.552a2.665 2.665 0 0 1-3.771 0 2.666 2.666 0 0 1-.222-3.52l.222-.251L28.228 32l-16.78-16.781a2.665 2.665 0 0 1 0-3.771 2.666 2.666 0 0 1 3.52-.222l.251.222 16.78 16.78 16.782-16.78a2.665 2.665 0 0 1 3.771 0z",fill:"#000",fillRule:"evenodd"})),Nf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},a.createElement("path",{className:"fill",d:"M7.33348 7.3335L2.00015 7.3335L2.00015 6.00016H5.05735L1.3335 2.27631L2.27631 1.3335L6.00015 5.05734V2.00016L7.33348 2.00016L7.33348 7.3335ZM8.66683 8.66683H14.0002V10.0002L10.943 10.0002L14.6668 13.724L13.724 14.6668L10.0002 10.943V14.0002H8.66683L8.66683 8.66683Z",fill:"#000",fillRule:"evenodd"})),Df=e=>a.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},a.createElement("path",{className:"fill",fillRule:"evenodd",clipRule:"evenodd",d:"M2 2H7.33333V3.33333L4.27613 3.33333L7.99999 7.05719L7.05718 8L3.33333 4.27616L3.33333 7.33333H2V2ZM14 14H8.66667V12.6667H11.7239L8.00001 8.94281L8.94282 8L12.6667 11.7238V8.66667H14V14Z",fill:"#000"})),Pf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},a.createElement("path",{className:"fill",fill:"#0D0D0D",d:"M50.667 18.667H13.333v-5.334h37.334zM50.667 34.667H13.333v-5.334h37.334zM13.333 50.667h37.334v-5.334H13.333z"})),$f=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{fill:"#000",fillRule:"evenodd",d:"M59.795 29.43 7.329 2.979C4.691 1.802 1.76 4.153 2.932 6.798l6.925 18.609a2 2 0 0 0 1.544 1.275l32.273 5.394L11.4 37.47a1.998 1.998 0 0 0-1.544 1.275L2.932 57.353c-.879 2.645 1.76 4.997 4.397 3.527l52.466-26.453c2.051-.882 2.051-3.82 0-4.996z",className:"fill"})),Ff=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Uf={close:Of,send:$f,menu:Pf,expand:Df,collapse:Nf,spinner:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs"))),activity:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DP95uu-Y.cjs")))},Bf=e=>({size:t=24,color:n=b.color.primary.main,flipInRtl:r=!1})=>a.createElement(Gf,{$size:t,$color:n,$rtlFlip:r},a.createElement(At,{errorFallback:a.createElement(zf,null)},a.createElement(e,null))),Ta=Object.fromEntries(Object.entries(Uf).map(([e,t])=>[e,Bf(t)])),Hf=F.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Gf=S.default.span.attrs({"aria-hidden":"true"})`
66
+ `}),Uf=F.css`[${Un}='light'] &{--sb-text-high-emphasis:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled:var(--sendbird-onlight-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-ondark-text-disabled);--sb-bg-50-600:var(--sendbird-background-50);--sb-bg-100-500:var(--sendbird-background-100);--sb-bg-300-500:var(--sendbird-background-300);--sb-bg-200-400:var(--sendbird-background-200);--sb-primary:var(--sendbird-primary-main);--sb-secondary:var(--sendbird-secondary-main);--sb-error:var(--sendbird-error-main);--sb-information:var(--sendbird-information-light);}[${Un}='dark'] &{--sb-text-high-emphasis:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled:var(--sendbird-ondark-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-onlight-text-disabled);--sb-bg-50-600:var(--sendbird-background-600);--sb-bg-100-500:var(--sendbird-background-500);--sb-bg-300-500:var(--sendbird-background-500);--sb-bg-200-400:var(--sendbird-background-400);--sb-primary:var(--sendbird-primary-light);--sb-secondary:var(--sendbird-secondary-light);--sb-error:var(--sendbird-error-light);--sb-information:var(--sendbird-information-light);}`,b={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},secondary:{dark:"var(--sendbird-secondary-dark)",light:"var(--sendbird-secondary-light)"},error:{dark:"var(--sendbird-error-dark)",light:"var(--sendbird-error-light)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background300:"var(--sendbird-background-300)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)",textDisabled:"var(--sendbird-onlight-text-disabled)"},ondark:{textHighEmphasis:"var(--sendbird-ondark-text-high-emphasis)",textMidEmphasis:"var(--sendbird-ondark-text-mid-emphasis)",textLowEmphasis:"var(--sendbird-ondark-text-low-emphasis)",textDisabled:"var(--sendbird-ondark-text-disabled)"},overlay:{dark:"var(--sendbird-overlay-dark)"}},themedColor:{textHighEmphasis:"var(--sb-text-high-emphasis)",textMidEmphasis:"var(--sb-text-mid-emphasis)",textLowEmphasis:"var(--sb-text-low-emphasis)",textDisabled:"var(--sb-text-disabled)",textHighEmphasisInverse:"var(--sb-text-high-emphasis-inverse)",textLowEmphasisInverse:"var(--sb-text-low-emphasis-inverse)",bg_50_600:"var(--sb-bg-50-600)",bg_100_500:"var(--sb-bg-100-500)",bg_300_500:"var(--sb-bg-300-500)",bg_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}};class At extends l.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){var n,r;(r=(n=this.props).onError)==null||r.call(n,t)}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:s}=this.props;return this.state.hasError?n:a.createElement(l.Suspense,{fallback:r},s)}}const nt=e=>{const t=e;return typeof t=="number"?`${t}px`:t},Bf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{className:"fill",d:"M52.552 11.448a2.666 2.666 0 0 1 .222 3.52l-.222.251-16.781 16.78 16.781 16.782a2.665 2.665 0 0 1 0 3.771 2.666 2.666 0 0 1-3.52.222l-.251-.222L32 35.771 15.219 52.552a2.665 2.665 0 0 1-3.771 0 2.666 2.666 0 0 1-.222-3.52l.222-.251L28.228 32l-16.78-16.781a2.665 2.665 0 0 1 0-3.771 2.666 2.666 0 0 1 3.52-.222l.251.222 16.78 16.78 16.782-16.78a2.665 2.665 0 0 1 3.771 0z",fill:"#000",fillRule:"evenodd"})),Hf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},a.createElement("path",{className:"fill",d:"M7.33348 7.3335L2.00015 7.3335L2.00015 6.00016H5.05735L1.3335 2.27631L2.27631 1.3335L6.00015 5.05734V2.00016L7.33348 2.00016L7.33348 7.3335ZM8.66683 8.66683H14.0002V10.0002L10.943 10.0002L14.6668 13.724L13.724 14.6668L10.0002 10.943V14.0002H8.66683L8.66683 8.66683Z",fill:"#000",fillRule:"evenodd"})),Gf=e=>a.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},a.createElement("path",{className:"fill",fillRule:"evenodd",clipRule:"evenodd",d:"M2 2H7.33333V3.33333L4.27613 3.33333L7.99999 7.05719L7.05718 8L3.33333 4.27616L3.33333 7.33333H2V2ZM14 14H8.66667V12.6667H11.7239L8.00001 8.94281L8.94282 8L12.6667 11.7238V8.66667H14V14Z",fill:"#000"})),zf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},a.createElement("path",{className:"fill",fill:"#0D0D0D",d:"M50.667 18.667H13.333v-5.334h37.334zM50.667 34.667H13.333v-5.334h37.334zM13.333 50.667h37.334v-5.334H13.333z"})),Vf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{fill:"#000",fillRule:"evenodd",d:"M59.795 29.43 7.329 2.979C4.691 1.802 1.76 4.153 2.932 6.798l6.925 18.609a2 2 0 0 0 1.544 1.275l32.273 5.394L11.4 37.47a1.998 1.998 0 0 0-1.544 1.275L2.932 57.353c-.879 2.645 1.76 4.997 4.397 3.527l52.466-26.453c2.051-.882 2.051-3.82 0-4.996z",className:"fill"})),Kf=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),qf={close:Bf,send:Vf,menu:zf,expand:Gf,collapse:Hf,spinner:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs"))),activity:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DP95uu-Y.cjs")))},Wf=e=>({size:t=24,color:n=b.color.primary.main,flipInRtl:r=!1})=>a.createElement(jf,{$size:t,$color:n,$rtlFlip:r},a.createElement(At,{errorFallback:a.createElement(Xf,null)},a.createElement(e,null))),xa=Object.fromEntries(Object.entries(qf).map(([e,t])=>[e,Wf(t)])),Yf=F.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,jf=v.default.span.attrs({"aria-hidden":"true"})`
67
67
  width: ${({$size:e})=>nt(e)};
68
68
  height: ${({$size:e})=>nt(e)};
69
69
  display: inline-block;
@@ -84,21 +84,21 @@ $2
84
84
  stroke-linejoin: round;
85
85
  }
86
86
 
87
- ${({$rtlFlip:e})=>e&&Hf};
88
- `,zf=()=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},a.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),a.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),a.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Vf,useContext:Kf}=ye("MessengerIcon",{icons:Ta}),qf=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:cm(Ta,e)}),[e]);return a.createElement(Vf,{value:n},t)},{Provider:Wf,useContext:Ia}=ye("MessengerTheme");function Yf(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(Xm,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},a.createElement(jf,{...e}))}function jf({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Wn();return l.useLayoutEffect(()=>{e.setAttribute(Un,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(F.ThemeProvider,{theme:n},a.createElement(Wf,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Xf=(e,t)=>{l.useEffect(()=>{const n=Et(t)instanceof ShadowRoot,r=Et(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const o=r.createElement("link");o.rel="stylesheet",o.href=e,(n?t:r.head).appendChild(o)}},[e,t])},Zf=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=Et(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let i=s.querySelector(`style#${o}`);i?i.textContent!==e&&(i.textContent=e):(i=s.ownerDocument.createElement("style"),i.id=o,i.textContent=e,s.appendChild(i))},[e,t])},Jf=80,Qf=()=>{const{stringSet:e}=le(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=l.useRef(t);return n.current=t,n},xa=ye("AriaLiveRegion",{announce:Ee,announceScreenEntry:Ee,announceStatus:Ee,announceError:Ee,flush:Ee,setSuppressionState:Ee}),ep=xa.Provider,Ss=xa.useContext,tp={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},np=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(Ee),s=Qf(),[o]=l.useState(()=>Kg(f=>{r.current(f)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=f=>{const p=t.current;p&&(p.textContent="",requestAnimationFrame(()=>{p.textContent=f}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(f=>{const p=Wg(f,s.current);i(p)},[i]),d=l.useCallback((f,p)=>{const v=Yg(f,s.current),_=(p==null?void 0:p.mode)??qg(f.event);i(v,{mode:_,dedupeKey:p==null?void 0:p.dedupeKey})},[i]),m=l.useCallback((f,p)=>{const v=jg(f,s.current);o.announceIgnoringSuppression(v),p&&setTimeout(()=>{p.focus()},Jf)},[o]),h=l.useCallback((f,p)=>{if(p){n.current.add(f);return}n.current.delete(f)},[]),g=l.useMemo(()=>({announce:i,announceScreenEntry:u,announceStatus:d,announceError:m,flush:c,setSuppressionState:h}),[i,m,u,d,c,h]);return a.createElement(ep,{value:g},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:tp}))},Ma=ye("ConversationAnnouncements",{announcementsEnabled:!0,announce:Ee,announceScreenEntry:Ee,announceStatus:Ee,announceError:Ee,setIsSuppressed:Ee,setStatusPauseState:Ee,flush:Ee}),rp=Ma.Provider,ht=Ma.useContext,sp=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=Ss(),u=l.useRef([]),d=l.useRef(new Set),m=l.useRef(Symbol("conversation-announcements")),h=l.useCallback(T=>{if(!t||!T){c(m.current,!1);return}c(m.current,!0)},[t,c]),g=l.useCallback(()=>{u.current=[]},[]),f=l.useCallback(()=>{if(u.current.length===0)return;if(!t){g();return}const T=[...u.current];g(),T.forEach(I=>{i(),s(I.params,I.options)})},[s,t,g,i]),p=l.useCallback((T,I)=>{if(I){d.current.add(T);return}d.current.delete(T),d.current.size===0&&f()},[f]),v=l.useCallback(T=>{t&&n(T)},[n,t]),_=l.useCallback(T=>{t&&r(T)},[r,t]),E=l.useCallback((T,I)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:I});return}s(T,I)}},[s,t]),A=l.useCallback((T,I)=>{t&&o(T,I)},[o,t]);l.useLayoutEffect(()=>(t||(g(),c(m.current,!1)),()=>{g(),c(m.current,!1)}),[t,g,c]);const y=l.useMemo(()=>({announcementsEnabled:t,announce:v,announceScreenEntry:_,announceStatus:E,announceError:A,setIsSuppressed:h,setStatusPauseState:p,flush:i}),[t,i,v,A,_,E,h,p]);return a.createElement(rp,{value:y},e)},Yn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),Ra=`${Yn}, [tabindex="-1"]`,Ft=e=>{if(!e.isConnected||e.hidden)return!1;let t=e;const n=e.ownerDocument.defaultView;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!1;if(n){const r=n.getComputedStyle(t);if(r.display==="none"||r.visibility==="hidden")return!1}t=t.parentElement}return!0},rn=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(Es)&&Ft(n))return n;return null},ka=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Yn))r.hasAttribute(Es)||Ft(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},wa=(e,t)=>e instanceof ShadowRoot&&!(t instanceof HTMLElement)?e.host.ownerDocument.activeElement===e.host:t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,op=(e,t,n)=>wa(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),vs=e=>rn(e,of),La=e=>vs(e)??rn(e,Yn),ip=e=>{const t=vs(e);if(t)return t;const n=e.querySelector(cf);return(n?rn(n,Ra):null)??rn(e,Yn)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(lp,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),Ao=new WeakMap,ap=(e,t)=>{let n=Ao.get(t);n||(n=new Map,Ao.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=F.css`font-size:${nt(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
87
+ ${({$rtlFlip:e})=>e&&Yf};
88
+ `,Xf=()=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},a.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),a.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),a.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Zf,useContext:Jf}=ye("MessengerIcon",{icons:xa}),Qf=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:mm(xa,e)}),[e]);return a.createElement(Zf,{value:n},t)},{Provider:ep,useContext:Ma}=ye("MessengerTheme");function tp(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(eh,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},a.createElement(np,{...e}))}function np({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Wn();return l.useLayoutEffect(()=>{e.setAttribute(Un,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(F.ThemeProvider,{theme:n},a.createElement(ep,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const rp=(e,t)=>{l.useEffect(()=>{const n=_t(t)instanceof ShadowRoot,r=_t(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const o=r.createElement("link");o.rel="stylesheet",o.href=e,(n?t:r.head).appendChild(o)}},[e,t])},sp=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=_t(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let i=s.querySelector(`style#${o}`);i?i.textContent!==e&&(i.textContent=e):(i=s.ownerDocument.createElement("style"),i.id=o,i.textContent=e,s.appendChild(i))},[e,t])},op=80,ip=()=>{const{stringSet:e}=le(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=l.useRef(t);return n.current=t,n},Ra=ye("AriaLiveRegion",{announce:Ee,announceScreenEntry:Ee,announceStatus:Ee,announceError:Ee,flush:Ee,setSuppressionState:Ee}),ap=Ra.Provider,Cs=Ra.useContext,cp={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},lp=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(Ee),s=ip(),[o]=l.useState(()=>Jg(f=>{r.current(f)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=f=>{const p=t.current;p&&(p.textContent="",requestAnimationFrame(()=>{p.textContent=f}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(f=>{const p=ef(f,s.current);i(p)},[i]),d=l.useCallback((f,p)=>{const C=tf(f,s.current),_=(p==null?void 0:p.mode)??Qg(f.event);i(C,{mode:_,dedupeKey:p==null?void 0:p.dedupeKey})},[i]),m=l.useCallback((f,p)=>{const C=nf(f,s.current);o.announceIgnoringSuppression(C),p&&setTimeout(()=>{p.focus()},op)},[o]),h=l.useCallback((f,p)=>{if(p){n.current.add(f);return}n.current.delete(f)},[]),g=l.useMemo(()=>({announce:i,announceScreenEntry:u,announceStatus:d,announceError:m,flush:c,setSuppressionState:h}),[i,m,u,d,c,h]);return a.createElement(ap,{value:g},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:cp}))},ka=ye("ConversationAnnouncements",{announcementsEnabled:!0,announce:Ee,announceScreenEntry:Ee,announceStatus:Ee,announceError:Ee,setIsSuppressed:Ee,setStatusPauseState:Ee,flush:Ee}),up=ka.Provider,gt=ka.useContext,dp=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=Cs(),u=l.useRef([]),d=l.useRef(new Set),m=l.useRef(Symbol("conversation-announcements")),h=l.useCallback(T=>{if(!t||!T){c(m.current,!1);return}c(m.current,!0)},[t,c]),g=l.useCallback(()=>{u.current=[]},[]),f=l.useCallback(()=>{if(u.current.length===0)return;if(!t){g();return}const T=[...u.current];g(),T.forEach(I=>{i(),s(I.params,I.options)})},[s,t,g,i]),p=l.useCallback((T,I)=>{if(I){d.current.add(T);return}d.current.delete(T),d.current.size===0&&f()},[f]),C=l.useCallback(T=>{t&&n(T)},[n,t]),_=l.useCallback(T=>{t&&r(T)},[r,t]),E=l.useCallback((T,I)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:I});return}s(T,I)}},[s,t]),A=l.useCallback((T,I)=>{t&&o(T,I)},[o,t]);l.useLayoutEffect(()=>(t||(g(),c(m.current,!1)),()=>{g(),c(m.current,!1)}),[t,g,c]);const y=l.useMemo(()=>({announcementsEnabled:t,announce:C,announceScreenEntry:_,announceStatus:E,announceError:A,setIsSuppressed:h,setStatusPauseState:p,flush:i}),[t,i,C,A,_,E,h,p]);return a.createElement(up,{value:y},e)},Yn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'iframe:not([tabindex="-1"])','[tabindex]:not([tabindex="-1"])'].join(", "),wa=`${Yn}, [tabindex="-1"]`,Ft=e=>{if(!e.isConnected||e.hidden)return!1;let t=e;const n=e.ownerDocument.defaultView;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!1;if(n){const r=n.getComputedStyle(t);if(r.display==="none"||r.visibility==="hidden")return!1}t=t.parentElement}return!0},rn=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(ps)&&Ft(n))return n;return null},La=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Yn))r.hasAttribute(ps)||Ft(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Oa=(e,t)=>e instanceof ShadowRoot&&!(t instanceof HTMLElement)?e.host.ownerDocument.activeElement===e.host:t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,mp=(e,t,n)=>Oa(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),Ss=e=>rn(e,hf),Na=e=>Ss(e)??rn(e,Yn),hp=e=>{const t=Ss(e);if(t)return t;const n=e.querySelector(ff);return(n?rn(n,wa):null)??rn(e,Yn)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(pp,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),Ao=new WeakMap,gp=(e,t)=>{let n=Ao.get(t);n||(n=new Map,Ao.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=F.css`font-size:${nt(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
89
89
  ${s.lineHeight?`line-height: ${s.lineHeight};`:"line-height: 100%;"}
90
- `;return n.set(e,o),o},cp=e=>e?F.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",lp=S.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>ap(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>cp(e)}`;async function bs(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const Br='[role="dialog"][aria-modal="true"]',up=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Br)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(Br);return r&&r!==e&&n.add(r),n},dp=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Br)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Ft(n)),mp=e=>{const t=La(e)??e;t===e&&Oa(e),t.focus()},Oa=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},hp=(e,t)=>{const n=ka(e);if(!n){Oa(e),e.focus();return}n[t].focus()},To=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Es,af),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>hp(e,t)),n},gp=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ka(t)||(e.preventDefault(),t.focus())))},jn=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=up(i,u);return()=>{u&&Re(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!wa(c,m)&&m.matches(Ra)&&Ft(m)||dp(i,d)||!u.isConnected||!Ft(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&Ft(m)){s.current=!0;return}s.current=!0,mp(o)};if(n)return Re(c),()=>{i=!0};const u=setTimeout(()=>Re(c),Ea);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=To(o,"last"),c=To(o,"first"),u=d=>gp(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},St=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=_s();return jn(n,d),yf(n,o?r:Ee),n?tl.createPortal(a.createElement(fp,{onClick:o?r:void 0,style:e},a.createElement(pp,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},fp=S.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${b.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${It.MODAL};`,pp=S.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${It.MODAL};`,Ep=({id:e,children:t})=>a.createElement(_p,{id:e},t),_p=S.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,Io=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:da}:n},Cp=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(Ep,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},xo=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ve(t??"")?r.A11Y_FILE_IMAGE(e):on(t??"")?r.A11Y_FILE_VIDEO(e):Ti({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},Sp=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Zt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Sp(e)}),vp=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},Mo=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:vp({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ue=()=>{const{stringSet:e}=le(),t=Cp(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ve(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":xo(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=rf({intent:ef({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:Io(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...uf},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},messageList:{item:({label:i,holding:c})=>c?{props:{"aria-hidden":!0},descriptionNode:null}:{props:{role:"listitem",tabIndex:-1,"aria-label":i},descriptionNode:null},typingItem:i=>({props:{role:"listitem",tabIndex:-1,"aria-label":en({sender:i,message:e.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER})},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...Zt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?xo({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...Zt({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:g,onChange:f})=>{var E;const p=c.trim()||c,v=e.A11Y_HINT_SELECT_RATING,_=t(v,`cs${i}`);return{props:{disabled:d,onClick:()=>f(i),...Mo(u,d,m,h,g,A=>f(A+1)),..._.props,"aria-label":((E=e.A11Y_CSAT_RATING_LABEL)==null?void 0:E.call(e,i,p))??`${i} / ${h} — ${p}`},descriptionNode:_.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,g)=>({props:{...Mo(c,u,d,m,h,g),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:Io(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...Zt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const g=Hg({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":g},descriptionNode:null};const f=e.A11Y_HINT_OPEN_CONVERSATION,p=t(f,"cli");return{props:{...Zt({onActivate:h}),...p.props,"aria-label":g},descriptionNode:p.node}}}}},bp=({title:e,description:t,highlightedText:n})=>{const r=fg(t,n);return a.createElement(Ap,null,a.createElement(Tp,null,a.createElement(B,{as:"div",variant:"h1",color:b.themedColor.textHighEmphasis},e),t&&a.createElement(Ip,null,a.createElement(B,{as:"div",variant:"body3",color:b.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(xp,null,r.highlightedText):null,r.afterText))))},yp=()=>{const{components:e}=Xn.useContext(),{stringSet:t}=le(),{messenger:n}=ue(),r=hg(),s=r.showDescription?gg(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(St,{portalContainerId:Ae.WINDOW,visible:r.visible,onClose:Ee,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Xn=Qe({template:yp,components:{Dialog:bp}}),Ap=S.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Tp=S.default.div`display:flex;flex-direction:column;`,Ip=S.default.div`margin-top:16px;`,xp=S.default.strong`font-weight:700;`,Mp=({url:e})=>bs(e),{Provider:Rp,Consumer:Na,useContext:me}=ye("Messenger");function kp({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=_s(),g=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);Af(m.opened,g);const f=l.useRef(m.opened);l.useLayoutEffect(()=>{const _=f.current&&!m.opened;if(f.current=m.opened,!_)return;const E=Et(o.rootElement),A=h(Ae.WINDOW);let y=!1;return Re(()=>{var T;y||op(E,E.activeElement,A)&&((T=h(Ae.LAUNCHER))==null||T.focus())}),()=>{y=!0}},[m.opened,o.rootElement,h]);const{Template:p}=Xn.useContext(),v=l.useMemo(()=>{var _;return{...o.handlers,onClickLink:((_=o.handlers)==null?void 0:_.onClickLink)??Mp}},[o.handlers]);return a.createElement(pm,{...o},_=>a.createElement(Rp,{value:{...o,..._,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(p,null),e))}const Da=/iPad|iPhone|iPod/.test(navigator.userAgent),wp=/Android/.test(navigator.userAgent),dn=e=>Da||wp;let Yt=null,Er=null;const Lp=(e,t=5e3)=>{Yt&&(clearInterval(Yt),clearTimeout(Er));const n=document.title;Yt=setInterval(()=>{document.title=document.title===e?n:e},750),Er=setTimeout(()=>{clearInterval(Yt),Yt=null,Er=null,document.title=n},t)},Pa=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},$a="0 16px 24px 2px rgba(33, 33, 33, 0.12), 0 6px 30px 5px rgba(33, 33, 33, 0.08), 0 6px 10px -5px rgba(33, 33, 33, 0.04)",ke=F.css`&:focus-visible{outline:2px solid ${b.themedColor.primary};outline-offset:2px;}`,Ro=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},mn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??Ro(t)??Ro(n),g=u?void 0:t?d:n?m:void 0,f=t&&n?m:void 0,p=()=>{c(),Re(()=>o==null?void 0:o())},v=()=>{c(),Re(()=>i==null?void 0:i())};return a.createElement(St,{portalContainerId:Ae.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":g,"aria-describedby":f},a.createElement(Op,null,a.createElement(Np,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:b.themedColor.textHighEmphasis},t)),n&&a.createElement(Dp,{id:m},a.createElement(B,{variant:"body3",color:b.themedColor.textMidEmphasis},n))),a.createElement(Pp,null,s&&a.createElement(ko,{onClick:v},a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},s)),a.createElement(ko,{onClick:p},a.createElement(B,{variant:"button",color:b.themedColor.primary},r)))))},Op=S.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Np=S.default.div`margin-bottom:16px;`,Dp=S.default.div`margin-top:16px;`,Pp=S.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ko=S.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${ke}`,{Provider:$p,useContext:De}=ye("MessengerSession"),Fp=l.forwardRef(function({children:e,...t},n){return a.createElement(eh,{ref:n,...t},r=>a.createElement(Up,{...r},e))}),Up=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=me(),{userSessionInfo:h,authenticate:g,userSession:f,aiAgentInfo:p,launcherInfo:v}=t,[_,E]=l.useState(!1),A=l.useRef(null);Ct(n,{async onUserJoined(T,I){var L,R,M,$;T.conversation&&T.conversation.type===Ce.ConversationType.PROACTIVE&&I.userId===((L=n.currentUser)==null?void 0:L.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(M=m.session)==null||M._updateActiveChannel({url:T.url,status:"open",conversationStatus:(R=T.conversation)==null?void 0:R.status}),c.setOpened(!0),Bp({sound:document.hidden||!c.opened}),($=A.current)==null||$.call(A,{channel:T}))}}),l.useEffect(()=>{g().then(({launcher:T})=>{T.auto_open&&!dn()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var I;r.error("messengerSession: failed to initialize",T),(I=u==null?void 0:u.onInitializeFailed)==null||I.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>E(!0);return d.subscribe(ze.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(ze.AnonymousSessionTokenExpired,T)},[d]);const y=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!f||!p||!v?null:a.createElement($p,{value:{...t,userSession:f,aiAgentInfo:{...p,...i==null?void 0:i.bot},launcherInfo:{...v,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>A.current=T}},e,a.createElement(mn,{visible:_,title:"Session timed out",description:"Start a new conversation.",onConfirm:y,onClose:Ee}))};function Bp({sound:e}){Lp("🔔You have received a new message"),e&&Pa()}const Bn=`@${Fe}-focused-channel`,Fa=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Hp=()=>{try{const e=localStorage.getItem(Bn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},wo=e=>{try{localStorage.setItem(Bn,JSON.stringify({channelUrl:e,tabId:Fa}))}catch{}},Lo=()=>{try{const e=localStorage.getItem(Bn);if(!e)return;JSON.parse(e).tabId===Fa&&localStorage.removeItem(Bn)}catch{}},Gp=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>wo(e),r=()=>Lo();return document.hasFocus()&&wo(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),Lo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Hp()===e}),zp=e=>{const{config:t,chatSDK:n}=me(),{sdkUser:r}=De(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=Gp(e,s);Ct(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Xe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&Pa()}})},Hr=new WeakMap;function Vp(e,t){Ve(e.type)&&!Hr.has(e)&&Hr.set(e,Ua(t))}async function Kp(e){const t=URL.createObjectURL(e),n=await Ua(t);return URL.revokeObjectURL(t),n}function Ua(e){return new Promise(t=>{const n=new Image;n.onload=function(){t({width:String(n.width),height:String(n.height)})},n.onerror=function(){t(void 0)},n.src=e})}async function qp(e){if("file"in e&&e.file instanceof File&&Ve(e.file.type)){const t=await(Hr.get(e.file)??Kp(e.file));return t?new we.MessageMetaArray({key:bi,value:[t.width,t.height]}):void 0}}const Wp=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=me(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await qp(s),i={...s,metaArrays:o?[o]:void 0},c=Yp(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===we.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===we.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Yp=e=>{if(!e)return null;const t={};return e.ai&&Object.keys(e.ai).length>0&&(t.ai_attrs=e.ai),e.safeguard&&Object.keys(e.safeguard).length>0&&(t.safeguard_attrs=e.safeguard),typeof e.use_prompt_cache=="boolean"&&(t.use_prompt_cache=e.use_prompt_cache),Object.keys(t).length>0?t:null},Nt=50,_r=Nt-40,{Provider:jp,useContext:Ba}=ye("ConversationScroll"),Oo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Cr=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),No=e=>Array.from(e.querySelectorAll(`#${Fe}-message-item`));function Xp({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(Oo),[u,d]=l.useState(0),[m,h]=l.useState(0),[g,f]=l.useState(!1),[p,v]=l.useState(!1),[_,E]=l.useState(!0),A=x=>{const w=Cr(x);return o.current.distanceFromBottom=w,h(w),w},y=()=>{const x=i.current;x.reconcileTimer&&(clearTimeout(x.reconcileTimer),x.reconcileTimer=null)},T=l.useCallback(()=>{const x=s.current;x.mutation&&(x.mutation.disconnect(),x.mutation=null),x.resize&&(x.resize.disconnect(),x.resize=null),x.resizeTargets.clear()},[]),I=l.useMemo(()=>g||t==="bottom"?"auto":e,[g,t,e]),k=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},L=()=>{const x=r.current;!x||!c.current.shouldUpdate||d(w=>{c.current.shouldUpdate=!1;const{contentHeight:D,contentSnapshotHeight:U,shouldRecalc:Z}=c.current,oe=x.clientHeight;if(U>D)return w;const Q=R(x,{messageType:"outgoing"});let Se=0;if(Q){const z=Q.message.offsetTop-_r+oe;Se=Math.max(0,z-D)}else{const z=D-U,he=oe-_r;Se=Math.max(0,z-he)}return w===0||Se!==w||Z?(c.current.shouldRecalc=!1,Se):w})},R=l.useCallback((x,w)=>{const{messageType:D="all"}=w??{},U=No(x);let Z=U;D==="outgoing"&&(Z=U.filter(ge=>ge.getAttribute("data-layout-id")==="outgoingmessage"));const oe=Z[Z.length-1];if(!oe)return null;const Q=x.getBoundingClientRect(),Se=oe.getBoundingClientRect(),z=x.scrollTop+(Se.top-Q.top),he=z+oe.offsetHeight;return{message:oe,scrollTop:z,lastMessageBottom:he}},[]),M=l.useCallback(()=>{const x=r.current;if(!x||I!=="fixed")return;const w=R(x);c.current.contentHeight=(w==null?void 0:w.lastMessageBottom)??x.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&k(),i.current.programmatic?o.current.distanceFromBottom=Cr(x):A(x),L()},[I,R]),$=l.useCallback(()=>{T(),y(),c.current=Oo,d(0),h(0),E(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),N=l.useCallback((x=!0)=>{const w=o.current.distanceFromBottom>Nt;if(i.current.awayByUser=!1,h(0),!w){Re(()=>{const D=r.current;D&&!i.current.awayByUser&&D.scrollTo({top:D.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,E(!1),y()),Re(()=>{const D=r.current;if(!D){i.current.programmatic=!1,E(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,A(D),E(!0);return}const U=()=>{if(r.current!==D){i.current.programmatic=!1,r.current&&A(r.current),E(!0);return}i.current.programmatic=!1,A(D),E(!0)};if(x&&!i.current.reconcileTimer){const Z=setTimeout(U,500);i.current.reconcileTimer=Z,D.addEventListener("scrollend",()=>{clearTimeout(Z),i.current.reconcileTimer=null,U()},{once:!0})}D.scrollTo({top:D.scrollHeight,behavior:x?"smooth":"auto"}),x||U()})},[]),J=l.useCallback(()=>{const x=r.current;if(x){if(i.current.awayByUser){A(x);return}N(!1)}},[N]),se=l.useCallback(()=>{const x=r.current,w=s.current;if(!x||!w.resize)return;const D=new Set(No(x));for(const U of w.resizeTargets)D.has(U)||(w.resize.unobserve(U),w.resizeTargets.delete(U));for(const U of D)w.resizeTargets.has(U)||(w.resize.observe(U),w.resizeTargets.add(U))},[]),Y=l.useCallback(x=>{T();const w=s.current;typeof ResizeObserver<"u"&&(w.resize=new ResizeObserver(J),se());const D=new MutationObserver(()=>{se(),J()});w.mutation=D,D.observe(x,{childList:!0})},[T,J,se]),j=l.useCallback(x=>{if(!x){r.current=null,T();return}if(r.current=x,I!=="fixed"){Y(x);return}$(),c.current.viewport=x.clientHeight;const w=new MutationObserver(()=>{M()});s.current.mutation=w,w.observe(x,{childList:!0,subtree:!0})},[T,I,M,$,Y]),P=l.useCallback(()=>{const x=r.current;if(!x)return;const w=R(x,{messageType:"outgoing"});w&&(x.scrollTo({top:w.message.offsetTop-_r,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[R]),K=(x,w,D)=>{const U=Cr(x);if(D&&U>Nt){i.current.programmatic=!1,i.current.awayByUser=!0,y(),A(x),E(!0),o.current.prevScrollTop=w;return}o.current.distanceFromBottom=U},q=(x,w,D)=>{const Z=A(x)<=Nt;w&&!Z&&(i.current.awayByUser=!0,y()),D&&Z&&(i.current.awayByUser=!1)},W=l.useCallback(x=>{const{scrollTop:w}=x.currentTarget,D=o.current.prevScrollTop;i.current.programmatic?K(x.currentTarget,w,w<D):q(x.currentTarget,w<D,w>D),o.current.prevScrollTop=w},[]),H=l.useCallback(()=>{I==="fixed"&&(v(!0),k())},[I]),G=l.useCallback(()=>{I==="fixed"?setTimeout(()=>P(),300):N()},[I,P]),V=l.useCallback(x=>{i.current.streaming=x,I==="fixed"?k():i.current.awayByUser||N()},[I,N]),ee=l.useCallback(x=>{f(x),x&&(d(0),I==="fixed"&&T())},[T,I]),ae=l.useCallback(x=>{I==="auto"&&x&&!i.current.awayByUser&&N()},[I,N]),be=!(m<=Nt)&&!p,xe=l.useCallback(()=>o.current.distanceFromBottom>Nt,[]),Oe=l.useMemo(()=>({ref:j,state:{bottomSpace:u,isAwayFromBottom:be,isScrollPositionReconciled:_,shouldCountNewMessages:xe},props:{onScroll:W},actions:{scrollToBottom:N,onBeforeMessageSend:H,onAfterMessageSend:G,onStreamingUpdate:V,onConversationClosed:ee,onTypingIndicatorUpdate:ae}}),[j,u,be,_,xe,W,N,H,G,V,ee,ae]);return a.createElement(jp,{value:Oe},n)}const{Provider:Zp,Context:Jp,useContext:Me}=ye("Conversation"),Qp=({children:e})=>{var s;const{channelSource:t}=Me(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=jh(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},eE=({context:e,scrollSource:t,goToActiveConversation:n,onNavigateToConversationList:r,children:s})=>{const o=l.useMemo(()=>({...e,scrollSource:t,goToActiveConversation:n,onNavigateToConversationList:r}),[e,t,n,r]);return a.createElement(Zp,{value:o},s)},tE=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,children:c})=>{const{activeChannel:u,refreshActiveChannel:d}=De(),m=Ba(),h=e||(u==null?void 0:u.url);zp(h);const{onBeforeSendMessage:g,onAfterSendMessage:f}=Wp({onScrollAfterSendMessage:()=>{m.actions.onAfterMessageSend()}}),p=l.useCallback(A=>(m.actions.onBeforeMessageSend(),g(A)),[m.actions,g]),v=l.useCallback(A=>{const y=A.some(T=>Te.isStreaming(T));m.actions.onStreamingUpdate(y)},[m.actions.onStreamingUpdate]),_=l.useCallback(A=>{m.actions.onConversationClosed(A===Ce.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),E=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(kh,{key:h,channelUrl:h,onBeforeSendMessage:p,onAfterSendMessage:f,onMessagesUpdated:v,onMessagesReceived:v,onChannelDeleted:E,onConversationStatusChanged:_,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,shouldCountNewMessages:m.state.shouldCountNewMessages},A=>a.createElement(eE,{context:A,scrollSource:m,goToActiveConversation:E,onNavigateToConversationList:n},a.createElement(Qp,null,c)))},Ha=({children:e,...t})=>{const{config:n}=Ie(),{agentPreviewConfigs:r}=me(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(Xp,{scrollMode:s,messageStackDirection:o},a.createElement(tE,{...t},e))},ys=l.createContext({onDrop:Ee,subscribe:()=>Ee}),Gr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(ys.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},nE=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(ys);l.useEffect(()=>t(e),[e])};Gr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(ys);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const Ga=ye("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>Ee,registerWindowTitlePending:()=>Ee}),rE=Ga.Provider,za=Ga.useContext,Do=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},As=({children:e})=>{const[t,n]=Do(),[r,s]=Do(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(rE,{value:i},e)},Zn=za,Va=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=za(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?Ae.WINDOW_TITLE:void 0}},sE=(e,t)=>{const r=(t?rn(e,t):null)??ip(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},Ka=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=vs(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,sE(e.current,s))};if(r)return Re(d),()=>{u=!0};const m=setTimeout(()=>Re(d),Ea);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},oE=(e,t)=>{const{announcementsEnabled:n}=ht(),{channelSource:r}=Me(),{isWindowNameReady:s}=Zn(),o=Aa(),i=r.channel!=null||r.error!=null;Ka(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?lf:void 0,suppressed:o})},iE=()=>{var s;const{_statsEnabled:e,channelSource:t}=Me(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o($r()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);_g({channelUrl:n,enabled:e,isInitiallyBackgrounded:$r,isForegrounded:hf,subscribeToForegroundState:r})},aE=e=>Ve(e)||on(e);function cE(e,t){return e.filter(n=>Te.isWelcomeMessage(n,t))}const qa=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!Te.isWelcomeMessage(r,n):!0),lE=[],Wa=()=>{var p,v,_,E,A,y;const{agentPreviewConfigs:e={},aiAgentId:t}=me(),{aiAgentInfo:n,userSession:r}=De(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Me(),u=e.welcomeMessages??lE,d=l.useMemo(()=>qa(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=dt(s.channel),h=(v=(p=Li(s.channel,r.userId))==null?void 0:p.nickname)==null?void 0:v.trim(),g=m?(E=(_=s.channel)==null?void 0:_.name)==null?void 0:E.trim():(A=n==null?void 0:n.nickname)==null?void 0:A.trim(),f=h||g||void 0;return{initialized:o.initialized,channelUrl:(y=s.channel)==null?void 0:y.url,agentName:f,isClosed:$e(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},uE=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=ht(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(g=>Le.isAdmin(g)&&Le.isCSAT(g)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},dE=()=>{const e=Wa();uE(e)},Ya=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),Po=(e,t,n=ft.format)=>{const r=ca(e,Ya(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},mE={senderName:!0,body:!0,time:!0},hE=Object.keys(mE),gE=(e,t)=>hE.every(n=>e[n]===t[n]),$o=2e3,Fo=400,zr=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},ja=e=>{if(!Le.isAdmin(e)||!Le.isCSAT(e))return null;const t=Jg(e);return t?`csat:${t}`:null},fE=e=>{const t=new Set;for(const n of e){const r=ja(n);r&&t.add(r)}return t},pE=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&zr(r).some(s=>t.includes(s)))return r}},Sr=(e,t)=>e.some(n=>t.includes(n)),Uo=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,vr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),EE=()=>{const{announceStatus:e,announcementsEnabled:t}=ht(),{stringSet:n,format:r}=le(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:g,currentUserId:f}=Wa(),{outgoingMessageStates:p,outgoingMessageStatusSignature:v}=l.useMemo(()=>{if(!f)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const W=o.flatMap(H=>{const G=Xg(H,f);return!G||!("sendingStatus"in H)?[]:[{key:G,sendingStatus:H.sendingStatus}]});return{outgoingMessageStates:W,outgoingMessageStatusSignature:W.map(({key:H,sendingStatus:G})=>`${H}:${G}`).join(",")}},[f,o]),_=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:vr(p)}),E=l.useRef({messages:o,currentUserId:f,inputDisabledBy:h,isStreamAnimating:g,stringSet:n,format:r}),A=l.useRef([]),y=l.useRef(null),T=l.useRef([]),I=l.useRef(new Set),k=l.useRef(new Set),L=l.useRef(!1),R=l.useRef(s);E.current={messages:o,currentUserId:f,inputDisabledBy:h,isStreamAnimating:g,stringSet:n,format:r};const M=()=>E.current.isStreamAnimating||E.current.inputDisabledBy==="ai_responding",$=()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},N=(W,H,G)=>{const V=G==null?void 0:G.replaceableForMs;if(W.length===0||!V)return;const ee=Date.now();T.current=[...T.current.filter(({replaceableUntil:ae})=>ae>ee),{eventKeys:W,parts:H,replaceableUntil:ee+V}]},J=()=>A.current.length>0,se=()=>{A.current=[]},Y=()=>{const[W,...H]=A.current;if(!W)return!1;A.current=H;const{eventKeys:G,parts:V,dedupeKey:ee}=W,ae=xe=>{N(G,xe,{replaceableForMs:G.length>0?$o:void 0}),e({event:"newMessage",...xe},ee?{dedupeKey:ee}:void 0)};if(G.length===0)return ae(V),!0;const O=E.current,be=pE(O.messages,G);if(be){const xe=Po(be,O.stringSet,O.format);return ae(xe),!0}return ae(V),!0},j=()=>{for($();Y(););},P=(W=$o)=>{$(),y.current=setTimeout(()=>{if(y.current=null,M())return;const H=Uo(),[G]=A.current;if(!G)return;if(G.focusTarget!==H){A.current=[{...G,focusTarget:H},...A.current.slice(1)],P(Fo);return}Y()&&J()&&P(Fo)},W)},K=(W,H,G)=>{const V={eventKeys:H,parts:W,focusTarget:Uo(),dedupeKey:G?G.dedupeKey??void 0:H[0]},ee=H.length===0?-1:A.current.findIndex(({eventKeys:ae})=>Sr(ae,H));ee>=0?A.current=A.current.map((ae,O)=>O===ee?{...V,dedupeKey:G?V.dedupeKey:ae.dedupeKey}:ae):A.current=[...A.current,V],P()},q=(W,H,G)=>{if(W!=="messagesUpdated"||H.length===0)return!1;const V=Date.now(),ee=T.current.find(ae=>ae.replaceableUntil>V&&Sr(ae.eventKeys,H));return ee?!gE(G,ee.parts):!1};l.useEffect(()=>{const W=R.current!==s;(!t||!d||W)&&(L.current=!1,k.current.clear(),se(),T.current=[],I.current.clear(),$(),W&&(R.current=s),!t||!d)||L.current||(L.current=!0,R.current=s,_.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:vr(p)},I.current=new Set(o.flatMap(H=>{if(!Te.isStreaming(H))return[];const G="sender"in H?H.sender:void 0;return(G==null?void 0:G.userId)===E.current.currentUserId?[]:zr(H)})),k.current=fE(o))},[e,t,s,d,m,i,c,v]),l.useEffect(()=>{const W=(H,G)=>{const V=E.current,ee=zr(H),ae=ja(H);if(ae!=null){if(k.current.has(ae))return;k.current.add(ae),e({event:"csatDisplayed"});return}if(Te.isStreaming(H)){ee.forEach(U=>{I.current.add(U)});return}const O=ee.filter(U=>I.current.has(U)),be=G==="messagesUpdated"&&O.length>0;be&&O.forEach(U=>{I.current.delete(U)});const xe=G==="messagesUpdated"&&A.current.some(({eventKeys:U})=>Sr(U,ee)),Oe=Po(H,V.stringSet,V.format),x=q(G,ee,Oe);if(!be&&G!=="messagesAdded"&&!xe&&!x)return;const w=x?{dedupeKey:null}:void 0;if(be||M()||xe){K(Oe,[...new Set([...O,...ee])],w);return}if(x){K(Oe,ee,w);return}J()&&j();const D=ee[0];e({event:"newMessage",...Oe},D?{dedupeKey:D}:void 0)};return qn.subscribe(H=>{if(!L.current||H.channelUrl!==s||H.kind==="initialized"||H.kind==="messagesDeleted"||!Qg(H.source))return;const G=E.current.currentUserId;for(const V of H.messages)V&&Zg(V,G)&&W(V,H.kind)})},[e,s]),l.useEffect(()=>{L.current&&(M()||J()&&P())},[h,g]),l.useEffect(()=>()=>{$()},[]),l.useEffect(()=>{if(!L.current)return;const W=_.current,H=W.outgoingMessageStatuses;W.outgoingMessageStatuses=vr(p),p.some(({key:V,sendingStatus:ee})=>{const ae=H.get(V);return ae!==void 0&&ae!=="failed"&&ee==="failed"})&&e({event:"sendFailed"})},[e,v]),l.useEffect(()=>{if(!L.current)return;const W=_.current;i&&!W.isClosed&&e({event:"conversationClosed"}),W.isClosed=i},[e,i]),l.useEffect(()=>{if(!L.current)return;const W=_.current;c&&!W.isHandedOff&&e({event:"agentConnected",agentName:u}),W.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!L.current)return;const W=_.current;m&&h!=="ai_responding"&&(!W.inputDisabled||W.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),W.inputDisabled=m,W.inputDisabledBy=h},[e,m,h])},_E=()=>{const{channelSource:e}=Me(),t=Qi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},CE=e=>{const{announceStatus:t,announcementsEnabled:n}=ht();tg(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},SE=()=>{const e=_E();CE(e)},te=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=Kf(),o=s[e];return a.createElement(vE,{className:n},a.createElement(o,{size:t,color:r??b.color.primary.main,flipInRtl:Ff.has(e)}))},vE=S.default.span.attrs({"aria-hidden":"true"})`
90
+ `;return n.set(e,o),o},fp=e=>e?F.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",pp=v.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>gp(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>fp(e)}`;async function vs(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const Ur='[role="dialog"][aria-modal="true"]',Ep=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Ur)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(Ur);return r&&r!==e&&n.add(r),n},_p=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Ur)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Ft(n)),Cp=e=>{const t=Na(e)??e;t===e&&Da(e),t.focus()},Da=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Sp=(e,t)=>{const n=La(e);if(!n){Da(e),e.focus();return}n[t].focus()},To=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(ps,gf),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Sp(e,t)),n},vp=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(La(t)||(e.preventDefault(),t.focus())))},jn=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=Ep(i,u);return()=>{u&&Re(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!Oa(c,m)&&m.matches(wa)&&Ft(m)||_p(i,d)||!u.isConnected||!Ft(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&Ft(m)){s.current=!0;return}s.current=!0,Cp(o)};if(n)return Re(c),()=>{i=!0};const u=setTimeout(()=>Re(c),Ca);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=To(o,"last"),c=To(o,"first"),u=d=>vp(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},St=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=Es();return jn(n,d),kf(n,o?r:Ee),n?rl.createPortal(a.createElement(bp,{onClick:o?r:void 0,style:e},a.createElement(yp,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},bp=v.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${b.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${It.MODAL};`,yp=v.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${It.MODAL};`,Ap=({id:e,children:t})=>a.createElement(Tp,{id:e},t),Tp=v.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,Io=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:ha}:n},Ip=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(Ap,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},xo=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ve(t??"")?r.A11Y_FILE_IMAGE(e):on(t??"")?r.A11Y_FILE_VIDEO(e):Ti({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},xp=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Zt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:xp(e)}),Mp=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},Mo=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:Mp({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ue=()=>{const{stringSet:e}=le(),t=Ip(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ve(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":xo(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=df({intent:cf({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:Io(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...Ef},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},messageList:{item:({label:i,holding:c})=>c?{props:{"aria-hidden":!0},descriptionNode:null}:{props:{role:"listitem",tabIndex:-1,"aria-label":i},descriptionNode:null},typingItem:i=>({props:{role:"listitem",tabIndex:-1,"aria-label":en({sender:i,message:e.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER})},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...Zt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?xo({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...Zt({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:g,onChange:f})=>{var E;const p=c.trim()||c,C=e.A11Y_HINT_SELECT_RATING,_=t(C,`cs${i}`);return{props:{disabled:d,onClick:()=>f(i),...Mo(u,d,m,h,g,A=>f(A+1)),..._.props,"aria-label":((E=e.A11Y_CSAT_RATING_LABEL)==null?void 0:E.call(e,i,p))??`${i} / ${h} — ${p}`},descriptionNode:_.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,g)=>({props:{...Mo(c,u,d,m,h,g),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:Io(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...Zt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const g=Yg({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":g},descriptionNode:null};const f=e.A11Y_HINT_OPEN_CONVERSATION,p=t(f,"cli");return{props:{...Zt({onActivate:h}),...p.props,"aria-label":g},descriptionNode:p.node}}}}},Rp=({title:e,description:t,highlightedText:n})=>{const r=bg(t,n);return a.createElement(wp,null,a.createElement(Lp,null,a.createElement(B,{as:"div",variant:"h1",color:b.themedColor.textHighEmphasis},e),t&&a.createElement(Op,null,a.createElement(B,{as:"div",variant:"body3",color:b.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(Np,null,r.highlightedText):null,r.afterText))))},kp=()=>{const{components:e}=Xn.useContext(),{stringSet:t}=le(),{messenger:n}=ue(),r=Sg(),s=r.showDescription?vg(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(St,{portalContainerId:Ae.WINDOW,visible:r.visible,onClose:Ee,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Xn=Qe({template:kp,components:{Dialog:Rp}}),wp=v.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Lp=v.default.div`display:flex;flex-direction:column;`,Op=v.default.div`margin-top:16px;`,Np=v.default.strong`font-weight:700;`,Dp=({url:e})=>vs(e),{Provider:Pp,Consumer:Pa,useContext:me}=ye("Messenger");function $p({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=Es(),g=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);wf(m.opened,g);const f=l.useRef(m.opened);l.useLayoutEffect(()=>{const _=f.current&&!m.opened;if(f.current=m.opened,!_)return;const E=_t(o.rootElement),A=h(Ae.WINDOW);let y=!1;return Re(()=>{var T;y||mp(E,E.activeElement,A)&&((T=h(Ae.LAUNCHER))==null||T.focus())}),()=>{y=!0}},[m.opened,o.rootElement,h]);const{Template:p}=Xn.useContext(),C=l.useMemo(()=>{var _;return{...o.handlers,onClickLink:((_=o.handlers)==null?void 0:_.onClickLink)??Dp}},[o.handlers]);return a.createElement(Sm,{...o},_=>a.createElement(Pp,{value:{...o,..._,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:C}},a.createElement(p,null),e))}const $a=/iPad|iPhone|iPod/.test(navigator.userAgent),Fp=/Android/.test(navigator.userAgent),dn=e=>$a||Fp;let Yt=null,pr=null;const Up=(e,t=5e3)=>{Yt&&(clearInterval(Yt),clearTimeout(pr));const n=document.title;Yt=setInterval(()=>{document.title=document.title===e?n:e},750),pr=setTimeout(()=>{clearInterval(Yt),Yt=null,pr=null,document.title=n},t)},Fa=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Ua="0 16px 24px 2px rgba(33, 33, 33, 0.12), 0 6px 30px 5px rgba(33, 33, 33, 0.08), 0 6px 10px -5px rgba(33, 33, 33, 0.04)",ke=F.css`&:focus-visible{outline:2px solid ${b.themedColor.primary};outline-offset:2px;}`,Ro=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},mn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??Ro(t)??Ro(n),g=u?void 0:t?d:n?m:void 0,f=t&&n?m:void 0,p=()=>{c(),Re(()=>o==null?void 0:o())},C=()=>{c(),Re(()=>i==null?void 0:i())};return a.createElement(St,{portalContainerId:Ae.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":g,"aria-describedby":f},a.createElement(Bp,null,a.createElement(Hp,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:b.themedColor.textHighEmphasis},t)),n&&a.createElement(Gp,{id:m},a.createElement(B,{variant:"body3",color:b.themedColor.textMidEmphasis},n))),a.createElement(zp,null,s&&a.createElement(ko,{onClick:C},a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},s)),a.createElement(ko,{onClick:p},a.createElement(B,{variant:"button",color:b.themedColor.primary},r)))))},Bp=v.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Hp=v.default.div`margin-bottom:16px;`,Gp=v.default.div`margin-top:16px;`,zp=v.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ko=v.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${ke}`,{Provider:Vp,useContext:De}=ye("MessengerSession"),Kp=l.forwardRef(function({children:e,...t},n){return a.createElement(oh,{ref:n,...t},r=>a.createElement(qp,{...r},e))}),qp=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=me(),{userSessionInfo:h,authenticate:g,userSession:f,aiAgentInfo:p,launcherInfo:C}=t,[_,E]=l.useState(!1),A=l.useRef(null);mt(n,{async onUserJoined(T,I){var L,R,M,$;T.conversation&&T.conversation.type===Ce.ConversationType.PROACTIVE&&I.userId===((L=n.currentUser)==null?void 0:L.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(M=m.session)==null||M._updateActiveChannel({url:T.url,status:"open",conversationStatus:(R=T.conversation)==null?void 0:R.status}),c.setOpened(!0),Wp({sound:document.hidden||!c.opened}),($=A.current)==null||$.call(A,{channel:T}))}}),l.useEffect(()=>{g().then(({launcher:T})=>{T.auto_open&&!dn()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var I;r.error("messengerSession: failed to initialize",T),(I=u==null?void 0:u.onInitializeFailed)==null||I.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>E(!0);return d.subscribe(ze.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(ze.AnonymousSessionTokenExpired,T)},[d]);const y=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!f||!p||!C?null:a.createElement(Vp,{value:{...t,userSession:f,aiAgentInfo:{...p,...i==null?void 0:i.bot},launcherInfo:{...C,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>A.current=T}},e,a.createElement(mn,{visible:_,title:"Session timed out",description:"Start a new conversation.",onConfirm:y,onClose:Ee}))};function Wp({sound:e}){Up("🔔You have received a new message"),e&&Fa()}const Bn=`@${Fe}-focused-channel`,Ba=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Yp=()=>{try{const e=localStorage.getItem(Bn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},wo=e=>{try{localStorage.setItem(Bn,JSON.stringify({channelUrl:e,tabId:Ba}))}catch{}},Lo=()=>{try{const e=localStorage.getItem(Bn);if(!e)return;JSON.parse(e).tabId===Ba&&localStorage.removeItem(Bn)}catch{}},jp=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>wo(e),r=()=>Lo();return document.hasFocus()&&wo(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),Lo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Yp()===e}),Xp=e=>{const{config:t,chatSDK:n}=me(),{sdkUser:r}=De(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=jp(e,s);mt(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Xe(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&Fa()}})},Br=new WeakMap;function Zp(e,t){Ve(e.type)&&!Br.has(e)&&Br.set(e,Ha(t))}async function Jp(e){const t=URL.createObjectURL(e),n=await Ha(t);return URL.revokeObjectURL(t),n}function Ha(e){return new Promise(t=>{const n=new Image;n.onload=function(){t({width:String(n.width),height:String(n.height)})},n.onerror=function(){t(void 0)},n.src=e})}async function Qp(e){if("file"in e&&e.file instanceof File&&Ve(e.file.type)){const t=await(Br.get(e.file)??Jp(e.file));return t?new we.MessageMetaArray({key:bi,value:[t.width,t.height]}):void 0}}const eE=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=me(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await Qp(s),i={...s,metaArrays:o?[o]:void 0},c=tE(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===we.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===we.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},tE=e=>{if(!e)return null;const t={};return e.ai&&Object.keys(e.ai).length>0&&(t.ai_attrs=e.ai),e.safeguard&&Object.keys(e.safeguard).length>0&&(t.safeguard_attrs=e.safeguard),typeof e.use_prompt_cache=="boolean"&&(t.use_prompt_cache=e.use_prompt_cache),Object.keys(t).length>0?t:null},Nt=50,Er=Nt-40,{Provider:nE,useContext:Ga}=ye("ConversationScroll"),Oo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},_r=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),No=e=>Array.from(e.querySelectorAll(`#${Fe}-message-item`));function rE({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(Oo),[u,d]=l.useState(0),[m,h]=l.useState(0),[g,f]=l.useState(!1),[p,C]=l.useState(!1),[_,E]=l.useState(!0),A=x=>{const w=_r(x);return o.current.distanceFromBottom=w,h(w),w},y=()=>{const x=i.current;x.reconcileTimer&&(clearTimeout(x.reconcileTimer),x.reconcileTimer=null)},T=l.useCallback(()=>{const x=s.current;x.mutation&&(x.mutation.disconnect(),x.mutation=null),x.resize&&(x.resize.disconnect(),x.resize=null),x.resizeTargets.clear()},[]),I=l.useMemo(()=>g||t==="bottom"?"auto":e,[g,t,e]),k=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},L=()=>{const x=r.current;!x||!c.current.shouldUpdate||d(w=>{c.current.shouldUpdate=!1;const{contentHeight:D,contentSnapshotHeight:U,shouldRecalc:J}=c.current,oe=x.clientHeight;if(U>D)return w;const ee=R(x,{messageType:"outgoing"});let Se=0;if(ee){const K=ee.message.offsetTop-Er+oe;Se=Math.max(0,K-D)}else{const K=D-U,he=oe-Er;Se=Math.max(0,K-he)}return w===0||Se!==w||J?(c.current.shouldRecalc=!1,Se):w})},R=l.useCallback((x,w)=>{const{messageType:D="all"}=w??{},U=No(x);let J=U;D==="outgoing"&&(J=U.filter(ge=>ge.getAttribute("data-layout-id")==="outgoingmessage"));const oe=J[J.length-1];if(!oe)return null;const ee=x.getBoundingClientRect(),Se=oe.getBoundingClientRect(),K=x.scrollTop+(Se.top-ee.top),he=K+oe.offsetHeight;return{message:oe,scrollTop:K,lastMessageBottom:he}},[]),M=l.useCallback(()=>{const x=r.current;if(!x||I!=="fixed")return;const w=R(x);c.current.contentHeight=(w==null?void 0:w.lastMessageBottom)??x.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&k(),i.current.programmatic?o.current.distanceFromBottom=_r(x):A(x),L()},[I,R]),$=l.useCallback(()=>{T(),y(),c.current=Oo,d(0),h(0),E(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),N=l.useCallback((x=!0)=>{const w=o.current.distanceFromBottom>Nt;if(i.current.awayByUser=!1,h(0),!w){Re(()=>{const D=r.current;D&&!i.current.awayByUser&&D.scrollTo({top:D.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,E(!1),y()),Re(()=>{const D=r.current;if(!D){i.current.programmatic=!1,E(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,A(D),E(!0);return}const U=()=>{if(r.current!==D){i.current.programmatic=!1,r.current&&A(r.current),E(!0);return}i.current.programmatic=!1,A(D),E(!0)};if(x&&!i.current.reconcileTimer){const J=setTimeout(U,500);i.current.reconcileTimer=J,D.addEventListener("scrollend",()=>{clearTimeout(J),i.current.reconcileTimer=null,U()},{once:!0})}D.scrollTo({top:D.scrollHeight,behavior:x?"smooth":"auto"}),x||U()})},[]),Q=l.useCallback(()=>{const x=r.current;if(x){if(i.current.awayByUser){A(x);return}N(!1)}},[N]),se=l.useCallback(()=>{const x=r.current,w=s.current;if(!x||!w.resize)return;const D=new Set(No(x));for(const U of w.resizeTargets)D.has(U)||(w.resize.unobserve(U),w.resizeTargets.delete(U));for(const U of D)w.resizeTargets.has(U)||(w.resize.observe(U),w.resizeTargets.add(U))},[]),Y=l.useCallback(x=>{T();const w=s.current;typeof ResizeObserver<"u"&&(w.resize=new ResizeObserver(Q),se());const D=new MutationObserver(()=>{se(),Q()});w.mutation=D,D.observe(x,{childList:!0})},[T,Q,se]),j=l.useCallback(x=>{if(!x){r.current=null,T();return}if(r.current=x,I!=="fixed"){Y(x);return}$(),c.current.viewport=x.clientHeight;const w=new MutationObserver(()=>{M()});s.current.mutation=w,w.observe(x,{childList:!0,subtree:!0})},[T,I,M,$,Y]),P=l.useCallback(()=>{const x=r.current;if(!x)return;const w=R(x,{messageType:"outgoing"});w&&(x.scrollTo({top:w.message.offsetTop-Er,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{C(!1)},500))},[R]),q=(x,w,D)=>{const U=_r(x);if(D&&U>Nt){i.current.programmatic=!1,i.current.awayByUser=!0,y(),A(x),E(!0),o.current.prevScrollTop=w;return}o.current.distanceFromBottom=U},W=(x,w,D)=>{const J=A(x)<=Nt;w&&!J&&(i.current.awayByUser=!0,y()),D&&J&&(i.current.awayByUser=!1)},G=l.useCallback(x=>{const{scrollTop:w}=x.currentTarget,D=o.current.prevScrollTop;i.current.programmatic?q(x.currentTarget,w,w<D):W(x.currentTarget,w<D,w>D),o.current.prevScrollTop=w},[]),H=l.useCallback(()=>{I==="fixed"&&(C(!0),k())},[I]),V=l.useCallback(()=>{I==="fixed"?setTimeout(()=>P(),300):N()},[I,P]),z=l.useCallback(x=>{i.current.streaming=x,I==="fixed"?k():i.current.awayByUser||N()},[I,N]),Z=l.useCallback(x=>{f(x),x&&(d(0),I==="fixed"&&T())},[T,I]),ae=l.useCallback(x=>{I==="auto"&&x&&!i.current.awayByUser&&N()},[I,N]),be=!(m<=Nt)&&!p,xe=l.useCallback(()=>o.current.distanceFromBottom>Nt,[]),Oe=l.useMemo(()=>({ref:j,state:{bottomSpace:u,isAwayFromBottom:be,isScrollPositionReconciled:_,shouldCountNewMessages:xe},props:{onScroll:G},actions:{scrollToBottom:N,onBeforeMessageSend:H,onAfterMessageSend:V,onStreamingUpdate:z,onConversationClosed:Z,onTypingIndicatorUpdate:ae}}),[j,u,be,_,xe,G,N,H,V,z,Z,ae]);return a.createElement(nE,{value:Oe},n)}const{Provider:sE,Context:oE,useContext:Me}=ye("Conversation"),iE=({children:e})=>{var s;const{channelSource:t}=Me(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=ng(n);return tg(n),l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},aE=({context:e,scrollSource:t,goToActiveConversation:n,onNavigateToConversationList:r,children:s})=>{const o=l.useMemo(()=>({...e,scrollSource:t,goToActiveConversation:n,onNavigateToConversationList:r}),[e,t,n,r]);return a.createElement(sE,{value:o},s)},cE=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,children:c})=>{const{activeChannel:u,refreshActiveChannel:d}=De(),m=Ga(),h=e||(u==null?void 0:u.url);Xp(h);const{onBeforeSendMessage:g,onAfterSendMessage:f}=eE({onScrollAfterSendMessage:()=>{m.actions.onAfterMessageSend()}}),p=l.useCallback(A=>(m.actions.onBeforeMessageSend(),g(A)),[m.actions,g]),C=l.useCallback(A=>{const y=A.some(T=>Ie.isStreaming(T));m.actions.onStreamingUpdate(y)},[m.actions.onStreamingUpdate]),_=l.useCallback(A=>{m.actions.onConversationClosed(A===Ce.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),E=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(Dh,{key:h,channelUrl:h,onBeforeSendMessage:p,onAfterSendMessage:f,onMessagesUpdated:C,onMessagesReceived:C,onChannelDeleted:E,onConversationStatusChanged:_,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,shouldCountNewMessages:m.state.shouldCountNewMessages},A=>a.createElement(aE,{context:A,scrollSource:m,goToActiveConversation:E,onNavigateToConversationList:n},a.createElement(iE,null,c)))},za=({children:e,...t})=>{const{config:n}=Te(),{agentPreviewConfigs:r}=me(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(rE,{scrollMode:s,messageStackDirection:o},a.createElement(cE,{...t},e))},bs=l.createContext({onDrop:Ee,subscribe:()=>Ee}),Hr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(bs.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},lE=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(bs);l.useEffect(()=>t(e),[e])};Hr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(bs);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const Va=ye("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>Ee,registerWindowTitlePending:()=>Ee}),uE=Va.Provider,Ka=Va.useContext,Do=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},ys=({children:e})=>{const[t,n]=Do(),[r,s]=Do(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(uE,{value:i},e)},Zn=Ka,qa=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=Ka(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?Ae.WINDOW_TITLE:void 0}},dE=(e,t)=>{const r=(t?rn(e,t):null)??hp(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},Wa=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=Ss(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,dE(e.current,s))};if(r)return Re(d),()=>{u=!0};const m=setTimeout(()=>Re(d),Ca);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},mE=(e,t)=>{const{announcementsEnabled:n}=gt(),{channelSource:r}=Me(),{isWindowNameReady:s}=Zn(),o=Ia(),i=r.channel!=null||r.error!=null;Wa(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?pf:void 0,suppressed:o})},hE=()=>{var s;const{_statsEnabled:e,channelSource:t}=Me(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(Pr()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Tg({channelUrl:n,enabled:e,isInitiallyBackgrounded:Pr,isForegrounded:Sf,subscribeToForegroundState:r})},gE=e=>Ve(e)||on(e);function fE(e,t){return e.filter(n=>Ie.isWelcomeMessage(n,t))}const Ya=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!Ie.isWelcomeMessage(r,n):!0),pE=[],ja=()=>{var f,p,C,_;const{agentPreviewConfigs:e={},aiAgentId:t}=me(),{aiAgentInfo:n,userSession:r}=De(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Me(),u=e.welcomeMessages??pE,d=l.useMemo(()=>Ya(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=dt(s.channel),g=((p=(f=Li(s.channel,r.userId))==null?void 0:f.nickname)==null?void 0:p.trim())||((C=n==null?void 0:n.nickname)==null?void 0:C.trim())||void 0;return{initialized:o.initialized,channelUrl:(_=s.channel)==null?void 0:_.url,agentName:g,isClosed:$e(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},EE=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=gt(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(g=>Le.isAdmin(g)&&Le.isCSAT(g)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},_E=()=>{const e=ja();EE(e)},Xa=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),Po=(e,t,n=pt.format)=>{const r=ua(e,Xa(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},CE={senderName:!0,body:!0,time:!0},SE=Object.keys(CE),vE=(e,t)=>SE.every(n=>e[n]===t[n]),$o=2e3,Fo=400,Gr=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},Za=e=>{if(!Le.isAdmin(e)||!Le.isCSAT(e))return null;const t=of(e);return t?`csat:${t}`:null},bE=e=>{const t=new Set;for(const n of e){const r=Za(n);r&&t.add(r)}return t},yE=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Gr(r).some(s=>t.includes(s)))return r}},Cr=(e,t)=>e.some(n=>t.includes(n)),Uo=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,Sr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),AE=()=>{const{announceStatus:e,announcementsEnabled:t}=gt(),{stringSet:n,format:r}=le(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:g,currentUserId:f}=ja(),{outgoingMessageStates:p,outgoingMessageStatusSignature:C}=l.useMemo(()=>{if(!f)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const G=o.flatMap(H=>{const V=rf(H,f);return!V||!("sendingStatus"in H)?[]:[{key:V,sendingStatus:H.sendingStatus}]});return{outgoingMessageStates:G,outgoingMessageStatusSignature:G.map(({key:H,sendingStatus:V})=>`${H}:${V}`).join(",")}},[f,o]),_=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:Sr(p)}),E=l.useRef({messages:o,currentUserId:f,inputDisabledBy:h,isStreamAnimating:g,stringSet:n,format:r}),A=l.useRef([]),y=l.useRef(null),T=l.useRef([]),I=l.useRef(new Set),k=l.useRef(new Set),L=l.useRef(!1),R=l.useRef(s);E.current={messages:o,currentUserId:f,inputDisabledBy:h,isStreamAnimating:g,stringSet:n,format:r};const M=()=>E.current.isStreamAnimating||E.current.inputDisabledBy==="ai_responding",$=()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},N=(G,H,V)=>{const z=V==null?void 0:V.replaceableForMs;if(G.length===0||!z)return;const Z=Date.now();T.current=[...T.current.filter(({replaceableUntil:ae})=>ae>Z),{eventKeys:G,parts:H,replaceableUntil:Z+z}]},Q=()=>A.current.length>0,se=()=>{A.current=[]},Y=()=>{const[G,...H]=A.current;if(!G)return!1;A.current=H;const{eventKeys:V,parts:z,dedupeKey:Z}=G,ae=xe=>{N(V,xe,{replaceableForMs:V.length>0?$o:void 0}),e({event:"newMessage",...xe},Z?{dedupeKey:Z}:void 0)};if(V.length===0)return ae(z),!0;const O=E.current,be=yE(O.messages,V);if(be){const xe=Po(be,O.stringSet,O.format);return ae(xe),!0}return ae(z),!0},j=()=>{for($();Y(););},P=(G=$o)=>{$(),y.current=setTimeout(()=>{if(y.current=null,M())return;const H=Uo(),[V]=A.current;if(!V)return;if(V.focusTarget!==H){A.current=[{...V,focusTarget:H},...A.current.slice(1)],P(Fo);return}Y()&&Q()&&P(Fo)},G)},q=(G,H,V)=>{const z={eventKeys:H,parts:G,focusTarget:Uo(),dedupeKey:V?V.dedupeKey??void 0:H[0]},Z=H.length===0?-1:A.current.findIndex(({eventKeys:ae})=>Cr(ae,H));Z>=0?A.current=A.current.map((ae,O)=>O===Z?{...z,dedupeKey:V?z.dedupeKey:ae.dedupeKey}:ae):A.current=[...A.current,z],P()},W=(G,H,V)=>{if(G!=="messagesUpdated"||H.length===0)return!1;const z=Date.now(),Z=T.current.find(ae=>ae.replaceableUntil>z&&Cr(ae.eventKeys,H));return Z?!vE(V,Z.parts):!1};l.useEffect(()=>{const G=R.current!==s;(!t||!d||G)&&(L.current=!1,k.current.clear(),se(),T.current=[],I.current.clear(),$(),G&&(R.current=s),!t||!d)||L.current||(L.current=!0,R.current=s,_.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:Sr(p)},I.current=new Set(o.flatMap(H=>{if(!Ie.isStreaming(H))return[];const V="sender"in H?H.sender:void 0;return(V==null?void 0:V.userId)===E.current.currentUserId?[]:Gr(H)})),k.current=bE(o))},[e,t,s,d,m,i,c,C]),l.useEffect(()=>{const G=(H,V)=>{const z=E.current,Z=Gr(H),ae=Za(H);if(ae!=null){if(k.current.has(ae))return;k.current.add(ae),e({event:"csatDisplayed"});return}if(Ie.isStreaming(H)){Z.forEach(U=>{I.current.add(U)});return}const O=Z.filter(U=>I.current.has(U)),be=V==="messagesUpdated"&&O.length>0;be&&O.forEach(U=>{I.current.delete(U)});const xe=V==="messagesUpdated"&&A.current.some(({eventKeys:U})=>Cr(U,Z)),Oe=Po(H,z.stringSet,z.format),x=W(V,Z,Oe);if(!be&&V!=="messagesAdded"&&!xe&&!x)return;const w=x?{dedupeKey:null}:void 0;if(be||M()||xe){q(Oe,[...new Set([...O,...Z])],w);return}if(x){q(Oe,Z,w);return}Q()&&j();const D=Z[0];e({event:"newMessage",...Oe},D?{dedupeKey:D}:void 0)};return qn.subscribe(H=>{if(!L.current||H.channelUrl!==s||H.kind==="initialized"||H.kind==="messagesDeleted"||!af(H.source))return;const V=E.current.currentUserId;for(const z of H.messages)z&&sf(z,V)&&G(z,H.kind)})},[e,s]),l.useEffect(()=>{L.current&&(M()||Q()&&P())},[h,g]),l.useEffect(()=>()=>{$()},[]),l.useEffect(()=>{if(!L.current)return;const G=_.current,H=G.outgoingMessageStatuses;G.outgoingMessageStatuses=Sr(p),p.some(({key:z,sendingStatus:Z})=>{const ae=H.get(z);return ae!==void 0&&ae!=="failed"&&Z==="failed"})&&e({event:"sendFailed"})},[e,C]),l.useEffect(()=>{if(!L.current)return;const G=_.current;i&&!G.isClosed&&e({event:"conversationClosed"}),G.isClosed=i},[e,i]),l.useEffect(()=>{if(!L.current)return;const G=_.current;c&&!G.isHandedOff&&e({event:"agentConnected",agentName:u}),G.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!L.current)return;const G=_.current;m&&h!=="ai_responding"&&(!G.inputDisabled||G.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),G.inputDisabled=m,G.inputDisabledBy=h},[e,m,h])},TE=()=>{const{channelSource:e}=Me(),t=ta(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},IE=e=>{const{announceStatus:t,announcementsEnabled:n}=gt();ag(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},xE=()=>{const e=TE();IE(e)},te=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=Jf(),o=s[e];return a.createElement(ME,{className:n,"data-testid":`sb-icon-${e}`},a.createElement(o,{size:t,color:r??b.color.primary.main,flipInRtl:Kf.has(e)}))},ME=v.default.span.attrs({"aria-hidden":"true"})`
91
91
  display: inline-flex;
92
92
  &:focus {
93
93
  outline: none;
94
94
  }
95
- `,bE=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(St,{portalContainerId:Ae.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(IE,null,n)),yE=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(AE,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(TE,null,a.createElement(te,{type:n,size:24,color:b.themedColor.primary})),s),pt=Object.assign(bE,{ActionItem:yE}),AE=S.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?b.themedColor.error:b.themedColor.textHighEmphasis};${ke}`,TE=S.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,IE=S.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Bo=40,Ho=.9,xE="[data-message-listitem]",ME='input, textarea, select, [role="textbox"], [contenteditable="true"]',RE=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Ho;case"PageUp":return t.clientHeight*-Ho;case"ArrowDown":return n?Bo:void 0;case"ArrowUp":return n?Bo*-1:void 0;default:return}},kE=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(ME))return;const o=s===r||s.matches(xE),i=RE({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),wE="[data-message-listitem]",LE=e=>Math.min(Math.max(0,e),1),OE=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(wE),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},NE=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},DE=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),g=l.useRef(null),f=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const E=t.current;E&&(u.current==="top"&&(E.scrollTop=E.scrollHeight-m.current,NE({list:E,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(E.scrollTop=d.current),u.current=void 0)},[t,r]);const p=l.useCallback(async E=>{const A=t.current;if(!A||(i==null||i(E),m.current=A.scrollHeight-A.scrollTop,d.current=A.scrollTop,c.current))return;const y=A.clientHeight*LE(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=OE(A),await o(),c.current=!1;return}if(A.scrollHeight-A.scrollTop-A.clientHeight<=y){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),v=l.useCallback(E=>{const A=t.current;if(!A)return;const y=f.current;if(y!=null){if(y===A.scrollTop){f.current=null;return}f.current=null}const T=g.current;if(T!=null&&T===A.scrollTop){g.current=null,f.current=A.scrollTop,p(E);return}g.current=null,p(E)},[p,t]),_=l.useCallback(E=>{const A=t.current;A&&(g.current=E,f.current=null,A.scrollTop=E,A.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{g.current=null,f.current=null},[]),{handleScroll:v,syncScrollPosition:_}},PE=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:g,overlayArea:f,onLoadPrev:p,onLoadNext:v,loadThreshold:_=.05,onScroll:E=Ee,depsForResetScrollPositionToBottom:A,stackDirection:y="top",bottomSpacerHeight:T=0,"aria-label":I}=t,k=l.useRef(null),L=l.useCallback(N=>{k.current=N,n&&(typeof n=="function"?n(N):n.current=N)},[n]),{handleScroll:R,syncScrollPosition:M}=DE({depsForResetScrollPositionToBottom:A,listRef:k,loadThreshold:_,messagesLength:r.length,onLoadNext:v,onLoadPrev:p,onScroll:E}),$=kE({listRef:k,syncScrollPosition:M});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement($E,{id:"infinite-list-container"},a.createElement(FE,{id:"infinite-list-inner",ref:L,onScroll:R,onKeyDown:$,role:"list","aria-label":I,tabIndex:0},y==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((N,J)=>s({message:N,index:J})),g,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(UE,{id:"infinite-list-overlay-container"},a.createElement(BE,{id:"infinite-list-overlay"},f)))}),$E=S.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,FE=S.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${b.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,UE=S.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,BE=S.default.div`pointer-events:auto;`,ot=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?b.themedColor.textDisabled:b.themedColor.textHighEmphasis;return a.createElement(HE,{as:e,disabled:s,...i},a.createElement(te,{type:t,size:n,color:r??c}),o)},HE=S.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${ke}&:disabled{cursor:not-allowed;}`,xt=({className:e,children:t,size:n=26})=>a.createElement(GE,{className:e,$size:n},t??a.createElement(te,{type:"spinner",size:n})),GE=S.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>nt(e)};height:${({$size:e})=>nt(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,zE=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=le(),{config:m}=me(),h=e.length,g=e[s],f=m.conversation.fileViewer.downloadEnabled,p=h>1,v=(g==null?void 0:g.type)||"",_=Ve(v),E=on(v),A=!aE(v);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const y=l.useCallback(()=>{s>0&&(o(I=>I-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(I=>I+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const I=k=>{k.key==="ArrowLeft"?y():k.key==="ArrowRight"&&T()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[r,y,T]),!r||!g?null:a.createElement(St,{onClose:n,visible:r,portalContainerId:Ae.MODAL_ROOT,"aria-label":(g==null?void 0:g.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(VE,null,a.createElement(KE,null,a.createElement(qE,null,a.createElement(WE,null,a.createElement(B,{variant:"button",maxTextLines:1,color:b.color.ondark.textHighEmphasis},g.name||u.IMAGE_VIEWER__DEFAULT_TITLE),g.timestamp&&a.createElement(B,{variant:"caption2",color:b.color.ondark.textHighEmphasis},d(new Date(g.timestamp),"h:mm a")))),a.createElement(YE,{type:"close",size:18,color:b.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(jE,null,p&&a.createElement(Go,{$position:"left",type:"chevron-right",size:22,color:b.color.ondark.textHighEmphasis,onClick:y,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(XE,{onClick:I=>I.currentTarget===I.target&&n()},_&&a.createElement(a.Fragment,null,!i&&a.createElement(ZE,null,a.createElement(xt,{size:32},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(JE,{src:g.url,alt:g.name||"Image",$loaded:i,onLoad:()=>c(!0)})),E&&a.createElement(QE,{controls:!0},a.createElement("source",{src:g.url,type:v})),A&&a.createElement(e_,null,a.createElement(B,{variant:"h1",color:b.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&a.createElement(Go,{$position:"right",type:"chevron-right",size:22,color:b.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(t_,null,p&&a.createElement(B,{variant:"body2",color:b.color.ondark.textHighEmphasis},s+1,"/",h),f&&!A&&a.createElement(n_,{forwardedAs:"a",href:g.url,download:g.name||"file",type:"download",size:24,color:b.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},VE=S.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${b.themedColor.bg_50_600};`,KE=S.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${b.color.overlay.dark};`,qE=S.default.div`flex:1;min-width:0;padding-right:8px;`,WE=S.default.div`display:flex;flex-direction:column;gap:2px;`,YE=S.default(ot)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Jn=S.default.div`display:flex;align-items:center;justify-content:center;`,jE=S.default(Jn)`flex:1;min-height:0;position:relative;`,XE=S.default(Jn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,ZE=S.default(Jn)`position:absolute;inset:0;pointer-events:none;`,JE=S.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,QE=S.default.video`max-width:100%;max-height:100%;object-fit:contain;`,e_=S.default(Jn)`flex-direction:column;gap:16px;`,Go=S.default(ot)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${b.color.overlay.dark};&:disabled{opacity:0.3;}`,t_=S.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${b.color.overlay.dark};`,n_=S.default(ot)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,r_=.75,Xa=6,s_=Xa*2;let Vr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Vr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const o_=e=>Vr?Array.from(Vr.segment(e),t=>t.segment):[...e],i_=e=>{const t=Math.floor(e.length*r_),n=Math.max(0,e.length-Xa);return Math.max(t,n)},zo=(e,t="")=>{if(e.length<s_)return{start:e+t,end:""};const n=o_(e),r=i_(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},a_=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return zo(t);const s=t.slice(0,n),o=t.slice(n);return zo(s,o)},Za=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>a_(e),[e]);return r?a.createElement(c_,null,a.createElement(l_,{...t},n),a.createElement(u_,{...t},r)):a.createElement(B,{...t},n)},c_=S.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,l_=S.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,u_=S.default(B)`flex-shrink:0;white-space:nowrap;`,Ts=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=F.useTheme(),{conversation:u}=ue(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(d_,{...d.props,$clickable:!!o},a.createElement(h_,{$bgColor:s??c.base.primary},a.createElement(te,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(g_,null,a.createElement(Za,{variant:"button",color:b.themedColor.textHighEmphasis},e),a.createElement(B,{color:b.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},d_=S.default.div`border:none;border-radius:12px;gap:8px;width:${re.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${b.themedColor.textDisabled};background-color:${b.themedColor.bg_50_600};${({$clickable:e})=>e&&m_}`,m_=F.css`cursor:pointer;${ke}&:hover{background-color:${b.themedColor.bg_100_500};}`,h_=S.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,g_=S.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function f_({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(p_,null,a.createElement(Ts,{name:e.name,mimeType:e.type,type:Jr(e.name,e.type),onClick:r}),t)}const p_=S.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Ke=`${Fe}-incoming-msg`,Vo=`${Fe}-marked-text`,E_="masked-text";function __({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=ue(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(v_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(b_,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${Ke}-media-body`,...c.props};return a.createElement(C_,null,a.createElement(S_,{...d},u(),c.descriptionNode),r)}return null}const C_=S.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,S_=S.default.div`width:${re.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${ne.light`
95
+ `,RE=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(St,{portalContainerId:Ae.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(OE,null,n)),kE=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(wE,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(LE,null,a.createElement(te,{type:n,size:24,color:b.themedColor.primary})),s),Et=Object.assign(RE,{ActionItem:kE}),wE=v.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?b.themedColor.error:b.themedColor.textHighEmphasis};${ke}`,LE=v.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,OE=v.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Bo=40,Ho=.9,NE="[data-message-listitem]",DE='input, textarea, select, [role="textbox"], [contenteditable="true"]',PE=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Ho;case"PageUp":return t.clientHeight*-Ho;case"ArrowDown":return n?Bo:void 0;case"ArrowUp":return n?Bo*-1:void 0;default:return}},$E=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(DE))return;const o=s===r||s.matches(NE),i=PE({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),FE="[data-message-listitem]",UE=e=>Math.min(Math.max(0,e),1),BE=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(FE),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},HE=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},GE=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),g=l.useRef(null),f=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const E=t.current;E&&(u.current==="top"&&(E.scrollTop=E.scrollHeight-m.current,HE({list:E,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(E.scrollTop=d.current),u.current=void 0)},[t,r]);const p=l.useCallback(async E=>{const A=t.current;if(!A||(i==null||i(E),m.current=A.scrollHeight-A.scrollTop,d.current=A.scrollTop,c.current))return;const y=A.clientHeight*UE(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=BE(A),await o(),c.current=!1;return}if(A.scrollHeight-A.scrollTop-A.clientHeight<=y){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),C=l.useCallback(E=>{const A=t.current;if(!A)return;const y=f.current;if(y!=null){if(y===A.scrollTop){f.current=null;return}f.current=null}const T=g.current;if(T!=null&&T===A.scrollTop){g.current=null,f.current=A.scrollTop,p(E);return}g.current=null,p(E)},[p,t]),_=l.useCallback(E=>{const A=t.current;A&&(g.current=E,f.current=null,A.scrollTop=E,A.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{g.current=null,f.current=null},[]),{handleScroll:C,syncScrollPosition:_}},zE=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:g,overlayArea:f,onLoadPrev:p,onLoadNext:C,loadThreshold:_=.05,onScroll:E=Ee,depsForResetScrollPositionToBottom:A,stackDirection:y="top",bottomSpacerHeight:T=0,"aria-label":I}=t,k=l.useRef(null),L=l.useCallback(N=>{k.current=N,n&&(typeof n=="function"?n(N):n.current=N)},[n]),{handleScroll:R,syncScrollPosition:M}=GE({depsForResetScrollPositionToBottom:A,listRef:k,loadThreshold:_,messagesLength:r.length,onLoadNext:C,onLoadPrev:p,onScroll:E}),$=$E({listRef:k,syncScrollPosition:M});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(VE,{id:"infinite-list-container"},a.createElement(KE,{id:"infinite-list-inner",ref:L,onScroll:R,onKeyDown:$,role:"list","aria-label":I,tabIndex:0},y==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((N,Q)=>s({message:N,index:Q})),g,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(qE,{id:"infinite-list-overlay-container"},a.createElement(WE,{id:"infinite-list-overlay"},f)))}),VE=v.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,KE=v.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${b.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,qE=v.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,WE=v.default.div`pointer-events:auto;`,ot=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?b.themedColor.textDisabled:b.themedColor.textHighEmphasis;return a.createElement(YE,{as:e,disabled:s,...i},a.createElement(te,{type:t,size:n,color:r??c}),o)},YE=v.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${ke}&:disabled{cursor:not-allowed;}`,xt=({className:e,children:t,size:n=26})=>a.createElement(jE,{className:e,$size:n},t??a.createElement(te,{type:"spinner",size:n})),jE=v.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>nt(e)};height:${({$size:e})=>nt(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,XE=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=le(),{config:m}=me(),h=e.length,g=e[s],f=m.conversation.fileViewer.downloadEnabled,p=h>1,C=(g==null?void 0:g.type)||"",_=Ve(C),E=on(C),A=!gE(C);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const y=l.useCallback(()=>{s>0&&(o(I=>I-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(I=>I+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const I=k=>{k.key==="ArrowLeft"?y():k.key==="ArrowRight"&&T()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[r,y,T]),!r||!g?null:a.createElement(St,{onClose:n,visible:r,portalContainerId:Ae.MODAL_ROOT,"aria-label":(g==null?void 0:g.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(ZE,null,a.createElement(JE,null,a.createElement(QE,null,a.createElement(e_,null,a.createElement(B,{variant:"button",maxTextLines:1,color:b.color.ondark.textHighEmphasis},g.name||u.IMAGE_VIEWER__DEFAULT_TITLE),g.timestamp&&a.createElement(B,{variant:"caption2",color:b.color.ondark.textHighEmphasis},d(new Date(g.timestamp),"h:mm a")))),a.createElement(t_,{type:"close",size:18,color:b.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(n_,null,p&&a.createElement(Go,{$position:"left",type:"chevron-right",size:22,color:b.color.ondark.textHighEmphasis,onClick:y,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(r_,{onClick:I=>I.currentTarget===I.target&&n()},_&&a.createElement(a.Fragment,null,!i&&a.createElement(s_,null,a.createElement(xt,{size:32},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(o_,{src:g.url,alt:g.name||"Image",$loaded:i,onLoad:()=>c(!0)})),E&&a.createElement(i_,{controls:!0},a.createElement("source",{src:g.url,type:C})),A&&a.createElement(a_,null,a.createElement(B,{variant:"h1",color:b.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&a.createElement(Go,{$position:"right",type:"chevron-right",size:22,color:b.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(c_,null,p&&a.createElement(B,{variant:"body2",color:b.color.ondark.textHighEmphasis},s+1,"/",h),f&&!A&&a.createElement(l_,{forwardedAs:"a",href:g.url,download:g.name||"file",type:"download",size:24,color:b.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},ZE=v.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${b.themedColor.bg_50_600};`,JE=v.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${b.color.overlay.dark};`,QE=v.default.div`flex:1;min-width:0;padding-right:8px;`,e_=v.default.div`display:flex;flex-direction:column;gap:2px;`,t_=v.default(ot)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Jn=v.default.div`display:flex;align-items:center;justify-content:center;`,n_=v.default(Jn)`flex:1;min-height:0;position:relative;`,r_=v.default(Jn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,s_=v.default(Jn)`position:absolute;inset:0;pointer-events:none;`,o_=v.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,i_=v.default.video`max-width:100%;max-height:100%;object-fit:contain;`,a_=v.default(Jn)`flex-direction:column;gap:16px;`,Go=v.default(ot)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${b.color.overlay.dark};&:disabled{opacity:0.3;}`,c_=v.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${b.color.overlay.dark};`,l_=v.default(ot)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,u_=.75,Ja=6,d_=Ja*2;let zr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(zr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const m_=e=>zr?Array.from(zr.segment(e),t=>t.segment):[...e],h_=e=>{const t=Math.floor(e.length*u_),n=Math.max(0,e.length-Ja);return Math.max(t,n)},zo=(e,t="")=>{if(e.length<d_)return{start:e+t,end:""};const n=m_(e),r=h_(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},g_=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return zo(t);const s=t.slice(0,n),o=t.slice(n);return zo(s,o)},Qa=({children:e,"data-testid":t,...n})=>{const{start:r,end:s}=l.useMemo(()=>g_(e),[e]);return s?a.createElement(f_,{"data-testid":t},a.createElement(p_,{...n},r),a.createElement(E_,{...n},s)):a.createElement(B,{"data-testid":t,...n},r)},f_=v.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,p_=v.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,E_=v.default(B)`flex-shrink:0;white-space:nowrap;`,As=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=F.useTheme(),{conversation:u}=ue(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(__,{...d.props,$clickable:!!o},a.createElement(S_,{$bgColor:s??c.base.primary},a.createElement(te,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(v_,null,a.createElement(Qa,{variant:"button",color:b.themedColor.textHighEmphasis},e),a.createElement(B,{color:b.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},__=v.default.div`border:none;border-radius:12px;gap:8px;width:${re.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${b.themedColor.textDisabled};background-color:${b.themedColor.bg_50_600};${({$clickable:e})=>e&&C_}`,C_=F.css`cursor:pointer;${ke}&:hover{background-color:${b.themedColor.bg_100_500};}`,S_=v.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,v_=v.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function b_({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(y_,null,a.createElement(As,{name:e.name,mimeType:e.type,type:Zr(e.name,e.type),onClick:r}),t)}const y_=v.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,Ke=`${Fe}-incoming-msg`,Vo=`${Fe}-marked-text`,A_="masked-text";function T_({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=ue(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(M_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(R_,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${Ke}-media-body`,...c.props};return a.createElement(I_,null,a.createElement(x_,{...d},u(),c.descriptionNode),r)}return null}const I_=v.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,x_=v.default.div`width:${re.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${ne.light`
96
96
  background-color: ${b.color.background100};
97
97
  `}
98
98
  ${ne.dark`
99
99
  background-color: ${b.color.background400};
100
100
  `}
101
- `,v_=S.default.img`width:100%;height:100%;object-fit:cover;`,b_=S.default.video`width:100%;height:100%;object-fit:cover;`,y_=e=>e.startsWith("blob:"),Ja=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=ue(),s=e.length;if(s===0)return null;const o=hm(s),i=!!n&&!t;return a.createElement(T_,{$width:re.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=gm({index:u,itemCount:s}),m=c.name||"",h=()=>{t||n==null||n(u)},g=c.type??"image/*",f=i?r.file.buttonLikePreview({name:m,mimeType:g,onActivate:h},u):r.file.preview({name:m,mimeType:g});return a.createElement(I_,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...f.props},a.createElement(A_,{src:c.url,alt:c.name||""}),t&&a.createElement(x_,null),f.descriptionNode)}))},A_=({src:e,alt:t})=>{const[n,r]=l.useState(()=>y_(e)),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(M_,null,a.createElement(xt,{size:20},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(R_,null,a.createElement(te,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(k_,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},T_=S.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,I_=S.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${ne.light`
101
+ `,M_=v.default.img`width:100%;height:100%;object-fit:cover;`,R_=v.default.video`width:100%;height:100%;object-fit:cover;`,k_=e=>e.startsWith("blob:"),ec=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=ue(),s=e.length;if(s===0)return null;const o=Em(s),i=!!n&&!t;return a.createElement(L_,{"data-testid":"sb-image-grid",$width:re.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=_m({index:u,itemCount:s}),m=c.name||"",h=()=>{t||n==null||n(u)},g=c.type??"image/*",f=i?r.file.buttonLikePreview({name:m,mimeType:g,onActivate:h},u):r.file.preview({name:m,mimeType:g});return a.createElement(O_,{key:c.url,"data-testid":"sb-image-grid-item",$clickable:i,$itemSpan:d,$isPending:t,...f.props},a.createElement(w_,{src:c.url,alt:c.name||""}),t&&a.createElement(N_,{"data-testid":"sb-image-grid-dim"}),f.descriptionNode)}))},w_=({src:e,alt:t})=>{const[n,r]=l.useState(()=>k_(e)),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(D_,null,a.createElement(xt,{size:20},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(P_,null,a.createElement(te,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement($_,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},L_=v.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,O_=v.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${ne.light`
102
102
  background-color: ${b.color.background100};
103
103
  `}
104
104
  ${ne.dark`
@@ -121,19 +121,19 @@ $2
121
121
  }
122
122
  `}
123
123
  }
124
- `,x_=S.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${b.color.overlay.dark};pointer-events:none;`,Qa=S.default.div`display:flex;align-items:center;justify-content:center;`,M_=S.default(Qa)`position:absolute;inset:0;`,R_=S.default(Qa)`position:absolute;inset:0;${ne.light`
124
+ `,N_=v.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${b.color.overlay.dark};pointer-events:none;`,tc=v.default.div`display:flex;align-items:center;justify-content:center;`,D_=v.default(tc)`position:absolute;inset:0;`,P_=v.default(tc)`position:absolute;inset:0;${ne.light`
125
125
  background-color: ${b.color.background200};
126
126
  `}
127
127
  ${ne.dark`
128
128
  background-color: ${b.color.background500};
129
129
  `}
130
- `,k_=S.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,w_=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=o=>{const i=e[o];i&&(r?r({files:e,index:o}):n&&n({url:i.url,type:i.type||"image/*"}))};return a.createElement(L_,null,a.createElement(Ja,{images:e,onClickImage:s}),t)},L_=S.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,O_=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs"))).MarkdownText})),Ko=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function N_(e){var s,o;const t=e.maxBodyWidth??re.BODY_MAX_WIDTH,n=l.useMemo(()=>El(e.message),[e.message]),r={id:`${Ke}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor};return n.length===0?e.children?a.createElement(qo,{...r},e.children):null:a.createElement(qo,{...r},n.map((i,c)=>i.type==="text"?a.createElement(Wo,{key:c,variant:"body3"},a.createElement(At,{fallback:i.value},a.createElement(O_,{onClickImage:u=>{var m;const d={url:u,type:"image/*"};e.onClickMediaFiles?e.onClickMediaFiles({files:[d],index:0}):(m=e.onClickMedia)==null||m.call(e,d)},onClickLink:e.onClickLink},i.value))):i.type==="code"?Ko?a.createElement(At,{key:c,fallback:a.createElement(Wo,{variant:"body3"},i.value)},a.createElement(Ko,{code:i.value,language:i.language})):a.createElement(D_,{key:c},a.createElement("code",null,i.value)):null),e.children)}const qo=S.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);border-radius:12px;overflow:hidden;padding:12px 0;${({theme:e,$color:t,$bgColor:n})=>F.css`
130
+ `,$_=v.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,F_=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=o=>{const i=e[o];i&&(r?r({files:e,index:o}):n&&n({url:i.url,type:i.type||"image/*"}))};return a.createElement(U_,null,a.createElement(ec,{images:e,onClickImage:s}),t)},U_=v.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${re.GAP_GROUPED}px;`,B_=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs"))).MarkdownText})),Ko=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function H_(e){var s,o;const t=e.maxBodyWidth??re.BODY_MAX_WIDTH,n=l.useMemo(()=>Cl(e.message),[e.message]),r={id:`${Ke}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor};return n.length===0?e.children?a.createElement(qo,{...r},e.children):null:a.createElement(qo,{...r},n.map((i,c)=>i.type==="text"?a.createElement(Wo,{key:c,variant:"body3"},a.createElement(At,{fallback:i.value},a.createElement(B_,{onClickImage:u=>{var m;const d={url:u,type:"image/*"};e.onClickMediaFiles?e.onClickMediaFiles({files:[d],index:0}):(m=e.onClickMedia)==null||m.call(e,d)},onClickLink:e.onClickLink},i.value))):i.type==="code"?Ko?a.createElement(At,{key:c,fallback:a.createElement(Wo,{variant:"body3"},i.value)},a.createElement(Ko,{code:i.value,language:i.language})):a.createElement(G_,{key:c},a.createElement("code",null,i.value)):null),e.children)}const qo=v.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);border-radius:12px;overflow:hidden;padding:12px 0;${({theme:e,$color:t,$bgColor:n})=>F.css`
131
131
  color: ${t||e.colors.messageIncoming.text};
132
132
  background-color: ${n||e.colors.messageIncoming.background};
133
133
  `}
134
134
  transition: max-width 0.3s;
135
135
  overflow-wrap: break-word;
136
- `,Wo=S.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,D_=S.default.pre`margin:0;padding:1em;overflow-x:auto;white-space:pre;font-family:monospace;font-size:13px;line-height:1.5;color:#d4d4d4;background:#1e1e1e;border-radius:4px;`;function ec({id:e,src:t,size:n=56,onClick:r,onImageError:s,onImageLoad:o,style:i,backgroundColor:c,...u}){const[d,m]=l.useState();return a.createElement(P_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:nt(n),$backgroundColor:c,style:i,...u},t&&t!==d?a.createElement($_,{src:t,alt:"",onLoad:()=>o==null?void 0:o(t),onError:()=>{m(t),s==null||s(t)}}):a.createElement(te,{type:"user",size:n}))}const P_=S.default.div`border-radius:50%;display:inline-block;overflow:hidden;position:relative;flex-shrink:0;height:${e=>e.$size};width:${e=>e.$size};background-color:${e=>e.$backgroundColor??b.themedColor.bg_100_500};&:focus{outline:none;}${ke}`,$_=S.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,F_=({sender:e,isBotMessage:t})=>{const n=`${Ke}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(U_,{id:n},a.createElement(te,{type:"delight",size:"100%"})):a.createElement(ec,{id:n,size:re.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},U_=S.default.div`flex-shrink:0;width:${re.AVATAR_SIZE}px;height:${re.AVATAR_SIZE}px;box-sizing:border-box;padding:4px;border-radius:50%;display:flex;justify-content:center;align-items:center;background-color:${({theme:e})=>e.colors.base.primary}!important;ellipse,path{fill:${({theme:e})=>e.colors.base.primaryContrastContent}!important;}}`,B_=({sender:e})=>a.createElement(H_,{id:`${Ke}-sender-name`,variant:"caption1",color:b.themedColor.textMidEmphasis},e.nickname),H_=S.default(B)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,G_=({createdAt:e})=>{const{stringSet:t,format:n}=le();return e?a.createElement(B,{id:`${Ke}-sent-time`,variant:"caption4",color:b.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},tc="(prefers-reduced-motion: reduce)",z_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(tc).matches,nc=()=>{const[e,t]=l.useState(z_);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(tc);t(n.matches);const r=s=>{t(s.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},V_=({thinkingMessage:e,customStyle:t})=>{const n=nc();return e?a.createElement(W_,{$prefersReducedMotion:n},a.createElement(Y_,null,e),!n&&a.createElement(j_,null)):a.createElement(K_,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(q_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},K_=S.default.div`align-items:center;border-radius:16px;display:flex;gap:6px;height:26px;justify-content:center;padding:0 12px;background-color:${({theme:e,$bgColor:t})=>t||e.colors.messageIncoming.background};`,q_=S.default.span`animation:${({$prefersReducedMotion:e})=>e?"none":"blink 1.4s infinite"};animation-fill-mode:both;border-radius:50%;height:8px;width:8px;background:${({theme:e,$color:t})=>t||e.colors.messageIncoming.text};opacity:${({$prefersReducedMotion:e})=>e?.38:void 0};@keyframes blink{0%{opacity:0.12;transform:scale(1);}21.43%{opacity:0.38;transform:scale(1.2);}42.86%{opacity:0.12;transform:scale(1);}100%{opacity:0.12;transform:scale(1);}}&:nth-child(1){animation-delay:0.4s;}&:nth-child(2){animation-delay:0.6s;}&:nth-child(3){animation-delay:0.8s;}`,W_=S.default.div.attrs({id:`${Ke}-typing-indicator`})`
136
+ `,Wo=v.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,G_=v.default.pre`margin:0;padding:1em;overflow-x:auto;white-space:pre;font-family:monospace;font-size:13px;line-height:1.5;color:#d4d4d4;background:#1e1e1e;border-radius:4px;`;function nc({id:e,src:t,size:n=56,onClick:r,onImageError:s,onImageLoad:o,style:i,backgroundColor:c,...u}){const[d,m]=l.useState();return a.createElement(z_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:nt(n),$backgroundColor:c,style:i,...u},t&&t!==d?a.createElement(V_,{"data-testid":"sb-avatar-image",src:t,alt:"",onLoad:()=>o==null?void 0:o(t),onError:()=>{m(t),s==null||s(t)}}):a.createElement(te,{type:"user",size:n}))}const z_=v.default.div`border-radius:50%;display:inline-block;overflow:hidden;position:relative;flex-shrink:0;height:${e=>e.$size};width:${e=>e.$size};background-color:${e=>e.$backgroundColor??b.themedColor.bg_100_500};&:focus{outline:none;}${ke}`,V_=v.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,K_=({sender:e,isBotMessage:t})=>{const n=`${Ke}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(q_,{id:n},a.createElement(te,{type:"delight",size:"100%"})):a.createElement(nc,{id:n,size:re.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},q_=v.default.div`flex-shrink:0;width:${re.AVATAR_SIZE}px;height:${re.AVATAR_SIZE}px;box-sizing:border-box;padding:4px;border-radius:50%;display:flex;justify-content:center;align-items:center;background-color:${({theme:e})=>e.colors.base.primary}!important;ellipse,path{fill:${({theme:e})=>e.colors.base.primaryContrastContent}!important;}}`,W_=({sender:e})=>a.createElement(Y_,{id:`${Ke}-sender-name`,variant:"caption1",color:b.themedColor.textMidEmphasis},e.nickname),Y_=v.default(B)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,j_=({createdAt:e})=>{const{stringSet:t,format:n}=le();return e?a.createElement(B,{id:`${Ke}-sent-time`,variant:"caption4",color:b.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},rc="(prefers-reduced-motion: reduce)",X_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(rc).matches,sc=()=>{const[e,t]=l.useState(X_);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(rc);t(n.matches);const r=s=>{t(s.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},Z_=({thinkingMessage:e,customStyle:t})=>{const n=sc();return e?a.createElement(eC,{$prefersReducedMotion:n},a.createElement(tC,null,e),!n&&a.createElement(nC,null)):a.createElement(J_,{"data-testid":"sb-typing-indicator-dots",$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(Q_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},J_=v.default.div`align-items:center;border-radius:16px;display:flex;gap:6px;height:26px;justify-content:center;padding:0 12px;background-color:${({theme:e,$bgColor:t})=>t||e.colors.messageIncoming.background};`,Q_=v.default.span`animation:${({$prefersReducedMotion:e})=>e?"none":"blink 1.4s infinite"};animation-fill-mode:both;border-radius:50%;height:8px;width:8px;background:${({theme:e,$color:t})=>t||e.colors.messageIncoming.text};opacity:${({$prefersReducedMotion:e})=>e?.38:void 0};@keyframes blink{0%{opacity:0.12;transform:scale(1);}21.43%{opacity:0.38;transform:scale(1.2);}42.86%{opacity:0.12;transform:scale(1);}100%{opacity:0.12;transform:scale(1);}}&:nth-child(1){animation-delay:0.4s;}&:nth-child(2){animation-delay:0.6s;}&:nth-child(3){animation-delay:0.8s;}`,eC=v.default.div.attrs({id:`${Ke}-typing-indicator`})`
137
137
  position: relative;
138
138
  overflow: hidden;
139
139
  animation: ${({$prefersReducedMotion:e})=>e?"none":"fadeIn 0.4s ease-in-out"};
@@ -145,12 +145,12 @@ $2
145
145
  opacity: 1;
146
146
  }
147
147
  }
148
- `,Y_=S.default(B).attrs({variant:"body3"})`
148
+ `,tC=v.default(B).attrs({variant:"body3"})`
149
149
  white-space: pre-wrap;
150
150
  word-break: break-word;
151
151
  color: ${b.themedColor.textHighEmphasis};
152
- `,j_=S.default.div`position:absolute;inset:0;pointer-events:none;background-size:33% 100%;background-repeat:no-repeat;animation:shimmerSweepLtr 1.6s linear infinite;@keyframes shimmerSweepLtr{from{background-position:-33% 0;}to{background-position:133% 0;}}[dir='rtl'] &{animation-name:shimmerSweepRtl;@keyframes shimmerSweepRtl{from{background-position:133% 0;}to{background-position:-33% 0;}}}background-image:${({theme:e})=>{const t=js(e.colors.base.background,.5),n=js(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
153
- `,X_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>bs(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(Z_,{id:`${Ke}-ext-cta-button`,onClick:r},a.createElement(J_,{variant:"button"},n.label))},Z_=S.default.button.attrs({type:"button"})`
152
+ `,nC=v.default.div`position:absolute;inset:0;pointer-events:none;background-size:33% 100%;background-repeat:no-repeat;animation:shimmerSweepLtr 1.6s linear infinite;@keyframes shimmerSweepLtr{from{background-position:-33% 0;}to{background-position:133% 0;}}[dir='rtl'] &{animation-name:shimmerSweepRtl;@keyframes shimmerSweepRtl{from{background-position:133% 0;}to{background-position:-33% 0;}}}background-image:${({theme:e})=>{const t=Ys(e.colors.base.background,.5),n=Ys(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
153
+ `,rC=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>vs(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(sC,{id:`${Ke}-ext-cta-button`,onClick:r},a.createElement(oC,{variant:"button"},n.label))},sC=v.default.button.attrs({type:"button"})`
154
154
  all: unset;
155
155
  display: flex;
156
156
  width: 100%;
@@ -167,7 +167,7 @@ $2
167
167
  `}
168
168
 
169
169
  ${ke}
170
- `,J_=S.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Q_=e=>a.createElement(a.Fragment,null),eC=({extendedMessagePayload:e,onClickCitation:t=n=>bs(n.link)})=>{const{stringSet:n}=le(),{theme:r}=Wn(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(tC,{id:`${Ke}-ext-citation`},a.createElement(nC,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(rC,null,s.map((o,i)=>a.createElement(oC,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(te,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(sC,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},tC=S.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,nC=S.default(B)`opacity:0.5;`,rC=S.default.div`display:flex;flex-direction:column;gap:8px;`,sC=S.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,oC=S.default.button.attrs({type:"button"})`
170
+ `,oC=v.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,iC=e=>a.createElement(a.Fragment,null),aC=({extendedMessagePayload:e,onClickCitation:t=n=>vs(n.link)})=>{const{stringSet:n}=le(),{theme:r}=Wn(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(cC,{id:`${Ke}-ext-citation`},a.createElement(lC,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(uC,null,s.map((o,i)=>a.createElement(mC,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(te,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(dC,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},cC=v.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,lC=v.default(B)`opacity:0.5;`,uC=v.default.div`display:flex;flex-direction:column;gap:8px;`,dC=v.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,mC=v.default.button.attrs({type:"button"})`
171
171
  background: none;
172
172
  border: none;
173
173
  padding: 0;
@@ -182,25 +182,25 @@ $2
182
182
  &:hover {
183
183
  opacity: 0.5;
184
184
  }
185
- `,iC=e=>a.createElement(a.Fragment,null),Kr=e=>`${e}-filled`,aC=e=>e==="good"?Ce.AIAgentMessageFeedbackRating.GOOD:Ce.AIAgentMessageFeedbackRating.BAD,Is=F.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,yn={good:{onlight:b.color.secondary.dark,ondark:b.color.secondary.light},bad:{onlight:b.color.error.dark,ondark:b.color.error.light}},cC={good:b.themedColor.secondary,bad:b.themedColor.error},rc=e=>F.css`color:${yn[e].onlight};border-color:${yn[e].onlight};${ne.dark`
185
+ `,hC=e=>a.createElement(a.Fragment,null),Vr=e=>`${e}-filled`,gC=e=>e==="good"?Ce.AIAgentMessageFeedbackRating.GOOD:Ce.AIAgentMessageFeedbackRating.BAD,Ts=F.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,yn={good:{onlight:b.color.secondary.dark,ondark:b.color.secondary.light},bad:{onlight:b.color.error.dark,ondark:b.color.error.light}},fC={good:b.themedColor.secondary,bad:b.themedColor.error},oc=e=>F.css`color:${yn[e].onlight};border-color:${yn[e].onlight};${ne.dark`
186
186
  color: ${yn[e].ondark};
187
187
  border-color: ${yn[e].ondark};
188
188
  `}
189
- `,lC=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=le(),{conversation:u}=ue(),{rootElement:d}=Ia(),m=Et(d),[h,g]=l.useState(r),[f,p]=l.useState(s),[v,_]=l.useState(!1),E=l.useRef(!1),A=h??r??"good",y=u.feedback;l.useLayoutEffect(()=>{e?(g(r),p(s)):(g(void 0),p(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const L=M=>{const $=M;$.metaKey||$.altKey||$.ctrlKey||(E.current=!0)},R=()=>{E.current=!1,_(!1)};return m.addEventListener("keydown",L),m.addEventListener("pointerdown",R),()=>{m.removeEventListener("keydown",L),m.removeEventListener("pointerdown",R)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:f.trim()||void 0}),t())},I=()=>{t()};if(!e)return null;const k={feedback:y.container()};return a.createElement(St,{portalContainerId:Ae.WINDOW,visible:e,onClose:I,"aria-label":c.FEEDBACK_TITLE},a.createElement(uC,null,a.createElement(dC,null,a.createElement(B,{variant:"h2",color:b.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(mC,null,a.createElement(hC,{...k.feedback.props},["good","bad"].map(L=>{const R=h===L,M=L==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,$=y.button(L,R);return a.createElement(l.Fragment,{key:L},a.createElement(gC,{type:"button",$selected:R,$rating:L,...$.props,onClick:()=>g(L),"data-sb-initial-focus":L===A?"true":void 0},a.createElement(te,{type:R?Kr(L):L,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},M)),$.descriptionNode)}),k.feedback.descriptionNode),i&&a.createElement(fC,null,a.createElement(B,{variant:"caption3",color:b.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(pC,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:f,onChange:L=>p(L.target.value),onFocus:()=>_(E.current),onBlur:()=>_(!1),maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),a.createElement(EC,null,a.createElement(_C,{onClick:I},a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(CC,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},uC=S.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,dC=S.default.div`padding:24px;`,mC=S.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,hC=S.default.div`display:flex;gap:4px;`,gC=S.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${b.themedColor.textDisabled};box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:0;gap:0;transition:background-color 0.2s;color:${b.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&rc(t)}${Is}`,fC=S.default.label`display:flex;flex-direction:column;gap:6px;`,pC=S.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${b.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${b.themedColor.textHighEmphasis};background-color:${b.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${b.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&F.css`
189
+ `,pC=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=le(),{conversation:u}=ue(),{rootElement:d}=Ma(),m=_t(d),[h,g]=l.useState(r),[f,p]=l.useState(s),[C,_]=l.useState(!1),E=l.useRef(!1),A=h??r??"good",y=u.feedback;l.useLayoutEffect(()=>{e?(g(r),p(s)):(g(void 0),p(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const L=M=>{const $=M;$.metaKey||$.altKey||$.ctrlKey||(E.current=!0)},R=()=>{E.current=!1,_(!1)};return m.addEventListener("keydown",L),m.addEventListener("pointerdown",R),()=>{m.removeEventListener("keydown",L),m.removeEventListener("pointerdown",R)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:f.trim()||void 0}),t())},I=()=>{t()};if(!e)return null;const k={feedback:y.container()};return a.createElement(St,{portalContainerId:Ae.WINDOW,visible:e,onClose:I,"aria-label":c.FEEDBACK_TITLE},a.createElement(EC,null,a.createElement(_C,null,a.createElement(B,{variant:"h2",color:b.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(CC,null,a.createElement(SC,{...k.feedback.props},["good","bad"].map(L=>{const R=h===L,M=L==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,$=y.button(L,R);return a.createElement(l.Fragment,{key:L},a.createElement(vC,{type:"button",$selected:R,$rating:L,...$.props,onClick:()=>g(L),"data-sb-initial-focus":L===A?"true":void 0},a.createElement(te,{type:R?Vr(L):L,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},M)),$.descriptionNode)}),k.feedback.descriptionNode),i&&a.createElement(bC,null,a.createElement(B,{variant:"caption3",color:b.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(yC,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:f,onChange:L=>p(L.target.value),onFocus:()=>_(E.current),onBlur:()=>_(!1),maxLength:100,$focusVisible:C,"data-focus-visible":C?"true":"false"}))),a.createElement(AC,null,a.createElement(TC,{onClick:I},a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(IC,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},EC=v.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,_C=v.default.div`padding:24px;`,CC=v.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,SC=v.default.div`display:flex;gap:4px;`,vC=v.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${b.themedColor.textDisabled};box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:0;gap:0;transition:background-color 0.2s;color:${b.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&oc(t)}${Ts}`,bC=v.default.label`display:flex;flex-direction:column;gap:6px;`,yC=v.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${b.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${b.themedColor.textHighEmphasis};background-color:${b.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${b.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&F.css`
190
190
  outline: 2px solid ${b.themedColor.primary};
191
191
  outline-offset: 2px;
192
192
  `}
193
- `,EC=S.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,sc=S.default.button`width:86px;height:40px;border-radius:20px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:opacity 0.2s;`,_C=S.default(sc)`background-color:transparent;${Is}`,CC=S.default(sc)`cursor:${({disabled:e})=>e?"not-allowed":"pointer"};opacity:${({disabled:e})=>e?.4:1};&:hover:not(:disabled){opacity:0.8;}&:active:not(:disabled){opacity:0.6;}background-color:${({theme:e})=>e.colors.base.primary};span{color:${({theme:e})=>e.colors.base.primaryContrastContent};}`,SC=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=le(),{conversation:u}=ue(),[d,m]=l.useState(!1),[h,g]=l.useState(!1),[f,p]=l.useState(void 0),[v,_]=l.useState(""),E=l.useRef(null),A=l.useRef(null),y=l.useRef(null),T=l.useRef(!1),I=u.feedback,k=o==null?void 0:o.feedback,L=(k==null?void 0:k.rating)??"none";if(L!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const M=P=>{P&&Re(()=>{const K=P==="good"?E.current:A.current;K==null||K.focus()})},$=({restoreTrigger:P=!0}={})=>{g(!1),P&&M(y.current)},N=P=>{L==="none"?(p(P),_(""),m(!0)):(y.current=P,g(!0))},J=()=>{i==null||i(null),$()},se=()=>{T.current=!0,$({restoreTrigger:!1}),p(k==null?void 0:k.rating),_((k==null?void 0:k.comment)??""),m(!0)},Y=P=>{T.current=!1,i==null||i(P),m(!1),M(y.current)},j=()=>{m(!1),T.current&&(T.current=!1,g(!0))};return t&&L!=="none"?a.createElement(Yo,{role:"presentation",$horizontal:!0},a.createElement(vC,null,a.createElement(te,{type:Kr(L),size:12,color:cC[L]})),(k==null?void 0:k.comment)&&a.createElement(jo,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):a.createElement(a.Fragment,null,a.createElement(Yo,{role:"presentation"},a.createElement(bC,{role:"presentation"},["good","bad"].map(P=>{const K=L===P,q=I.button(P,K);return a.createElement(l.Fragment,{key:P},a.createElement(yC,{$selected:K,$rating:P,ref:P==="good"?E:A,...q.props,onClick:()=>N(P)},a.createElement(te,{type:K?Kr(P):P,size:14,color:"currentColor"})),q.descriptionNode)})),L!=="none"&&(k==null?void 0:k.comment)&&a.createElement(jo,{variant:"caption2"},k.comment)),a.createElement(pt,{visible:h,onClose:$,...I.optionsBottomSheet().props},a.createElement(pt.ActionItem,{onClick:se,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(pt.ActionItem,{onClick:J,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(lC,{visible:d,onClose:j,isEdit:L!=="none",initialRating:f,initialComment:v,onSubmit:Y,isCommentEnabled:s}))},Yo=S.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${re.BODY_MAX_WIDTH}px;`,vC=S.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,bC=S.default.div`display:flex;gap:2px;`,yC=S.default.button`width:38px;height:20px;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;transition:opacity 0.2s;box-sizing:border-box;color:${b.themedColor.textMidEmphasis};border:1px solid ${b.color.background200};background-color:transparent;${ne.dark`
193
+ `,AC=v.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,ic=v.default.button`width:86px;height:40px;border-radius:20px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:opacity 0.2s;`,TC=v.default(ic)`background-color:transparent;${Ts}`,IC=v.default(ic)`cursor:${({disabled:e})=>e?"not-allowed":"pointer"};opacity:${({disabled:e})=>e?.4:1};&:hover:not(:disabled){opacity:0.8;}&:active:not(:disabled){opacity:0.6;}background-color:${({theme:e})=>e.colors.base.primary};span{color:${({theme:e})=>e.colors.base.primaryContrastContent};}`,xC=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=le(),{conversation:u}=ue(),[d,m]=l.useState(!1),[h,g]=l.useState(!1),[f,p]=l.useState(void 0),[C,_]=l.useState(""),E=l.useRef(null),A=l.useRef(null),y=l.useRef(null),T=l.useRef(!1),I=u.feedback,k=o==null?void 0:o.feedback,L=(k==null?void 0:k.rating)??"none";if(L!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const M=P=>{P&&Re(()=>{const q=P==="good"?E.current:A.current;q==null||q.focus()})},$=({restoreTrigger:P=!0}={})=>{g(!1),P&&M(y.current)},N=P=>{L==="none"?(p(P),_(""),m(!0)):(y.current=P,g(!0))},Q=()=>{i==null||i(null),$()},se=()=>{T.current=!0,$({restoreTrigger:!1}),p(k==null?void 0:k.rating),_((k==null?void 0:k.comment)??""),m(!0)},Y=P=>{T.current=!1,i==null||i(P),m(!1),M(y.current)},j=()=>{m(!1),T.current&&(T.current=!1,g(!0))};return t&&L!=="none"?a.createElement(Yo,{role:"presentation",$horizontal:!0},a.createElement(MC,null,a.createElement(te,{type:Vr(L),size:12,color:fC[L]})),(k==null?void 0:k.comment)&&a.createElement(jo,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):a.createElement(a.Fragment,null,a.createElement(Yo,{role:"presentation"},a.createElement(RC,{role:"presentation"},["good","bad"].map(P=>{const q=L===P,W=I.button(P,q);return a.createElement(l.Fragment,{key:P},a.createElement(kC,{$selected:q,$rating:P,ref:P==="good"?E:A,...W.props,onClick:()=>N(P)},a.createElement(te,{type:q?Vr(P):P,size:14,color:"currentColor"})),W.descriptionNode)})),L!=="none"&&(k==null?void 0:k.comment)&&a.createElement(jo,{variant:"caption2"},k.comment)),a.createElement(Et,{visible:h,onClose:$,...I.optionsBottomSheet().props},a.createElement(Et.ActionItem,{onClick:se,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(Et.ActionItem,{onClick:Q,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(pC,{visible:d,onClose:j,isEdit:L!=="none",initialRating:f,initialComment:C,onSubmit:Y,isCommentEnabled:s}))},Yo=v.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${re.BODY_MAX_WIDTH}px;`,MC=v.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,RC=v.default.div`display:flex;gap:2px;`,kC=v.default.button`width:38px;height:20px;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;transition:opacity 0.2s;box-sizing:border-box;color:${b.themedColor.textMidEmphasis};border:1px solid ${b.color.background200};background-color:transparent;${ne.dark`
194
194
  border: 1px solid ${b.color.background400};
195
195
  `}
196
196
 
197
- ${({$selected:e,$rating:t})=>e&&rc(t)}
197
+ ${({$selected:e,$rating:t})=>e&&oc(t)}
198
198
 
199
- ${Is}
200
- `,jo=S.default(B)`color:${b.themedColor.textMidEmphasis};${ne.dark`
199
+ ${Ts}
200
+ `,jo=v.default(B)`color:${b.themedColor.textMidEmphasis};${ne.dark`
201
201
  color: ${b.themedColor.textHighEmphasis};
202
202
  `}
203
- `,xs=F.css`width:100%;height:36px;border-radius:6px;cursor:pointer;transition:all 0.2s ease;padding:0 12px;border:none;outline:none;display:flex;align-items:center;justify-content:center;${ke}&:disabled{cursor:not-allowed;}`,Xo=S.default.button`${xs};background-color:${b.themedColor.primary};color:${b.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,AC=S.default.button`${xs};color:${b.themedColor.primary};${ne.light`
203
+ `,Is=F.css`width:100%;height:36px;border-radius:6px;cursor:pointer;transition:all 0.2s ease;padding:0 12px;border:none;outline:none;display:flex;align-items:center;justify-content:center;${ke}&:disabled{cursor:not-allowed;}`,Xo=v.default.button`${Is};background-color:${b.themedColor.primary};color:${b.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,wC=v.default.button`${Is};color:${b.themedColor.primary};${ne.light`
204
204
  background-color: ${b.color.background50};
205
205
  `};
206
206
  ${ne.dark`
@@ -210,7 +210,7 @@ $2
210
210
  &:hover:not(:disabled) {
211
211
  opacity: 0.9;
212
212
  }
213
- `,TC=S.default.button`${xs};background-color:transparent;color:${b.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,IC=e=>{switch(e){case"primary":return Xo;case"secondary":return AC;case"clear":return TC;default:return Xo}},xC=S.default.div`animation:1s infinite linear;animation-name:rotate;display:flex;align-items:center;justify-content:center;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,MC=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return b.themedColor.textHighEmphasisInverse;case"secondary":return b.themedColor.primary;case"clear":return b.themedColor.textHighEmphasis;default:return b.themedColor.textHighEmphasisInverse}},u=IC(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(xC,null,a.createElement(te,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},RC=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(B,{variant:"caption4",color:b.themedColor.error,className:t,style:n,id:r,role:s},e),kC=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=le();return a.createElement(B,{id:e,variant:"caption3",color:b.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:b.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},wC=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:i=!1,max:c,...u})=>{const d=h=>{const f=h.target.value.replace(/[^0-9.-]/g,""),p=f.split("."),_=p.length>1?p[0]+"."+p.slice(1).join("").replace(/\./g,""):f;if(h.target.value=_,_===""||_==="-")t==null||t(null);else{const E=Number(_);if(!isNaN(E)){if(c!==void 0&&E>c)return;t==null||t(E)}}},m=e==null?"":String(e);return a.createElement(PC,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},LC=F.css`width:100%;box-sizing:border-box;height:36px;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${ke}&::placeholder{color:${b.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,OC=F.css`color:${b.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
213
+ `,LC=v.default.button`${Is};background-color:transparent;color:${b.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,OC=e=>{switch(e){case"primary":return Xo;case"secondary":return wC;case"clear":return LC;default:return Xo}},NC=v.default.div`animation:1s infinite linear;animation-name:rotate;display:flex;align-items:center;justify-content:center;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,DC=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return b.themedColor.textHighEmphasisInverse;case"secondary":return b.themedColor.primary;case"clear":return b.themedColor.textHighEmphasis;default:return b.themedColor.textHighEmphasisInverse}},u=OC(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(NC,null,a.createElement(te,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},PC=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(B,{variant:"caption4",color:b.themedColor.error,className:t,style:n,id:r,role:s},e),$C=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=le();return a.createElement(B,{id:e,variant:"caption3",color:b.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:b.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},FC=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:i=!1,max:c,...u})=>{const d=h=>{const f=h.target.value.replace(/[^0-9.-]/g,""),p=f.split("."),_=p.length>1?p[0]+"."+p.slice(1).join("").replace(/\./g,""):f;if(h.target.value=_,_===""||_==="-")t==null||t(null);else{const E=Number(_);if(!isNaN(E)){if(c!==void 0&&E>c)return;t==null||t(E)}}},m=e==null?"":String(e);return a.createElement(zC,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},UC=F.css`width:100%;box-sizing:border-box;height:36px;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${ke}&::placeholder{color:${b.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,BC=F.css`color:${b.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
214
214
  background-color: ${b.color.ondark.textMidEmphasis};
215
215
  `}
216
216
  ${ne.dark`
@@ -220,13 +220,13 @@ $2
220
220
  &::placeholder {
221
221
  color: ${b.themedColor.textLowEmphasis};
222
222
  }
223
- `,NC=F.css`border:1px solid ${b.themedColor.error};color:${b.themedColor.textHighEmphasis};${ne.light`
223
+ `,HC=F.css`border:1px solid ${b.themedColor.error};color:${b.themedColor.textHighEmphasis};${ne.light`
224
224
  background-color: ${b.color.background50};
225
225
  `}
226
226
  ${ne.dark`
227
227
  background-color: ${b.color.onlight.textLowEmphasis};
228
228
  `}
229
- `,DC=F.css`border:1px solid ${b.themedColor.textDisabled};color:${b.themedColor.textHighEmphasis};${ne.light`
229
+ `,GC=F.css`border:1px solid ${b.themedColor.textDisabled};color:${b.themedColor.textHighEmphasis};${ne.light`
230
230
  background-color: ${b.color.background50};
231
231
  `}
232
232
  ${ne.dark`
@@ -236,12 +236,12 @@ $2
236
236
  &:focus {
237
237
  border-color: ${b.themedColor.primary};
238
238
  }
239
- `,PC=S.default.input`${LC}${({$error:e,$submitted:t})=>t?OC:e?NC:DC}`,$C=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:i=>{if(s)return;if(t.includes(i)){const u=t.filter(d=>d!==i);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,i];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},oc=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=ue(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=$C(e),m=t.some(h=>u.includes(h.value));return a.createElement(UC,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,g)=>{const f=u.includes(h.value),p=o?`${o}, ${h.label}`:h.label;return a.createElement(qC,{key:h.value,type:"button",$active:f,$submitted:n,$error:r,...(c?i.form.multiSelectOption(p,f,n):i.form.singleSelectOption(p,f,n,g,t.length,m,v=>{const _=t[v];_&&d(_.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:FC(f,n)},h.label))}))},FC=(e,t)=>t?e?b.themedColor.textHighEmphasis:b.themedColor.textDisabled:e?b.themedColor.primary:b.themedColor.textMidEmphasis,UC=S.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,BC=F.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,HC=F.css`cursor:default;background-color:${b.color.ondark.textMidEmphasis};color:${b.themedColor.textHighEmphasis};${ne.dark`
239
+ `,zC=v.default.input`${UC}${({$error:e,$submitted:t})=>t?BC:e?HC:GC}`,VC=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:i=>{if(s)return;if(t.includes(i)){const u=t.filter(d=>d!==i);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,i];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},ac=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=ue(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=VC(e),m=t.some(h=>u.includes(h.value));return a.createElement(qC,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,g)=>{const f=u.includes(h.value),p=o?`${o}, ${h.label}`:h.label;return a.createElement(QC,{key:h.value,type:"button",$active:f,$submitted:n,$error:r,...(c?i.form.multiSelectOption(p,f,n):i.form.singleSelectOption(p,f,n,g,t.length,m,C=>{const _=t[C];_&&d(_.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:KC(f,n)},h.label))}))},KC=(e,t)=>t?e?b.themedColor.textHighEmphasis:b.themedColor.textDisabled:e?b.themedColor.primary:b.themedColor.textMidEmphasis,qC=v.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,WC=F.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,YC=F.css`cursor:default;background-color:${b.color.ondark.textMidEmphasis};color:${b.themedColor.textHighEmphasis};${ne.dark`
240
240
  background-color: transparent;
241
241
  border: 1px solid white;
242
242
  color: white;
243
243
  `}
244
- `,GC=F.css`cursor:default;${ne.light`
244
+ `,jC=F.css`cursor:default;${ne.light`
245
245
  background-color: ${b.color.ondark.textMidEmphasis};
246
246
  color: ${b.themedColor.textDisabled};
247
247
  `}
@@ -250,7 +250,7 @@ $2
250
250
  border: 1px solid ${b.color.onlight.textLowEmphasis};
251
251
  color: ${b.themedColor.textDisabled};
252
252
  `}
253
- `,zC=F.css`cursor:pointer;border:1px solid ${b.themedColor.primary};${ne.light`
253
+ `,XC=F.css`cursor:pointer;border:1px solid ${b.themedColor.primary};${ne.light`
254
254
  background-color: ${b.color.background50};
255
255
  color: ${b.themedColor.primary};
256
256
  `}
@@ -258,7 +258,7 @@ $2
258
258
  background-color: ${b.color.onlight.textLowEmphasis};
259
259
  color: ${b.themedColor.primary};
260
260
  `}
261
- `,VC=F.css`cursor:pointer;border:1px solid ${b.themedColor.textDisabled};${ne.light`
261
+ `,ZC=F.css`cursor:pointer;border:1px solid ${b.themedColor.textDisabled};${ne.light`
262
262
  background-color: ${b.color.background50};
263
263
  color: ${b.themedColor.textMidEmphasis};
264
264
  `}
@@ -266,10 +266,10 @@ $2
266
266
  background-color: ${b.color.onlight.textLowEmphasis};
267
267
  color: ${b.themedColor.textMidEmphasis};
268
268
  `}
269
- `,KC=F.css`border-color:${b.themedColor.error}!important;`,qC=S.default.button`${BC}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?HC:GC;const r=e?zC:VC;return n?F.css`
270
- ${r} ${KC}
269
+ `,JC=F.css`border-color:${b.themedColor.error}!important;`,QC=v.default.button`${WC}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?YC:jC;const r=e?XC:ZC;return n?F.css`
270
+ ${r} ${JC}
271
271
  `:r}}
272
- `,WC=e=>a.createElement(oc,{...e,multiple:!1}),YC=e=>a.createElement(oc,{...e,multiple:!0}),jC=S.default.div`width:100%;height:1px;background-color:${b.themedColor.textDisabled};`,XC=({className:e})=>a.createElement(jC,{className:e}),ZC=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:i=!1,className:c,disabled:u=!1,maxLength:d,...m})=>{const g={id:e,value:t,onChange:f=>{const p=f.target.value;d&&p.length>d||n==null||n(p)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(QC,{...g}):a.createElement(JC,{...g})},ic=F.css`width:100%;box-sizing:border-box;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${ke}&::placeholder{color:${b.themedColor.textLowEmphasis};}`,ac=F.css`color:${b.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
272
+ `,eS=e=>a.createElement(ac,{...e,multiple:!1}),tS=e=>a.createElement(ac,{...e,multiple:!0}),nS=v.default.div`width:100%;height:1px;background-color:${b.themedColor.textDisabled};`,rS=({className:e})=>a.createElement(nS,{className:e}),sS=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:i=!1,className:c,disabled:u=!1,maxLength:d,...m})=>{const g={id:e,value:t,onChange:f=>{const p=f.target.value;d&&p.length>d||n==null||n(p)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(iS,{...g}):a.createElement(oS,{...g})},cc=F.css`width:100%;box-sizing:border-box;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${ke}&::placeholder{color:${b.themedColor.textLowEmphasis};}`,lc=F.css`color:${b.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
273
273
  background-color: ${b.color.ondark.textMidEmphasis};
274
274
  `}
275
275
  ${ne.dark`
@@ -279,13 +279,13 @@ $2
279
279
  &::placeholder {
280
280
  color: ${b.themedColor.textLowEmphasis};
281
281
  }
282
- `,cc=F.css`border:1px solid ${b.themedColor.error};color:${b.themedColor.textHighEmphasis};${ne.light`
282
+ `,uc=F.css`border:1px solid ${b.themedColor.error};color:${b.themedColor.textHighEmphasis};${ne.light`
283
283
  background-color: ${b.color.background50};
284
284
  `}
285
285
  ${ne.dark`
286
286
  background-color: ${b.color.onlight.textLowEmphasis};
287
287
  `}
288
- `,lc=F.css`border:1px solid ${b.themedColor.textDisabled};color:${b.themedColor.textHighEmphasis};${ne.light`
288
+ `,dc=F.css`border:1px solid ${b.themedColor.textDisabled};color:${b.themedColor.textHighEmphasis};${ne.light`
289
289
  background-color: ${b.color.background50};
290
290
  `}
291
291
  ${ne.dark`
@@ -295,14 +295,14 @@ $2
295
295
  &:focus {
296
296
  border-color: ${b.themedColor.primary};
297
297
  }
298
- `,JC=S.default.input`${ic};height:36px;${({$error:e,$submitted:t})=>t?ac:e?cc:lc}`,QC=S.default.textarea`${ic};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?ac:e?cc:lc}`,eS=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis,className:t,style:n},e),Ne={Title:eS,Label:kC,ErrorLabel:RC,Separator:XC,Button:MC,TextInput:ZC,NumberInput:wC,SingleSelect:WC,MultiSelect:YC},tS=1,nS=new Set(["text","number","single-select","multi-select"]),uc=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,rS=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(uc||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},sS=e=>{var E,A;const t=(E=e.extendedMessagePayload)==null?void 0:E.form;if(rS({messageForm:t,onError:(A=e.statsCallbacks)==null?void 0:A.onFormRenderError}),!uc)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=le(),{conversation:r}=ue(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:g}=Yh(t,{labels:{required:n.FORM_VALIDATION_REQUIRED,regex:n.FORM_VALIDATION_REGEX_FAILED,minLength:n.FORM_VALIDATION_MIN_LENGTH,maxLength:n.FORM_VALIDATION_MAX_LENGTH,min:n.FORM_VALIDATION_MIN,max:n.FORM_VALIDATION_MAX,minSelect:n.FORM_VALIDATION_MIN_SELECT,maxSelect:n.FORM_VALIDATION_MAX_SELECT},onSubmit:y=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:y})},onCancel:()=>{var y;return(y=e.onCancelForm)==null?void 0:y.call(e,{key:t.key})}}),f=u==="submitted",p=async()=>{o(y=>({...y,submitting:!0}));try{await m()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,submitting:!1}))}},v=async()=>{o(y=>({...y,canceling:!0}));try{await h()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,canceling:!1}))}},_=l.useMemo(()=>{const y=()=>t.version>tS,T=()=>t.fields.some(I=>!nS.has(I.type));return y()||T()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:_.visible?a.createElement(l.Fragment,null,a.createElement(Zo,{id:`${Ke}-ext-form`,$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(Ne.Title,null,t.title),a.createElement(oS,null,d.map(y=>a.createElement(iS,{key:y.key},a.createElement(Ne.Label,{style:{marginBottom:"6px"},required:y.required},y.label),y.type==="text"&&a.createElement(Ne.TextInput,{value:y.value||"",placeholder:y.placeholder,onChange:T=>g(y.key,T),disabled:f,error:!!y.error,submitted:f,variant:y.layout==="multiline"?"multi-line":"single-line",maxLength:y.maxLength,...r.form.textInput(y.label,y.required??!1,f).props}),y.type==="number"&&a.createElement(Ne.NumberInput,{value:y.value||null,placeholder:y.placeholder,onChange:T=>g(y.key,T),disabled:f,error:!!y.error,submitted:f,max:y.max,...r.form.numberInput(y.label,y.required??!1,f).props}),y.type==="single-select"&&a.createElement(Ne.SingleSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||"",onChange:T=>g(y.key,T),submitted:f,groupLabel:y.label}),y.type==="multi-select"&&a.createElement(Ne.MultiSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||[],onChange:T=>g(y.key,T),submitted:f,maxSelect:y.maxSelect,groupLabel:y.label}),y.error&&a.createElement(Ne.ErrorLabel,{style:{marginTop:"4px"}},y.error)))),a.createElement(Ne.Separator,null),a.createElement(aS,null,a.createElement(Ne.Button,{variant:f?"clear":"primary",...r.form.button(f?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:p,disabled:f||s.canceling,loading:s.submitting},f?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&a.createElement(Ne.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(mn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Zo,{id:`${Ke}-ext-form`,$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},_.reason),_.cancelable&&a.createElement(Ne.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,loading:s.canceling},n.BUTTON__CANCEL))},Zo=S.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;width:100%;box-sizing:border-box;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>F.css`
298
+ `,oS=v.default.input`${cc};height:36px;${({$error:e,$submitted:t})=>t?lc:e?uc:dc}`,iS=v.default.textarea`${cc};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?lc:e?uc:dc}`,aS=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis,className:t,style:n},e),Ne={Title:aS,Label:$C,ErrorLabel:PC,Separator:rS,Button:DC,TextInput:sS,NumberInput:FC,SingleSelect:eS,MultiSelect:tS},cS=1,lS=new Set(["text","number","single-select","multi-select"]),mc=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,uS=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(mc||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},dS=e=>{var E,A;const t=(E=e.extendedMessagePayload)==null?void 0:E.form;if(uS({messageForm:t,onError:(A=e.statsCallbacks)==null?void 0:A.onFormRenderError}),!mc)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=le(),{conversation:r}=ue(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:g}=Qh(t,{labels:{required:n.FORM_VALIDATION_REQUIRED,regex:n.FORM_VALIDATION_REGEX_FAILED,minLength:n.FORM_VALIDATION_MIN_LENGTH,maxLength:n.FORM_VALIDATION_MAX_LENGTH,min:n.FORM_VALIDATION_MIN,max:n.FORM_VALIDATION_MAX,minSelect:n.FORM_VALIDATION_MIN_SELECT,maxSelect:n.FORM_VALIDATION_MAX_SELECT},onSubmit:y=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:y})},onCancel:()=>{var y;return(y=e.onCancelForm)==null?void 0:y.call(e,{key:t.key})}}),f=u==="submitted",p=async()=>{o(y=>({...y,submitting:!0}));try{await m()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,submitting:!1}))}},C=async()=>{o(y=>({...y,canceling:!0}));try{await h()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,canceling:!1}))}},_=l.useMemo(()=>{const y=()=>t.version>cS,T=()=>t.fields.some(I=>!lS.has(I.type));return y()||T()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:_.visible?a.createElement(l.Fragment,null,a.createElement(Zo,{id:`${Ke}-ext-form`,$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(Ne.Title,null,t.title),a.createElement(mS,null,d.map(y=>a.createElement(hS,{key:y.key},a.createElement(Ne.Label,{style:{marginBottom:"6px"},required:y.required},y.label),y.type==="text"&&a.createElement(Ne.TextInput,{value:y.value||"",placeholder:y.placeholder,onChange:T=>g(y.key,T),disabled:f,error:!!y.error,submitted:f,variant:y.layout==="multiline"?"multi-line":"single-line",maxLength:y.maxLength,...r.form.textInput(y.label,y.required??!1,f).props}),y.type==="number"&&a.createElement(Ne.NumberInput,{value:y.value||null,placeholder:y.placeholder,onChange:T=>g(y.key,T),disabled:f,error:!!y.error,submitted:f,max:y.max,...r.form.numberInput(y.label,y.required??!1,f).props}),y.type==="single-select"&&a.createElement(Ne.SingleSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||"",onChange:T=>g(y.key,T),submitted:f,groupLabel:y.label}),y.type==="multi-select"&&a.createElement(Ne.MultiSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||[],onChange:T=>g(y.key,T),submitted:f,maxSelect:y.maxSelect,groupLabel:y.label}),y.error&&a.createElement(Ne.ErrorLabel,{style:{marginTop:"4px"}},y.error)))),a.createElement(Ne.Separator,null),a.createElement(gS,null,a.createElement(Ne.Button,{variant:f?"clear":"primary",...r.form.button(f?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:p,disabled:f||s.canceling,loading:s.submitting},f?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&a.createElement(Ne.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:C,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(mn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Zo,{id:`${Ke}-ext-form`,$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},_.reason),_.cancelable&&a.createElement(Ne.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:C,loading:s.canceling},n.BUTTON__CANCEL))},Zo=v.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;width:100%;box-sizing:border-box;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>F.css`
299
299
  color: ${e.colors.messageIncoming.text};
300
300
  background-color: ${e.colors.messageIncoming.background};
301
301
  `}
302
302
  padding: 16px 12px;
303
303
  transition: max-width 0.3s;
304
304
  overflow-wrap: break-word;
305
- `,oS=S.default.div`display:flex;flex-direction:column;gap:12px;`,iS=S.default.div`display:flex;flex-direction:column;`,aS=S.default.div`display:flex;flex-direction:column;gap:8px;`,cS=e=>a.createElement(a.Fragment,null),qr=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ZOM6SoNd.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,lS=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(qr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},uS=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return lS({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),qr?a.createElement(At,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(qr,{...e})):null},dS=e=>a.createElement(a.Fragment,null),mS=({data:e,extendedMessagePayload:t,onClickSuggestedReply:n,onConfirmTicketClosure:r,suggestedRepliesDirection:s="vertical"})=>{const{conversation:o}=ue(),{stringSet:i}=le(),[c,u]=l.useState(!1),[d,m]=l.useState(!1),h=l.useRef(!1),{suggestedReplies:g}=o,f=im({data:e,extendedMessagePayload:t,ticketClosureLabels:{confirm:i.DESK__TICKET_CLOSURE_CONFIRM,decline:i.DESK__TICKET_CLOSURE_DECLINE}});if(f.length===0||c)return null;const p=v=>{if(v.action==="confirmTicketClosure"){if(h.current||!r)return;h.current=!0,r({ticketId:v.ticketId,confirmed:v.confirmed}).catch(()=>{h.current=!1,m(!0)});return}n&&(n({reply:v.label}),u(!0))};return a.createElement(a.Fragment,null,a.createElement(hS,{id:`${Ke}-ext-suggested-replies`,role:"presentation",$type:s},f.map((v,_)=>{const E=g.item(v.label,_);return a.createElement(l.Fragment,{key:_},a.createElement(gS,{$type:s,...E.props,onClick:()=>p(v)},a.createElement(fS,{variant:"body3"},v.label)),E.descriptionNode)})),a.createElement(mn,{visible:d,title:i.PLACE_HOLDER__WRONG,description:i.DESK__TICKET_CLOSURE_ERROR_MESSAGE,onClose:()=>m(!1)}))},hS=S.default.div`margin:16px 0;padding:0 ${re.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?pS:ES};`,gS=S.default.button.attrs({type:"button"})`
305
+ `,mS=v.default.div`display:flex;flex-direction:column;gap:12px;`,hS=v.default.div`display:flex;flex-direction:column;`,gS=v.default.div`display:flex;flex-direction:column;gap:8px;`,fS=e=>a.createElement(a.Fragment,null),Kr=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ZOM6SoNd.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,pS=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Kr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},ES=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return pS({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),Kr?a.createElement(At,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(Kr,{...e})):null},_S=e=>a.createElement(a.Fragment,null),CS=({data:e,extendedMessagePayload:t,onClickSuggestedReply:n,onConfirmTicketClosure:r,suggestedRepliesDirection:s="vertical"})=>{const{conversation:o}=ue(),{stringSet:i}=le(),[c,u]=l.useState(!1),[d,m]=l.useState(!1),h=l.useRef(!1),{suggestedReplies:g}=o,f=um({data:e,extendedMessagePayload:t,ticketClosureLabels:{confirm:i.DESK__TICKET_CLOSURE_CONFIRM,decline:i.DESK__TICKET_CLOSURE_DECLINE}});if(f.length===0||c)return null;const p=C=>{if(C.action==="confirmTicketClosure"){if(h.current||!r)return;h.current=!0,r({ticketId:C.ticketId,confirmed:C.confirmed}).catch(()=>{h.current=!1,m(!0)});return}n&&(n({reply:C.label}),u(!0))};return a.createElement(a.Fragment,null,a.createElement(SS,{id:`${Ke}-ext-suggested-replies`,role:"presentation",$type:s},f.map((C,_)=>{const E=g.item(C.label,_);return a.createElement(l.Fragment,{key:_},a.createElement(vS,{$type:s,...E.props,onClick:()=>p(C)},a.createElement(bS,{variant:"body3"},C.label)),E.descriptionNode)})),a.createElement(mn,{visible:d,title:i.PLACE_HOLDER__WRONG,description:i.DESK__TICKET_CLOSURE_ERROR_MESSAGE,onClose:()=>m(!1)}))},SS=v.default.div`margin:16px 0;padding:0 ${re.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?yS:AS};`,vS=v.default.button.attrs({type:"button"})`
306
306
  all: unset;
307
307
  box-sizing: border-box;
308
308
  padding: 8px 12px;
@@ -322,60 +322,60 @@ $2
322
322
 
323
323
  ${ke}
324
324
 
325
- ${({$type:e,theme:t})=>F.css`${e==="vertical"?_S:CS};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
326
- `,fS=S.default(B)`color:inherit;`,pS=F.css`flex-direction:column;align-items:flex-end;`,ES=F.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,_S=F.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,CS=F.css`white-space:nowrap;`,SS=e=>{const{components:t}=_t.useContext(),{stringSet:n}=le(),r=xi(e)?a.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const s=e.file;return s.type.startsWith("image")||s.type.startsWith("video")?a.createElement(t.MediaMessageBody,{...e},r):a.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},r):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},vS=Object.freeze({}),bS=e=>{var T,I,k,L,R;const{components:t}=_t.useContext(),{streamText:n,isAnimating:r,isHolding:s}=ug({text:e.message,enabled:e.isStreaming,snapOnDisable:((T=e.extendedMessagePayload)==null?void 0:T.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onAnimationHoldChange:e.onStreamAnimationHoldChange,onVisibleTextProgress:(I=e.statsCallbacks)==null?void 0:I.onVisibleTextProgress,onRenderedTextProgress:(k=e.statsCallbacks)==null?void 0:k.onRenderedTextProgress});if(s)return null;const o={...e,message:n,extendedMessagePayload:r?vS:e.extendedMessagePayload},i=!!o.isTyping,c=!!o.isSenderAvatarVisible,u=sn(o.extendedMessagePayload),d=u.hasCTAButton,m=u.hasChallenge,h=u.hasCitations,g=u.hasForm,f=u.hasMessageTemplate,p=!!o.createdAt,v=d||h,_=o.groupType==="top"||o.groupType==="single",E=o.groupType==="bottom"||o.groupType==="single",A=c?re.AVATAR_SIZE:0,y=v&&a.createElement(l.Fragment,null,d&&a.createElement(AS,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...o})),h&&a.createElement(t.Citation,{...o}));return a.createElement(yS,{$marginBottom:i?0:Vn(o.groupType)},_&&a.createElement(TS,null,c&&a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(t.Prechecks,{...o}),a.createElement(xS,null,a.createElement(br,{$extraStartPadding:A},i?a.createElement(t.TypingIndicator,{...o}):a.createElement(t.MessageBody,{...o},y)),f&&a.createElement(Jo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(br,{$extraStartPadding:A},a.createElement(t.MessageBody,{...o,messageType:"user",message:((R=(L=o.extendedMessagePayload)==null?void 0:L.message_template)==null?void 0:R.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??a.createElement(br,{$extraStartPadding:A},a.createElement(t.TypingIndicator,{...o}))})),a.createElement(t.CustomMessageTemplate,{...o}),m&&a.createElement(t.Challenge,{...o}),g&&a.createElement(Jo,{$extraStartPadding:A},a.createElement(t.Form,{...o}))),a.createElement(t.MessageLogs,{...o}),E&&p&&a.createElement(IS,{$extraStartPadding:A+8},a.createElement(t.SentTime,{...o})),a.createElement(l.Fragment,null,!i&&a.createElement(hn,{$extraStartPadding:A+8},a.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},_t=Qe({template:bS,components:{SenderName:B_,SenderAvatar:F_,SentTime:G_,MessageBody:SS,TextMessageBody:N_,MediaMessageBody:__,FileMessageBody:f_,MultipleFilesMessageBody:w_,TypingIndicator:V_,SuggestedReplies:mS,MessageTemplate:uS,CustomMessageTemplate:iC,Challenge:Q_,CTAButton:X_,Citation:eC,Form:sS,Feedback:SC,MessageLogs:cS,Prechecks:dS}}),yS=S.default.div.attrs({role:"presentation"})`
325
+ ${({$type:e,theme:t})=>F.css`${e==="vertical"?TS:IS};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
326
+ `,bS=v.default(B)`color:inherit;`,yS=F.css`flex-direction:column;align-items:flex-end;`,AS=F.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,TS=F.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,IS=F.css`white-space:nowrap;`,xS=e=>{const{components:t}=Ct.useContext(),{stringSet:n}=le(),r=xi(e)?a.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const s=e.file;return s.type.startsWith("image")||s.type.startsWith("video")?a.createElement(t.MediaMessageBody,{...e},r):a.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},r):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},MS=Object.freeze({}),RS=e=>{var T,I,k,L,R;const{components:t}=Ct.useContext(),{streamText:n,isAnimating:r,isHolding:s}=Eg({text:e.message,enabled:e.isStreaming,snapOnDisable:((T=e.extendedMessagePayload)==null?void 0:T.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onAnimationHoldChange:e.onStreamAnimationHoldChange,onVisibleTextProgress:(I=e.statsCallbacks)==null?void 0:I.onVisibleTextProgress,onRenderedTextProgress:(k=e.statsCallbacks)==null?void 0:k.onRenderedTextProgress});if(s)return null;const o={...e,message:n,extendedMessagePayload:r?MS:e.extendedMessagePayload},i=!!o.isTyping,c=!!o.isSenderAvatarVisible,u=sn(o.extendedMessagePayload),d=u.hasCTAButton,m=u.hasChallenge,h=u.hasCitations,g=u.hasForm,f=u.hasMessageTemplate,p=!!o.createdAt,C=d||h,_=o.groupType==="top"||o.groupType==="single",E=o.groupType==="bottom"||o.groupType==="single",A=c?re.AVATAR_SIZE:0,y=C&&a.createElement(l.Fragment,null,d&&a.createElement(wS,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...o})),h&&a.createElement(t.Citation,{...o}));return a.createElement(kS,{$marginBottom:i?0:Vn(o.groupType)},_&&a.createElement(LS,null,c&&a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(t.Prechecks,{...o}),a.createElement(NS,null,a.createElement(vr,{$extraStartPadding:A},i?a.createElement(t.TypingIndicator,{...o}):a.createElement(t.MessageBody,{...o},y)),f&&a.createElement(Jo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(vr,{$extraStartPadding:A},a.createElement(t.MessageBody,{...o,messageType:"user",message:((R=(L=o.extendedMessagePayload)==null?void 0:L.message_template)==null?void 0:R.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??a.createElement(vr,{$extraStartPadding:A},a.createElement(t.TypingIndicator,{...o}))})),a.createElement(t.CustomMessageTemplate,{...o}),m&&a.createElement(t.Challenge,{...o}),g&&a.createElement(Jo,{$extraStartPadding:A},a.createElement(t.Form,{...o}))),a.createElement(t.MessageLogs,{...o}),E&&p&&a.createElement(OS,{$extraStartPadding:A+8},a.createElement(t.SentTime,{...o})),a.createElement(l.Fragment,null,!i&&a.createElement(hn,{$extraStartPadding:A+8},a.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},Ct=Qe({template:RS,components:{SenderName:W_,SenderAvatar:K_,SentTime:j_,MessageBody:xS,TextMessageBody:H_,MediaMessageBody:T_,FileMessageBody:b_,MultipleFilesMessageBody:F_,TypingIndicator:Z_,SuggestedReplies:CS,MessageTemplate:ES,CustomMessageTemplate:hC,Challenge:iC,CTAButton:rC,Citation:aC,Form:dS,Feedback:xC,MessageLogs:fS,Prechecks:_S}}),kS=v.default.div.attrs({role:"presentation"})`
327
327
  display: flex;
328
328
  flex-direction: column;
329
329
  align-items: flex-start;
330
330
  margin-bottom: ${({$marginBottom:e})=>`${e}px`};
331
- `,hn=S.default.div.attrs({role:"presentation"})`
331
+ `,hn=v.default.div.attrs({role:"presentation"})`
332
332
  display: flex;
333
333
  align-self: stretch;
334
334
  justify-content: flex-start;
335
335
  ${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
336
336
  padding-inline: ${e+n}px ${t}px;
337
337
  `}
338
- `,AS=S.default.div.attrs({role:"presentation"})`
338
+ `,wS=v.default.div.attrs({role:"presentation"})`
339
339
  display: flex;
340
340
  flex-direction: column;
341
341
  min-width: 0;
342
342
  ${({$marginTop:e=0,$paddingInline:t=0})=>F.css`margin-top:${e}px;padding-inline:${t}px;`}
343
- `,TS=S.default(hn)`display:flex;flex-direction:row;align-items:center;gap:8px;`,br=S.default(hn)`display:flex;`,IS=S.default(hn)`margin-top:${re.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Jo=S.default(hn).attrs({role:"presentation"})`
343
+ `,LS=v.default(hn)`display:flex;flex-direction:row;align-items:center;gap:8px;`,vr=v.default(hn)`display:flex;`,OS=v.default(hn)`margin-top:${re.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Jo=v.default(hn).attrs({role:"presentation"})`
344
344
  display: flex;
345
345
  ${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
346
346
  padding-inline: ${e+n}px ${t}px;
347
347
  `}
348
- `,xS=S.default.div.attrs({role:"presentation"})`
348
+ `,NS=v.default.div.attrs({role:"presentation"})`
349
349
  display: flex;
350
350
  flex-direction: column;
351
351
  align-self: stretch;
352
352
  min-width: 0;
353
353
  max-width: 100%;
354
354
  gap: ${re.GAP_GROUPED}px;
355
- `;function MS({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(RS,null,a.createElement(Ts,{name:e.name,mimeType:e.type,type:Jr(e.name,e.type),onClick:s}),t)}const RS=S.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,Hn=new WeakMap;function Ms(e){const t=Hn.get(e);if(t)return t;const n=URL.createObjectURL(e);return Hn.set(e,n),n}function Qo(e){const t=Hn.get(e);t&&(URL.revokeObjectURL(t),Hn.delete(e))}function kS({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=ue(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?Ms(u):void 0),m=d??t.url,[h,g]=l.useState(()=>u instanceof Blob),f=(()=>{if(e==="failed")return;const _=e==="succeeded"?t.url:m;if(s)return()=>s({files:[{url:_,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:_})})(),p=f?i.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:f}):i.file.preview({name:t.name,mimeType:t.type}),v={...p.props,$ratio:c,$clickable:!!f};return a.createElement(wS,null,a.createElement(LS,{...v},!h&&a.createElement(xt,{size:26},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:26})),m?a.createElement(OS,{$loaded:h,src:m,alt:"image-message",onLoad:()=>g(!0)}):null,p.descriptionNode),o)}const wS=S.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,LS=S.default.div`width:${re.BODY_MAX_WIDTH}px;border-radius:12px;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};height:auto;aspect-ratio:${e=>e.$ratio};position:relative;display:flex;align-items:center;justify-content:center;${ne.light`
355
+ `;function DS({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(PS,null,a.createElement(As,{name:e.name,mimeType:e.type,type:Zr(e.name,e.type),onClick:s}),t)}const PS=v.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,Hn=new WeakMap;function xs(e){const t=Hn.get(e);if(t)return t;const n=URL.createObjectURL(e);return Hn.set(e,n),n}function Qo(e){const t=Hn.get(e);t&&(URL.revokeObjectURL(t),Hn.delete(e))}function $S({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=ue(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?xs(u):void 0),m=d??t.url,[h,g]=l.useState(()=>u instanceof Blob),f=(()=>{if(e==="failed")return;const _=e==="succeeded"?t.url:m;if(s)return()=>s({files:[{url:_,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:_})})(),p=f?i.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:f}):i.file.preview({name:t.name,mimeType:t.type}),C={...p.props,$ratio:c,$clickable:!!f};return a.createElement(FS,null,a.createElement(US,{...C},!h&&a.createElement(xt,{size:26},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:26})),m?a.createElement(BS,{$loaded:h,src:m,alt:"image-message",onLoad:()=>g(!0)}):null,p.descriptionNode),o)}const FS=v.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,US=v.default.div`width:${re.BODY_MAX_WIDTH}px;border-radius:12px;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};height:auto;aspect-ratio:${e=>e.$ratio};position:relative;display:flex;align-items:center;justify-content:center;${ne.light`
356
356
  background-color: ${b.color.background100};
357
357
  `}
358
358
  ${ne.dark`
359
359
  background-color: ${b.color.background400};
360
360
  `}
361
- `,OS=S.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;border-radius:inherit;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`;function NS(e){return typeof e=="object"&&e!==null&&"url"in e}const DS=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[i]=l.useState(()=>{if(!n.localFiles)return null;const h=n.localFiles.flatMap(g=>g instanceof Blob?{url:Ms(g),type:g.type,name:g instanceof File?g.name:""}:NS(g)?g:[]);return h.length>0?h:null}),c=i??t,u=e==="pending",d=e==="succeeded",m=h=>{if(!d)return;const g=t[h];g&&(s?s({files:t,index:h}):r&&r({url:g.url,type:g.type||"image/*"}))};return a.createElement(PS,null,a.createElement(Ja,{images:c,isPending:u,onClickImage:d?m:void 0}),o)},PS=S.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,dc=({children:e})=>a.createElement("span",{id:Vo,className:Vo,"aria-label":E_},e),mc="✱",ei=e=>{var t,n;return{files:e.fileInfoList.map(r=>({url:r.url,type:r.mimeType??"",name:r.fileName??""})),metadata:{localFiles:(n=(t=e.messageParams)==null?void 0:t.fileInfoList)==null?void 0:n.map(r=>{if(r.file)return r.file;if(r.fileUrl)return{url:r.fileUrl,name:r.fileName??"",type:r.mimeType??""}})}}},$S=e=>{const t=new RegExp(`(\`+)[^\`]+?\\1|(${mc}+)`,"g"),n=[];let r;for(;(r=t.exec(e))!==null;)r[2]&&n.push({start:r.index,end:r.index+r[0].length,text:r[2]});return n},yr=(e,t,n,r)=>{const s=[];let o=t;for(const i of r)i.start<o||i.end>n||(i.start>o&&s.push(e.slice(o,i.start)),s.push(a.createElement(dc,{key:i.start},i.text)),o=i.end);return o<n&&s.push(e.slice(o,n)),s},FS=e=>{const t=$S(e),n=/\*\*.*?\*\*/g,r=[];let s=0,o;for(;(o=n.exec(e))!==null;){const i=o.index+o[0].length;r.push(...yr(e,s,o.index,t)),r.push(a.createElement("b",{key:o.index},yr(e,o.index+2,i-2,t))),s=i}return r.push(...yr(e,s,e.length,t)),r};function US(e){var n,r;const t=l.useMemo(()=>FS(e.message),[e.message]);return a.createElement(BS,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(HS,{variant:"body3"},t))}const BS=S.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>F.css`
361
+ `,BS=v.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;border-radius:inherit;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`;function HS(e){return typeof e=="object"&&e!==null&&"url"in e}const GS=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[i]=l.useState(()=>{if(!n.localFiles)return null;const h=n.localFiles.flatMap(g=>g instanceof Blob?{url:xs(g),type:g.type,name:g instanceof File?g.name:""}:HS(g)?g:[]);return h.length>0?h:null}),c=i??t,u=e==="pending",d=e==="succeeded",m=h=>{if(!d)return;const g=t[h];g&&(s?s({files:t,index:h}):r&&r({url:g.url,type:g.type||"image/*"}))};return a.createElement(zS,null,a.createElement(ec,{images:c,isPending:u,onClickImage:d?m:void 0}),o)},zS=v.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${re.GAP_GROUPED}px;`,hc=({children:e})=>a.createElement("span",{id:Vo,className:Vo,"aria-label":A_},e),gc="✱",ei=e=>{var t,n;return{files:e.fileInfoList.map(r=>({url:r.url,type:r.mimeType??"",name:r.fileName??""})),metadata:{localFiles:(n=(t=e.messageParams)==null?void 0:t.fileInfoList)==null?void 0:n.map(r=>{if(r.file)return r.file;if(r.fileUrl)return{url:r.fileUrl,name:r.fileName??"",type:r.mimeType??""}})}}},VS=e=>{const t=new RegExp(`(\`+)[^\`]+?\\1|(${gc}+)`,"g"),n=[];let r;for(;(r=t.exec(e))!==null;)r[2]&&n.push({start:r.index,end:r.index+r[0].length,text:r[2]});return n},br=(e,t,n,r)=>{const s=[];let o=t;for(const i of r)i.start<o||i.end>n||(i.start>o&&s.push(e.slice(o,i.start)),s.push(a.createElement(hc,{key:i.start},i.text)),o=i.end);return o<n&&s.push(e.slice(o,n)),s},KS=e=>{const t=VS(e),n=/\*\*.*?\*\*/g,r=[];let s=0,o;for(;(o=n.exec(e))!==null;){const i=o.index+o[0].length;r.push(...br(e,s,o.index,t)),r.push(a.createElement("b",{key:o.index},br(e,o.index+2,i-2,t))),s=i}return r.push(...br(e,s,e.length,t)),r};function qS(e){var n,r;const t=l.useMemo(()=>KS(e.message),[e.message]);return a.createElement(WS,{$maxWidth:e.maxBodyWidth??re.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(YS,{variant:"body3"},t))}const WS=v.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>F.css`
362
362
  color: ${t||e.colors.messageOutgoing.text};
363
363
  background-color: ${n||e.colors.messageOutgoing.background};
364
364
  `}
365
365
  padding: 12px 0;
366
366
  transition: max-width 0.3s;
367
367
  overflow-wrap: break-word;
368
- `,HS=S.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,GS=({sendingStatus:e})=>{const t=F.useTheme();switch(e){case"pending":return a.createElement(zS,{size:16},a.createElement(te,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"error",color:b.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"done",color:b.themedColor.secondary,size:16}))}},zS=S.default(xt)`margin-bottom:2px;width:16px;height:16px;`,VS=({createdAt:e})=>{const{stringSet:t,format:n}=le();return e?a.createElement(B,{variant:"caption4",color:b.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},KS=e=>{const{components:t}=Gt.useContext(),{stringSet:n}=le(),r=()=>{const i=xi(e)?a.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?i:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(t.MediaMessageBody,{...e},i):a.createElement(t.FileMessageBody,{...e},i):e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},i):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,o=s?Zt({onActivate:()=>{var i;return(i=e.onClickFailedMessage)==null?void 0:i.call(e)}}):{};return a.createElement("div",{...o,style:{display:"contents",cursor:s?"pointer":"default"}},r())},qS=e=>a.createElement(a.Fragment,null),WS=e=>{const{components:t}=Gt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(YS,{$marginBottom:Vn(e.groupType)},a.createElement(jS,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(XS,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Gt=Qe({template:WS,components:{SendingStatus:GS,SentTime:VS,MessageBody:KS,TextMessageBody:US,MediaMessageBody:kS,FileMessageBody:MS,MultipleFilesMessageBody:DS,MessageLogs:qS}}),YS=S.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
369
- `,hc=S.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
370
- `,jS=S.default(hc)``,XS=S.default(hc)`margin-top:${re.BODY_TIME_GAP}px;`,ZS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),JS=e=>e.messageType!=="admin"?null:a.createElement(tv,null,a.createElement(QS,{forwardedAs:"div",variant:"caption2",color:b.themedColor.textMidEmphasis},a.createElement(At,{fallback:e.message},a.createElement(ev,{onClickLink:e.onClickLink},e.message)))),QS=S.default(B)`&&{line-height:${4/3};}`,ev=S.default(ZS)`&& p{font-size:inherit;line-height:inherit;}&& a{font-weight:inherit;}`,tv=S.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${re.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,nv=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,gc=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var g;(g=i.current[h])==null||g.focus()})},m=h=>{const g=e[h];!g||n||(o==null||o(g.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:g=>{i.current[h]=g},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:g=>{m(nv({direction:g,currentIndex:h,totalCount:e.length}))}})}},rv=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},sv=({event:e,onClick:t,onArrowNavigate:n})=>{if(ov(e))return;const r=rv(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},ov=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Rs=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?b.themedColor.primary:r?b.themedColor.textDisabled:b.themedColor.textLowEmphasis,m=t?b.themedColor.textHighEmphasis:r?b.themedColor.textLowEmphasis:b.themedColor.textHighEmphasis;return a.createElement(cv,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>sv({event:h,onClick:e,onArrowNavigate:c})},a.createElement(iv,{"aria-hidden":"true"},a.createElement(te,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(av,{"aria-hidden":"true",variant:o,color:m},n))});Rs.displayName="Radio";const iv=S.default.div`width:20px;height:20px;`,av=S.default(B)`line-height:20px;word-break:break-word;`,cv=S.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${ke}&[aria-disabled='false']{cursor:pointer;}`,lv=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=gc({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(uv,null,a.createElement(Ne.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(dv,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(Rs,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},uv=S.default.div`display:flex;flex-direction:column;gap:8px;`,dv=S.default.div`display:flex;flex-direction:column;gap:8px;`,mv=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=le(),{conversation:i}=ue(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(g=>({label:g,value:g})):[],h=gc({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(hv,null,a.createElement(Ne.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Ne.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:g=>r(g),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(gv,{...h.radioGroupProps(e.question)},m.map((g,f)=>a.createElement(Rs,{key:g.value,checked:n===g.value,label:g.label,disabled:t,...h.getRadioProps(f),onClick:()=>r==null?void 0:r(g.value),labelVariant:"body3"}))),s&&a.createElement(fv,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},hv=S.default.div`display:flex;flex-direction:column;gap:8px;`,gv=S.default.div`display:flex;flex-direction:column;gap:8px;`,fv=S.default(Ne.ErrorLabel)``,pv=({value:e,selected:t})=>a.createElement(Ev,{$selected:t,"aria-hidden":"true"},_v[e-1]),Ev=S.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,_v=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],Cv=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=ue(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(vv,null,a.createElement(B,{variant:"caption3",color:b.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(bv,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,g=e.csat_scores.length,f=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:g,hasSelection:!s,onChange:r});return a.createElement(yv,{key:d,type:"button",...f.props},a.createElement(Sv,{value:m,selected:s||h,src:u}),!!c&&a.createElement(B,{"aria-hidden":"true",color:h?b.themedColor.textHighEmphasis:b.themedColor.textLowEmphasis,variant:"caption3"},c),f.descriptionNode)})))},Sv=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(pv,{value:e,selected:n}):a.createElement(Tv,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(Av,null,o)},vv=S.default.div`display:flex;flex-direction:column;gap:8px;`,bv=S.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,yv=S.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${ke}&:not(:disabled):hover span{color:${b.themedColor.textHighEmphasis};}`,Av=S.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${b.color.background200};${ne.dark`
368
+ `,YS=v.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,jS=({sendingStatus:e})=>{const t=F.useTheme();switch(e){case"pending":return a.createElement(XS,{size:16},a.createElement(te,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"error",color:b.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"done",color:b.themedColor.secondary,size:16}))}},XS=v.default(xt)`margin-bottom:2px;width:16px;height:16px;`,ZS=({createdAt:e})=>{const{stringSet:t,format:n}=le();return e?a.createElement(B,{variant:"caption4",color:b.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},JS=e=>{const{components:t}=Gt.useContext(),{stringSet:n}=le(),r=()=>{const i=xi(e)?a.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?i:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(t.MediaMessageBody,{...e},i):a.createElement(t.FileMessageBody,{...e},i):e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},i):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,o=s?Zt({onActivate:()=>{var i;return(i=e.onClickFailedMessage)==null?void 0:i.call(e)}}):{};return a.createElement("div",{...o,style:{display:"contents",cursor:s?"pointer":"default"}},r())},QS=e=>a.createElement(a.Fragment,null),ev=e=>{const{components:t}=Gt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(tv,{$marginBottom:Vn(e.groupType)},a.createElement(nv,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(rv,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Gt=Qe({template:ev,components:{SendingStatus:jS,SentTime:ZS,MessageBody:JS,TextMessageBody:qS,MediaMessageBody:$S,FileMessageBody:DS,MultipleFilesMessageBody:GS,MessageLogs:QS}}),tv=v.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
369
+ `,fc=v.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
370
+ `,nv=v.default(fc)``,rv=v.default(fc)`margin-top:${re.BODY_TIME_GAP}px;`,sv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),ov=e=>e.messageType!=="admin"?null:a.createElement(cv,null,a.createElement(iv,{forwardedAs:"div",variant:"caption2",color:b.themedColor.textMidEmphasis},a.createElement(At,{fallback:e.message},a.createElement(av,{onClickLink:e.onClickLink},e.message)))),iv=v.default(B)`&&{line-height:${4/3};}`,av=v.default(sv)`&& p{font-size:inherit;line-height:inherit;}&& a{font-weight:inherit;}`,cv=v.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${re.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,lv=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,pc=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var g;(g=i.current[h])==null||g.focus()})},m=h=>{const g=e[h];!g||n||(o==null||o(g.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:g=>{i.current[h]=g},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:g=>{m(lv({direction:g,currentIndex:h,totalCount:e.length}))}})}},uv=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},dv=({event:e,onClick:t,onArrowNavigate:n})=>{if(mv(e))return;const r=uv(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},mv=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Ms=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?b.themedColor.primary:r?b.themedColor.textDisabled:b.themedColor.textLowEmphasis,m=t?b.themedColor.textHighEmphasis:r?b.themedColor.textLowEmphasis:b.themedColor.textHighEmphasis;return a.createElement(fv,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>dv({event:h,onClick:e,onArrowNavigate:c})},a.createElement(hv,{"aria-hidden":"true"},a.createElement(te,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(gv,{"aria-hidden":"true",variant:o,color:m},n))});Ms.displayName="Radio";const hv=v.default.div`width:20px;height:20px;`,gv=v.default(B)`line-height:20px;word-break:break-word;`,fv=v.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${ke}&[aria-disabled='false']{cursor:pointer;}`,pv=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=pc({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(Ev,null,a.createElement(Ne.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(_v,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(Ms,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},Ev=v.default.div`display:flex;flex-direction:column;gap:8px;`,_v=v.default.div`display:flex;flex-direction:column;gap:8px;`,Cv=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=le(),{conversation:i}=ue(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(g=>({label:g,value:g})):[],h=pc({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(Sv,null,a.createElement(Ne.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Ne.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:g=>r(g),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(vv,{...h.radioGroupProps(e.question)},m.map((g,f)=>a.createElement(Ms,{key:g.value,checked:n===g.value,label:g.label,disabled:t,...h.getRadioProps(f),onClick:()=>r==null?void 0:r(g.value),labelVariant:"body3"}))),s&&a.createElement(bv,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},Sv=v.default.div`display:flex;flex-direction:column;gap:8px;`,vv=v.default.div`display:flex;flex-direction:column;gap:8px;`,bv=v.default(Ne.ErrorLabel)``,yv=({value:e,selected:t})=>a.createElement(Av,{$selected:t,"aria-hidden":"true"},Tv[e-1]),Av=v.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Tv=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],Iv=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=ue(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(Mv,null,a.createElement(B,{variant:"caption3",color:b.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(Rv,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,g=e.csat_scores.length,f=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:g,hasSelection:!s,onChange:r});return a.createElement(kv,{key:d,type:"button",...f.props},a.createElement(xv,{value:m,selected:s||h,src:u}),!!c&&a.createElement(B,{"aria-hidden":"true",color:h?b.themedColor.textHighEmphasis:b.themedColor.textLowEmphasis,variant:"caption3"},c),f.descriptionNode)})))},xv=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(yv,{value:e,selected:n}):a.createElement(Lv,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(wv,null,o)},Mv=v.default.div`display:flex;flex-direction:column;gap:8px;`,Rv=v.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,kv=v.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${ke}&:not(:disabled):hover span{color:${b.themedColor.textHighEmphasis};}`,wv=v.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${b.color.background200};${ne.dark`
371
371
  background-color: ${b.color.background500};
372
372
  `}
373
373
  }
374
- `,Tv=S.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Iv=({csatPayload:e})=>a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},e.title),Ar=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:i,setParams:c,error:u,setError:d,followUpItem:m,state:h,validateParams:g,itemProps:f}=sg({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(xv,null,a.createElement(Iv,{...f}),t===st.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(lv,{...f,defaultValue:o,value:i.isResolved,onChange:p=>c({isResolved:p})}),a.createElement(Cv,{...f,value:i.csat,onChange:p=>c({csat:p})}),m&&a.createElement(mv,{...f,followUpItem:m,value:i.csatReason,onChange:p=>{c({csatReason:p}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Ne.Separator,null),n({state:h,params:i,validateParams:g})))},xv=S.default.div`display:flex;flex-direction:column;gap:12px;`,Mv=e=>{const{stringSet:t}=le();return eu(e,{title:t.CSAT_TITLE_UNSUBMITTED,question:t.CSAT_RATING_TITLE,cre:{question:t.CSAT_CRE_TITLE,positive_label:t.CSAT_CRE_SOLVED,negative_label:t.CSAT_CRE_NOT_SOLVED},followUp:{question:t.CSAT_REASON_PLACEHOLDER},submit_label:t.CSAT_SUBMIT_LABEL,submitted_label:t.CSAT_TITLE_SUBMITTED})},Rv=()=>{const{stringSet:e}=le();return a.createElement(B,{variant:"body2",color:b.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},kv=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Re(e)},[]),t),wv=e=>{const{conversation:t}=ue();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:n,onSubmitCSAT:r,onScrollToBottom:s}=e,{csat:o,csatReason:i,csatExpireAt:c,isResolvedWhenDeterminedByUser:u}=e,d=Kn(),m=Mv(n==null?void 0:n.csat),h=l.useRef(null),g=l.useRef(null),[f,p]=l.useState(!1),v=l.useRef(!1),_=l.useCallback(()=>{Re(()=>{var I;return(I=g.current)==null?void 0:I.focus()})},[]),{isExpiredNow:E,isRenderableCSAT:A}=og({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:f});if(ng({csat:o,csatPayload:m,isRenderableCSAT:A,isExpiredNow:E,announceStatus:e.announceStatus,onSubmittedAnnounced:_}),!A||!m)return null;const y=()=>{var k;const I=(k=h.current)==null?void 0:k.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},T=m.type===st.AI_AGENT_CSAT_5||m.type===st.AI_AGENT_CSAT_5_WITH_CRE||m.type===st.HELPDESK_CSAT_5?Ar:()=>null;return a.createElement(Lv,{ref:h},!o&&E?a.createElement(Rv,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:I,params:k,validateParams:L})=>I==="submitted"?a.createElement(Nv,{ref:g,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(B,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(kv,{onMount:s},a.createElement(Ov,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(v.current)return;const R=Oi(c);if(!R&&L()){v.current=!0,p(!0);try{await r(k)}catch(M){throw v.current=!1,p(!1),M}}else d(),R||Re(()=>{var M;(M=e.announceError)==null||M.call(e,{type:"csatFormError"},y())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},Lv=S.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,Ov=S.default.button`all:unset;width:100%;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.primary};color:${({theme:e})=>e.colors.base.primaryContrastContent};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;cursor:pointer;text-align:center;word-break:break-word;${ke}&:hover{background-color:${b.color.primary.dark};}`,Nv=S.default.div`width:100%;box-sizing:border-box;color:${b.themedColor.textHighEmphasis};background-color:${b.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${ne.dark`
374
+ `,Lv=v.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Ov=({csatPayload:e})=>a.createElement(B,{variant:"button",color:b.themedColor.textHighEmphasis},e.title),yr=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:i,setParams:c,error:u,setError:d,followUpItem:m,state:h,validateParams:g,itemProps:f}=ug({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(Nv,null,a.createElement(Ov,{...f}),t===st.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(pv,{...f,defaultValue:o,value:i.isResolved,onChange:p=>c({isResolved:p})}),a.createElement(Iv,{...f,value:i.csat,onChange:p=>c({csat:p})}),m&&a.createElement(Cv,{...f,followUpItem:m,value:i.csatReason,onChange:p=>{c({csatReason:p}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(Ne.Separator,null),n({state:h,params:i,validateParams:g})))},Nv=v.default.div`display:flex;flex-direction:column;gap:12px;`,Dv=e=>{const{stringSet:t}=le();return su(e,{title:t.CSAT_TITLE_UNSUBMITTED,question:t.CSAT_RATING_TITLE,cre:{question:t.CSAT_CRE_TITLE,positive_label:t.CSAT_CRE_SOLVED,negative_label:t.CSAT_CRE_NOT_SOLVED},followUp:{question:t.CSAT_REASON_PLACEHOLDER},submit_label:t.CSAT_SUBMIT_LABEL,submitted_label:t.CSAT_TITLE_SUBMITTED})},Pv=()=>{const{stringSet:e}=le();return a.createElement(B,{variant:"body2",color:b.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},$v=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Re(e)},[]),t),Fv=e=>{const{conversation:t}=ue();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:n,onSubmitCSAT:r,onScrollToBottom:s}=e,{csat:o,csatReason:i,csatExpireAt:c,isResolvedWhenDeterminedByUser:u}=e,d=Kn(),m=Dv(n==null?void 0:n.csat),h=l.useRef(null),g=l.useRef(null),[f,p]=l.useState(!1),C=l.useRef(!1),_=l.useCallback(()=>{Re(()=>{var I;return(I=g.current)==null?void 0:I.focus()})},[]),{isExpiredNow:E,isRenderableCSAT:A}=dg({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:f});if(cg({csat:o,csatPayload:m,isRenderableCSAT:A,isExpiredNow:E,announceStatus:e.announceStatus,onSubmittedAnnounced:_}),!A||!m)return null;const y=()=>{var k;const I=(k=h.current)==null?void 0:k.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},T=m.type===st.AI_AGENT_CSAT_5||m.type===st.AI_AGENT_CSAT_5_WITH_CRE||m.type===st.HELPDESK_CSAT_5?yr:()=>null;return a.createElement(Uv,{ref:h},!o&&E?a.createElement(Pv,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:I,params:k,validateParams:L})=>I==="submitted"?a.createElement(Hv,{ref:g,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(B,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement($v,{onMount:s},a.createElement(Bv,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(C.current)return;const R=Oi(c);if(!R&&L()){C.current=!0,p(!0);try{await r(k)}catch(M){throw C.current=!1,p(!1),M}}else d(),R||Re(()=>{var M;(M=e.announceError)==null||M.call(e,{type:"csatFormError"},y())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},Uv=v.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,Bv=v.default.button`all:unset;width:100%;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.primary};color:${({theme:e})=>e.colors.base.primaryContrastContent};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;cursor:pointer;text-align:center;word-break:break-word;${ke}&:hover{background-color:${b.color.primary.dark};}`,Hv=v.default.div`width:100%;box-sizing:border-box;color:${b.themedColor.textHighEmphasis};background-color:${b.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${ne.dark`
375
375
  background-color: ${b.color.onlight.textDisabled};
376
376
  `}
377
- `,Dv=e=>{const{components:t}=Qn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(Pv,{$marginBottom:Vn(e.groupType)},n)},Qn=Qe({template:Dv,components:{AdminMessage:JS,CSATMessage:wv}}),Pv=S.default.div`padding-inline:${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,ks=({title:e,titleId:t,description:n,descriptionId:r,negativeText:s,positiveText:o,onCancel:i,onConfirm:c,buttonLayout:u="horizontal",styles:d})=>{const m=s!==void 0&&i!==void 0,h=o!==void 0&&c!==void 0,g=m?a.createElement(Hv,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.negativeText)??b.themedColor.textHighEmphasis},s)):null,f=h?a.createElement(Gv,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.positiveText)??b.themedColor.textHighEmphasisInverse},o)):null;return a.createElement($v,null,a.createElement(Fv,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??b.themedColor.textHighEmphasis},e)),a.createElement(Uv,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??b.themedColor.textMidEmphasis},n)),a.createElement(Bv,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,g,f):a.createElement(a.Fragment,null,f,g)))},$v=S.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Fv=S.default.div`padding:24px 24px 16px;`,Uv=S.default.div`padding-inline:24px;`,Bv=S.default.div`display:flex;flex-direction:${({$buttonLayout:e})=>e==="vertical-full-width"?"column":"row"};align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,Hv=S.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background:${({$background:e})=>e??"none"};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,Gv=S.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background-color:${({$background:e})=>e??b.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,An=16,zv=({status:e})=>e===wn.COMPLETED?a.createElement(te,{type:"done-circle",size:An,color:b.themedColor.textHighEmphasis}):e===wn.CANCELED?a.createElement(te,{type:"stop-circle",size:An,color:b.themedColor.textLowEmphasis}):a.createElement(xt,{size:An},a.createElement(te,{type:"spinner",size:An,color:b.themedColor.textHighEmphasis})),fc=24,Vv=8,Kv=40,qv=({task:e,isFirst:t,isLast:n})=>a.createElement(Wv,{role:"listitem"},a.createElement(Yv,null,a.createElement(ti,{$hidden:t}),a.createElement(jv,null,a.createElement(zv,{status:e.status})),a.createElement(ti,{$hidden:n})),a.createElement(Xv,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===wn.CANCELED?b.themedColor.textLowEmphasis:b.themedColor.textHighEmphasis},e.user_facing_title))),Wv=S.default.div`display:flex;gap:4px;`,Yv=S.default.div`display:flex;flex-direction:column;align-items:center;width:${fc}px;flex-shrink:0;`,ti=S.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${b.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,jv=S.default.div`display:flex;height:${fc}px;align-items:center;justify-content:center;`,Xv=S.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${Kv}px;padding-block:${Vv}px;`,Zv=({steward:e,onCancelSteward:t})=>{const{logger:n}=me(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=dl(e.status);return a.createElement(Jv,{$marginBottom:Vn("single")},a.createElement(Qv,null,a.createElement(eb,null,a.createElement(tb,null,a.createElement(B,{as:"div",variant:"caption1",color:b.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(B,{as:"div",variant:"caption4",color:b.themedColor.textLowEmphasis},e.description)),c&&a.createElement(ob,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(te,{type:"stop",size:16,color:o?b.themedColor.textDisabled:b.themedColor.textHighEmphasis}))),a.createElement(nb,null),e.tasks.length===0?u!==Qt.IN_PROGRESS?null:a.createElement(sb,null,a.createElement(xt,{size:16},a.createElement(te,{type:"spinner",size:16,color:b.themedColor.textHighEmphasis}))):a.createElement(rb,{role:"list"},e.tasks.map((d,m)=>a.createElement(qv,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(St,{portalContainerId:Ae.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(ks,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>s(!1),onConfirm:async()=>{s(!1),i(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{i(!1)}}})))},Jv=S.default.div`display:flex;flex-direction:column;margin:0 ${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
378
- `,Qv=S.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${b.themedColor.bg_300_500};background-color:${b.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,eb=S.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,tb=S.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,nb=S.default.div`height:1px;margin-block:12px;background-color:${b.themedColor.bg_200_400};`,rb=S.default.div`display:flex;flex-direction:column;`,sb=S.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,ob=S.default.button`width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:none;cursor:pointer;color:${b.themedColor.textHighEmphasis};background-color:${b.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,ib=({className:e,label:t,onClick:n})=>{const{colors:r}=F.useTheme(),{conversation:s}=ue(),o={newMessages:s.newMessagesButton()};return a.createElement(ab,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(te,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},ab=S.default.button`all:unset;cursor:pointer;display:flex;align-items:center;gap:4px;padding:10px 12px 10px 16px;border-radius:24px;background-color:${({theme:e})=>e.colors.base.primary};box-shadow:0 8px 10px 1px rgba(13,13,13,0.12),0 3px 14px 2px rgba(13,13,13,0.08),0 3px 5px -3px rgba(13,13,13,0.04);&:focus{outline:none;}${ke}`,ws=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(lb,{className:n},t&&a.createElement(te,{type:t,size:e,color:b.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:b.themedColor.textMidEmphasis},r),s),cb=S.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,lb=S.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,ub=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(ws,{icon:t,label:e,...r},n&&a.createElement(db,{onClick:n.onClick,label:n.label??"Retry"})),db=({label:e,onClick:t})=>{const{conversation:n}=ue();return a.createElement(mb,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(te,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:b.color.primary.main},e))},mb=S.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${ke}`,hb=({iconSize:e=48,className:t})=>a.createElement(xt,{size:e,className:t}),gb=({label:e="No channels",icon:t="chat",...n})=>a.createElement(ws,{icon:t,label:e,...n}),fb=({label:e="No messages",icon:t="message",...n})=>a.createElement(ws,{icon:t,label:e,...n}),pb=e=>{const{components:t}=er.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(cb,null,n)},er=Qe({template:pb,components:{Loading:hb,Error:ub,NoChannels:gb,NoMessages:fb}}),tn=e=>{const{Template:t}=er.useContext();return a.createElement(t,{...e})},Eb=[0,150,450];function _b({enabled:e}){const{state:t,actions:n}=Ba(),r=l.useRef(0),s=l.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,l.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const i=Eb.map(c=>setTimeout(()=>{Re(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const Cb=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=le();return a.createElement(Sb,{id:`${Fe}-date-separator`,role:n,style:r,className:e},a.createElement(B,{variant:"caption4",color:b.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},Sb=S.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,vb=({className:e,style:t,onClick:n})=>{const{conversation:r}=ue(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(bb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(te,{size:24,type:"chevron-down",color:b.color.primary.main}),s.scrollToBottom.descriptionNode??null)},bb=S.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:24px;box-shadow:0 2px 8px 0 rgba(0,0,0,0.08),0 4px 6px 0 rgba(0,0,0,0.12);${ne.light`
377
+ `,Gv=e=>{const{components:t}=Qn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(zv,{$marginBottom:Vn(e.groupType)},n)},Qn=Qe({template:Gv,components:{AdminMessage:ov,CSATMessage:Fv}}),zv=v.default.div`padding-inline:${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Rs=({title:e,titleId:t,description:n,descriptionId:r,negativeText:s,positiveText:o,onCancel:i,onConfirm:c,buttonLayout:u="horizontal",styles:d})=>{const m=s!==void 0&&i!==void 0,h=o!==void 0&&c!==void 0,g=m?a.createElement(Yv,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.negativeText)??b.themedColor.textHighEmphasis},s)):null,f=h?a.createElement(jv,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.positiveText)??b.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(Vv,null,a.createElement(Kv,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??b.themedColor.textHighEmphasis},e)),a.createElement(qv,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??b.themedColor.textMidEmphasis},n)),a.createElement(Wv,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,g,f):a.createElement(a.Fragment,null,f,g)))},Vv=v.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Kv=v.default.div`padding:24px 24px 16px;`,qv=v.default.div`padding-inline:24px;`,Wv=v.default.div`display:flex;flex-direction:${({$buttonLayout:e})=>e==="vertical-full-width"?"column":"row"};align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,Yv=v.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background:${({$background:e})=>e??"none"};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,jv=v.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background-color:${({$background:e})=>e??b.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,An=16,Xv=({status:e})=>e===wn.COMPLETED?a.createElement(te,{type:"done-circle",size:An,color:b.themedColor.textHighEmphasis}):e===wn.CANCELED?a.createElement(te,{type:"stop-circle",size:An,color:b.themedColor.textLowEmphasis}):a.createElement(xt,{size:An},a.createElement(te,{type:"spinner",size:An,color:b.themedColor.textHighEmphasis})),Ec=24,Zv=8,Jv=40,Qv=({task:e,isFirst:t,isLast:n})=>a.createElement(eb,{role:"listitem"},a.createElement(tb,null,a.createElement(ti,{$hidden:t}),a.createElement(nb,null,a.createElement(Xv,{status:e.status})),a.createElement(ti,{$hidden:n})),a.createElement(rb,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===wn.CANCELED?b.themedColor.textLowEmphasis:b.themedColor.textHighEmphasis},e.user_facing_title))),eb=v.default.div`display:flex;gap:4px;`,tb=v.default.div`display:flex;flex-direction:column;align-items:center;width:${Ec}px;flex-shrink:0;`,ti=v.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${b.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,nb=v.default.div`display:flex;height:${Ec}px;align-items:center;justify-content:center;`,rb=v.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${Jv}px;padding-block:${Zv}px;`,sb=({steward:e,onCancelSteward:t})=>{const{logger:n}=me(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=hl(e.status);return a.createElement(ob,{$marginBottom:Vn("single")},a.createElement(ib,null,a.createElement(ab,null,a.createElement(cb,null,a.createElement(B,{as:"div",variant:"caption1",color:b.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(B,{as:"div",variant:"caption4",color:b.themedColor.textLowEmphasis},e.description)),c&&a.createElement(mb,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(te,{type:"stop",size:16,color:o?b.themedColor.textDisabled:b.themedColor.textHighEmphasis}))),a.createElement(lb,null),e.tasks.length===0?u!==Qt.IN_PROGRESS?null:a.createElement(db,null,a.createElement(xt,{size:16},a.createElement(te,{type:"spinner",size:16,color:b.themedColor.textHighEmphasis}))):a.createElement(ub,{role:"list"},e.tasks.map((d,m)=>a.createElement(Qv,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(St,{portalContainerId:Ae.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(Rs,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>s(!1),onConfirm:async()=>{s(!1),i(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{i(!1)}}})))},ob=v.default.div`display:flex;flex-direction:column;margin:0 ${re.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
378
+ `,ib=v.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${b.themedColor.bg_300_500};background-color:${b.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,ab=v.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,cb=v.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,lb=v.default.div`height:1px;margin-block:12px;background-color:${b.themedColor.bg_200_400};`,ub=v.default.div`display:flex;flex-direction:column;`,db=v.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,mb=v.default.button`width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:none;cursor:pointer;color:${b.themedColor.textHighEmphasis};background-color:${b.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,hb=({className:e,label:t,onClick:n})=>{const{colors:r}=F.useTheme(),{conversation:s}=ue(),o={newMessages:s.newMessagesButton()};return a.createElement(gb,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(te,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},gb=v.default.button`all:unset;cursor:pointer;display:flex;align-items:center;gap:4px;padding:10px 12px 10px 16px;border-radius:24px;background-color:${({theme:e})=>e.colors.base.primary};box-shadow:0 8px 10px 1px rgba(13,13,13,0.12),0 3px 14px 2px rgba(13,13,13,0.08),0 3px 5px -3px rgba(13,13,13,0.04);&:focus{outline:none;}${ke}`,ks=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(pb,{className:n},t&&a.createElement(te,{type:t,size:e,color:b.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:b.themedColor.textMidEmphasis},r),s),fb=v.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,pb=v.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,Eb=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(ks,{icon:t,label:e,...r},n&&a.createElement(_b,{onClick:n.onClick,label:n.label??"Retry"})),_b=({label:e,onClick:t})=>{const{conversation:n}=ue();return a.createElement(Cb,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(te,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:b.color.primary.main},e))},Cb=v.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${ke}`,Sb=({iconSize:e=48,className:t})=>a.createElement(xt,{size:e,className:t}),vb=({label:e="No channels",icon:t="chat",...n})=>a.createElement(ks,{icon:t,label:e,...n}),bb=({label:e="No messages",icon:t="message",...n})=>a.createElement(ks,{icon:t,label:e,...n}),yb=e=>{const{components:t}=er.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(fb,{"data-testid":`sb-placeholder-${e.type}`},n)},er=Qe({template:yb,components:{Loading:Sb,Error:Eb,NoChannels:vb,NoMessages:bb}}),tn=e=>{const{Template:t}=er.useContext();return a.createElement(t,{...e})},Ab=[0,150,450];function Tb({enabled:e}){const{state:t,actions:n}=Ga(),r=l.useRef(0),s=l.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,l.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const i=Ab.map(c=>setTimeout(()=>{Re(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const Ib=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=le();return a.createElement(xb,{id:`${Fe}-date-separator`,role:n,style:r,className:e},a.createElement(B,{variant:"caption4",color:b.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},xb=v.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Mb=({className:e,style:t,onClick:n})=>{const{conversation:r}=ue(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(Rb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(te,{size:24,type:"chevron-down",color:b.color.primary.main}),s.scrollToBottom.descriptionNode??null)},Rb=v.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:24px;box-shadow:0 2px 8px 0 rgba(0,0,0,0.08),0 4px 6px 0 rgba(0,0,0,0.12);${ne.light`
379
379
  background-color: ${b.color.background50};
380
380
  &:hover {
381
381
  background-color: ${b.color.background100};
@@ -399,18 +399,18 @@ $2
399
399
  }
400
400
 
401
401
  ${ke}
402
- `,yb=()=>null,tr=Qe({template:yb,components:{DateSeparator:Cb,ScrollToBottomButton:vb}}),Ab=()=>{const{stringSet:e,format:t}=le(),{agentPreviewConfigs:n={},aiAgentId:r}=me(),{aiAgentInfo:s}=De(),{messageSource:o}=Me(),{Template:i}=_t.useContext(),{components:c}=tr.useContext(),u=n.welcomeMessages??[],d=o.messages,m=cE(d,r),h=d[m.length+1],g=m[0]??h;return{filteredMessages:qa(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:f=>f>0||u.length===0?!0:h&&!ft.isSameDay(h.createdAt,(g==null?void 0:g.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:a.createElement(a.Fragment,null,a.createElement(c.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:g==null?void 0:g.createdAt}),u.map((f,p)=>{const v=p===u.length-1,_=m.length!==d.length,E=u.length===1?"single":p===0?"top":v||_?"bottom":"middle",A=(g==null?void 0:g.createdAt)??Date.now();return a.createElement("div",{key:p,role:"listitem",tabIndex:-1,"aria-label":en({sender:(s==null?void 0:s.nickname)||"",message:f.message,messageFormat:"markdown",time:t(A,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},a.createElement(i,{messageType:"user",message:f.message,sender:s,groupType:E,createdAt:A,extendedMessagePayload:{suggested_replies:f.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!_,isBotMessage:!0,onClickSuggestedReply:async({reply:y})=>{o.sendUserMessage({message:y})}}))}))}},Tb=()=>{const{messageSource:e,scrollSource:t}=Me();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},ni="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",Ib=({style:e})=>{const{stringSet:t}=le(),{handlers:n}=me(),{conversation:r}=ue();return fs("powered-by")?a.createElement(xb,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Mb,{variant:"caption2",forwardedAs:"a",href:ni,...r.poweredByLink().props,rel:Ca,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:ni})}},"Sendbird")):null},xb=S.default(B)`color:${b.themedColor.textLowEmphasis};text-align:center;`,Mb=S.default(B)`color:${b.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,Rb=()=>{var c;const{stringSet:e}=le(),{conversation:t}=ue(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Me(),o=$e(n.channel),i=l.useRef(o);return l.useEffect(()=>{if(!i.current&&o){const m=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(m)}i.current=o},[o,s.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!o?null:a.createElement(kb,null,a.createElement(wb,{variant:"button",color:b.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},kb=S.default.div`display:flex;justify-content:center;margin-bottom:16px;`,wb=S.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${b.color.background50};border:1px solid ${b.color.onlight.textDisabled};${ne.dark`
402
+ `,kb=()=>null,tr=Qe({template:kb,components:{DateSeparator:Ib,ScrollToBottomButton:Mb}}),wb=()=>{const{stringSet:e,format:t}=le(),{agentPreviewConfigs:n={},aiAgentId:r}=me(),{aiAgentInfo:s}=De(),{messageSource:o}=Me(),{Template:i}=Ct.useContext(),{components:c}=tr.useContext(),u=n.welcomeMessages??[],d=o.messages,m=fE(d,r),h=d[m.length+1],g=m[0]??h;return{filteredMessages:Ya(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:f=>f>0||u.length===0?!0:h&&!pt.isSameDay(h.createdAt,(g==null?void 0:g.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:a.createElement(a.Fragment,null,a.createElement(c.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:g==null?void 0:g.createdAt}),u.map((f,p)=>{const C=p===u.length-1,_=m.length!==d.length,E=u.length===1?"single":p===0?"top":C||_?"bottom":"middle",A=(g==null?void 0:g.createdAt)??Date.now();return a.createElement("div",{key:p,role:"listitem",tabIndex:-1,"aria-label":en({sender:(s==null?void 0:s.nickname)||"",message:f.message,messageFormat:"markdown",time:t(A,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},a.createElement(i,{messageType:"user",message:f.message,sender:s,groupType:E,createdAt:A,extendedMessagePayload:{suggested_replies:f.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:C&&!_,isBotMessage:!0,onClickSuggestedReply:async({reply:y})=>{o.sendUserMessage({message:y})}}))}))}},Lb=()=>{const{messageSource:e,scrollSource:t}=Me();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},ni="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",Ob=({style:e})=>{const{stringSet:t}=le(),{handlers:n}=me(),{conversation:r}=ue();return gs("powered-by")?a.createElement(Nb,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Db,{variant:"caption2",forwardedAs:"a",href:ni,...r.poweredByLink().props,rel:va,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:ni})}},"Sendbird")):null},Nb=v.default(B)`color:${b.themedColor.textLowEmphasis};text-align:center;`,Db=v.default(B)`color:${b.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,Pb=()=>{var c;const{stringSet:e}=le(),{conversation:t}=ue(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Me(),o=$e(n.channel),i=l.useRef(o);return l.useEffect(()=>{if(!i.current&&o){const m=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(m)}i.current=o},[o,s.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!o?null:a.createElement($b,null,a.createElement(Fb,{variant:"button",color:b.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},$b=v.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Fb=v.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${b.color.background50};border:1px solid ${b.color.onlight.textDisabled};${ne.dark`
403
403
  background-color: ${b.color.background700};
404
404
  border-color: ${b.color.ondark.textLowEmphasis};
405
405
  `}
406
- `,Lb=({statsCallbacks:e,...t})=>(Eg(e),a.createElement(Zv,{...t})),Ob=(e,t,n)=>t&&Te.isWelcomeMessage(e,n)&&Te.isWelcomeMessage(t,n)?!1:!nl.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Nb=()=>{var ae;const{Template:e}=Gt.useContext(),{Template:t}=_t.useContext(),{Template:n}=Qn.useContext(),{components:r}=tr.useContext(),{stringSet:s,format:o}=le(),{announceError:i,announceStatus:c}=ht(),{messageList:u}=ue().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:g,handlers:f,state:p,_aiAgentSDK:v}=me(),{userSession:_,aiAgentInfo:E,connectionError:A}=De(),{_statsEnabled:y,_stats:T,conversation:I,channelSource:k,messageSource:L,scrollSource:R,state:{input:M,streamAnimation:$}}=Me(),{filteredMessages:N,shouldShowOriginalDate:J,renderAgentPreviewWelcomeMessages:se}=Ab(),Y=pg({enabled:y}),j=Jh(Qi(k.channel),Ml(N,_.userId)),[P,K]=l.useState(null),[q,W]=l.useState(null),H=$e(k.channel)?void 0:j??$.heldTypingInfo;l.useEffect(()=>{R.actions.onTypingIndicatorUpdate(!!H)},[!!H,R.actions.onTypingIndicatorUpdate]),Tb(),_b({enabled:L.initialized&&L.messages.length>0});const G=O=>{var be;return ml(O,{aiAgentInfo:E,members:(be=k.channel)==null?void 0:be.members})},V=O=>{if(O.sendingStatus==="failed"&&!M.disabled)return()=>W(O)},ee=({message:O,index:be})=>{const xe=hl(O),Oe=N[be-1],x=N[be+1],w=N[N.length-1],D=O===w,U=Ue(O,E.userId),Z=!(E.isUserFeedbackEnabled&&U&&!Te.isWelcomeMessage(O)),oe=gl(O,Oe,x,Z),Q=Ob(O,Oe,E.userId)&&J(be),Se=Pe=>{K({files:Pe.files.map(tt=>({...tt,timestamp:O.createdAt})),index:Pe.index})},z=Pe=>{Se({files:[Pe],index:0})},he=Q?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:O.createdAt}):null,ge={data:O.data,maxBodyWidth:p.expanded?re.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:O.extendedMessagePayload,createdAt:O.createdAt,groupType:oe,onClickMedia:z,onClickMediaFiles:Se,onClickFile:f.onClickLink,onClickCTA:f.onClickLink,onClickCitation:Pe=>f.onClickLink({url:Pe.link}),onClickLink:f.onClickLink},ie=()=>{if(Le.isOutgoing(O,_.userId))return"outgoingmessage";if(Le.isIncoming(O,_.userId))return"incomingmessage"},pe=O.createdAt!=null&&O.createdAt!==0?o(O.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,de=(()=>{var tt;const Pe=(tt=O.message)==null?void 0:tt.trim();return O.isFileMessage()||O.isMultipleFilesMessage()?Pr(ca(O,Ya(s))):Pe?zg({markdownText:Pe}):Pr("")})(),ve=(()=>{if(Le.isAdmin(O))return en({message:de.text,messageFormat:de.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Le.isOutgoing(O,_.userId))return en({sender:s.A11Y_MESSAGE_SENDER_YOU,message:de.text,messageFormat:"plain",time:pe,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Le.isIncoming(O,_.userId))return en({sender:G(O).nickname,message:de.text,messageFormat:de.format,time:pe,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),Be=(()=>{var Pe,tt;if(Le.isAdmin(O))return Le.isCSAT(O)?I?a.createElement(n,{...ge,...I,isResolvedWhenDeterminedByUser:Jl(I),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async it=>{var at;await((at=k.channel)==null?void 0:at.submitCSAT(it))},onScrollToBottom:()=>R.actions.scrollToBottom()}):null:a.createElement(n,{...ge,messageType:"admin",message:O.message});if(Le.isSteward(O)){const it=Y({message:O,isBotMessage:U,aiAgentUserId:E.userId});return a.createElement(Lb,{steward:O.extendedMessagePayload.steward,statsCallbacks:it,onCancelSteward:async()=>{await g.aiAgent.cancelStewardTask({channelUrl:O.channelUrl,messageId:O.messageId})}})}if(Le.isOutgoing(O,_.userId)){const it={...ge,message:O.message,sender:G(O),sendingStatus:O.sendingStatus,onClickFailedMessage:V(O)};if(O.isUserMessage())return a.createElement(e,{messageType:"user",...it});if(O.isFileMessage()){const[at,gt]=((Pe=O.metaArrays.find(fe=>fe.key===bi))==null?void 0:Pe.value)??[];return a.createElement(e,{messageType:"file",file:O,metadata:{aspectRatio:at&&gt?`${at}/${gt}`:"1/1",localFile:(tt=O.messageParams)==null?void 0:tt.file},...it})}if(O.isMultipleFilesMessage()){const{files:at,metadata:gt}=ei(O);return a.createElement(e,{messageType:"multipleFiles",files:at,metadata:gt,...it})}}if(Le.isIncoming(O,_.userId)){const it=Te.isStreaming(O),at=Y({message:O,isBotMessage:U,aiAgentUserId:E.userId}),gt={...ge,statsCallbacks:at,sender:G(O),message:O.message,suggestedRepliesVisible:D,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:U,isStreaming:it,isHandedOff:dt(k.channel),isConversationClosed:$e(k.channel),isFeedbackEnabled:E.isUserFeedbackEnabled,isFeedbackCommentEnabled:E.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:fe})=>{L.sendUserMessage({message:fe})},onConfirmTicketClosure:async({ticketId:fe,confirmed:Ge})=>{await v.confirmEndOfChat({messageId:O.messageId,ticketId:fe,confirmed:Ge})},onRequestMessageTemplate:async fe=>{const{template:Ge}=await g.aiAgent.getMessageTemplate(fe);return m.template.set(fe,Ge),Ge},onGetCachedMessageTemplate:fe=>m.template.get(fe),onHandleTemplateInternalAction:fe=>{if(fe.type==="internal"&&fe.internalData){const{method:Ge,payload:ct}=fe.internalData;Ge==="message.send"&&(ct!=null&&ct.message)&&L.sendUserMessage({message:ct.message})}},onFeedbackUpdate:fe=>{const Ge={messageId:O.messageId,channelUrl:O.channelUrl};if(!fe)return g.aiAgent.deleteMessageFeedback(Ge);const ct={...Ge,rating:aC(fe.rating),comment:fe.comment};return Te.hasFeedback(O)?g.aiAgent.updateMessageFeedback(ct):g.aiAgent.createMessageFeedback(ct)},onSubmitForm:({key:fe,data:Ge})=>g.aiAgent.submitForm({messageId:O.messageId,channelUrl:O.channelUrl,formKey:fe,formData:Ge}),onCancelForm:({key:fe})=>g.aiAgent.cancelForm({messageId:O.messageId,channelUrl:O.channelUrl,formKey:fe}),onSendChallengeAction:({key:fe,requestId:Ge,action:ct,data:Zc})=>g.aiAgent.sendChallengeAction({channelUrl:O.channelUrl,key:fe,requestId:Ge,action:ct,data:Zc}),onStreamAnimationStart:()=>{$.start(O.messageId),T.onMessageLifecycleAnimationStart(O.messageId)},onStreamAnimationProgress:()=>{R.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:({completed:fe})=>{$.stop(O.messageId),R.actions.onStreamingUpdate(!1),T.onMessageLifecycleAnimationComplete(O.messageId,fe)},onStreamAnimationHoldChange:fe=>{fe?$.holdStart(O.messageId,{user:G(O),isBot:U}):$.holdStop(O.messageId)}};if(O.isUserMessage())return a.createElement(t,{messageType:"user",...gt});if(O.isFileMessage())return a.createElement(t,{messageType:"file",file:O,...gt});if(O.isMultipleFilesMessage()){const{files:fe}=ei(O);return a.createElement(t,{messageType:"multipleFiles",files:fe,...gt})}}})(),He=$.isHolding(O.messageId),Ze=u.item({label:ve,holding:He});return a.createElement(l.Fragment,{key:xe},he,a.createElement("div",{id:`${Fe}-message-item`,...Ze.props,"data-message-listitem":"","data-layout-id":ie()},Be))};return a.createElement(Db,{id:`${Fe}-message-list`},a.createElement(PE,{ref:R.ref,onScroll:R.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:N,renderMessage:ee,onLoadPrev:L.loadPrevious,onLoadNext:L.loadNext,depsForResetScrollPositionToBottom:[L.initialized,L.messages.length!==0],bottomSpacerHeight:R.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!L.initialized||!k.channel,empty:N.length===0&&!H,error:!!(A||k.error),LoadingComponent:a.createElement(tn,{type:"loading"}),EmptyComponent:(()=>{const O=se();return O?a.createElement("div",{style:{width:"100%"}},O):a.createElement(tn,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(tn,{type:"error",label:(A==null?void 0:A.message)??((ae=k.error)==null?void 0:ae.message),action:k.error?{label:s.RETRY,onClick:()=>k.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Ib,{style:{marginTop:16}}),se()),messageBottomArea:a.createElement(a.Fragment,null,H&&a.createElement("div",{id:`${Fe}-message-item`,...u.typingItem(H.user.nickname).props,"data-message-listitem":"",style:{marginTop:N.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:H.isBot,sender:H.user,thinkingMessage:H.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(Rb,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&R.state.isAwayFromBottom&&L.newMessages.length>0&&a.createElement(Pb,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(L.newMessages),onClick:()=>R.actions.scrollToBottom()}),R.state.isAwayFromBottom&&L.newMessages.length===0&&!H&&a.createElement(r.ScrollToBottomButton,{onClick:()=>R.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),P&&a.createElement(zE,{files:P.files,initialIndex:P.index,onClose:()=>K(null),visible:!0}),q&&a.createElement(pt,{visible:!0,onClose:()=>W(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(pt.ActionItem,{onClick:()=>{L.resendMessage(q),W(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(pt.ActionItem,{destructive:!0,onClick:()=>{L.deleteMessage(q),W(null)}},s.FAILED_MESSAGE_REMOVE)))},Db=S.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Pb=S.default(ib)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,$b=()=>a.createElement(Nb,null),ri={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},pc=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:g=p=>p.default,style:f={}})=>{const{iconColor:p="#000000",textColor:v="#000000",highlightColor:_=nn.DEFAULT_PRIMARY}=f;return a.createElement(si,null,m,e&&a.createElement(si,null,a.createElement(Gn,null,a.createElement(jt,null,a.createElement(te,{size:16,type:"actionbook",color:p})),a.createElement(Tn,{$clickable:!!o,$highlightColor:_,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(E=>a.createElement(Rn,{key:E.key},a.createElement(jt,null,a.createElement(te,{size:16,type:"function",color:p})),a.createElement(Gn,null,a.createElement(Tn,{$clickable:!!i,$highlightColor:_,variant:"body2",color:v,onClick:()=>i==null?void 0:i(E),maxTextLines:1},E.name),c&&a.createElement(Fb,{role:"button",onClick:()=>c==null?void 0:c(E)},a.createElement(B,{variant:"body2",color:_},"View details"),a.createElement(te,{type:"chevron-right",size:16,color:_}))))),n==null?void 0:n.map(E=>a.createElement(Rn,{key:E.id},a.createElement(jt,null,g({default:a.createElement(te,{size:16,type:ri[E.source_type]??ri.snippet,color:p}),sourceType:E.source_type})),a.createElement(Tn,{$clickable:!!u,$highlightColor:_,variant:"body2",color:v,onClick:()=>u==null?void 0:u(E),maxTextLines:1},E.preview_title))),r==null?void 0:r.map(E=>a.createElement(Rn,{key:E.key},a.createElement(jt,null,a.createElement(te,{size:16,type:"template",color:p})),a.createElement(Tn,{$clickable:!!d,$highlightColor:_,variant:"body2",color:v,onClick:()=>d==null?void 0:d(E),maxTextLines:1},E.name))),!!(s!=null&&s.length)&&a.createElement(Ub,null,a.createElement(jt,null,a.createElement(te,{size:16,type:"activity",color:p})),a.createElement(Bb,{variant:"body2",color:v},s.map(E=>E.replace(/_/g," ")).join(" · "))),h)},Ec=S.default(B)`font-weight:400;`,Tn=S.default(Ec)`${({$clickable:e,$highlightColor:t})=>e&&F.css`
406
+ `,Ub=({statsCallbacks:e,...t})=>(Ag(e),a.createElement(sb,{...t})),Bb=(e,t,n)=>t&&Ie.isWelcomeMessage(e,n)&&Ie.isWelcomeMessage(t,n)?!1:!sl.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Hb=()=>{var ae;const{Template:e}=Gt.useContext(),{Template:t}=Ct.useContext(),{Template:n}=Qn.useContext(),{components:r}=tr.useContext(),{stringSet:s,format:o}=le(),{announceError:i,announceStatus:c}=gt(),{messageList:u}=ue().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:g,handlers:f,state:p,_aiAgentSDK:C}=me(),{userSession:_,aiAgentInfo:E,connectionError:A}=De(),{_statsEnabled:y,_stats:T,conversation:I,channelSource:k,messageSource:L,scrollSource:R,state:{input:M,streamAnimation:$}}=Me(),{filteredMessages:N,shouldShowOriginalDate:Q,renderAgentPreviewWelcomeMessages:se}=wb(),Y=yg({enabled:y}),j=sg(ta(k.channel),kl(N,_.userId)),[P,q]=l.useState(null),[W,G]=l.useState(null),H=$e(k.channel)?void 0:j??$.heldTypingInfo;l.useEffect(()=>{R.actions.onTypingIndicatorUpdate(!!H)},[!!H,R.actions.onTypingIndicatorUpdate]),Lb(),Tb({enabled:L.initialized&&L.messages.length>0});const V=O=>{var be;return gl(O,{aiAgentInfo:E,members:(be=k.channel)==null?void 0:be.members})},z=O=>{if(O.sendingStatus==="failed"&&!M.disabled)return()=>G(O)},Z=({message:O,index:be})=>{const xe=fl(O),Oe=N[be-1],x=N[be+1],w=N[N.length-1],D=O===w,U=Ue(O,E.userId),J=!(E.isUserFeedbackEnabled&&U&&!Ie.isWelcomeMessage(O)),oe=pl(O,Oe,x,J),ee=Bb(O,Oe,E.userId)&&Q(be),Se=Pe=>{q({files:Pe.files.map(tt=>({...tt,timestamp:O.createdAt})),index:Pe.index})},K=Pe=>{Se({files:[Pe],index:0})},he=ee?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:O.createdAt}):null,ge={data:O.data,maxBodyWidth:p.expanded?re.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:O.extendedMessagePayload,createdAt:O.createdAt,groupType:oe,onClickMedia:K,onClickMediaFiles:Se,onClickFile:f.onClickLink,onClickCTA:f.onClickLink,onClickCitation:Pe=>f.onClickLink({url:Pe.link}),onClickLink:f.onClickLink},ie=()=>{if(Le.isOutgoing(O,_.userId))return"outgoingmessage";if(Le.isIncoming(O,_.userId))return"incomingmessage"},pe=O.createdAt!=null&&O.createdAt!==0?o(O.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,de=(()=>{var tt;const Pe=(tt=O.message)==null?void 0:tt.trim();return O.isFileMessage()||O.isMultipleFilesMessage()?Dr(ua(O,Xa(s))):Pe?Xg({markdownText:Pe}):Dr("")})(),ve=(()=>{if(Le.isAdmin(O))return en({message:de.text,messageFormat:de.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Le.isOutgoing(O,_.userId))return en({sender:s.A11Y_MESSAGE_SENDER_YOU,message:de.text,messageFormat:"plain",time:pe,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Le.isIncoming(O,_.userId))return en({sender:V(O).nickname,message:de.text,messageFormat:de.format,time:pe,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),Be=(()=>{var Pe,tt;if(Le.isAdmin(O))return Le.isCSAT(O)?I?a.createElement(n,{...ge,...I,isResolvedWhenDeterminedByUser:nu(I),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async it=>{var at;await((at=k.channel)==null?void 0:at.submitCSAT(it))},onScrollToBottom:()=>R.actions.scrollToBottom()}):null:a.createElement(n,{...ge,messageType:"admin",message:O.message});if(Le.isSteward(O)){const it=Y({message:O,isBotMessage:U,aiAgentUserId:E.userId});return a.createElement(Ub,{steward:O.extendedMessagePayload.steward,statsCallbacks:it,onCancelSteward:async()=>{await g.aiAgent.cancelStewardTask({channelUrl:O.channelUrl,messageId:O.messageId})}})}if(Le.isOutgoing(O,_.userId)){const it={...ge,message:O.message,sender:V(O),sendingStatus:O.sendingStatus,onClickFailedMessage:z(O)};if(O.isUserMessage())return a.createElement(e,{messageType:"user",...it});if(O.isFileMessage()){const[at,ft]=((Pe=O.metaArrays.find(fe=>fe.key===bi))==null?void 0:Pe.value)??[];return a.createElement(e,{messageType:"file",file:O,metadata:{aspectRatio:at&&ft?`${at}/${ft}`:"1/1",localFile:(tt=O.messageParams)==null?void 0:tt.file},...it})}if(O.isMultipleFilesMessage()){const{files:at,metadata:ft}=ei(O);return a.createElement(e,{messageType:"multipleFiles",files:at,metadata:ft,...it})}}if(Le.isIncoming(O,_.userId)){const it=Ie.isStreaming(O),at=Y({message:O,isBotMessage:U,aiAgentUserId:E.userId}),ft={...ge,statsCallbacks:at,sender:V(O),message:O.message,suggestedRepliesVisible:D,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:U,isStreaming:it,isHandedOff:dt(k.channel),isConversationClosed:$e(k.channel),isFeedbackEnabled:E.isUserFeedbackEnabled,isFeedbackCommentEnabled:E.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:fe})=>{L.sendUserMessage({message:fe})},onConfirmTicketClosure:async({ticketId:fe,confirmed:Ge})=>{await C.confirmEndOfChat({messageId:O.messageId,ticketId:fe,confirmed:Ge})},onRequestMessageTemplate:async fe=>{const{template:Ge}=await g.aiAgent.getMessageTemplate(fe);return m.template.set(fe,Ge),Ge},onGetCachedMessageTemplate:fe=>m.template.get(fe),onHandleTemplateInternalAction:fe=>{if(fe.type==="internal"&&fe.internalData){const{method:Ge,payload:ct}=fe.internalData;Ge==="message.send"&&(ct!=null&&ct.message)&&L.sendUserMessage({message:ct.message})}},onFeedbackUpdate:fe=>{const Ge={messageId:O.messageId,channelUrl:O.channelUrl};if(!fe)return g.aiAgent.deleteMessageFeedback(Ge);const ct={...Ge,rating:gC(fe.rating),comment:fe.comment};return Ie.hasFeedback(O)?g.aiAgent.updateMessageFeedback(ct):g.aiAgent.createMessageFeedback(ct)},onSubmitForm:({key:fe,data:Ge})=>g.aiAgent.submitForm({messageId:O.messageId,channelUrl:O.channelUrl,formKey:fe,formData:Ge}),onCancelForm:({key:fe})=>g.aiAgent.cancelForm({messageId:O.messageId,channelUrl:O.channelUrl,formKey:fe}),onSendChallengeAction:({key:fe,requestId:Ge,action:ct,data:Qc})=>g.aiAgent.sendChallengeAction({channelUrl:O.channelUrl,key:fe,requestId:Ge,action:ct,data:Qc}),onStreamAnimationStart:()=>{$.start(O.messageId),T.onMessageLifecycleAnimationStart(O.messageId)},onStreamAnimationProgress:()=>{R.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:({completed:fe})=>{$.stop(O.messageId),R.actions.onStreamingUpdate(!1),T.onMessageLifecycleAnimationComplete(O.messageId,fe)},onStreamAnimationHoldChange:fe=>{fe?$.holdStart(O.messageId,{user:V(O),isBot:U}):$.holdStop(O.messageId)}};if(O.isUserMessage())return a.createElement(t,{messageType:"user",...ft});if(O.isFileMessage())return a.createElement(t,{messageType:"file",file:O,...ft});if(O.isMultipleFilesMessage()){const{files:fe}=ei(O);return a.createElement(t,{messageType:"multipleFiles",files:fe,...ft})}}})(),He=$.isHolding(O.messageId),Ze=u.item({label:ve,holding:He});return a.createElement(l.Fragment,{key:xe},he,a.createElement("div",{id:`${Fe}-message-item`,...Ze.props,"data-message-listitem":"","data-layout-id":ie()},Be))};return a.createElement(Gb,{id:`${Fe}-message-list`},a.createElement(zE,{ref:R.ref,onScroll:R.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:N,renderMessage:Z,onLoadPrev:L.loadPrevious,onLoadNext:L.loadNext,depsForResetScrollPositionToBottom:[L.initialized,L.messages.length!==0],bottomSpacerHeight:R.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!L.initialized||!k.channel,empty:N.length===0&&!H,error:!!(A||k.error),LoadingComponent:a.createElement(tn,{type:"loading"}),EmptyComponent:(()=>{const O=se();return O?a.createElement("div",{style:{width:"100%"}},O):a.createElement(tn,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(tn,{type:"error",label:(A==null?void 0:A.message)??((ae=k.error)==null?void 0:ae.message),action:k.error?{label:s.RETRY,onClick:()=>k.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(Ob,{style:{marginTop:16}}),se()),messageBottomArea:a.createElement(a.Fragment,null,H&&a.createElement("div",{id:`${Fe}-message-item`,...u.typingItem(H.user.nickname).props,"data-message-listitem":"",style:{marginTop:N.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:H.isBot,sender:H.user,thinkingMessage:H.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(Pb,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&R.state.isAwayFromBottom&&L.newMessages.length>0&&a.createElement(zb,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(L.newMessages),onClick:()=>R.actions.scrollToBottom()}),R.state.isAwayFromBottom&&L.newMessages.length===0&&!H&&a.createElement(r.ScrollToBottomButton,{onClick:()=>R.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),P&&a.createElement(XE,{files:P.files,initialIndex:P.index,onClose:()=>q(null),visible:!0}),W&&a.createElement(Et,{visible:!0,onClose:()=>G(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(Et.ActionItem,{onClick:()=>{L.resendMessage(W),G(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(Et.ActionItem,{destructive:!0,onClick:()=>{L.deleteMessage(W),G(null)}},s.FAILED_MESSAGE_REMOVE)))},Gb=v.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,zb=v.default(hb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Vb=()=>a.createElement(Hb,null),ri={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},_c=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:g=p=>p.default,style:f={}})=>{const{iconColor:p="#000000",textColor:C="#000000",highlightColor:_=nn.DEFAULT_PRIMARY}=f;return a.createElement(si,null,m,e&&a.createElement(si,null,a.createElement(Gn,null,a.createElement(jt,null,a.createElement(te,{size:16,type:"actionbook",color:p})),a.createElement(Tn,{$clickable:!!o,$highlightColor:_,variant:"body2",color:C,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(E=>a.createElement(Rn,{key:E.key},a.createElement(jt,null,a.createElement(te,{size:16,type:"function",color:p})),a.createElement(Gn,null,a.createElement(Tn,{$clickable:!!i,$highlightColor:_,variant:"body2",color:C,onClick:()=>i==null?void 0:i(E),maxTextLines:1},E.name),c&&a.createElement(Kb,{role:"button",onClick:()=>c==null?void 0:c(E)},a.createElement(B,{variant:"body2",color:_},"View details"),a.createElement(te,{type:"chevron-right",size:16,color:_}))))),n==null?void 0:n.map(E=>a.createElement(Rn,{key:E.id},a.createElement(jt,null,g({default:a.createElement(te,{size:16,type:ri[E.source_type]??ri.snippet,color:p}),sourceType:E.source_type})),a.createElement(Tn,{$clickable:!!u,$highlightColor:_,variant:"body2",color:C,onClick:()=>u==null?void 0:u(E),maxTextLines:1},E.preview_title))),r==null?void 0:r.map(E=>a.createElement(Rn,{key:E.key},a.createElement(jt,null,a.createElement(te,{size:16,type:"template",color:p})),a.createElement(Tn,{$clickable:!!d,$highlightColor:_,variant:"body2",color:C,onClick:()=>d==null?void 0:d(E),maxTextLines:1},E.name))),!!(s!=null&&s.length)&&a.createElement(qb,null,a.createElement(jt,null,a.createElement(te,{size:16,type:"activity",color:p})),a.createElement(Wb,{variant:"body2",color:C},s.map(E=>E.replace(/_/g," ")).join(" · "))),h)},Cc=v.default(B)`font-weight:400;`,Tn=v.default(Cc)`${({$clickable:e,$highlightColor:t})=>e&&F.css`
407
407
  cursor: pointer;
408
408
  text-decoration: underline;
409
409
  &:hover {
410
410
  color: ${t};
411
411
  }
412
412
  `}
413
- `,jt=S.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Gn=S.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Fb=S.default(Gn)`cursor:pointer;gap:4px;`,Rn=S.default(Gn)`flex-direction:row;align-items:center;`,Ub=S.default(Rn)`align-items:flex-start;max-width:100%;`,Bb=S.default(Ec)`min-width:0;`,si=S.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Hb=e=>{const t=e.replace(/[_-]+/g," ").trim().toLowerCase();return t?t.charAt(0).toUpperCase()+t.slice(1):""},_c=({prechecks:e,maxBodyWidth:t})=>{const{theme:n}=Wn();return e.length===0?null:a.createElement(Gb,{id:`${Ke}-ext-prechecks`},a.createElement(zb,{$maxWidth:t??re.BODY_MAX_WIDTH},e.map(r=>a.createElement(Vb,{key:r.key},a.createElement(Kb,{type:"done-circle",size:16,color:b.themedColor.secondary}),a.createElement(B,{variant:"caption2",color:n.colors.messageIncoming.text},Hb(r.key))))))},Gb=S.default.div`align-self:stretch;padding-block-end:8px;padding-inline-start:${re.HORIZONTAL_PADDING+re.AVATAR_SIZE}px;padding-inline-end:${re.HORIZONTAL_PADDING}px;`,zb=S.default.div`display:flex;flex-wrap:wrap;gap:4px 14px;width:fit-content;max-width:min(${({$maxWidth:e})=>e}px,100%);padding:8px 12px;border-radius:8px;background-color:${({theme:e})=>e.colors.messageIncoming.background};`,Vb=S.default.div`display:flex;align-items:center;gap:6px;min-width:0;overflow-wrap:anywhere;`,Kb=S.default(te)`flex-shrink:0;`,Cc=ye("DashboardTester"),qb=Cc.Provider;function Wb({testerType:e,origin:t,children:n}){return a.createElement(qb,{value:{testerType:e,origin:t}},e&&a.createElement(Yb,null),n)}const Sc=Cc.useContext,Yb=()=>a.createElement(a.Fragment,null,a.createElement(_t.Prechecks,{component:jb}),a.createElement(_t.MessageLogs,{component:oi}),a.createElement(Gt.MessageLogs,{component:oi})),jb=({extendedMessagePayload:e={},maxBodyWidth:t})=>a.createElement(_c,{prechecks:e.prechecks??[],maxBodyWidth:t}),oi=({extendedMessagePayload:e={}})=>{const{handlers:t}=me(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:o,flagged_types:i,is_thinking:c}=e,u=!!n||[r,s,o,i].some(d=>d==null?void 0:d.length);return c||!u?a.createElement(a.Fragment,null):a.createElement(Xb,null,a.createElement(Zb,{$width:4}),a.createElement(pc,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:b.themedColor.textHighEmphasis,textColor:b.themedColor.textHighEmphasis,barColor:b.themedColor.textDisabled},topContent:a.createElement(B,{variant:"caption4",color:b.themedColor.textLowEmphasis},"Only visible in the tester")}))},Xb=S.default.div`display:flex;gap:16px;margin:6px ${re.HORIZONTAL_PADDING}px 4px ${re.HORIZONTAL_PADDING+re.AVATAR_SIZE}px;align-self:stretch;`,Zb=S.default.div`width:${({$width:e})=>e}px;background-color:${b.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Jb=()=>{var s;const{origin:e}=Sc(),{appId:t,aiAgentId:n}=Ie(),{channelSource:r}=Me();return(s=r.channel)!=null&&s.conversation?a.createElement(Qb,null,a.createElement(Wr,{style:{gap:4}},a.createElement(te,{color:b.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(B,{as:"i",color:b.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(Wr,{role:"button",style:{gap:4},onClick:()=>{var u,d;const o=e??window.location.origin,i=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,c=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(c)}},a.createElement(B,{variant:"body3",color:b.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:b.themedColor.primary}},"conversation link")),a.createElement(te,{color:b.themedColor.primary,size:14,type:"copy"}))):null},Wr=S.default.div`display:flex;justify-content:center;align-items:center;`,Qb=S.default(Wr)`flex-direction:column;padding-block:16px;background-color:${b.themedColor.bg_100_500};gap:8px;`,ey=(e,t)=>{const n=[],r=[],s=[];for(const o of e){const i=t.isSupportedMimeType(o.type),c=o.size<=t.getUploadSizeLimit(o.type);i&&c?n.push(o):i?r.push(o):s.push(o)}return{passed:n,failedBySize:r,failedByType:s}},vc=l.createContext(void 0),ty=({children:e})=>{var J,se;const{chatSDK:t}=me(),{createAttachmentRules:n}=De(),{stringSet:r}=le(),{channelSource:s,state:o}=Me(),[i,c]=l.useState([]),{announceError:u}=Ss(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(J=t.appInfo)==null?void 0:J.uploadSizeLimit}),g=((se=o==null?void 0:o.input)==null?void 0:se.disabled)??!1,f=h.isEnabled(),p=h.maxAttachmentCount,v=()=>m(null),_=Y=>m(Y),E=()=>{_({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString())})},A=Y=>{_({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",Y.toString())}),u({type:"fileSizeExceeded",maxSizeMB:Y})},y=Y=>{_({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",Y.toString())})},T=Y=>Y.map(j=>{const P=Ms(j);return Vp(j,P),{file:j,preview:{url:P,type:j.type,name:j.name}}}),I=Y=>{c(j=>[...j,...Y])},k=Y=>{c(j=>(j.forEach(P=>Qo(P.file)),Y))},L=Y=>{const{passed:j,failedBySize:P,failedByType:K}=ey(Y,h),q=P.length+K.length,W=Y.length===1?P[0]:void 0;return W?A(h.getUploadSizeLimitInMB(W.type)):q>0&&y(q),j},R=Y=>{const j=L(Y.files);if(j.length===0)return;const P=T(j);Y.type==="append"?I(P):k(P)},M=Y=>{if(!f||g||!um(Y))return;const j=mm({currentFiles:i.map(({file:P})=>P),incomingFiles:Y,maxAttachmentCount:p});switch(j.type){case"reject":E();return;case"confirm_replace":_({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>R(j.action)});return;case"apply":R(j.action);return}},$=Y=>{c(j=>{var K;const P=(K=j[Y])==null?void 0:K.file;return P&&Qo(P),j.filter((q,W)=>W!==Y)})},N=()=>{c([])};return a.createElement(vc.Provider,{value:{files:i,addFiles:M,removeFile:$,clearFiles:N,isFileUploadEnabled:f,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:_}},e,a.createElement(mn,{visible:!!d,...d??{},onClose:v}))},Ls=()=>{const e=l.useContext(vc);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function ny({elementRef:e,ready:t,onRestore:n}){const r=l.useRef(!1);l.useEffect(()=>{var i;!t||!r.current||(n==null||n(),(i=e.current)==null||i.focus(),r.current=!1)},[t,n]);const s=l.useCallback(()=>{r.current=!0},[]),o=l.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function ry({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=l.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),l.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const sy=()=>{const{announceError:e}=ht();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},oy=1e3,iy=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=ht(),o=n??!0,i=l.useRef(!1),c=l.useRef(void 0),u=l.useCallback(d=>{var h;const m=()=>{};d&&o&&(i.current=!0,c.current=e,e==null||e.startTyping().catch(m)),d||(i.current&&o&&((h=c.current)==null||h.endTyping().catch(m)),i.current=!1,c.current=void 0),s(d)},[e,s,o]);l.useLayoutEffect(()=>{s(i.current)},[r,s]),Qh(t,u,{enabled:o,idleMs:oy})},ay=({enabled:e=!0,focusRoot:t})=>{const[n,r]=l.useState(!1),s=l.useRef(!1),o=l.useRef(!1);l.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const g=h;g.metaKey||g.altKey||g.ctrlKey||(s.current=!0)},m=()=>{s.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const i=l.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),c=l.useCallback(()=>{r(!1)},[]),u=l.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:i,onBlur:c}}},cy=S.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,ly=S.default.div`display:flex;flex-shrink:0;position:relative;margin-block-start:8px;border-radius:12px;height:64px;img{border-radius:12px;object-fit:cover;width:64px;-webkit-user-drag:none;}&:hover button,&:focus-within button{opacity:1;}`,uy=S.default.button`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;border:none;padding:0;opacity:${({$mobile:e})=>e?1:0};transition:opacity 0.12s ease-in-out;${ne.light`
413
+ `,jt=v.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Gn=v.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Kb=v.default(Gn)`cursor:pointer;gap:4px;`,Rn=v.default(Gn)`flex-direction:row;align-items:center;`,qb=v.default(Rn)`align-items:flex-start;max-width:100%;`,Wb=v.default(Cc)`min-width:0;`,si=v.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Yb=e=>{const t=e.replace(/[_-]+/g," ").trim().toLowerCase();return t?t.charAt(0).toUpperCase()+t.slice(1):""},Sc=({prechecks:e,maxBodyWidth:t})=>{const{theme:n}=Wn();return e.length===0?null:a.createElement(jb,{id:`${Ke}-ext-prechecks`},a.createElement(Xb,{$maxWidth:t??re.BODY_MAX_WIDTH},e.map(r=>a.createElement(Zb,{key:r.key},a.createElement(Jb,{type:"done-circle",size:16,color:b.themedColor.secondary}),a.createElement(B,{variant:"caption2",color:n.colors.messageIncoming.text},Yb(r.key))))))},jb=v.default.div`align-self:stretch;padding-block-end:8px;padding-inline-start:${re.HORIZONTAL_PADDING+re.AVATAR_SIZE}px;padding-inline-end:${re.HORIZONTAL_PADDING}px;`,Xb=v.default.div`display:flex;flex-wrap:wrap;gap:4px 14px;width:fit-content;max-width:min(${({$maxWidth:e})=>e}px,100%);padding:8px 12px;border-radius:8px;background-color:${({theme:e})=>e.colors.messageIncoming.background};`,Zb=v.default.div`display:flex;align-items:center;gap:6px;min-width:0;overflow-wrap:anywhere;`,Jb=v.default(te)`flex-shrink:0;`,vc=ye("DashboardTester"),Qb=vc.Provider;function ey({testerType:e,origin:t,children:n}){return a.createElement(Qb,{value:{testerType:e,origin:t}},e&&a.createElement(ty,null),n)}const bc=vc.useContext,ty=()=>a.createElement(a.Fragment,null,a.createElement(Ct.Prechecks,{component:ny}),a.createElement(Ct.MessageLogs,{component:oi}),a.createElement(Gt.MessageLogs,{component:oi})),ny=({extendedMessagePayload:e={},maxBodyWidth:t})=>a.createElement(Sc,{prechecks:e.prechecks??[],maxBodyWidth:t}),oi=({extendedMessagePayload:e={}})=>{const{handlers:t}=me(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:o,flagged_types:i,is_thinking:c}=e,u=!!n||[r,s,o,i].some(d=>d==null?void 0:d.length);return c||!u?a.createElement(a.Fragment,null):a.createElement(ry,null,a.createElement(sy,{$width:4}),a.createElement(_c,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:b.themedColor.textHighEmphasis,textColor:b.themedColor.textHighEmphasis,barColor:b.themedColor.textDisabled},topContent:a.createElement(B,{variant:"caption4",color:b.themedColor.textLowEmphasis},"Only visible in the tester")}))},ry=v.default.div`display:flex;gap:16px;margin:6px ${re.HORIZONTAL_PADDING}px 4px ${re.HORIZONTAL_PADDING+re.AVATAR_SIZE}px;align-self:stretch;`,sy=v.default.div`width:${({$width:e})=>e}px;background-color:${b.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,oy=()=>{var s;const{origin:e}=bc(),{appId:t,aiAgentId:n}=Te(),{channelSource:r}=Me();return(s=r.channel)!=null&&s.conversation?a.createElement(iy,null,a.createElement(qr,{style:{gap:4}},a.createElement(te,{color:b.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(B,{as:"i",color:b.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(qr,{role:"button",style:{gap:4},onClick:()=>{var u,d;const o=e??window.location.origin,i=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,c=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(c)}},a.createElement(B,{variant:"body3",color:b.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:b.themedColor.primary}},"conversation link")),a.createElement(te,{color:b.themedColor.primary,size:14,type:"copy"}))):null},qr=v.default.div`display:flex;justify-content:center;align-items:center;`,iy=v.default(qr)`flex-direction:column;padding-block:16px;background-color:${b.themedColor.bg_100_500};gap:8px;`,ay=(e,t)=>{const n=[],r=[],s=[];for(const o of e){const i=t.isSupportedMimeType(o.type),c=o.size<=t.getUploadSizeLimit(o.type);i&&c?n.push(o):i?r.push(o):s.push(o)}return{passed:n,failedBySize:r,failedByType:s}},yc=l.createContext(void 0),cy=({children:e})=>{var Q,se;const{chatSDK:t}=me(),{createAttachmentRules:n}=De(),{stringSet:r}=le(),{channelSource:s,state:o}=Me(),[i,c]=l.useState([]),{announceError:u}=Cs(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(Q=t.appInfo)==null?void 0:Q.uploadSizeLimit}),g=((se=o==null?void 0:o.input)==null?void 0:se.disabled)??!1,f=h.isEnabled(),p=h.maxAttachmentCount,C=()=>m(null),_=Y=>m(Y),E=()=>{_({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString())})},A=Y=>{_({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",Y.toString())}),u({type:"fileSizeExceeded",maxSizeMB:Y})},y=Y=>{_({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",Y.toString())})},T=Y=>Y.map(j=>{const P=xs(j);return Zp(j,P),{file:j,preview:{url:P,type:j.type,name:j.name}}}),I=Y=>{c(j=>[...j,...Y])},k=Y=>{c(j=>(j.forEach(P=>Qo(P.file)),Y))},L=Y=>{const{passed:j,failedBySize:P,failedByType:q}=ay(Y,h),W=P.length+q.length,G=Y.length===1?P[0]:void 0;return G?A(h.getUploadSizeLimitInMB(G.type)):W>0&&y(W),j},R=Y=>{const j=L(Y.files);if(j.length===0)return;const P=T(j);Y.type==="append"?I(P):k(P)},M=Y=>{if(!f||g||!gm(Y))return;const j=pm({currentFiles:i.map(({file:P})=>P),incomingFiles:Y,maxAttachmentCount:p});switch(j.type){case"reject":E();return;case"confirm_replace":_({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>R(j.action)});return;case"apply":R(j.action);return}},$=Y=>{c(j=>{var q;const P=(q=j[Y])==null?void 0:q.file;return P&&Qo(P),j.filter((W,G)=>G!==Y)})},N=()=>{c([])};return a.createElement(yc.Provider,{value:{files:i,addFiles:M,removeFile:$,clearFiles:N,isFileUploadEnabled:f,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:_}},e,a.createElement(mn,{visible:!!d,...d??{},onClose:C}))},ws=()=>{const e=l.useContext(yc);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function ly({elementRef:e,ready:t,onRestore:n}){const r=l.useRef(!1);l.useEffect(()=>{var i;!t||!r.current||(n==null||n(),(i=e.current)==null||i.focus(),r.current=!1)},[t,n]);const s=l.useCallback(()=>{r.current=!0},[]),o=l.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function uy({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=l.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),l.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const dy=()=>{const{announceError:e}=gt();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},my=1e3,hy=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=gt(),o=n??!0,i=l.useRef(!1),c=l.useRef(void 0),u=l.useCallback(d=>{var h;const m=()=>{};d&&o&&(i.current=!0,c.current=e,e==null||e.startTyping().catch(m)),d||(i.current&&o&&((h=c.current)==null||h.endTyping().catch(m)),i.current=!1,c.current=void 0),s(d)},[e,s,o]);l.useLayoutEffect(()=>{s(i.current)},[r,s]),og(t,u,{enabled:o,idleMs:my})},gy=({enabled:e=!0,focusRoot:t})=>{const[n,r]=l.useState(!1),s=l.useRef(!1),o=l.useRef(!1);l.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const g=h;g.metaKey||g.altKey||g.ctrlKey||(s.current=!0)},m=()=>{s.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const i=l.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),c=l.useCallback(()=>{r(!1)},[]),u=l.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:i,onBlur:c}}},fy=v.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,py=v.default.div`display:flex;flex-shrink:0;position:relative;margin-block-start:8px;border-radius:12px;height:64px;img{border-radius:12px;object-fit:cover;width:64px;-webkit-user-drag:none;}&:hover button,&:focus-within button{opacity:1;}`,Ey=v.default.button`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;border:none;padding:0;opacity:${({$mobile:e})=>e?1:0};transition:opacity 0.12s ease-in-out;${ne.light`
414
414
  background-color: ${b.color.background50};
415
415
  `}
416
416
  ${ne.dark`
@@ -435,7 +435,7 @@ $2
435
435
  circle {
436
436
  stroke: ${b.themedColor.bg_50_600};
437
437
  }
438
- `,dy=()=>{const e=dn(),{conversation:t}=ue(),{files:n,removeFile:r,isFileUploadEnabled:s}=Ls();return s&&n.length>0?a.createElement(cy,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Ts,{name:c,mimeType:i,type:Jr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(ly,{key:u},a.createElement(uy,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(te,{type:"close-filled",color:b.themedColor.textMidEmphasis})),m)})):null},my={textArea:F.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},bc=S.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${ke}`,ii=S.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,ai=S.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,ci=S.default.textarea`all:unset;display:block;flex:1;min-width:0;padding-top:8px;padding-bottom:8px;padding-inline-start:16px;padding-inline-end:12px;box-sizing:border-box;font-size:14px;line-height:20px;color:${({theme:e})=>e.colors.messageInput.text};resize:none;width:100%;height:${_a}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${Da&&my.textArea};${({$focusVisible:e})=>e&&F.css`
438
+ `,_y=()=>{const e=dn(),{conversation:t}=ue(),{files:n,removeFile:r,isFileUploadEnabled:s}=ws();return s&&n.length>0?a.createElement(fy,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(As,{name:c,mimeType:i,type:Zr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(py,{key:u},a.createElement(Ey,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(te,{type:"close-filled",color:b.themedColor.textMidEmphasis})),m)})):null},Cy={textArea:F.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Ac=v.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${ke}`,ii=v.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,ai=v.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,ci=v.default.textarea`all:unset;display:block;flex:1;min-width:0;padding-top:8px;padding-bottom:8px;padding-inline-start:16px;padding-inline-end:12px;box-sizing:border-box;font-size:14px;line-height:20px;color:${({theme:e})=>e.colors.messageInput.text};resize:none;width:100%;height:${Sa}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${$a&&Cy.textArea};${({$focusVisible:e})=>e&&F.css`
439
439
  outline: 2px solid ${b.themedColor.primary};
440
440
  outline-offset: 2px;
441
441
  `}
@@ -452,17 +452,17 @@ $2
452
452
  }
453
453
 
454
454
  ${({$blocked:e})=>e&&F.css`cursor:not-allowed;&::placeholder{color:${b.themedColor.textDisabled};}`}
455
- `,hy=S.default.input`display:none;`;S.default.div`display:flex;align-items:center;gap:24px;`;const gy=S.default(bc)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${b.themedColor.bg_100_500};path{fill:${b.themedColor.textHighEmphasis};}}&:active{background-color:${b.themedColor.bg_200_400};}}`,li=S.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,ui=e=>e.startsWith("image/"),di=({disabled:e})=>{const{stringSet:t}=le(),{conversation:n}=ue(),{config:r}=me(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=Ls(),g=m.includes(xr),f=g?["image/*"]:m.filter(ui),p=g?[xr]:m.filter(L=>!ui(L)),v=r.conversation.input.gallery.photoEnabled,_=r.conversation.input.fileEnabled,E=()=>g||f.length>0,A=()=>g||p.length>0,y=L=>{const R=L.currentTarget.files;R&&u(Array.from(R)),L.target.value=""},T=()=>{c(!0)},I=l.useMemo(()=>{const L=[];return v&&L.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:f.join(","),inputRef:s,onSelect:()=>{if(!E()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var R;return(R=s.current)==null?void 0:R.click()},100)}}),_&&L.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!A()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var R;return(R=o.current)==null?void 0:R.click()},100)}}),L},[f,m,t,v,_]);if(!d)return null;const k={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(gy,{...k.attach.props,disabled:e,onClick:T},a.createElement(te,{type:"add",color:e?b.themedColor.textDisabled:b.color.primary.main,size:20}),k.attach.descriptionNode),I.map(L=>a.createElement(hy,{key:L.type,type:"file",ref:L.inputRef,multiple:L.type==="image",onChange:y,accept:L.accept})),a.createElement(pt,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},I.map(L=>a.createElement(pt.ActionItem,{key:L.type,onClick:L.onSelect,icon:L.icon},L.label))))},fy=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=le(),{conversation:s}=ue(),{rootElement:o}=me(),i=Et(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=ay({focusRoot:i}),{channelSource:m,messageSource:h,state:g}=Me(),{files:f,addFiles:p,clearFiles:v}=Ls(),_=sy(),{focusPolicy:E,disabled:A,disabledBy:y}=g.input,T=E==="preserve",I=E==="release",k=(()=>{if(!A)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(y){case"form_active":return r.FORM_PLACEHOLDER;case"ai_responding":return r.MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE;case"suggested_replies":return r.MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES;case"steward":return r.MESSAGE_INPUT__PLACE_HOLDER__STEWARD;case"system":return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED;case"reconnecting":return r.MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING;case"unavailable":case"conversation_closed":default:return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED}})();nE({onDropFiles:V=>{p(V)}}),ry({blurred:I,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),iy(m.channel,t,!A);const L=t.trim().length>0,R=f.length>0,M=!A&&(L||R),$={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},N=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},J=()=>{var V;d(),(V=e.current)==null||V.focus()},{requestRestore:se,cancelRestore:Y}=ny({elementRef:e,ready:T,onRestore:d}),j=V=>{Y(),_(V)},P=()=>{Y()},K=async V=>{try{await V(),P()}catch{j(e.current)}},q=async()=>{if(A)return;const V=t.trim();if(!V&&!f.length)return;const ee=[...f];if(se(),N(),J(),ee.length===0){await K(()=>h.sendUserMessage({message:V}));return}if(ee.length===1)await K(()=>h.sendFileMessage({message:V,file:ee[0].file}));else{const ae=ee.map(({file:O})=>({file:O}));await K(()=>h.sendMultipleFilesMessage({message:V,fileInfoList:ae}))}},W=V=>{const ee=Array.from(V.clipboardData.files);ee.length>0&&(V.preventDefault(),p(ee))},H=V=>{V.key!=="Enter"||V.nativeEvent.isComposing||V.shiftKey||(V.preventDefault(),q())},G=V=>{if(A){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const ee=Math.min(df,e.current.scrollHeight);_a<ee&&(e.current.style.height=`${ee}px`)}n(V.target.value)};return I?a.createElement(li,null,a.createElement(di,{disabled:!0}),a.createElement(ii,null,a.createElement(ai,null,a.createElement(ci,{rows:1,...$.input.props,disabled:!0,placeholder:k,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(li,{"data-message-composer":""},a.createElement(di,{disabled:A}),a.createElement(ii,null,a.createElement(dy,null),a.createElement(ai,null,a.createElement(ci,{ref:e,rows:1,...$.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:k,maxLength:5e3,$blocked:A,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:H,onChange:G,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:W}))),M&&a.createElement(bc,{...$.send.props,onClick:()=>q()},a.createElement(te,{type:"send",color:b.color.primary.main,size:20}),$.send.descriptionNode))},py=S.default.div`padding:8px 16px;text-align:center;word-break:break-word;white-space:pre-wrap;line-height:1.43;letter-spacing:-0.2px;font-size:14px;font-weight:400;color:${b.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${ne.light`
455
+ `,Sy=v.default.input`display:none;`;v.default.div`display:flex;align-items:center;gap:24px;`;const vy=v.default(Ac)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${b.themedColor.bg_100_500};path{fill:${b.themedColor.textHighEmphasis};}}&:active{background-color:${b.themedColor.bg_200_400};}}`,li=v.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,ui=e=>e.startsWith("image/"),di=({disabled:e})=>{const{stringSet:t}=le(),{conversation:n}=ue(),{config:r}=me(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=ws(),g=m.includes(Ir),f=g?["image/*"]:m.filter(ui),p=g?[Ir]:m.filter(L=>!ui(L)),C=r.conversation.input.gallery.photoEnabled,_=r.conversation.input.fileEnabled,E=()=>g||f.length>0,A=()=>g||p.length>0,y=L=>{const R=L.currentTarget.files;R&&u(Array.from(R)),L.target.value=""},T=()=>{c(!0)},I=l.useMemo(()=>{const L=[];return C&&L.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:f.join(","),inputRef:s,onSelect:()=>{if(!E()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var R;return(R=s.current)==null?void 0:R.click()},100)}}),_&&L.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!A()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var R;return(R=o.current)==null?void 0:R.click()},100)}}),L},[f,m,t,C,_]);if(!d)return null;const k={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(vy,{...k.attach.props,disabled:e,onClick:T},a.createElement(te,{type:"add",color:e?b.themedColor.textDisabled:b.color.primary.main,size:20}),k.attach.descriptionNode),I.map(L=>a.createElement(Sy,{key:L.type,type:"file",ref:L.inputRef,multiple:L.type==="image",onChange:y,accept:L.accept})),a.createElement(Et,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},I.map(L=>a.createElement(Et.ActionItem,{key:L.type,onClick:L.onSelect,icon:L.icon},L.label))))},by=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=le(),{conversation:s}=ue(),{rootElement:o}=me(),i=_t(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=gy({focusRoot:i}),{channelSource:m,messageSource:h,state:g}=Me(),{files:f,addFiles:p,clearFiles:C}=ws(),_=dy(),{focusPolicy:E,disabled:A,disabledBy:y}=g.input,T=E==="preserve",I=E==="release",k=(()=>{if(!A)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(y){case"form_active":return r.FORM_PLACEHOLDER;case"ai_responding":return r.MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE;case"suggested_replies":return r.MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES;case"steward":return r.MESSAGE_INPUT__PLACE_HOLDER__STEWARD;case"system":return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED;case"reconnecting":return r.MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING;case"unavailable":case"conversation_closed":default:return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED}})();lE({onDropFiles:z=>{p(z)}}),uy({blurred:I,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),hy(m.channel,t,!A);const L=t.trim().length>0,R=f.length>0,M=!A&&(L||R),$={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},N=()=>{e.current&&(e.current.value="",e.current.style.height=""),C(),n("")},Q=()=>{var z;d(),(z=e.current)==null||z.focus()},{requestRestore:se,cancelRestore:Y}=ly({elementRef:e,ready:T,onRestore:d}),j=z=>{Y(),_(z)},P=()=>{Y()},q=async z=>{try{await z(),P()}catch{j(e.current)}},W=async()=>{if(A)return;const z=t.trim();if(!z&&!f.length)return;const Z=[...f];if(se(),N(),Q(),Z.length===0){await q(()=>h.sendUserMessage({message:z}));return}if(Z.length===1)await q(()=>h.sendFileMessage({message:z,file:Z[0].file}));else{const ae=Z.map(({file:O})=>({file:O}));await q(()=>h.sendMultipleFilesMessage({message:z,fileInfoList:ae}))}},G=z=>{const Z=Array.from(z.clipboardData.files);Z.length>0&&(z.preventDefault(),p(Z))},H=z=>{z.key!=="Enter"||z.nativeEvent.isComposing||z.shiftKey||(z.preventDefault(),W())},V=z=>{if(A){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const Z=Math.min(_f,e.current.scrollHeight);Sa<Z&&(e.current.style.height=`${Z}px`)}n(z.target.value)};return I?a.createElement(li,null,a.createElement(di,{disabled:!0}),a.createElement(ii,null,a.createElement(ai,null,a.createElement(ci,{rows:1,...$.input.props,disabled:!0,placeholder:k,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(li,{"data-message-composer":""},a.createElement(di,{disabled:A}),a.createElement(ii,null,a.createElement(_y,null),a.createElement(ai,null,a.createElement(ci,{ref:e,rows:1,...$.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:k,maxLength:5e3,$blocked:A,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:H,onChange:V,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:G}))),M&&a.createElement(Ac,{...$.send.props,onClick:()=>W()},a.createElement(te,{type:"send",color:b.color.primary.main,size:20}),$.send.descriptionNode))},yy=v.default.div`padding:8px 16px;text-align:center;word-break:break-word;white-space:pre-wrap;line-height:1.43;letter-spacing:-0.2px;font-size:14px;font-weight:400;color:${b.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${ne.light`
456
456
  color: ${b.color.information.light};
457
457
  `};
458
458
  ${ne.dark`
459
459
  color: ${b.color.information.main};
460
460
  `};
461
461
  }
462
- `,Ey=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),_y=()=>{const{aiAgentInfo:e,userSession:t}=De(),{handlers:n}=me(),{messageSource:r,channelSource:s}=Me(),[o,i]=l.useState(null),c=fs("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>Ue(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(py,null,a.createElement(At,{fallback:e.specialNotice},a.createElement(Ey,{onClickLink:n.onClickLink},e.specialNotice)))},Cy=()=>a.createElement(Sy,null,a.createElement(_y,null),a.createElement(ty,null,a.createElement(fy,null))),Sy=S.default.div`z-index:0;border:none;width:100%;`,vy=()=>{var s;const{testerType:e}=Sc(),{channelSource:t}=Me(),n=$e(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(Jb,null):a.createElement(Cy,null)},yc=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(by,{...s},a.createElement(yy,null,n==="center"&&t&&a.createElement(Ay,{$sideWidth:Math.max(c,d)},a.createElement(Ty,null,t)),a.createElement(Iy,null,a.createElement(xy,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Ry,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(My,{ref:i},r))))},by=S.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${b.themedColor.textDisabled};`,yy=S.default.div`position:relative;height:56px;padding:11px 12px;`,Ay=S.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,Ty=S.default.div`max-width:100%;overflow:hidden;`,Iy=S.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,xy=S.default.div`flex-shrink:0;display:flex;align-items:center;`,My=S.default.div`flex-shrink:0;display:flex;align-items:center;`,Ry=S.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,zt=(e=16)=>dn()?e*1.5:e,ky=()=>{const{state:e}=me(),{messenger:t}=ue(),n=zt(),r=()=>{e.setOpened(!1)};return a.createElement(ot,{...t.closeButton().props,type:"close",size:n,onClick:r})},wy=()=>{const{enableCloseConversationButton:e,dispatcher:t}=me(),{channelSource:n}=Me(),{conversation:r}=ue(),s=n.channel,o=zt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!ts(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(ut.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(ot,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},Ly=()=>{const{state:e,enableExpandButton:t}=me(),{messenger:n}=ue(),r=zt();return t?a.createElement(ot,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Oy=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Yr,null,t,a.createElement(Py,{$position:n},a.createElement($y,{variant:"caption1"},e),a.createElement(Ny,{$position:n}))),Ny=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:b.themedColor.textHighEmphasis})),Dy={top:F.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:F.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Yr=S.default.div`position:relative;`,Py=S.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${It.TOOLTIP};${({$position:e})=>Dy[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Yr}:hover &,${Yr}:focus-within &{opacity:1;}`,$y=S.default(B)`padding:6px 8px;background:${b.themedColor.textHighEmphasis};color:${b.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Fy=2e3,mi=0,Uy=1500,In=Symbol("header-focus-status-pause"),hi="data-sb-header-focus-protected",By="[data-message-composer]",gi=new WeakMap,Tr=e=>{const t=gi.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return gi.set(e,n),n},Ir=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},kn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},Hy=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),kn(e)},Gy=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},zy=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(By),!1),Os=()=>{const{setStatusPauseState:e}=ht(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+Uy,o();const u=Tr(e);Ir(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(In,!0),kn(u),u.maxPauseTimeout=setTimeout(()=>{Hy(u),e(In,!1)},Fy)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=Tr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;Ir(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const f=d.ownerDocument.activeElement,p=f instanceof HTMLElement&&f.hasAttribute(hi);if(f===d||p||!zy(f))return;const v=Gy(d);d.focus({preventScroll:!0}),v()},mi)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(kn(m),e(In,!1))},mi))},[o,e]);return l.useEffect(()=>()=>{const u=Tr(e);n.current=!1,o(),Ir(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(kn(u),e(In,!1))},[o,e]),{[hi]:"true",onFocus:i,onBlur:c}},Vy=()=>{const{logger:e}=me(),{stringSet:t}=le(),{channelSource:n}=Me(),{conversation:r}=ue(),s=n.channel,o=zt(),i=fs("handoff-button",s),c=!ts(s)||dt(s),[u,d]=l.useState(!1),m=Os(),h=async()=>{d(!1);try{const f=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",f)}catch(f){e.error("conversation.handleAgentHandoff: error",f)}};if(!i)return null;const g={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(Oy,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(ot,{...g.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),g.handoff.descriptionNode),a.createElement(St,{portalContainerId:Ae.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ks,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},Ky=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),qy=()=>{const{logger:e,_aiAgentSDK:t}=me(),{stringSet:n}=le(),{memoryInfo:r,sdkUser:s}=De(),{actions:o}=Me(),{conversation:i}=ue(),c=zt(20),u=Os(),[d,m]=l.useState(null),[h,g]=l.useState(!1),f=l.useRef(!1);if(l.useEffect(()=>{s&&(r!=null&&r.consentDialog)&&m({...r})},[s,r==null?void 0:r.consentDialog]),!s||!r)return null;const p=i.header.memoryIndicator(r.enabled),v=(A,y,T)=>{t.liveMetricManager.track({type:"memory",variant:A,action:y,deleteOnOff:T})},_=()=>m(null),E=async A=>{if(!f.current){f.current=!0,g(!1);try{await o.setUserMemoryState({enabled:A}),_()}catch(y){e.error("memoryIndicator.setUserMemoryState: error",y),g(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,r.showIndicator&&a.createElement(a.Fragment,null,a.createElement(Xy,{...p.props,as:"button",type:"button",onClick:()=>m({...r}),...u,$size:c},a.createElement(te,{type:"memory",size:c,color:b.themedColor.textHighEmphasis}),a.createElement(Zy,{$enabled:r.enabled})),p.descriptionNode),d&&a.createElement(Wy,{memoryInfo:d,onClose:_,onSetEnabled:E,trackMemory:v}),a.createElement(mn,{visible:h,title:n.PLACE_HOLDER__WRONG,description:n.MEMORY__ERROR_MESSAGE,onClose:()=>g(!1)}))},Wy=({memoryInfo:e,onClose:t,onSetEnabled:n,trackMemory:r})=>{var E;const{stringSet:s}=le(),{colors:o}=F.useTheme(),i=l.useId(),c=l.useId(),u=lm(e),d=u==="consent",m=l.useRef(!1),h=l.useRef(!1),g=A=>{A!=="shown"&&(h.current=!0),r(u,A,e.deleteOnOff)};l.useEffect(()=>{m.current||(m.current=!0,g("shown"))},[]);const f=()=>{h.current||g("dismiss"),t()},p={consent:{body:((E=e.consentDialog)==null?void 0:E.body)??"",negativeText:s.MEMORY__BUTTON_DONT_USE,positiveText:s.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:s.MEMORY__DESC_ON,negativeText:e.deleteOnOff?s.MEMORY__BUTTON_DISABLE_AND_DELETE:s.MEMORY__BUTTON_DISABLE,positiveText:s.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:s.MEMORY__DESC_OFF,negativeText:s.MEMORY__BUTTON_ENABLE,positiveText:s.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?s.MEMORY__DESC_ON:s.MEMORY__DESC_OFF,negativeText:void 0,positiveText:s.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[u],{onCancel:v}=p,_=o.memoryDialog;return a.createElement(St,{visible:!0,portalContainerId:Ae.WINDOW,onClose:f,cancelable:!d,"aria-labelledby":i,"aria-describedby":c},a.createElement(ks,{title:s.MEMORY__DIALOG_TITLE,titleId:i,description:a.createElement(Yy,null,p.body),descriptionId:c,negativeText:p.negativeText,positiveText:p.positiveText,buttonLayout:d?"horizontal":"vertical-full-width",onCancel:v&&(()=>{g("cancel"),v()}),onConfirm:()=>{g("confirm"),p.onConfirm()},styles:{titleColor:_.titleText,positiveBackground:_.positiveBackground,positiveText:_.positiveText,positiveBorderColor:_.positiveBorderColor,negativeBackground:_.negativeBackground,negativeText:_.negativeText,negativeBorderColor:_.negativeBorderColor}}))},Yy=({children:e})=>{const{handlers:t}=me();return a.createElement(Jy,null,a.createElement(At,{fallback:e},a.createElement(Ky,{onClickLink:t.onClickLink},e)))},jy=F.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,Xy=S.default.button`${jy};cursor:pointer;${ke}`,Zy=S.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?b.themedColor.secondary:b.color.background300};box-shadow:0 0 0 2px ${b.color.background50};${ne.dark`
462
+ `,Ay=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),Ty=()=>{const{aiAgentInfo:e,userSession:t}=De(),{handlers:n}=me(),{messageSource:r,channelSource:s}=Me(),[o,i]=l.useState(null),c=gs("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>Ue(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(yy,{"data-testid":"sb-special-notice"},a.createElement(At,{fallback:e.specialNotice},a.createElement(Ay,{onClickLink:n.onClickLink},e.specialNotice)))},Iy=()=>a.createElement(xy,null,a.createElement(Ty,null),a.createElement(cy,null,a.createElement(by,null))),xy=v.default.div`z-index:0;border:none;width:100%;`,My=()=>{var s;const{testerType:e}=bc(),{channelSource:t}=Me(),n=$e(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(oy,null):a.createElement(Iy,null)},Tc=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(Ry,{...s},a.createElement(ky,null,n==="center"&&t&&a.createElement(wy,{$sideWidth:Math.max(c,d)},a.createElement(Ly,null,t)),a.createElement(Oy,null,a.createElement(Ny,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Py,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Dy,{ref:i},r))))},Ry=v.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${b.themedColor.textDisabled};`,ky=v.default.div`position:relative;height:56px;padding:11px 12px;`,wy=v.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,Ly=v.default.div`max-width:100%;overflow:hidden;`,Oy=v.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Ny=v.default.div`flex-shrink:0;display:flex;align-items:center;`,Dy=v.default.div`flex-shrink:0;display:flex;align-items:center;`,Py=v.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,zt=(e=16)=>dn()?e*1.5:e,$y=()=>{const{state:e}=me(),{messenger:t}=ue(),n=zt(),r=()=>{e.setOpened(!1)};return a.createElement(ot,{...t.closeButton().props,type:"close",size:n,onClick:r})},Fy=()=>{const{enableCloseConversationButton:e,dispatcher:t}=me(),{channelSource:n}=Me(),{conversation:r}=ue(),s=n.channel,o=zt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!es(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(ut.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(ot,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},Uy=()=>{const{state:e,enableExpandButton:t}=me(),{messenger:n}=ue(),r=zt();return t?a.createElement(ot,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},By=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Wr,null,t,a.createElement(zy,{$position:n},a.createElement(Vy,{variant:"caption1"},e),a.createElement(Hy,{$position:n}))),Hy=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:b.themedColor.textHighEmphasis})),Gy={top:F.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:F.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Wr=v.default.div`position:relative;`,zy=v.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${It.TOOLTIP};${({$position:e})=>Gy[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Wr}:hover &,${Wr}:focus-within &{opacity:1;}`,Vy=v.default(B)`padding:6px 8px;background:${b.themedColor.textHighEmphasis};color:${b.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Ky=2e3,mi=0,qy=1500,In=Symbol("header-focus-status-pause"),hi="data-sb-header-focus-protected",Wy="[data-message-composer]",gi=new WeakMap,Ar=e=>{const t=gi.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return gi.set(e,n),n},Tr=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},kn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},Yy=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),kn(e)},jy=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},Xy=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(Wy),!1),Ls=()=>{const{setStatusPauseState:e}=gt(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+qy,o();const u=Ar(e);Tr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(In,!0),kn(u),u.maxPauseTimeout=setTimeout(()=>{Yy(u),e(In,!1)},Ky)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=Ar(e),h=d instanceof HTMLElement&&Date.now()<=r.current;Tr(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const f=d.ownerDocument.activeElement,p=f instanceof HTMLElement&&f.hasAttribute(hi);if(f===d||p||!Xy(f))return;const C=jy(d);d.focus({preventScroll:!0}),C()},mi)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(kn(m),e(In,!1))},mi))},[o,e]);return l.useEffect(()=>()=>{const u=Ar(e);n.current=!1,o(),Tr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(kn(u),e(In,!1))},[o,e]),{[hi]:"true",onFocus:i,onBlur:c}},Zy=()=>{const{logger:e}=me(),{stringSet:t}=le(),{channelSource:n}=Me(),{conversation:r}=ue(),s=n.channel,o=zt(),i=gs("handoff-button",s),c=!es(s)||dt(s),[u,d]=l.useState(!1),m=Ls(),h=async()=>{d(!1);try{const f=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",f)}catch(f){e.error("conversation.handleAgentHandoff: error",f)}};if(!i)return null;const g={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(By,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(ot,{...g.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),g.handoff.descriptionNode),a.createElement(St,{portalContainerId:Ae.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(Rs,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},Jy=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),Qy=()=>{const{logger:e,_aiAgentSDK:t}=me(),{stringSet:n}=le(),{memoryInfo:r,sdkUser:s}=De(),{actions:o}=Me(),{conversation:i}=ue(),c=zt(20),u=Ls(),[d,m]=l.useState(null),[h,g]=l.useState(!1),f=l.useRef(!1);if(l.useEffect(()=>{s&&(r!=null&&r.consentDialog)&&m({...r})},[s,r==null?void 0:r.consentDialog]),!s||!r)return null;const p=i.header.memoryIndicator(r.enabled),C=(A,y,T)=>{t.liveMetricManager.track({type:"memory",variant:A,action:y,deleteOnOff:T})},_=()=>m(null),E=async A=>{if(!f.current){f.current=!0,g(!1);try{await o.setUserMemoryState({enabled:A}),_()}catch(y){e.error("memoryIndicator.setUserMemoryState: error",y),g(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,r.showIndicator&&a.createElement(a.Fragment,null,a.createElement(rA,{...p.props,as:"button",type:"button",onClick:()=>m({...r}),...u,$size:c},a.createElement(te,{type:"memory",size:c,color:b.themedColor.textHighEmphasis}),a.createElement(sA,{$enabled:r.enabled})),p.descriptionNode),d&&a.createElement(eA,{memoryInfo:d,onClose:_,onSetEnabled:E,trackMemory:C}),a.createElement(mn,{visible:h,title:n.PLACE_HOLDER__WRONG,description:n.MEMORY__ERROR_MESSAGE,onClose:()=>g(!1)}))},eA=({memoryInfo:e,onClose:t,onSetEnabled:n,trackMemory:r})=>{var E;const{stringSet:s}=le(),{colors:o}=F.useTheme(),i=l.useId(),c=l.useId(),u=hm(e),d=u==="consent",m=l.useRef(!1),h=l.useRef(!1),g=A=>{A!=="shown"&&(h.current=!0),r(u,A,e.deleteOnOff)};l.useEffect(()=>{m.current||(m.current=!0,g("shown"))},[]);const f=()=>{h.current||g("dismiss"),t()},p={consent:{body:((E=e.consentDialog)==null?void 0:E.body)??"",negativeText:s.MEMORY__BUTTON_DONT_USE,positiveText:s.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:s.MEMORY__DESC_ON,negativeText:e.deleteOnOff?s.MEMORY__BUTTON_DISABLE_AND_DELETE:s.MEMORY__BUTTON_DISABLE,positiveText:s.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:s.MEMORY__DESC_OFF,negativeText:s.MEMORY__BUTTON_ENABLE,positiveText:s.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?s.MEMORY__DESC_ON:s.MEMORY__DESC_OFF,negativeText:void 0,positiveText:s.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[u],{onCancel:C}=p,_=o.memoryDialog;return a.createElement(St,{visible:!0,portalContainerId:Ae.WINDOW,onClose:f,cancelable:!d,"aria-labelledby":i,"aria-describedby":c},a.createElement(Rs,{title:s.MEMORY__DIALOG_TITLE,titleId:i,description:a.createElement(tA,null,p.body),descriptionId:c,negativeText:p.negativeText,positiveText:p.positiveText,buttonLayout:d?"horizontal":"vertical-full-width",onCancel:C&&(()=>{g("cancel"),C()}),onConfirm:()=>{g("confirm"),p.onConfirm()},styles:{titleColor:_.titleText,positiveBackground:_.positiveBackground,positiveText:_.positiveText,positiveBorderColor:_.positiveBorderColor,negativeBackground:_.negativeBackground,negativeText:_.negativeText,negativeBorderColor:_.negativeBorderColor}}))},tA=({children:e})=>{const{handlers:t}=me();return a.createElement(oA,null,a.createElement(At,{fallback:e},a.createElement(Jy,{onClickLink:t.onClickLink},e)))},nA=F.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,rA=v.default.button`${nA};cursor:pointer;${ke}`,sA=v.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?b.themedColor.secondary:b.color.background300};box-shadow:0 0 0 2px ${b.color.background50};${ne.dark`
463
463
  box-shadow: 0 0 0 2px ${b.color.background500};
464
464
  `}
465
- `,Jy=S.default.div`color:${({theme:e})=>e.colors.memoryDialog.markdownBodyText};line-height:20px;word-break:break-word;&& a{color:${({theme:e})=>e.colors.memoryDialog.markdownLinkText};font-weight:inherit;text-decoration:underline;}`,Qy=()=>{const{conversation:e}=ue(),{onNavigateToConversationList:t}=Me();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(ot,{...n.menu.props,...da,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Ac=({channel:e,size:t=40,skeletonColor:n=b.themedColor.bg_100_500})=>{const{userSession:r,aiAgentInfo:s}=De(),{fallbackIcon:o,url:i}=ps({channel:e,aiAgentInfo:s,userSession:r}),[c,u]=l.useState();c&&c.url!==i&&u(void 0);const d=F.useTheme(),{primary:m,primaryContrastContent:h}=d.colors.base;if(!o)return a.createElement(fi,{"aria-hidden":"true",$size:t,$bgColor:n});if(i&&(c==null?void 0:c.status)!=="failed"){const g=(c==null?void 0:c.status)==="loaded"?m:n;return a.createElement(ec,{src:i,size:t,"aria-hidden":"true",onImageError:f=>u({url:f,status:"failed"}),onImageLoad:f=>u({url:f,status:"loaded"}),backgroundColor:g})}return a.createElement(fi,{"aria-hidden":"true",$size:t,$bgColor:m},a.createElement(te,{type:o,size:t*.55,color:h}))},fi=S.default.div`width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;border-radius:50%;background-color:${({$bgColor:e})=>e};display:flex;align-items:center;justify-content:center;flex-shrink:0;`,eA=e=>{const{channelSource:t}=Me(),{aiAgentInfo:n,userSession:r}=De(),{conversation:s}=ue(),{config:o}=Ie(),{announcementsEnabled:i}=ht(),c=F.useTheme(),u=t.channel,d=ps({channel:u,userSession:r,aiAgentInfo:n}),m=e.title??d.title,h=o.conversation.header.avatarEnabled,g=Os(),f=Va({enabled:i,label:m}),p={title:s.header.title(m,{active:f.enabled,titleId:f.id,initialFocus:!1})};return a.createElement(tA,null,h&&a.createElement(Ac,{channel:u,size:34,skeletonColor:c.colors.conversation.headerProfileSkeleton}),a.createElement(nA,{...p.title.props,...g},m))},tA=S.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,nA=S.default(B).attrs({variant:"h2",color:b.themedColor.textHighEmphasis})`
465
+ `,oA=v.default.div`color:${({theme:e})=>e.colors.memoryDialog.markdownBodyText};line-height:20px;word-break:break-word;&& a{color:${({theme:e})=>e.colors.memoryDialog.markdownLinkText};font-weight:inherit;text-decoration:underline;}`,iA=()=>{const{conversation:e}=ue(),{onNavigateToConversationList:t}=Me();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(ot,{...n.menu.props,...ha,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Ic=({channel:e,size:t=40,skeletonColor:n=b.themedColor.bg_100_500})=>{const{userSession:r,aiAgentInfo:s}=De(),{fallbackIcon:o,url:i}=fs({channel:e,aiAgentInfo:s,userSession:r}),[c,u]=l.useState();c&&c.url!==i&&u(void 0);const d=F.useTheme(),{primary:m,primaryContrastContent:h}=d.colors.base;if(!o)return a.createElement(fi,{"aria-hidden":"true",$size:t,$bgColor:n});if(i&&(c==null?void 0:c.status)!=="failed"){const g=(c==null?void 0:c.status)==="loaded"?m:n;return a.createElement(nc,{src:i,size:t,"aria-hidden":"true",onImageError:f=>u({url:f,status:"failed"}),onImageLoad:f=>u({url:f,status:"loaded"}),backgroundColor:g})}return a.createElement(fi,{"aria-hidden":"true",$size:t,$bgColor:m},a.createElement(te,{type:o,size:t*.55,color:h}))},fi=v.default.div`width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;border-radius:50%;background-color:${({$bgColor:e})=>e};display:flex;align-items:center;justify-content:center;flex-shrink:0;`,aA=e=>{const{channelSource:t}=Me(),{aiAgentInfo:n,userSession:r}=De(),{conversation:s}=ue(),{config:o}=Te(),{announcementsEnabled:i}=gt(),c=F.useTheme(),u=t.channel,d=fs({channel:u,userSession:r,aiAgentInfo:n}),m=e.title??d.title,h=o.conversation.header.avatarEnabled,g=Ls(),f=qa({enabled:i,label:m}),p={title:s.header.title(m,{active:f.enabled,titleId:f.id,initialFocus:!1})};return a.createElement(cA,null,h&&a.createElement(Ic,{channel:u,size:34,skeletonColor:c.colors.conversation.headerProfileSkeleton}),a.createElement(lA,{...p.title.props,...g},m))},cA=v.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,lA=v.default(B).attrs({variant:"h2",color:b.themedColor.textHighEmphasis})`
466
466
  margin: 0;
467
467
  flex: 1;
468
468
  min-width: 0;
@@ -474,10 +474,10 @@ $2
474
474
  &:focus {
475
475
  outline: none;
476
476
  }
477
- `,rA=e=>{const{components:t}=Mt.useContext();return a.createElement(yc,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:ga})},sA=()=>{const{components:e}=Mt.useContext();return a.createElement(e.MenuButton,null)},oA=()=>{const{components:e}=Mt.useContext();return a.createElement(e.Title,null)},iA=()=>{const{components:e}=Mt.useContext();return a.createElement(cA,null,a.createElement(e.MemoryIndicator,null),a.createElement(e.HandoffButton,null),a.createElement(e.ConversationCloseButton,null),a.createElement(e.ExpandButton,null),a.createElement(e.CloseButton,null))},Mt=Qe({template:rA,components:{StartArea:sA,TitleArea:oA,EndArea:iA,MenuButton:Qy,Title:eA,MemoryIndicator:qy,HandoffButton:Vy,ConversationCloseButton:wy,ExpandButton:Ly,CloseButton:ky}}),aA=()=>{const{Template:e}=Mt.useContext();return a.createElement(e,{titleAlign:"start"})},cA=S.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Tc=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,announcementsEnabled:c=!0,conversationStatsEnabled:u,initialFocusTarget:d,style:m,closedChannelUrl:h,onClearClosedChannelUrl:g})=>{const{Template:f}=nr.useContext();return a.createElement(Ha,{onNavigateToConversationList:t,channelUrl:n??h,onClearChannelUrl:r??g,conversationStatsEnabled:u,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i},a.createElement(Gr,null,a.createElement(Gr.Consumer,null,p=>a.createElement(sp,{announcementsEnabled:c},a.createElement(lA,null),a.createElement(uA,null),a.createElement(dA,{style:m,dragHandlers:p,initialFocusTarget:d},a.createElement(f,null)),e))))},lA=()=>(iE(),null),uA=()=>(SE(),dE(),EE(),null),dA=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return oE(s,n),a.createElement(hA,{ref:s,style:e,...t},r)},mA=e=>{const{components:t}=nr.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},nr=Qe({template:mA,components:{Header:aA,Body:$b,Footer:vy}}),hA=S.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Ic=ye("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:Ee}),gA=Ic.Provider,Ns=Ic.useContext,fA=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=Ss(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(gA,{value:s},e)},{Provider:pA,Context:EA,useContext:gn}=ye("ConversationList");function xc({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=Ee,children:s}){return a.createElement(Nh,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(pA,{value:{...o,onOpenConversationView:r}},s))}const _A=e=>{const{announcementsEnabled:t}=Ns(),{listSource:n}=gn(),r=Aa();Ka(e,{enabled:t,ready:n.initialized,suppressed:r})},CA=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=Ns(),{listSource:n}=gn(),r=l.useRef(!1);l.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const s=n.channels.length,o=setTimeout(()=>{e({screen:"conversationList",conversationCount:s}),r.current=!0},0);return()=>clearTimeout(o)},[e,t,n.initialized])},SA=({channel:e})=>a.createElement(Ac,{channel:e}),jr=99,vA=e=>{var _,E;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=le(),{userSession:o,aiAgentInfo:i}=De(),{conversationList:c}=ue(),u=ps({channel:t,userSession:o,aiAgentInfo:i}),d=nm(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=sm(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),h=t.unreadMessageCount,g=(_=t.lastMessage)!=null&&_.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,f=$e(t)?r.CONVERSATION_LIST__ENDED:"",p=n?()=>n():void 0,v=c.item({agent:g,status:f,lastMessage:d,time:m,unreadCount:h,onActivate:p});return a.createElement(bA,{"data-testid":"sb-conversation-list-item",$clickable:!!p,...v.props},a.createElement(yA,null,a.createElement(SA,{...e})),a.createElement(AA,null,a.createElement(TA,null,(E=t.lastMessage)!=null&&E.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(Za,{variant:"subtitle1",color:b.themedColor.textHighEmphasis},d):a.createElement(B,{variant:"subtitle1",color:b.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(IA,null,$e(t)&&a.createElement(a.Fragment,null,a.createElement(B,{variant:"caption1",color:b.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(xA,null)),a.createElement(B,{variant:"caption2",color:b.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(MA,{$count:h},a.createElement(B,{variant:"caption3",color:b.themedColor.textHighEmphasisInverse},h<=jr?h:`${jr}+`))),v.descriptionNode)},Ds=Qe({template:vA,components:{}}),bA=S.default.div`display:flex;flex-shrink:0;flex-direction:row;align-items:center;position:relative;width:100%;height:72px;box-sizing:border-box;gap:16px;cursor:${({$clickable:e})=>e?"pointer":"default"};`,yA=S.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,AA=S.default.div`display:flex;flex-direction:row;align-items:center;flex:1;min-width:0;padding-inline-end:16px;height:100%;gap:8px;border-bottom:1px solid ${b.themedColor.textDisabled};`,TA=S.default.div`display:flex;flex-direction:column;justify-content:center;flex:1;min-width:0;gap:4px;word-break:break-word;overflow-wrap:break-word;`,IA=S.default.div`display:flex;align-items:center;gap:6px;`,xA=S.default.div`width:2px;height:2px;border-radius:1px;background-color:${b.themedColor.textLowEmphasis};`,MA=S.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${b.themedColor.error};${({$count:e})=>e<=jr&&F.css`
477
+ `,uA=e=>{const{components:t}=Mt.useContext();return a.createElement(Tc,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:pa})},dA=()=>{const{components:e}=Mt.useContext();return a.createElement(e.MenuButton,null)},mA=()=>{const{components:e}=Mt.useContext();return a.createElement(e.Title,null)},hA=()=>{const{components:e}=Mt.useContext();return a.createElement(fA,null,a.createElement(e.MemoryIndicator,null),a.createElement(e.HandoffButton,null),a.createElement(e.ConversationCloseButton,null),a.createElement(e.ExpandButton,null),a.createElement(e.CloseButton,null))},Mt=Qe({template:uA,components:{StartArea:dA,TitleArea:mA,EndArea:hA,MenuButton:iA,Title:aA,MemoryIndicator:Qy,HandoffButton:Zy,ConversationCloseButton:Fy,ExpandButton:Uy,CloseButton:$y}}),gA=()=>{const{Template:e}=Mt.useContext();return a.createElement(e,{titleAlign:"start"})},fA=v.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,xc=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,announcementsEnabled:c=!0,conversationStatsEnabled:u,initialFocusTarget:d,style:m,closedChannelUrl:h,onClearClosedChannelUrl:g})=>{const{Template:f}=nr.useContext();return a.createElement(za,{onNavigateToConversationList:t,channelUrl:n??h,onClearChannelUrl:r??g,conversationStatsEnabled:u,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i},a.createElement(Hr,null,a.createElement(Hr.Consumer,null,p=>a.createElement(dp,{announcementsEnabled:c},a.createElement(pA,null),a.createElement(EA,null),a.createElement(_A,{style:m,dragHandlers:p,initialFocusTarget:d},a.createElement(f,null)),e))))},pA=()=>(hE(),null),EA=()=>(xE(),_E(),AE(),null),_A=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return mE(s,n),a.createElement(SA,{ref:s,style:e,...t},r)},CA=e=>{const{components:t}=nr.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},nr=Qe({template:CA,components:{Header:gA,Body:Vb,Footer:My}}),SA=v.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Mc=ye("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:Ee}),vA=Mc.Provider,Os=Mc.useContext,bA=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=Cs(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(vA,{value:s},e)},{Provider:yA,Context:AA,useContext:gn}=ye("ConversationList");function Rc({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=Ee,children:s}){return a.createElement(Uh,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(yA,{value:{...o,onOpenConversationView:r}},s))}const TA=e=>{const{announcementsEnabled:t}=Os(),{listSource:n}=gn(),r=Ia();Wa(e,{enabled:t,ready:n.initialized,suppressed:r})},IA=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=Os(),{listSource:n}=gn(),r=l.useRef(!1);l.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const s=n.channels.length,o=setTimeout(()=>{e({screen:"conversationList",conversationCount:s}),r.current=!0},0);return()=>clearTimeout(o)},[e,t,n.initialized])},xA=({channel:e})=>a.createElement(Ic,{channel:e}),Yr=99,MA=e=>{var _,E;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=le(),{userSession:o,aiAgentInfo:i}=De(),{conversationList:c}=ue(),u=fs({channel:t,userSession:o,aiAgentInfo:i}),d=im(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=cm(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),h=t.unreadMessageCount,g=(_=t.lastMessage)!=null&&_.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,f=$e(t)?r.CONVERSATION_LIST__ENDED:"",p=n?()=>n():void 0,C=c.item({agent:g,status:f,lastMessage:d,time:m,unreadCount:h,onActivate:p});return a.createElement(RA,{"data-testid":"sb-conversation-list-item",$clickable:!!p,...C.props},a.createElement(kA,null,a.createElement(xA,{...e})),a.createElement(wA,null,a.createElement(LA,null,(E=t.lastMessage)!=null&&E.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(Qa,{"data-testid":"sb-conversation-list-item-preview",variant:"subtitle1",color:b.themedColor.textHighEmphasis},d):a.createElement(B,{"data-testid":"sb-conversation-list-item-preview",variant:"subtitle1",color:b.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(OA,null,$e(t)&&a.createElement(a.Fragment,null,a.createElement(B,{"data-testid":"sb-conversation-list-item-ended",variant:"caption1",color:b.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(NA,null)),a.createElement(B,{"data-testid":"sb-conversation-list-item-time",variant:"caption2",color:b.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(DA,{"data-testid":"sb-conversation-list-item-unread-badge",$count:h},a.createElement(B,{variant:"caption3",color:b.themedColor.textHighEmphasisInverse},h<=Yr?h:`${Yr}+`))),C.descriptionNode)},Ns=Qe({template:MA,components:{}}),RA=v.default.div`display:flex;flex-shrink:0;flex-direction:row;align-items:center;position:relative;width:100%;height:72px;box-sizing:border-box;gap:16px;cursor:${({$clickable:e})=>e?"pointer":"default"};`,kA=v.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,wA=v.default.div`display:flex;flex-direction:row;align-items:center;flex:1;min-width:0;padding-inline-end:16px;height:100%;gap:8px;border-bottom:1px solid ${b.themedColor.textDisabled};`,LA=v.default.div`display:flex;flex-direction:column;justify-content:center;flex:1;min-width:0;gap:4px;word-break:break-word;overflow-wrap:break-word;`,OA=v.default.div`display:flex;align-items:center;gap:6px;`,NA=v.default.div`width:2px;height:2px;border-radius:1px;background-color:${b.themedColor.textLowEmphasis};`,DA=v.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${b.themedColor.error};${({$count:e})=>e<=Yr&&F.css`
478
478
  width: 20px;
479
479
  `}
480
- `,RA=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=i=>{const c=i.target;c.scrollHeight-c.scrollTop-c.clientHeight<=2&&(n==null||n())};return a.createElement(kA,{role:r,"aria-label":s,onScroll:i=>o(i)},e.map((i,c)=>{const u=t(i,c);if(r!=="list")return u;const d=l.isValidElement(u)&&u.key!=null?u.key:c;return a.createElement(wA,{key:d,role:"listitem"},u)}))},kA=S.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,wA=S.default.div`flex-shrink:0;`,LA=()=>{const{stringSet:e}=le(),{listSource:t,onOpenConversationView:n}=gn(),{Template:r}=Ds.useContext();return t.initialized?t.channels.length===0?a.createElement(tn,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(RA,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:s=>{var o,i,c;return a.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,$e(s)?"closed":"open"),channelUrl:s.url,title:(i=(o=s.conversation)==null?void 0:o.topics)==null?void 0:i.join(", "),lastMessageTimestamp:(c=s.lastMessage)==null?void 0:c.createdAt})},onEndReached:()=>{t.loadMore()}}):a.createElement(tn,{type:"loading"})},OA=()=>{const{stringSet:e}=le(),{_aiAgentSDK:t}=Ie(),{language:n,countryCode:r,context:s}=me(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=De(),{onOpenConversationView:u}=gn(),{conversationList:d}=ue(),m=async()=>{var h;if(o.isMultipleActiveConversationsEnabled){const g=await c({aiAgentId:o.userId,language:n,country:r,context:s});(h=t.session)==null||h._updateActiveChannel({url:g,status:"open"}),u(g,"open",{initialFocusTarget:"messageInput"})}else{const g=await i();u(g,"open",{initialFocusTarget:"messageInput"})}};return a.createElement(NA,{...d.footer.button({onActivate:m}).props},a.createElement(DA,{variant:"h1"},e.TALK_TO_AGENT))},NA=S.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,DA=S.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,PA=()=>{const{state:e}=me(),{messenger:t}=ue(),n=zt(),r=()=>{e.setOpened(!1)};return a.createElement(ot,{...t.closeButton().props,type:"close",size:n,onClick:r})},$A=()=>{const{stringSet:e}=le(),{announcementsEnabled:t}=Ns(),{conversationList:n}=ue(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=Va({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(FA,{forwardedAs:"h2",variant:"h2",color:b.themedColor.textHighEmphasis,...o.title.props},r)},FA=S.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,UA=e=>{const{components:t}=Vt.useContext();return a.createElement(yc,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:ga})},BA=()=>null,HA=()=>{const{components:e}=Vt.useContext();return a.createElement(e.Title,null)},GA=()=>{const{components:e}=Vt.useContext();return a.createElement(e.CloseButton,null)},Vt=Qe({template:UA,components:{StartArea:BA,TitleArea:HA,EndArea:GA,Title:$A,CloseButton:PA}}),zA=()=>{const{Template:e}=Vt.useContext();return a.createElement(e,{titleAlign:"start"})},VA=()=>(CA(),null),Mc=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=rr.useContext();return a.createElement(xc,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(fA,{announcementsEnabled:s},a.createElement(VA,null),a.createElement(KA,{style:i},a.createElement(c,null)),n))},KA=({style:e,children:t})=>{const n=l.useRef(null);return _A(n),a.createElement(WA,{ref:n,style:e},t)},qA=()=>{const{components:e}=rr.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},rr=Qe({template:qA,components:{Header:zA,Body:LA,Footer:OA}}),WA=S.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,YA=F.css`:where(#${Ae.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,jA=[YA,wf,Lf],XA=(e,...t)=>F.createGlobalStyle(e,...jA,...t),ZA=XA``,JA=tm(nr,_t,Gt,Qn,tr,rr,Mt,Ds,Vt,er,Xn),QA=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Rc({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){Zf(QA?_f:"",t);const[g,f]=l.useState(null),p=l.useCallback(E=>{f(A=>A===E?A:E)},[]),v=m??g,_=a.createElement(F.StyleSheetManager,{target:t},a.createElement(Yf,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(bf,{rootElement:t,boundaryElement:v},a.createElement(Fh,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(kf,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(qf,{icons:u},a.createElement(JA,null,a.createElement(Sf,{entryElement:v,modalRootElement:h,rootElement:t},i),a.createElement(ZA,null))))))));return m?_:a.createElement("div",{ref:p,style:{display:"contents"}},_)}const eT=()=>{const[e,t]=l.useState(null),[n,r]=l.useState(null),s=l.useCallback(i=>{t(c=>c===i?c:i)},[]),o=l.useCallback(i=>{r(c=>c===i?c:i)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},Ps=l.forwardRef(function({rootElement:t=document.body,logLevel:n=_e.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var _,E,A;Jt.level!==n&&(Jt.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:g,setModalRootElement:f}=eT();Xf("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const p=va(r),v=ba.has(p)?p:un;return a.createElement("div",{ref:g,id:Ae.ENTRY,lang:v,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(Rc,{logger:Jt,rootElement:t,appearance:(_=u.agentPreviewConfigs)==null?void 0:_.appearance,stringSet:u.stringSet,language:v,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(kp,{rootElement:t,language:r,logger:Jt,dispatcher:kc,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(E=u.agentPreviewConfigs)==null?void 0:E.forceCreateChannel,_agentVersion:(A=u.agentPreviewConfigs)==null?void 0:A.agentVersion,...u},a.createElement(Fp,{ref:d,userSessionInfo:s},a.createElement(Wb,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(np,null,o))))),a.createElement("div",{ref:f,id:Ae.MODAL_ROOT,dir:u.dir}))}),Jt=new Ni(_e.LogLevel.WARN),kc=new wi(Jt),zn=()=>{const[e,t]=l.useState(null),n=l.useCallback(r=>t(()=>r),[]);return[e,n]},{Provider:tT,useContext:fn}=ye("PageChildren"),wc=({children:e})=>{const[t,n]=zn(),[r,s]=zn(),[o,i]=l.useState(null),[c,u]=l.useState(null);return a.createElement(tT,{value:{conversationComponent:t,setConversationComponent:n,conversationChildren:o,setConversationChildren:i,conversationListComponent:r,setConversationListComponent:s,conversationListChildren:c,setConversationListChildren:u}},e)},nT=48,rT=2/3,pi=12;function Lc({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:i,imageUrl:c,dir:u,animated:d=!0,backgroundColor:m,size:h=nT,hasUnread:g=!1}){const f=nc(),p=d&&!f,v=Dr(m),_=Math.round(h*rT);return a.createElement(iT,{dir:u,id:Ae.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:p,$backgroundColor:m,$prefersReducedMotion:f,$size:h},a.createElement(aT,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:_,$prefersReducedMotion:f},a.createElement(Ei.Open,{url:c,isDefaultIcon:i==="default_icon",size:_})),a.createElement(cT,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:_,$prefersReducedMotion:f},a.createElement(Ei.Close,{size:_})),g&&a.createElement(lT,null),t)}const sT=F.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,oT=F.css`img{width:100%;height:100%;object-fit:cover;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-drag:none;&[data-default-icon='true']{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;filter:${({$fillColor:e})=>e===nn.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Oc=F.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>F.css`
480
+ `,PA=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=i=>{const c=i.target;c.scrollHeight-c.scrollTop-c.clientHeight<=2&&(n==null||n())};return a.createElement($A,{role:r,"aria-label":s,onScroll:i=>o(i)},e.map((i,c)=>{const u=t(i,c);if(r!=="list")return u;const d=l.isValidElement(u)&&u.key!=null?u.key:c;return a.createElement(FA,{key:d,role:"listitem"},u)}))},$A=v.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,FA=v.default.div`flex-shrink:0;`,UA=()=>{const{stringSet:e}=le(),{listSource:t,onOpenConversationView:n}=gn(),{Template:r}=Ns.useContext();return t.initialized?t.channels.length===0?a.createElement(tn,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(PA,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:s=>{var o,i,c;return a.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,$e(s)?"closed":"open"),channelUrl:s.url,title:(i=(o=s.conversation)==null?void 0:o.topics)==null?void 0:i.join(", "),lastMessageTimestamp:(c=s.lastMessage)==null?void 0:c.createdAt})},onEndReached:()=>{t.loadMore()}}):a.createElement(tn,{type:"loading"})},BA=()=>{const{stringSet:e}=le(),{_aiAgentSDK:t}=Te(),{language:n,countryCode:r,context:s}=me(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=De(),{onOpenConversationView:u}=gn(),{conversationList:d}=ue(),m=async()=>{var h;if(o.isMultipleActiveConversationsEnabled){const g=await c({aiAgentId:o.userId,language:n,country:r,context:s});(h=t.session)==null||h._updateActiveChannel({url:g,status:"open"}),u(g,"open",{initialFocusTarget:"messageInput"})}else{const g=await i();u(g,"open",{initialFocusTarget:"messageInput"})}};return a.createElement(HA,{...d.footer.button({onActivate:m}).props},a.createElement(GA,{variant:"h1"},e.TALK_TO_AGENT))},HA=v.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,GA=v.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,zA=()=>{const{state:e}=me(),{messenger:t}=ue(),n=zt(),r=()=>{e.setOpened(!1)};return a.createElement(ot,{...t.closeButton().props,type:"close",size:n,onClick:r})},VA=()=>{const{stringSet:e}=le(),{announcementsEnabled:t}=Os(),{conversationList:n}=ue(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=qa({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(KA,{forwardedAs:"h2",variant:"h2",color:b.themedColor.textHighEmphasis,...o.title.props},r)},KA=v.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,qA=e=>{const{components:t}=Vt.useContext();return a.createElement(Tc,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:pa})},WA=()=>null,YA=()=>{const{components:e}=Vt.useContext();return a.createElement(e.Title,null)},jA=()=>{const{components:e}=Vt.useContext();return a.createElement(e.CloseButton,null)},Vt=Qe({template:qA,components:{StartArea:WA,TitleArea:YA,EndArea:jA,Title:VA,CloseButton:zA}}),XA=()=>{const{Template:e}=Vt.useContext();return a.createElement(e,{titleAlign:"start"})},ZA=()=>(IA(),null),kc=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=rr.useContext();return a.createElement(Rc,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(bA,{announcementsEnabled:s},a.createElement(ZA,null),a.createElement(JA,{style:i},a.createElement(c,null)),n))},JA=({style:e,children:t})=>{const n=l.useRef(null);return TA(n),a.createElement(eT,{ref:n,style:e},t)},QA=()=>{const{components:e}=rr.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},rr=Qe({template:QA,components:{Header:XA,Body:UA,Footer:BA}}),eT=v.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,tT=F.css`:where(#${Ae.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,nT=[tT,Ff,Uf],rT=(e,...t)=>F.createGlobalStyle(e,...nT,...t),sT=rT``,oT=om(nr,Ct,Gt,Qn,tr,rr,Mt,Ns,Vt,er,Xn),iT=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function wc({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){sp(iT?Tf:"",t);const[g,f]=l.useState(null),p=l.useCallback(E=>{f(A=>A===E?A:E)},[]),C=m??g,_=a.createElement(F.StyleSheetManager,{target:t},a.createElement(tp,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(Rf,{rootElement:t,boundaryElement:C},a.createElement(zh,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement($f,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(Qf,{icons:u},a.createElement(oT,null,a.createElement(xf,{entryElement:C,modalRootElement:h,rootElement:t},i),a.createElement(sT,null))))))));return m?_:a.createElement("div",{ref:p,style:{display:"contents"}},_)}const aT=()=>{const[e,t]=l.useState(null),[n,r]=l.useState(null),s=l.useCallback(i=>{t(c=>c===i?c:i)},[]),o=l.useCallback(i=>{r(c=>c===i?c:i)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},Ds=l.forwardRef(function({rootElement:t=document.body,logLevel:n=_e.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var _,E,A;Jt.level!==n&&(Jt.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:g,setModalRootElement:f}=aT();rp("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const p=ya(r),C=Aa.has(p)?p:un;return a.createElement("div",{ref:g,id:Ae.ENTRY,lang:C,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(wc,{logger:Jt,rootElement:t,appearance:(_=u.agentPreviewConfigs)==null?void 0:_.appearance,stringSet:u.stringSet,language:C,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement($p,{rootElement:t,language:r,logger:Jt,dispatcher:Lc,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(E=u.agentPreviewConfigs)==null?void 0:E.forceCreateChannel,_agentVersion:(A=u.agentPreviewConfigs)==null?void 0:A.agentVersion,...u},a.createElement(Kp,{ref:d,userSessionInfo:s},a.createElement(ey,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(lp,null,o))))),a.createElement("div",{ref:f,id:Ae.MODAL_ROOT,dir:u.dir}))}),Jt=new Ni(_e.LogLevel.WARN),Lc=new wi(Jt),zn=()=>{const[e,t]=l.useState(null),n=l.useCallback(r=>t(()=>r),[]);return[e,n]},{Provider:cT,useContext:fn}=ye("PageChildren"),Oc=({children:e})=>{const[t,n]=zn(),[r,s]=zn(),[o,i]=l.useState(null),[c,u]=l.useState(null);return a.createElement(cT,{value:{conversationComponent:t,setConversationComponent:n,conversationChildren:o,setConversationChildren:i,conversationListComponent:r,setConversationListComponent:s,conversationListChildren:c,setConversationListChildren:u}},e)},lT=48,uT=2/3,pi=12;function Nc({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:i,imageUrl:c,dir:u,animated:d=!0,backgroundColor:m,size:h=lT,hasUnread:g=!1}){const f=sc(),p=d&&!f,C=Nr(m),_=Math.round(h*uT);return a.createElement(hT,{dir:u,id:Ae.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:p,$backgroundColor:m,$prefersReducedMotion:f,$size:h},a.createElement(gT,{$isOpened:n,$animated:p,$fillColor:C,$iconSize:_,$prefersReducedMotion:f},a.createElement(Ei.Open,{url:c,isDefaultIcon:i==="default_icon",size:_})),a.createElement(fT,{$isOpened:n,$animated:p,$fillColor:C,$iconSize:_,$prefersReducedMotion:f},a.createElement(Ei.Close,{size:_})),g&&a.createElement(pT,null),t)}const dT=F.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,mT=F.css`img{width:100%;height:100%;object-fit:cover;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-drag:none;&[data-default-icon='true']{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;filter:${({$fillColor:e})=>e===nn.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,Dc=F.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>F.css`
481
481
  ellipse,
482
482
  path {
483
483
  fill: ${e};
@@ -487,7 +487,7 @@ $2
487
487
  }
488
488
  `}
489
489
  }
490
- `,iT=S.default.button`position:relative;padding:0;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;background:${({$backgroundColor:e})=>e};border-radius:50%;transition:${({$prefersReducedMotion:e})=>e?"none":"all 0.3s cubic-bezier(0.31, -0.105, 0.43, 1.4)"};border:none;display:flex;justify-content:center;align-items:center;box-shadow:${$a};${({$animated:e})=>e&&sT}`,Nc=S.default.span.attrs({"aria-hidden":"true"})`
490
+ `,hT=v.default.button`position:relative;padding:0;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;background:${({$backgroundColor:e})=>e};border-radius:50%;transition:${({$prefersReducedMotion:e})=>e?"none":"all 0.3s cubic-bezier(0.31, -0.105, 0.43, 1.4)"};border:none;display:flex;justify-content:center;align-items:center;box-shadow:${Ua};${({$animated:e})=>e&&dT}`,Pc=v.default.span.attrs({"aria-hidden":"true"})`
491
491
  position: absolute;
492
492
  width: 100%;
493
493
  height: 100%;
@@ -497,7 +497,7 @@ $2
497
497
  display: flex;
498
498
  justify-content: center;
499
499
  align-items: center;
500
- `,aT=S.default(Nc)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};opacity:${({$isOpened:e})=>e?0:1};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(-90deg) scale(0)":"rotate(0deg)")};${oT}${Oc}`,cT=S.default(Nc)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};scale:${({$isOpened:e})=>e?1:0};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(0deg)":"rotate(-90deg)")};${Oc}`,lT=S.default.span.attrs({"aria-hidden":"true"})`
500
+ `,gT=v.default(Pc)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};opacity:${({$isOpened:e})=>e?0:1};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(-90deg) scale(0)":"rotate(0deg)")};${mT}${Dc}`,fT=v.default(Pc)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};scale:${({$isOpened:e})=>e?1:0};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(0deg)":"rotate(-90deg)")};${Dc}`,pT=v.default.span.attrs({"aria-hidden":"true"})`
501
501
  position: absolute;
502
502
  top: 1px;
503
503
  inset-inline-end: 1px;
@@ -505,15 +505,15 @@ $2
505
505
  height: ${pi}px;
506
506
  border-radius: 50%;
507
507
  background-color: ${b.themedColor.error};
508
- `,Ei={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(te,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(te,{size:e,type:"chevron-down"})};function Dc({opened:e,setOpened:t,className:n,size:r,entryPoint:s="Conversation",activeRoute:o}){const{colors:i}=F.useTheme(),{chatSDK:c,config:u,dir:d}=me(),{resolveElement:m}=_s(),{launcher:h}=ue(),{launcherInfo:g}=De(),f=u.launcher.unreadBadgeEnabled,p=Xi(),v=Sg(c,{enabled:f,opened:e,filter:p}),_=(o??s)==="ConversationList",E={launcher:h.button({isOpened:e,opensConversationList:_})},A=()=>{Re(()=>{const I=m(Ae.WINDOW),k=I?La(I):null;k==null||k.focus()})},y=()=>{Re(()=>{var I;(I=m(Ae.LAUNCHER))==null||I.focus()})},T=()=>{const I=!e;t(I),I?A():y()};return a.createElement(Lc,{dir:d,className:n,isOpened:e,onClick:T,type:g.type,imageUrl:g.imageUrl,backgroundColor:i.base.primary,size:r,hasUnread:f&&!e&&v,...E.launcher.props},E.launcher.descriptionNode)}const Pc=()=>(Cg("launcher_toggle"),null),$c=l.createContext(null);function sr(){const e=l.useContext($c);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Fc({children:e}){const t=sr();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}function Uc({children:e}){return a.createElement(a.Fragment,null,e)}const uT=F.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,dT=F.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,mT=F.css`animation-name:${uT};animation-duration:0.3s;animation-fill-mode:forwards;`,hT=F.css``,gT=F.css`animation-name:${dT};animation-duration:0.3s;animation-fill-mode:forwards;`,fT=F.css`visibility:hidden;`,pT=S.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return mT;case"entered":return hT;case"exiting":return gT;case"exited":return fT;default:return""}}}${({$active:e})=>e?F.css`
508
+ `,Ei={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(te,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(te,{size:e,type:"chevron-down"})};function $c({opened:e,setOpened:t,className:n,size:r,entryPoint:s="Conversation",activeRoute:o}){const{colors:i}=F.useTheme(),{chatSDK:c,config:u,dir:d}=me(),{resolveElement:m}=Es(),{launcher:h}=ue(),{launcherInfo:g}=De(),f=u.launcher.unreadBadgeEnabled,p=Xi(),C=xg(c,{enabled:f,opened:e,filter:p}),_=(o??s)==="ConversationList",E={launcher:h.button({isOpened:e,opensConversationList:_})},A=()=>{Re(()=>{const I=m(Ae.WINDOW),k=I?Na(I):null;k==null||k.focus()})},y=()=>{Re(()=>{var I;(I=m(Ae.LAUNCHER))==null||I.focus()})},T=()=>{const I=!e;t(I),I?A():y()};return a.createElement(Nc,{dir:d,className:n,isOpened:e,onClick:T,type:g.type,imageUrl:g.imageUrl,backgroundColor:i.base.primary,size:r,hasUnread:f&&!e&&C,...E.launcher.props},E.launcher.descriptionNode)}const Fc=()=>(Ig("launcher_toggle"),null),Uc=l.createContext(null);function sr(){const e=l.useContext(Uc);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Bc({children:e}){const t=sr();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}function Hc({children:e}){return a.createElement(a.Fragment,null,e)}const ET=F.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,_T=F.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,CT=F.css`animation-name:${ET};animation-duration:0.3s;animation-fill-mode:forwards;`,ST=F.css``,vT=F.css`animation-name:${_T};animation-duration:0.3s;animation-fill-mode:forwards;`,bT=F.css`visibility:hidden;`,yT=v.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return CT;case"entered":return ST;case"exiting":return vT;case"exited":return bT;default:return""}}}${({$active:e})=>e?F.css`
509
509
  z-index: 999;
510
510
  `:F.css`z-index:1;pointer-events:none;`}
511
- `;function Pt({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((E,A)=>{r(y=>[...y,E]),g(y=>({...y,[E]:!0})),A!=null&&A.reset&&_(y=>({...y,[E]:(y[E]||0)+1})),p(y=>({...y,[E]:"entering"})),setTimeout(()=>{p(y=>({...y,[E]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(E=>{if(E.length<=1)return E;const A=E[E.length-1];return p(y=>({...y,[A]:"exiting"})),setTimeout(()=>{p(y=>({...y,[A]:"exited"})),r(y=>y.slice(0,-1))},300),E})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(E=>E.type===Fc),[t]),d=l.useMemo(()=>l.Children.toArray(t).filter(E=>E.type===Uc),[t]),m=l.useMemo(()=>{const E={};return u.forEach(A=>{const{id:y,lazy:T,children:I}=A.props;E[y]={lazy:T,element:typeof I=="function"?I(c):I}}),E},[u,c]),[h,g]=l.useState(()=>{const E={};return Object.entries(m).forEach(([A,{lazy:y}])=>{y===!1&&(E[A]=!0)}),E[e]=!0,E}),[f,p]=l.useState(()=>{const E={};return Object.keys(m).forEach(A=>{A===e?E[A]="entered":E[A]="exited"}),E}),[v,_]=l.useState({});return a.createElement($c.Provider,{value:c},d,a.createElement(ET,null,Object.keys(m).map(E=>{var I;if(!h[E])return null;const A=f[E]||"exited",y=E===s,T=`${E}-${v[E]||0}`;return a.createElement(pT,{key:T,$transitionState:A,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(I=m[E])==null?void 0:I.element)})))}const ET=S.default.div`position:relative;width:100%;height:100%;`;Pt.Screen=Fc;Pt.Effect=Uc;const Ye={conv:"conv",convList:"conv-list"},_T=e=>e===Ye.convList?"ConversationList":"Conversation",Bc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,nudgeConversation:s,onActiveRouteChange:o})=>{const{conversationComponent:i,conversationChildren:c,conversationListComponent:u,conversationListChildren:d}=fn(),m=i??Tc,h=u??Mc,[g,f]=l.useState(),p=(()=>{switch(t){case"Conversation":return Ye.conv;case"ConversationList":return Ye.convList;default:return Ye.conv}})(),v=a.createElement(a.Fragment,null,a.createElement(CT,{onOpenConversationView:(_,E)=>{r(E),f(void 0),_.navigate(Ye.conv)}}),a.createElement(vT,{onActiveRouteChange:o}));return a.createElement(Pt,{initialId:p},a.createElement(Pt.Effect,null,a.createElement(ST,{nudgeConversation:s,onNavigate:_=>{f("messageInput"),_.navigate(Ye.conv)}})),a.createElement(Pt.Screen,{id:Ye.conv},({navigation:_,activeScreenId:E})=>{const A=E===Ye.conv,y=e&&A;return a.createElement(a.Fragment,null,v,a.createElement(m,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{f(void 0),_.navigate(Ye.convList)},announcementsEnabled:y,conversationStatsEnabled:y,shouldMarkAsRead:y,shouldInitializeConversation:y,initialUserMessage:s&&s.channelUrl===n?s.initialUserMessage:void 0,initialFocusTarget:g},c))}),a.createElement(Pt.Screen,{id:Ye.convList,lazy:!0},({navigation:_,activeScreenId:E})=>{const A=E===Ye.convList,y=e&&A;return a.createElement(a.Fragment,null,v,a.createElement(h,{announcementsEnabled:y,conversationListStatsEnabled:y,onOpenConversationView:(T,I,k)=>{r(T),f(k==null?void 0:k.initialFocusTarget),_.navigate(Ye.conv)}},d))}))},CT=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=De(),{navigation:n}=sr();return t(({channel:r})=>{e(n,r.url)}),null},ST=({nudgeConversation:e,onNavigate:t})=>{const{navigation:n}=sr();return l.useEffect(()=>{e&&t(n)},[e]),null},vT=({onActiveRouteChange:e})=>{const{activeScreenId:t}=sr();return l.useEffect(()=>{e==null||e(_T(t))},[t,e]),null},$s=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Ae.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},bT=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(As,null,a.createElement(yT,{isExpanded:e,isOpened:t,launcher:r},n)),yT=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=me(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Zn();return jn(t,o,{nameReady:c}),a.createElement(AT,null,a.createElement(TT,{ref:o,dir:s,id:Ae.WINDOW,...$s(t,i),$isExpanded:e,$isOpened:t},n),r)},AT=S.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,TT=S.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;transform:scale(0.15);opacity:0;transform-origin:right bottom;[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform-origin:left bottom;}${({$isOpened:e})=>e&&xT};${({$isExpanded:e})=>e&&IT};`,IT=F.css`width:743px;height:723px;`,xT=F.css`pointer-events:all;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;`,MT=({isMessengerOpened:e,onConversationStarted:t,className:n})=>{const r=Ji({isMessengerOpened:e,onConversationStarted:t});return a.createElement(Hc,{...r,className:n})},Hc=({nudgeMessage:e,nudgeMessageKey:t,dismissNudgeMessage:n,startNudgeConversation:r,className:s})=>{const{stringSet:o}=le(),{dir:i}=me();return e?a.createElement(kT,{key:t,id:Ae.NUDGE_MESSAGE,className:s,dir:i},a.createElement(wT,{onClick:r},a.createElement(LT,{variant:"body3",color:b.themedColor.textHighEmphasis,maxTextLines:2},e.message)),a.createElement(OT,{type:"close",size:16,"aria-label":o.A11Y_DISMISS_NUDGE_MESSAGE,onClick:n})):null},Gc=12,RT=F.keyframes`from{opacity:0;transform:scale(0.8);}`,kT=S.default.div`position:relative;display:flex;align-items:flex-start;gap:8px;padding:16px;min-width:120px;max-width:320px;box-sizing:border-box;border-radius:${Gc}px;background-color:${b.themedColor.bg_50_600};box-shadow:${$a};animation-name:${RT};animation-duration:0.3s;animation-timing-function:cubic-bezier(0.31,-0.105,0.43,1.4);@media (prefers-reduced-motion:reduce){animation-name:none;}`,wT=S.default.button`all:unset;flex:1;min-width:0;cursor:pointer;text-align:start;${ke}&::after{content:'';position:absolute;inset:0;border-radius:${Gc}px;}`,LT=S.default(B)`line-height:20px;overflow-wrap:anywhere;white-space:pre-line;`,OT=S.default(ot)`position:relative;margin:-4px;`,NT=1e3*60,zc=()=>{const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=me();return l.useEffect(()=>{if(!r)return;if(t.opened){e.connectionState===_e.ConnectionState.CLOSED&&(e.reconnect(),n.debug("SDKInactivityTimeout: reconnected"));return}const s=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("SDKInactivityTimeout: disconnected")},NT);return n.debug("SDKInactivityTimeout: schedule disconnect"),()=>clearTimeout(s)},[r,e,t.opened,n]),null},DT=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(),[u,d]=l.useState(n.entryPoint??"Conversation");return a.createElement(Ps,{enableExpandButton:!dn(),ref:r,...n},a.createElement(Na,null,({state:m})=>a.createElement(wc,null,a.createElement(zc,null),a.createElement(Pc,null),a.createElement(bT,{isExpanded:m.expanded,isOpened:m.opened,launcher:a.createElement(a.Fragment,null,a.createElement(MT,{isMessengerOpened:m.opened,onConversationStarted:h=>{o(h.channelUrl),c(h),m.setOpened(!0)}}),a.createElement(Dc,{opened:m.opened,setOpened:m.setOpened,entryPoint:n.entryPoint,activeRoute:u}))},a.createElement(Bc,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,nudgeConversation:i,onActiveRouteChange:d})),e)))}),{Provider:PT,useContext:Kt}=ye("FixedMessengerStyle"),$T=({children:e,isOpened:t,zIndex:n=It.WINDOW})=>a.createElement(As,null,a.createElement(FT,{isOpened:t,zIndex:n},e)),FT=({children:e,isOpened:t,zIndex:n=It.WINDOW})=>{const{dir:r,rootElement:s}=me(),o=Et(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Zn();return jn(t,i,{nameReady:u}),l.useEffect(()=>{const d="sb-agent-block-scroll";return t?o.body.classList.add(d):o.body.classList.remove(d),()=>{o.body.classList.remove(d)}},[o,t]),a.createElement(UT,{ref:i,id:Ae.WINDOW,dir:r,...$s(t,c),$visible:t,$zIndex:n},e)},UT=S.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`;function Vc(e,t,n,r){const{top:s,bottom:o,start:i,end:c}=n;return{...e==="start"?{insetInlineStart:nt(i)}:{insetInlineEnd:nt(c)},...t==="top"?{top:`calc(${nt(s)} + ${r}px)`}:{bottom:`calc(${nt(o)} + ${r}px)`}}}const Xr={position:"fixed",zIndex:It.LAUNCHER};function Kc(e,t,n,r=0){return F.css`&&{position:${Xr.position};z-index:${Xr.zIndex};${qc(e,t,n,r)};}`}function qc(e,t,n,r=0){return F.css(Vc(e,t,n,r))}function Wc(e,t,n,r,s){return{...Xr,direction:s,...Vc(e,t,n,r)}}function BT(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Kt();return a.createElement(HT,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const HT=S.default(Dc)`${({$horizontal:e,$vertical:t,$margin:n})=>Kc(e,t,n)};`,Yc=ye("FixedMessengerSlots"),GT=Yc.Provider,or=Yc.useContext,zT=({children:e})=>{const[t,n]=zn(),[r,s]=zn();return a.createElement(GT,{value:{launcherComponent:t,setLauncherComponent:n,nudgeMessageComponent:r,setNudgeMessageComponent:s}},e)},VT=({isExpanded:e,isOpened:t,children:n})=>a.createElement(As,null,a.createElement(KT,{isExpanded:e,isOpened:t},n)),KT=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=me(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=Kt(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Zn();return jn(t,u,{nameReady:m}),a.createElement(qT,{ref:u,dir:r,id:Ae.WINDOW,...$s(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},qT=S.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;position:fixed;pointer-events:none;visibility:hidden;${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>qc(e,t,n,r+12)};height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 150ms;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
511
+ `;function Pt({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((E,A)=>{r(y=>[...y,E]),g(y=>({...y,[E]:!0})),A!=null&&A.reset&&_(y=>({...y,[E]:(y[E]||0)+1})),p(y=>({...y,[E]:"entering"})),setTimeout(()=>{p(y=>({...y,[E]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(E=>{if(E.length<=1)return E;const A=E[E.length-1];return p(y=>({...y,[A]:"exiting"})),setTimeout(()=>{p(y=>({...y,[A]:"exited"})),r(y=>y.slice(0,-1))},300),E})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(E=>E.type===Bc),[t]),d=l.useMemo(()=>l.Children.toArray(t).filter(E=>E.type===Hc),[t]),m=l.useMemo(()=>{const E={};return u.forEach(A=>{const{id:y,lazy:T,children:I}=A.props;E[y]={lazy:T,element:typeof I=="function"?I(c):I}}),E},[u,c]),[h,g]=l.useState(()=>{const E={};return Object.entries(m).forEach(([A,{lazy:y}])=>{y===!1&&(E[A]=!0)}),E[e]=!0,E}),[f,p]=l.useState(()=>{const E={};return Object.keys(m).forEach(A=>{A===e?E[A]="entered":E[A]="exited"}),E}),[C,_]=l.useState({});return a.createElement(Uc.Provider,{value:c},d,a.createElement(AT,null,Object.keys(m).map(E=>{var I;if(!h[E])return null;const A=f[E]||"exited",y=E===s,T=`${E}-${C[E]||0}`;return a.createElement(yT,{key:T,$transitionState:A,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(I=m[E])==null?void 0:I.element)})))}const AT=v.default.div`position:relative;width:100%;height:100%;`;Pt.Screen=Bc;Pt.Effect=Hc;const Ye={conv:"conv",convList:"conv-list"},TT=e=>e===Ye.convList?"ConversationList":"Conversation",Gc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,nudgeConversation:s,onActiveRouteChange:o})=>{const{conversationComponent:i,conversationChildren:c,conversationListComponent:u,conversationListChildren:d}=fn(),m=i??xc,h=u??kc,[g,f]=l.useState(),p=(()=>{switch(t){case"Conversation":return Ye.conv;case"ConversationList":return Ye.convList;default:return Ye.conv}})(),C=a.createElement(a.Fragment,null,a.createElement(IT,{onOpenConversationView:(_,E)=>{r(E),f(void 0),_.navigate(Ye.conv)}}),a.createElement(MT,{onActiveRouteChange:o}));return a.createElement(Pt,{initialId:p},a.createElement(Pt.Effect,null,a.createElement(xT,{nudgeConversation:s,onNavigate:_=>{f("messageInput"),_.navigate(Ye.conv)}})),a.createElement(Pt.Screen,{id:Ye.conv},({navigation:_,activeScreenId:E})=>{const A=E===Ye.conv,y=e&&A;return a.createElement(a.Fragment,null,C,a.createElement(m,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{f(void 0),_.navigate(Ye.convList)},announcementsEnabled:y,conversationStatsEnabled:y,shouldMarkAsRead:y,shouldInitializeConversation:y,initialUserMessage:s&&s.channelUrl===n?s.initialUserMessage:void 0,initialFocusTarget:g},c))}),a.createElement(Pt.Screen,{id:Ye.convList,lazy:!0},({navigation:_,activeScreenId:E})=>{const A=E===Ye.convList,y=e&&A;return a.createElement(a.Fragment,null,C,a.createElement(h,{announcementsEnabled:y,conversationListStatsEnabled:y,onOpenConversationView:(T,I,k)=>{r(T),f(k==null?void 0:k.initialFocusTarget),_.navigate(Ye.conv)}},d))}))},IT=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=De(),{navigation:n}=sr();return t(({channel:r})=>{e(n,r.url)}),null},xT=({nudgeConversation:e,onNavigate:t})=>{const{navigation:n}=sr();return l.useEffect(()=>{e&&t(n)},[e]),null},MT=({onActiveRouteChange:e})=>{const{activeScreenId:t}=sr();return l.useEffect(()=>{e==null||e(TT(t))},[t,e]),null},Ps=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Ae.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},RT=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(ys,null,a.createElement(kT,{isExpanded:e,isOpened:t,launcher:r},n)),kT=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=me(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Zn();return jn(t,o,{nameReady:c}),a.createElement(wT,null,a.createElement(LT,{ref:o,dir:s,id:Ae.WINDOW,...Ps(t,i),$isExpanded:e,$isOpened:t},n),r)},wT=v.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,LT=v.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;transform:scale(0.15);opacity:0;transform-origin:right bottom;[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform-origin:left bottom;}${({$isOpened:e})=>e&&NT};${({$isExpanded:e})=>e&&OT};`,OT=F.css`width:743px;height:723px;`,NT=F.css`pointer-events:all;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;`,DT=({isMessengerOpened:e,onConversationStarted:t,className:n})=>{const r=Ji({isMessengerOpened:e,onConversationStarted:t});return a.createElement(zc,{...r,className:n})},zc=({nudgeMessage:e,nudgeMessageKey:t,dismissNudgeMessage:n,startNudgeConversation:r,className:s})=>{const{stringSet:o}=le(),{dir:i}=me();return e?a.createElement($T,{key:t,id:Ae.NUDGE_MESSAGE,className:s,dir:i},a.createElement(FT,{onClick:r},a.createElement(UT,{variant:"body3",color:b.themedColor.textHighEmphasis,maxTextLines:2},e.message)),a.createElement(BT,{type:"close",size:16,"aria-label":o.A11Y_DISMISS_NUDGE_MESSAGE,onClick:n})):null},Vc=12,PT=F.keyframes`from{opacity:0;transform:scale(0.8);}`,$T=v.default.div`position:relative;display:flex;align-items:flex-start;gap:8px;padding:16px;min-width:120px;max-width:320px;box-sizing:border-box;border-radius:${Vc}px;background-color:${b.themedColor.bg_50_600};box-shadow:${Ua};animation-name:${PT};animation-duration:0.3s;animation-timing-function:cubic-bezier(0.31,-0.105,0.43,1.4);@media (prefers-reduced-motion:reduce){animation-name:none;}`,FT=v.default.button`all:unset;flex:1;min-width:0;cursor:pointer;text-align:start;${ke}&::after{content:'';position:absolute;inset:0;border-radius:${Vc}px;}`,UT=v.default(B)`line-height:20px;overflow-wrap:anywhere;white-space:pre-line;`,BT=v.default(ot)`position:relative;margin:-4px;`,HT=1e3*60,Kc=()=>{const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=me();return l.useEffect(()=>{if(!r)return;if(t.opened){e.connectionState===_e.ConnectionState.CLOSED&&(e.reconnect(),n.debug("SDKInactivityTimeout: reconnected"));return}const s=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("SDKInactivityTimeout: disconnected")},HT);return n.debug("SDKInactivityTimeout: schedule disconnect"),()=>clearTimeout(s)},[r,e,t.opened,n]),null},GT=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(),[u,d]=l.useState(n.entryPoint??"Conversation");return a.createElement(Ds,{enableExpandButton:!dn(),ref:r,...n},a.createElement(Pa,null,({state:m})=>a.createElement(Oc,null,a.createElement(Kc,null),a.createElement(Fc,null),a.createElement(RT,{isExpanded:m.expanded,isOpened:m.opened,launcher:a.createElement(a.Fragment,null,a.createElement(DT,{isMessengerOpened:m.opened,onConversationStarted:h=>{o(h.channelUrl),c(h),m.setOpened(!0)}}),a.createElement($c,{opened:m.opened,setOpened:m.setOpened,entryPoint:n.entryPoint,activeRoute:u}))},a.createElement(Gc,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,nudgeConversation:i,onActiveRouteChange:d})),e)))}),{Provider:zT,useContext:Kt}=ye("FixedMessengerStyle"),VT=({children:e,isOpened:t,zIndex:n=It.WINDOW})=>a.createElement(ys,null,a.createElement(KT,{isOpened:t,zIndex:n},e)),KT=({children:e,isOpened:t,zIndex:n=It.WINDOW})=>{const{dir:r,rootElement:s}=me(),o=_t(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Zn();return jn(t,i,{nameReady:u}),l.useEffect(()=>{const d="sb-agent-block-scroll";return t?o.body.classList.add(d):o.body.classList.remove(d),()=>{o.body.classList.remove(d)}},[o,t]),a.createElement(qT,{ref:i,id:Ae.WINDOW,dir:r,...Ps(t,c),$visible:t,$zIndex:n},e)},qT=v.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`;function qc(e,t,n,r){const{top:s,bottom:o,start:i,end:c}=n;return{...e==="start"?{insetInlineStart:nt(i)}:{insetInlineEnd:nt(c)},...t==="top"?{top:`calc(${nt(s)} + ${r}px)`}:{bottom:`calc(${nt(o)} + ${r}px)`}}}const jr={position:"fixed",zIndex:It.LAUNCHER};function Wc(e,t,n,r=0){return F.css`&&{position:${jr.position};z-index:${jr.zIndex};${Yc(e,t,n,r)};}`}function Yc(e,t,n,r=0){return F.css(qc(e,t,n,r))}function jc(e,t,n,r,s){return{...jr,direction:s,...qc(e,t,n,r)}}function WT(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Kt();return a.createElement(YT,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const YT=v.default($c)`${({$horizontal:e,$vertical:t,$margin:n})=>Wc(e,t,n)};`,Xc=ye("FixedMessengerSlots"),jT=Xc.Provider,or=Xc.useContext,XT=({children:e})=>{const[t,n]=zn(),[r,s]=zn();return a.createElement(jT,{value:{launcherComponent:t,setLauncherComponent:n,nudgeMessageComponent:r,setNudgeMessageComponent:s}},e)},ZT=({isExpanded:e,isOpened:t,children:n})=>a.createElement(ys,null,a.createElement(JT,{isExpanded:e,isOpened:t},n)),JT=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=me(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=Kt(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Zn();return jn(t,u,{nameReady:m}),a.createElement(QT,{ref:u,dir:r,id:Ae.WINDOW,...Ps(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},QT=v.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;position:fixed;pointer-events:none;visibility:hidden;${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>Yc(e,t,n,r+12)};height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 150ms;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
512
512
  [dir='rtl'] &:not([dir='ltr']),
513
513
  &[dir='rtl'] {
514
514
  transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
515
515
  }
516
516
 
517
- ${({$isOpened:e})=>e&&YT};
518
- ${({$isExpanded:e})=>e&&WT};
519
- `,WT=F.css`width:743px;height:723px;`,YT=F.css`z-index:${It.WINDOW};pointer-events:all;visibility:visible;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 0s;`,jT=8,jc=e=>e+jT,XT=e=>{const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Kt();return a.createElement(ZT,{...e,$horizontal:t,$vertical:n,$margin:r,$launcherSize:s})},ZT=S.default(Hc)`${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>Kc(e,t,n,jc(r))};`,Xc={top:24,bottom:24,start:24,end:24},JT=e=>{const{launcherComponent:t}=or(),{horizontal:n,vertical:r,margin:s,launcherSize:o}=Kt(),{dir:i}=me();if(t){const c=Wc(n,r,s,0,i);return a.createElement(t,{...e,size:o,style:c})}return a.createElement(BT,{...e})},QT=({isMessengerOpened:e,onConversationStarted:t})=>{const{nudgeMessageComponent:n}=or(),{horizontal:r,vertical:s,margin:o,launcherSize:i}=Kt(),{dir:c}=me(),u=Ji({isMessengerOpened:e,onConversationStarted:t});if(n){const{nudgeMessageKey:d,...m}=u,h=Wc(r,s,o,jc(i),c);return a.createElement(n,{key:d,...m,style:h})}return a.createElement(XT,{...u})},eI=l.forwardRef(function({children:e,initialChannelUrl:t,entryPoint:n="Conversation",...r},s){const[o,i]=l.useState(t),[c,u]=l.useState(),[d,m]=l.useState(n),[h,g]=l.useState("end-bottom"),[f,p]=l.useState(Xc),[v,_]=l.useState(48),E=dn(),A=E?$T:VT,{horizontal:y,vertical:T}=l.useMemo(()=>{const[I,k]=h.split("-");return{horizontal:I==="start"?"start":"end",vertical:k==="top"?"top":"bottom"}},[h]);return a.createElement(Ps,{enableExpandButton:!E,ref:s,...r},a.createElement(Na,null,({state:I})=>a.createElement(PT,{value:{horizontal:y,vertical:T,margin:f,launcherSize:v,setPosition:g,setMargin:p,setLauncherSize:_}},a.createElement(wc,null,a.createElement(zT,null,a.createElement(zc,null),a.createElement(Pc,null),a.createElement(A,{isExpanded:I.expanded,isOpened:I.opened},a.createElement(Bc,{isOpened:I.opened,entryPoint:n,selectedChannelUrl:o,setSelectedChannelUrl:i,nudgeConversation:c,onActiveRouteChange:m})),a.createElement(JT,{opened:I.opened,setOpened:I.setOpened,entryPoint:n,activeRoute:d}),a.createElement(QT,{isMessengerOpened:I.opened,onConversationStarted:k=>{i(k.channelUrl),u(k),I.setOpened(!0)}}),e)))))}),tI=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=Kt();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...Xc,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(s=e.margin)==null?void 0:s.top,(o=e.margin)==null?void 0:o.bottom,(i=e.margin)==null?void 0:i.start,(c=e.margin)==null?void 0:c.end,e.launcherSize]),null},qt=(e,t)=>{l.useLayoutEffect(()=>(e(t),()=>e(null)),[t,e])},nI=({component:e})=>(qt(or().setLauncherComponent,e),null),rI=({component:e})=>(qt(or().setNudgeMessageComponent,e),null),sI=({component:e})=>(qt(fn().setConversationComponent,e),null),oI=({component:e})=>(qt(fn().setConversationListComponent,e),null),iI=({children:e})=>(qt(fn().setConversationChildren,e),null),aI=({children:e})=>(qt(fn().setConversationListChildren,e),null),cI=Object.assign(eI,{Style:tI,Launcher:nI,NudgeMessage:rI,Conversation:sI,ConversationChildren:iI,ConversationList:oI,ConversationListChildren:aI}),lI=e=>{const{refreshActiveChannel:t}=De(),[n,r]=l.useState(!1),s=l.useRef(null),o=l.useRef(null);return l.useEffect(()=>{n&&t().then(()=>{var i;(i=s.current)==null||i.call(s),r(!1)}).catch(i=>{var c;(c=o.current)==null||c.call(o,i),r(!1)})},[n]),l.useCallback(()=>new Promise((i,c)=>{s.current=i,o.current=c,e().then(()=>r(!0)).catch(c)}),[e])};Hi.set(_e.SendbirdPlatform.JS,{deviceOSPlatform:Rl()?_e.DeviceOsPlatform.MOBILE_WEB:_e.DeviceOsPlatform.WEB,messengerVersion:mf,keyValueStorage:pf(),networkStateAdapter:ff(),foregroundStateAdapter:gf});exports.ANCHOR_REL=Ca;exports.AgentProviderContainer=Ps;exports.AgentUIProviderContainer=Rc;exports.AnonymousSessionInfo=kr;exports.CSATType=st;exports.Commands=ut;exports.ConnectionDelayLayout=Xn;exports.Conversation=Tc;exports.ConversationContext=Jp;exports.ConversationContextProvider=Ha;exports.ConversationHeaderLayout=Mt;exports.ConversationLayout=nr;exports.ConversationList=Mc;exports.ConversationListContext=EA;exports.ConversationListContextProvider=xc;exports.ConversationListHeaderLayout=Vt;exports.ConversationListItemLayout=Ds;exports.ConversationListLayout=rr;exports.DefaultMessenger=DT;exports.DeskTicketPriority=ms;exports.DeskTicketStatus=ds;exports.FixedMessenger=cI;exports.ID_INCOMING=Ke;exports.IncomingMessageLayout=_t;exports.LauncherBase=Lc;exports.LogLevel=ss;exports.MARK_CHAR=mc;exports.ManualSessionInfo=Di;exports.MaskedText=dc;exports.MessageListUILayout=tr;exports.MessageLogs=pc;exports.OutgoingMessageLayout=Gt;exports.PlaceholderLayout=er;exports.Prechecks=_c;exports.SystemMessageLayout=Qn;exports.createMarkdownPreprocessor=Il;exports.cssVars=b;exports.flattenObject=Nd;exports.mapCommonStringsToReactFormat=Sa;exports.messengerDispatcher=kc;exports.noop=Ee;exports.parseToMessageTemplate=Ui;exports.parseToUITemplate=Ld;exports.pickColorByTheme=Od;exports.replaceVariablesAsync=Pd;exports.replaceVariablesSync=Dd;exports.useAIAgentContext=Ie;exports.useConversationContext=Me;exports.useConversationListContext=gn;exports.useLocalizationContext=le;exports.useMessageTemplateFetchingContext=$h;exports.useMessengerContext=me;exports.useMessengerSessionContext=De;exports.useMessengerThemeContext=Ia;exports.useRefreshActiveChannel=lI;
517
+ ${({$isOpened:e})=>e&&tI};
518
+ ${({$isExpanded:e})=>e&&eI};
519
+ `,eI=F.css`width:743px;height:723px;`,tI=F.css`z-index:${It.WINDOW};pointer-events:all;visibility:visible;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 0s;`,nI=8,Zc=e=>e+nI,rI=e=>{const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Kt();return a.createElement(sI,{...e,$horizontal:t,$vertical:n,$margin:r,$launcherSize:s})},sI=v.default(zc)`${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>Wc(e,t,n,Zc(r))};`,Jc={top:24,bottom:24,start:24,end:24},oI=e=>{const{launcherComponent:t}=or(),{horizontal:n,vertical:r,margin:s,launcherSize:o}=Kt(),{dir:i}=me();if(t){const c=jc(n,r,s,0,i);return a.createElement(t,{...e,size:o,style:c})}return a.createElement(WT,{...e})},iI=({isMessengerOpened:e,onConversationStarted:t})=>{const{nudgeMessageComponent:n}=or(),{horizontal:r,vertical:s,margin:o,launcherSize:i}=Kt(),{dir:c}=me(),u=Ji({isMessengerOpened:e,onConversationStarted:t});if(n){const{nudgeMessageKey:d,...m}=u,h=jc(r,s,o,Zc(i),c);return a.createElement(n,{key:d,...m,style:h})}return a.createElement(rI,{...u})},aI=l.forwardRef(function({children:e,initialChannelUrl:t,entryPoint:n="Conversation",...r},s){const[o,i]=l.useState(t),[c,u]=l.useState(),[d,m]=l.useState(n),[h,g]=l.useState("end-bottom"),[f,p]=l.useState(Jc),[C,_]=l.useState(48),E=dn(),A=E?VT:ZT,{horizontal:y,vertical:T}=l.useMemo(()=>{const[I,k]=h.split("-");return{horizontal:I==="start"?"start":"end",vertical:k==="top"?"top":"bottom"}},[h]);return a.createElement(Ds,{enableExpandButton:!E,ref:s,...r},a.createElement(Pa,null,({state:I})=>a.createElement(zT,{value:{horizontal:y,vertical:T,margin:f,launcherSize:C,setPosition:g,setMargin:p,setLauncherSize:_}},a.createElement(Oc,null,a.createElement(XT,null,a.createElement(Kc,null),a.createElement(Fc,null),a.createElement(A,{isExpanded:I.expanded,isOpened:I.opened},a.createElement(Gc,{isOpened:I.opened,entryPoint:n,selectedChannelUrl:o,setSelectedChannelUrl:i,nudgeConversation:c,onActiveRouteChange:m})),a.createElement(oI,{opened:I.opened,setOpened:I.setOpened,entryPoint:n,activeRoute:d}),a.createElement(iI,{isMessengerOpened:I.opened,onConversationStarted:k=>{i(k.channelUrl),u(k),I.setOpened(!0)}}),e)))))}),cI=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=Kt();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...Jc,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(s=e.margin)==null?void 0:s.top,(o=e.margin)==null?void 0:o.bottom,(i=e.margin)==null?void 0:i.start,(c=e.margin)==null?void 0:c.end,e.launcherSize]),null},qt=(e,t)=>{l.useLayoutEffect(()=>(e(t),()=>e(null)),[t,e])},lI=({component:e})=>(qt(or().setLauncherComponent,e),null),uI=({component:e})=>(qt(or().setNudgeMessageComponent,e),null),dI=({component:e})=>(qt(fn().setConversationComponent,e),null),mI=({component:e})=>(qt(fn().setConversationListComponent,e),null),hI=({children:e})=>(qt(fn().setConversationChildren,e),null),gI=({children:e})=>(qt(fn().setConversationListChildren,e),null),fI=Object.assign(aI,{Style:cI,Launcher:lI,NudgeMessage:uI,Conversation:dI,ConversationChildren:hI,ConversationList:mI,ConversationListChildren:gI}),pI=e=>{const{refreshActiveChannel:t}=De(),[n,r]=l.useState(!1),s=l.useRef(null),o=l.useRef(null);return l.useEffect(()=>{n&&t().then(()=>{var i;(i=s.current)==null||i.call(s),r(!1)}).catch(i=>{var c;(c=o.current)==null||c.call(o,i),r(!1)})},[n]),l.useCallback(()=>new Promise((i,c)=>{s.current=i,o.current=c,e().then(()=>r(!0)).catch(c)}),[e])};Hi.set(_e.SendbirdPlatform.JS,{deviceOSPlatform:wl()?_e.DeviceOsPlatform.MOBILE_WEB:_e.DeviceOsPlatform.WEB,messengerVersion:Cf,keyValueStorage:yf(),networkStateAdapter:bf(),foregroundStateAdapter:vf});exports.ANCHOR_REL=va;exports.AgentProviderContainer=Ds;exports.AgentUIProviderContainer=wc;exports.AnonymousSessionInfo=Rr;exports.CSATType=st;exports.Commands=ut;exports.ConnectionDelayLayout=Xn;exports.Conversation=xc;exports.ConversationContext=oE;exports.ConversationContextProvider=za;exports.ConversationHeaderLayout=Mt;exports.ConversationLayout=nr;exports.ConversationList=kc;exports.ConversationListContext=AA;exports.ConversationListContextProvider=Rc;exports.ConversationListHeaderLayout=Vt;exports.ConversationListItemLayout=Ns;exports.ConversationListLayout=rr;exports.DefaultMessenger=GT;exports.DeskTicketPriority=ds;exports.DeskTicketStatus=us;exports.FixedMessenger=fI;exports.ID_INCOMING=Ke;exports.IncomingMessageLayout=Ct;exports.LauncherBase=Nc;exports.LogLevel=rs;exports.MARK_CHAR=gc;exports.ManualSessionInfo=Di;exports.MaskedText=hc;exports.MessageListUILayout=tr;exports.MessageLogs=_c;exports.OutgoingMessageLayout=Gt;exports.PlaceholderLayout=er;exports.Prechecks=Sc;exports.SystemMessageLayout=Qn;exports.createMarkdownPreprocessor=Ml;exports.cssVars=b;exports.flattenObject=Fd;exports.mapCommonStringsToReactFormat=ba;exports.messengerDispatcher=Lc;exports.noop=Ee;exports.parseToMessageTemplate=Ui;exports.parseToUITemplate=Pd;exports.pickColorByTheme=$d;exports.replaceVariablesAsync=Bd;exports.replaceVariablesSync=Ud;exports.useAIAgentContext=Te;exports.useConversationContext=Me;exports.useConversationListContext=gn;exports.useLocalizationContext=le;exports.useMessageTemplateFetchingContext=Gh;exports.useMessengerContext=me;exports.useMessengerSessionContext=De;exports.useMessengerThemeContext=Ma;exports.useRefreshActiveChannel=pI;