@sendbird/ai-agent-messenger-react 1.43.0 → 1.43.3

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.
Files changed (4) hide show
  1. package/dist/index.cjs +173 -173
  2. package/dist/index.d.ts +753 -4969
  3. package/dist/index.js +3823 -3834
  4. package/package.json +4 -3
package/dist/index.cjs CHANGED
@@ -1,20 +1,20 @@
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(`
1
+ "use strict";var Qc=Object.defineProperty;var el=(e,t,n)=>t in e?Qc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var C=(e,t,n)=>el(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const pe=require("@sendbird/chat"),l=require("react"),F=require("styled-components"),pt=require("date-fns"),tl=require("date-fns/locale/en-US"),ke=require("@sendbird/chat/message"),Ce=require("@sendbird/chat/aiAgent"),nl=require("react-dom"),rt=require("@sendbird/chat/groupChannel"),rl=require("date-fns/isSameDay"),_i=e=>e&&e.__esModule?e:{default:e};function sl(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 ol=_i(pe),a=sl(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??{},il=e=>!!vi(e).stream,Ps=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},jr=e=>{const t=vi(e),n=Ps(t.user_message_id)??Ps(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="*/*",se={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 al=e=>!!(e!=null&&e.cta_button),cl=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},yi=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,ll=e=>{var t;return yi(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},ul=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},tt=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},Vn=e=>Object.defineProperties({},{hasMessageTemplate:tt(()=>!!(e!=null&&e.message_template)),hasCTAButton:tt(()=>al(e)),hasChallenge:tt(()=>!!(e!=null&&e.challenge)),hasCSAT:tt(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:tt(()=>ul(e)),hasCustomMessageTemplates:tt(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:tt(()=>yi(e)),hasActiveForm:tt(()=>ll(e)),hasSteward:tt(()=>!!(e!=null&&e.steward)),hasCitations:tt(()=>cl(e))}),dl=e=>{const t=Vn(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasChallenge||t.hasCSAT||t.hasSuggestedReplies||t.hasCustomMessageTemplates||t.hasForm||t.hasSteward||t.hasCitations},Ai=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},ml=e=>e===Qt.COMPLETED||e===Qt.CANCELED?e:Qt.IN_PROGRESS,ir=e=>Xe(e)&&!Ai(e),Xe=e=>!!e&&"sender"in e,hl=(e,{aiAgentInfo:t,members:n})=>t&&Fe(e,t.userId)?t:(n==null?void 0:n.find(r=>r.userId===e.sender.userId))??e.sender,gl=e=>Xe(e)&&e.reqId?e.reqId:String(e.messageId),fl=(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"},Fe=(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,we={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===ke.SendingStatus.PENDING)},Ve=e=>e.startsWith("image/"),sn=e=>e.startsWith("video/"),pl=e=>e.startsWith("audio/"),Ti=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Xr=(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},Kn=e=>{switch(e){case"top":case"middle":return se.GAP_GROUPED;default:return se.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},Zr=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 b=0;for(;c[p.start-1-b]==="\\";)b+=1;if(b%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},$s=(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)},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
4
+ `)+1;return i>=c?n:n.slice(0,i)+e(n.slice(i,c))+n.slice(c)},_l=e=>t=>{const n=Zr(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 Zr(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,y)=>{for(;E.index<_.length&&_[E.index][1]<=y;)E.index+=1;return E.index<_.length&&y>=_[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 y=0;for(;e[_-1-y]==="\\";)y+=1;if(y%2===1)continue;const T=e[_-1],A=e[E],I=!pn(A)&&(!Rt(A)||pn(T)||Rt(T)),k=!pn(T)&&(!Rt(T)||pn(A)||Rt(A));d.push({start:_,end:E,canOpen:I&&(!k||Rt(T)),canClose:k&&(!I||Rt(A)),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="",b=0;for(const _ of d)_.paired||(p+=e.slice(b,_.start)+"\\_".repeat(_.end-_.start),b=_.end);return p+e.slice(b)},yl=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
- `),Il=e=>e.replace(/~~/g,"\\~\\~"),xl=e=>{const t=e.replace(/\r\n?/g,`
8
+ `),Al=e=>e.replace(/~~/g,"\\~\\~"),Tl=e=>{const t=e.replace(/\r\n?/g,`
9
9
  `),n=s=>s.replace(/(\S[ \t]*)\n(?![ \t]*\n)/g,`$1
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
- `),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
- `)},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.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`},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`
10
+ `),r=Zr(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),Fs=xr(_l(xr($s(yl,{anchorsLineEnd:!0}),Cl,$s(Sl),Al)),bl),Il=({convertSoftBreaks:e=!1}={})=>e?xr(Tl,Fs):Fs,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}},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)},Ml=(e,t)=>{const n=Mr(e,[ke.SendingStatus.SUCCEEDED]);return n&&we.isIncoming(n,t)?n:void 0},Me=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function _e(){}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 ye={isStreaming(e){return il(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(ye.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!Fe(e,t))return!1;const n=jr(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:b,copilotSupportChannelUrl:_}=s.params,E={aiAgentChannelFilter:h,aiAgentIds:g,deskChannelFilter:f,pinnedChannelUrls:p,copilotConversationOnly:b,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:b}of m)h.delete(p.url),h.set(p.url,{channel:p,context:b});const g=new Map;for(const{channel:p,context:b}of h.values())g.has(b)||g.set(b,new Map),g.get(b).set(p.url,p);for(const[p,b]of g){const _=Array.from(b.values()),E=(f=this._sdk.currentUser)==null?void 0:f.userId,y=_.filter(A=>this.filter.match(A,E)),T=_.filter(A=>!this.filter.match(A,E)).map(A=>A.url);y.length>0&&this._base._addChannelsToView(y,p,!1),T.length>0&&this._removeChannels(T,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=_e,t=_e;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 dt={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 on{constructor(t){C(this,"category","connection");this.userId=t}get data(){return Bt({user_id:this.userId})}}class Hl extends on{constructor(){super(...arguments);C(this,"metricKey","connection_connected")}}class Gl extends on{constructor(){super(...arguments);C(this,"metricKey","connection_reconnect_started")}}class zl extends on{constructor(){super(...arguments);C(this,"metricKey","connection_reconnect_succeeded")}}class Vl extends on{constructor(){super(...arguments);C(this,"metricKey","connection_reconnect_failed")}}class Kl extends on{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 Jr{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 Jr{constructor(){super(...arguments);C(this,"metricKey","conversation_initialized")}}class Yl extends Jr{constructor(){super(...arguments);C(this,"metricKey","conversation_open")}}class jl extends Jr{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 Zl=(e,t)=>{if(e)return e.members.find(n=>n.userId!==t)},Jl=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?Jl(e):Zl(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")},Qr=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 mt(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 Ql(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!mt(e):!1}function eu(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 tu(e){return!e.title}function nu(e,t){var n;if(e)return tu(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 es{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 ru extends es{constructor(){super(...arguments);C(this,"metricKey","handoff_started")}}class su extends es{constructor(){super(...arguments);C(this,"metricKey","handoff_succeeded")}}class ou extends es{constructor(){super(...arguments);C(this,"metricKey","handoff_failed")}}class iu{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 ru(t.url,r.id):o==="succeeded"?new su(t.url,r.id):new ou(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 au{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 cu=(e,t)=>{const n=Xe(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class lu{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 au({channelUrl:t.url,messageId:n.messageId,senderType:cu(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!Fe(t,this.getCurrentUserId())&&n!==null}}class ts{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 uu extends ts{constructor(){super(...arguments);C(this,"metricKey","memory_consent")}}class du extends ts{constructor(){super(...arguments);C(this,"metricKey","memory_on")}}class mu extends ts{constructor(){super(...arguments);C(this,"metricKey","memory_off")}}const hu={consent:{Metric:uu,actions:{shown:"shown",confirm:"enable",cancel:"disable"}},on:{Metric:du,actions:{shown:"shown",confirm:"keep",cancel:"disable",dismiss:"dismiss"}},off:{Metric:mu,actions:{shown:"shown",confirm:"keep",cancel:"enable",dismiss:"dismiss"}}};class gu{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}=hu[t],i=o[n];i&&this.dispatch(new s({action:i,deleteOnOff:t==="on"?r:void 0,userId:this.getCurrentUserId()}))}}class fu{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 pu=e=>{switch(e){case ke.SendingStatus.PENDING:return"pending";case ke.SendingStatus.SUCCEEDED:return"succeeded";case ke.SendingStatus.FAILED:return"failed";case ke.SendingStatus.SCHEDULED:return"scheduled";default:return}};class Eu{constructor(t,n){C(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!Fe(n,this.getCurrentUserId()))return;const r=pu(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 fu({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:mt(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 _u{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 iu(this.emit),incomingMessage:new lu(this.emit,n),outgoingMessage:new Eu(this.emit,n),memory:new gu(this.emit,n)}}start(){const t=new pe.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 ns=(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))(ns||{});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 Rr{constructor(){C(this,"userId");C(this,"authToken");C(this,"sessionHandler")}}const Cu=e=>({onSessionTokenRequired:t=>{t(null),e.send(dt.AnonymousSessionTokenExpired())}}),rs=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),Su="ai_agent:stats",ss="ai_agent:assertion",vu="conversation_initial_render",bu="conversation_not_interactive_timeout",yu="recovery_not_interactive_timeout",Au="conversation_list_initial_render",Tu="message_pending_stuck",Iu="aiev_auth_expired_unhandled",xu="user_perceived_response_time",Mu="stream_stalled",Ru="ai_typing_indicator_absent_timeout",ku="rendered_content_unusable",wu="streaming_message_validation",Lu="duplicate_message_response",Ou="message_lifecycle_event",Nu=800220;var j=(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))(j||{});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,Du=e=>{if(Pi(e))return typeof e.code=="number"?e.code:void 0},Pu=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 Su}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=Du(t)??Nu,this.errorDescription=Pu(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=rs({...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 Us 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 Iu}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 os{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),wr=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&yt(n.measure.channelUrl,t))return!0;return!1},an=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class $u extends Ht{onPayloadParseFailed(t){new Us().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new Us().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Fu 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(j.PAGE_RENDER),this.timers.delete(j.PAGE_RENDER_FROM_CACHE),this.timers.delete(j.GET_CHANNEL),this.timers.delete(j.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return vu}buildPayload(){const n=this.getTimer(j.AUTH),r=this.getTimer(j.PAGE_RENDER),s=this.getTimer(j.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,[j.AUTH]:n.duration,[j.GET_CHANNEL]:this.getTimer(j.GET_CHANNEL).duration,[j.GET_MESSAGES]:this.getTimer(j.GET_MESSAGES).duration,[j.PAGE_RENDER_FROM_CACHE]:i}})}}class Uu extends os{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(j.PAGE_RENDER).startTimer(j.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(j.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(j.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(j.GET_CHANNEL).setError(r).stopTimer(j.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(j.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(j.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(j.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(j.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(j.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(j.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Bu 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 Fu().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(j.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(j.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(j.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 Uu(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 Hu extends qe{constructor(){super(...arguments);C(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(j.PAGE_RENDER),this.timers.delete(j.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Au}buildPayload(){const n=this.getTimer(j.AUTH),r=this.getTimer(j.PAGE_RENDER),s=this.getTimer(j.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,[j.AUTH]:n.duration,[j.GET_LIST]:s}})}}class Gu extends os{constructor(n,r){var s;super(n,r);C(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(j.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(j.PAGE_RENDER),this.stats.startTimer(j.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(j.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(j.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(j.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(j.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class zu 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 Hu().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(j.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(j.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(j.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(j.AUTH),this.activeSpan=new Gu(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Vu 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 bu}buildPayload(){const n=this.getTimer(j.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class Ku extends Tt{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new Vu().setCommitCallback(this.commitCallback).startTimer(j.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(j.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 qu 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 ss}getMetricKey(){return Lu}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 Wu=500,Yu=(e,t)=>Fe(e,t)&&!ye.isStreaming(e)&&!!e.message;class ju 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!==ke.SendingStatus.SUCCEEDED)&&Fe(i,r)){if(!Yu(i,r))return"stop";if(!s)s=i;else return o=i,"stop"}}),s&&o?{latest:s,previous:o}:null}emit(n,r,s){an(this.emittedMessageChannels,Wu),this.emittedMessageChannels.set(n.messageId,s.channelUrl),new qu().setDuplicatePair({previousMessageId:r.messageId,nextMessageId:n.messageId}).setConversationId(s.conversationId).setCommitCallback(this.commitCallback).commit()}}const Xu=-1;class Zu extends qe{constructor(){super(...arguments);C(this,"timestamps")}setTimestamps(n){return this.timestamps=n,this}setFailure(n){return this.setError(n),this}getStatType(){return ss}getMetricKey(){return Ou}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?Xu: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 Ju=3e4,Qu=1e4,ed=e=>{var t;return((t=e.extendedMessagePayload)==null?void 0:t.is_last_in_turn)===!0};class td extends os{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"),Ju)}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),ye.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"),Qu)}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 nd 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===pe.CollectionEventSource.EVENT_MESSAGE_UPDATED;s.messages.forEach(i=>{Fe(i,n.aiAgentUserId)&&jr(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=ye.isStreaming(r);ed(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 Zu().setConversationId(n).setCommitCallback(this.commitCallback);return new td(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 rd 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 Tu}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 sd=5e3,Bs=1e4;class od extends Tt{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new rd().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?Bs:sd;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),Bs))}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 yu}buildPayload(){const n=this.getTimer(j.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class id 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(j.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(j.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 ad 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 ku}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 cd=500;class ld extends Ht{constructor(){super(...arguments);C(this,"measure",{committed:new Set})}onMessageUpdated(n){const r=n.message;Fe(r,n.aiAgentUserId)&&r.isUserMessage()&&(ye.isStreaming(r)||ye.isWelcomeMessage(r,n.aiAgentUserId)||r.message.trim().length>0||dl(r.extendedMessagePayload)||this.commitOnce({messageId:r.messageId,contentKind:"text",errorDomain:"empty_render"}))}onTemplateError(n){this.commitOnce({messageId:n.messageId,contentKind:"template",errorDomain:"template_error",errored:!0})}onFormError(n){this.commitOnce({messageId:n.messageId,contentKind:"form",errorDomain:"form_error",errored:!0})}clear(){this.measure.committed.clear()}commitOnce(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;an(this.measure.committed,cd),this.measure.committed.add(r),new ad().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.errored?{message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}}class ud 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 Mu}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 Hs=1e4,kt=5e3,dd=500;class md 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=Hs-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),Hs))}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 ud().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)||an(this.emittedMessageChannels,dd),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 hd 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 ss}getMetricKey(){return wu}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 gd=-1,fd=e=>e===pe.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===pe.CollectionEventSource.EVENT_MESSAGE_UPDATED;class pd 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"||!fd(r.source))return;const s=r.source===pe.CollectionEventSource.EVENT_MESSAGE_RECEIVED;r.messages.forEach(o=>{const i=this.records.get(o.messageId);if(!i){s&&Fe(o,n.aiAgentUserId)&&ye.isStreaming(o)&&this.start(o,n.channelUrl,n.conversationId);return}i.measure.channelUrl===n.channelUrl&&(i.stats.setConversationId(n.conversationId),this.advance(i,o),ye.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 hd().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(gd));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 Ed 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 Ru}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[j.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[j.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const Gs=3e3,_d=3e4;class Cd extends Tt{constructor(){super(...arguments);C(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new Ed().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),_d),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)||(an(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>=Gs&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=Gs&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class Sd 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 xu}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,[j.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[j.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[j.SEND_TO_ACK]:this.sendToAckMs}})}}const vd=.15,bd=10,yd=e=>e<=0?!1:e>=1?!0:Math.random()<e;class Ad 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)??vd}startTurn(n){if(this.collectedCount>=bd||!yd(this.samplingRate))return;this.collectedCount+=1;const r={stats:new Sd().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)||(an(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 Td(){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 zs={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},is={conversation:{...zs,messageAlertSoundEnabled:!1,list:{...zs,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Vs=e=>e?{conversation:Md(e.conversation),launcher:Id(e.launcher)}:is,Id=e=>Lt(is.launcher,e),xd=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},Md=e=>{const t=is.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:xd(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,rs(r));return n},Rd=(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(!Ks(e)||!Ks(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>Lr(e[r],t[r]))},Ks=e=>typeof e=="object"&&e!==null,kd=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}),wd=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 Ld{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 pe.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 Od{constructor(t){C(this,"_sdkUser");C(this,"_userSession");C(this,"_dispatcher");C(this,"_activeChannel");C(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(dt.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});C(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(dt.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),Nd=e=>JSON.parse(e);function Dd(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Pd(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 $d({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 Fd({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 as=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(as||{});const Bi=e=>typeof e=="object"&&e!==null,lr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Ud=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},Bd={1:Ud};function Hd(e){if(!Bi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Bd[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Gd(e,t,n,r){const s=ol.default.init({appId:e,modules:[new rt.GroupChannelModule,new Ce.AIAgentModule],localCacheEnabled:!0,options:new pe.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:pe.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function zd(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 Vd=[400300,400301,400302,400310],Kd=as.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),qd=e=>`${Kd}:${e}`;class cs{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 pe.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=Hd(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==as.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=>Vd.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=qd(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(zd(t.chatSDK),n=t.chatSDK):n=Gd(t.appId,t.extensions,t.messengerVersion,t.chatParams),new cs(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Wd=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},Yd=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 jd=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 qs 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 ls=(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))(ls||{}),us=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(us||{}),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 Xd=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Zd{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(!Xd(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 qs(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new qs(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??ls.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??us.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 ds{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:rs({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 Zd(t)}static init(t){return new ds(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class ms{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 ms}}function Jd(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 Qd=1440*60*1e3,em=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function We(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function tm(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const nm=e=>{const t={conversationInitialRender:new Bu(e),conversationNotInteractiveTimeout:new Ku(e),recoveryNotInteractiveTimeout:new id(e),conversationListInitialRender:new zu(e),aievAuthExpiredUnhandled:new $u(e),messagePendingStuck:new od(e),userPerceivedResponseTime:new Ad(e),streamStalled:new md(e),typingIndicatorAbsentTimeout:new Cd(e),renderedContentUnusable:new ld(e),streamingMessageValidation:new pd(e),duplicateMessageResponse:new ju(e),messageLifecycleEvent:new nd(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class Nn extends Ld{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",Vs());C(this,"_networkStateAdapter");C(this,"_scheduleForegroundTask");C(this,"_watchBackgrounded");C(this,"_forceCreateChannel");C(this,"_agentVersion");C(this,"_statsTrackers");C(this,"_liveMetricManager");C(this,"_operationQueue",Td());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(dt.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:b,session_token:_,expire_at:E}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:b,authToken:_,expireAt:E}),g={userId:b,authToken:_},this._logger.debug("AIAgent.authenticate: anonymous user created",b)}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(dt.MessengerSettingsUpdated({settings:h,source:"server"}));const f=(()=>{var b;return s.type==="anonymous"?Cu(this._dispatcher):(b=s.userSessionCandidate)==null?void 0:b.sessionHandler})(),p=await this._chatClient.connect(g,f,b=>{var _;this._logger.debug("AIAgent: session token refreshed"),(_=this._session)==null||_._updateAuthToken(b),this._deskClient.refreshDeskAuthToken(b)},()=>{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:b})=>{var _;if(b===zi.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,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 Od({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)tm(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(dt.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"),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(dt.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),Or(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 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});C(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Qd<=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 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=Wd(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&Yd(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 _u(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var f;const r=Hi.get(n.platform),s=n.logger??new Ni(n.logLevel??ns.WARN),o=n.dispatcher??new wi(s),i=n.useMMKVStorage?Jd(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=nm((p,b)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,b)});d=cs.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=em?ds.init({appId:n.appId,logger:s,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):ms.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=Vs(n);Rd(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 be=(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(b=>b[f]===p?b:{...b,[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 rm(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function sm(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":om(e,t)}function om(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 im(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 am=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__,cm=({data:e,extendedMessagePayload:t,ticketClosureLabels:n})=>{if(am){const r=jd(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}))},lm=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"),Ws=(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=lm(e);return r?`#${_n(r[0])}${_n(r[1])}${_n(r[2])}${n}`:e},um=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},dm=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",mm=e=>e.length>0,hm=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},Ys=e=>e.length===0?"empty":e.every(t=>Ve(t.type))?"images":"non_images",gm=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=hm(t),s=Ys(e),o=Ys(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,fm=e=>e%Dt===0?Dt:Vi,pm=({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=be("AIAgent"),Em=Ki.Provider,Te=Ki.useContext;function _m(e){const t=Cm(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(Em,{value:n},e.children)}function Cm(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=Sm(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 Sm(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 qn=()=>{const[e,t]=l.useState(0),n=l.useCallback(()=>t(r=>r+1),[]);return n.revision=e,n};let vm=0;function bm(){return l.useState(()=>`${vm++}`)[0]}const ht=(e,t,n)=>{const r=l.useRef(t),o=bm();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 ym(e,t){return!e||!t?!0:e.url!==t.url}function je(e){return e!=null&&"sendingStatus"in e}function Am(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return je(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Tm(e,t){return Am(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function js(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 Xs(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Zs(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const Im=({...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=xm(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];Mm(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=>Tm(s,n));return t.value.clearBeforeAction?e.newMessageMap=Zs(r,js):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Zs(r,js)}),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}}},xm=e=>e.reduce((t,n)=>(je(n)?(t[n.reqId]=n,n.sendingStatus===ke.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Mm=(e,t,n=!1)=>{if(!je(e)||!je(t))return!0;if(n&&e&&ye.isStreaming(t)){if(!ye.isStreaming(e))return!1;const r=e.message??"",s=t.message??"";if(s.length<r.length&&r.startsWith(s))return!1}return e.sendingStatus===ke.SendingStatus.SUCCEEDED?t.sendingStatus===ke.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Rm=(e=km)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(Im,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(_,E,y,T)=>{i({type:"update_messages",value:{messages:_,clearBeforeAction:E,currentUserId:y,strictStreamingOrder:T}})},u=(_,E)=>{i({type:"delete_messages",value:{messageIds:_,reqIds:E}})},d=(_,E,y)=>{i({type:"update_new_messages",value:{messages:_,clearBeforeAction:E,currentUserId:y}})},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]),b=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:b,newMessages:p,updateNewMessages:d,deleteNewMessages:m}},Js=Math.floor(Number.MAX_SAFE_INTEGER/10);function km(e,t){let n=0,r=0;return je(e)&&e.sendingStatus!=="succeeded"&&(n=Js),je(t)&&t.sendingStatus!=="succeeded"&&(r=Js),e.createdAt+n-(t.createdAt+r)}const wm=(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 Qs(e){return e<Date.now()?Dn.collection.message.searchLimit:Dn.collection.message.defaultLimit}const Lm=(e,t,n={})=>{var Ie,Le;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=Qs(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=qn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:g,loading:f,refreshing:p,messages:b,newMessages:_,updateMessages:E,updateNewMessages:y,deleteNewMessages:T,deleteMessages:A,updateInitialized:I,updateLoading:k,updateRefreshing:L}=Rm(n==null?void 0:n.sortComparator),R=ce(x=>{var w,D,z,Q;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 pe.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case pe.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case pe.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(z=(D=r.current).markAsRead)==null||z.call(D,[s.current]);break}}catch(ie){(Q=o==null?void 0:o.warn)==null||Q.call(o,"[useGroupChannelMessages/markAsReadBySource]",ie)}}),M=ce((x,w)=>{var D,z,Q,ie,te;if(w.length>0)switch(x){case pe.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case pe.CollectionEventSource.SYNC_MESSAGE_FILL:{(z=(D=r.current).shouldCountNewMessages)!=null&&z.call(D)&&y(w,!1,(Q=e.currentUser)==null?void 0:Q.userId),(te=(ie=r.current).onMessagesReceived)==null||te.call(ie,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((z,Q)=>{var Oe,W,ge;h.current.instance&&h.current.instance.dispose(),R(),y([],!0,(Oe=e.currentUser)==null?void 0:Oe.userId);const ie=()=>{var ue,Ee;const{pendingMessages:Z,failedMessages:me}=h.current.instance??{};Xs(Z)&&E(Z,!1,(ue=e.currentUser)==null?void 0:ue.userId),Xs(me)&&E(me,!1,(Ee=e.currentUser)==null?void 0:Ee.userId)},te=wm(x,D,{...r.current,startingPoint:w});h.current={apiInitialized:!1,initialized:!1,instance:te},te.setMessageCollectionHandler({onMessagesAdded:(Z,me,ue)=>{var Ee;R(Z.source),M(Z.source,ue),E(ue,!1,(Ee=e.currentUser)==null?void 0:Ee.userId,u),$({kind:"messagesAdded",source:Z.source,channelUrl:x.url,messages:ue})},onMessagesUpdated:(Z,me,ue)=>{var Ee,Be,He;R(Z.source),M(Z.source,ue),E(ue,!1,(Ee=e.currentUser)==null?void 0:Ee.userId,u),Z.source===pe.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((He=(Be=r.current).onMessagesUpdated)==null||He.call(Be,ue)),$({kind:"messagesUpdated",source:Z.source,channelUrl:x.url,messages:ue})},onMessagesDeleted:(Z,me,ue,Ee)=>{const Be=Ee.map(Je=>Je.messageId),He=Ee.filter(je).map(Je=>Je.reqId);A(Be,He),T(Be,He),$({kind:"messagesDeleted",source:Z.source,channelUrl:x.url,messages:Ee})},onChannelDeleted:(Z,me)=>{var ue,Ee;(Ee=(ue=r.current).onChannelDeleted)==null||Ee.call(ue,me)},onChannelUpdated:(Z,me)=>{var ue,Ee;m(),(Ee=(ue=r.current).onChannelUpdated)==null||Ee.call(ue,me,Z)},onHugeGapDetected:()=>{N(x,Number.MAX_SAFE_INTEGER,Dn.collection.message.defaultLimit)}});let Se=!1;(ge=(W=r.current).onCollectionInitializeStart)==null||ge.call(W),te.initialize(rt.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((Z,me)=>{var ue,Ee,Be,He,Je;(Ee=(ue=r.current).onCacheResult)==null||Ee.call(ue,Z,me??[],x.url),Z?(e.isCacheEnabled&&((Be=o==null?void 0:o.error)==null||Be.call(o,"[useGroupChannelMessages/onCacheResult]",Z)),Se=!0):me&&((He=o==null?void 0:o.debug)==null||He.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",me.length),E(te.succeededMessages,!0,(Je=e.currentUser)==null?void 0:Je.userId),ie(),me.length>0&&(h.current.initialized=!0,z())),$({kind:"initialized",source:"cache",channelUrl:x.url,messages:me??[],error:Z})}).onApiResult((Z,me)=>{var ue,Ee,Be,He,Je,Pe,et;(Ee=(ue=r.current).onApiResult)==null||Ee.call(ue,Z,me??[],x.url),h.current.initialized=!0,h.current.apiInitialized=!0,Z?((Be=o==null?void 0:o.warn)==null||Be.call(o,"[useGroupChannelMessages/onApiResult]",Z),Se?Q(Z):z()):me&&((He=o==null?void 0:o.debug)==null||He.call(o,"[useGroupChannelMessages/onApiResult]","message length:",me.length),E(te.succeededMessages,!0,(Je=e.currentUser)==null?void 0:Je.userId),r.current.startingPoint||(et=(Pe=r.current).onMessagesReceived)==null||et.call(Pe,me),e.isCacheEnabled&&ie(),z()),$({kind:"initialized",source:"api",channelUrl:x.url,messages:me??[],error:Z})})}));ht(e,{onUserBanned(x,w){var D,z,Q;x.isGroupChannel()&&!ym(x,s.current)&&(w.userId===((D=e.currentUser)==null?void 0:D.userId)?(Q=(z=r.current).onCurrentUserBanned)==null||Q.call(z):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,(Ie=e.currentUser)==null?void 0:Ie.userId,(Le=s.current)==null?void 0:Le.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const ee=ce(async()=>{e.currentUser&&s.current&&(L(!0),await N(s.current,Number.MAX_SAFE_INTEGER,Dn.collection.message.defaultLimit),L(!1))}),oe=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}}),q=ce(()=>{const{initialized:x,instance:w}=h.current;return x&&w?w.hasPrevious:!1}),Y=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}}),B=ce(()=>{const{initialized:x,apiInitialized:w,instance:D}=h.current;return w&&x&&D?D.hasNext:!1}),X=x=>{var w,D,z,Q;!x||x.channelUrl!==((w=s.current)==null?void 0:w.url)||(E([x],!1,(D=e.currentUser)==null?void 0:D.userId),(Q=(z=r.current).onOutgoingMessageStatusChanged)==null||Q.call(z,x))},P=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((z,Q)=>{s.current.sendUserMessage(x).onPending(ie=>{X(ie),w==null||w(ie)}).onSucceeded(ie=>{X(ie),z(ie)}).onFailed((ie,te)=>{X(te),Q(ie)})})}),V=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((z,Q)=>{s.current.sendFileMessage(x).onPending(ie=>{X(ie),w==null||w(ie)}).onSucceeded(ie=>{X(ie),z(ie)}).onFailed((ie,te)=>{X(te),Q(ie)})})}),H=ce((x,w,D)=>{var z;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((Q,ie)=>{s.current.sendMultipleFilesMessage(x).onPending(te=>{X(te),w==null||w(te)}).onFileUploaded(te=>{D==null||D(te),m()}).onSucceeded(te=>{X(te),Q(te)}).onFailed((te,Se)=>{X(Se),ie(te)})})}),K=ce(async(x,w)=>{var z,Q;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.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,(Q=e.currentUser)==null?void 0:Q.userId),D}),G=ce(async(x,w)=>{var z,Q;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.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,(Q=e.currentUser)==null?void 0:Q.userId),D}),J=ce(async(x,w,D)=>{var z;if(!s.current||!s.current.url)throw(z=o==null?void 0:o.error)==null||z.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((Q,ie)=>{let te;x.isUserMessage()&&(te=s.current.resendMessage(x)),x.isFileMessage()&&(te=s.current.resendMessage(x)),x.isMultipleFilesMessage()&&(te=s.current.resendMessage(x)),te&&("onPending"in te&&te.onPending(Se=>{X(Se),w==null||w(Se)}),"onFileUploaded"in te&&te.onFileUploaded(Se=>{D==null||D(Se),m()}),"onSucceeded"in te&&te.onSucceeded(Se=>{X(Se),Q(Se)}),"onFailed"in te&&te.onFailed((Se,Oe)=>{X(Oe),ie(Se)}))})}),ae=ce(async x=>{var w,D,z,Q;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{A([],[x.reqId]),(Q=(z=r.current).onLocalMessageDeleted)==null||Q.call(z,x)}}),O=ce(()=>{var x;y([],!0,(x=e.currentUser)==null?void 0:x.userId)}),ve=ce(async x=>{var w;if(e.currentUser&&s.current){const D=Qs(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:b,newMessages:_,resetNewMessages:O,refresh:ee,loadPrevious:oe,hasPrevious:q,loadNext:Y,hasNext:B,sendUserMessage:P,sendFileMessage:V,sendMultipleFilesMessage:H,updateUserMessage:K,updateFileMessage:G,resendMessage:J,deleteMessage:ae,resetWithStartingPoint:ve,_dangerous_reducer_updateMessages:E,_dangerous_reducer_deleteMessages:A}},Om=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,Nm=(e,t,n)=>{const r=Lm(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!Om(o)),[r.messages]);return{...r,messages:s}},Dm=()=>{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))}}}},cn=Dm(),Pm=({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:b})=>{i.current=!0,n.markChannelJoined(b,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}},$m=({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 Fm(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 Um(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Bm(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 Hm(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]=Fm(e),[i,c,u]=Bm(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,g,f]=Hm(i,m,d);return Um([Math.round(h),Math.round(g),Math.round(f)])}function Gm(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 zm(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 Vm=(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 eo(e){const t=Km(e),n=qm(e,t),r=Ym(n,e.colors,e.selectedTheme),s=Xm(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 Km({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Sn.primary.main?Sn.primary:Gm(n,e):Sn.primary;return{...Sn,primary:r,...t}}function qm({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"?zm:Vm)(s,o,i,c,u)}function Wm(e,t,n){return typeof e=="string"?e:e[t]??n}function Ym(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]=Wm(m,n,h)}}}return r}function jm(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Xm({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]=jm(s,r,o)}}),t}const{Provider:Zm,useContext:Wn}=be("AIAgentTheme");function Jm({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>eo({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,b={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!b.primary&&(p!=null&&p.primary_color)&&(b.primary=p.primary_color,b.primaryContrast=p.primary_contrast_color),!b.botMessageBackground&&(p!=null&&p.bot_message_bg_color)&&(b.botMessageBackground=p.bot_message_bg_color,b.botMessageBackgroundContrast=p.bot_message_bg_contrast_color);const _=eo({selectedTheme:f,palette:t,typography:n,colors:r,...b});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(Zm,{value:m},o)}const Qm=25*1024*1024,to=1,no=new Set(["image/png","image/jpeg","image/jpg"]),ro=new Set(["application/pdf"]),eh={off:"off",always:"always",handed_off_only:"handed_off_only"},th=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:to,attachmentMode:"handed_off_only",defaultUploadSizeLimit:void 0,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:no,supportedFileMimeTypes:ro})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??to,attachmentMode:eh[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)??no),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??ro)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i}=s,c=e.defaultUploadSizeLimit??i??Qm,u=(m=!0)=>o!=null&&o.isAIAgent?m?mt(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 mt(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}},so=(...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:nh,useContext:Ze}=be("AIAgentMessengerSession"),rh=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,b]=l.useState(null),[_,E]=l.useState(null),[y,T]=l.useState(null),[A,I]=l.useState(null),{updateBaseAttachmentRules:k,createAttachmentRules:L}=th();l.useEffect(()=>{const N=r.onMessengerSettingsUpdated(({settings:q})=>{const{appearance:Y,bot:B,launcher:X,memory:P}=q;c(Y.selected_theme,Y),E(kd(B)),T(wd(X)),I(P?Or(P):null),k(q)}),ee=r.onActiveChannelUpdated(({channelUrl:q,status:Y,conversationStatus:B})=>{h({url:q,status:Y,conversationStatus:B})}),oe=r.onAuthTokenRefreshed(()=>{var Y;const q=(Y=r.session)==null?void 0:Y.userSession.authToken;q&&b(B=>B?{...B,authToken:q}:null)});return()=>{N(),ee(),oe()}},[r,c,k]);const R=l.useCallback(async()=>{try{const N=await r.authenticate(e),ee=r.session;return f(ee.sdkUser),b(ee.userSession),h(ee.activeChannel),d(void 0),N}catch(N){throw f(null),b(null),h(void 0),d(N),N}},[r,e]),M=l.useCallback(async()=>{await r.deauthenticate(),f(null),h(void 0),b(null),E(null),T(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(...ee)=>{const oe=so(...ee);if(oe.type==="active"){const B=await(await N()).updateContext(o,oe.context);return Wt(B)}const q=await s.aiAgent.updateContext(oe.aiAgentId,oe.channelUrl,oe.context);return Wt(q)},patchContext:async(...ee)=>{const oe=so(...ee);if(oe.type==="active"){const B=await(await N()).patchContext(o,oe.context);return Wt(B)}const q=await s.aiAgent.patchContext(oe.aiAgentId,oe.channelUrl,oe.context);return Wt(q)},getContextObject:async()=>{const oe=await(await N()).getContextObject(o);return Wt(oe)},requestNudgeMessage:ee=>r.requestNudgeMessage(ee)}},[R,M,m,s,o,i,r]),a.createElement(nh,{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:y,memoryInfo:A,authenticate:R,deauthenticate:M,createAttachmentRules:L}},t)}),sh={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"},oh=e=>e.disabled?sh[e.disabledBy]==="ready":!0,ih=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&&sn(t)?"file_video":t&&pl(t)?"file_audio":"file_document"};let oo=0;const ah=e=>(oo+=1,`${e??"unknown"}:${oo}`),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)},ch=(e,t)=>{Wi(e,t)},lh=(e,t)=>{Yi(e,t)},uh=(e,t,n)=>{var o;if(!Fe(e,n))return;const{hasResponseMetadata:r,...s}=jr(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}))},io=(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))},dh=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=Te(),{aiAgentInfo:r}=Ze(),s=l.useRef(!1),o=r==null?void 0:r.userId;ht(!!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])},mh=({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])},hh=({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=>io(p,r));return}t&&f.messages.forEach(p=>uh(p,r,e))}},onCacheResult:(f,p,b)=>{if(!h(m)||!Ot(n,b))return;const _={error:f,messages:p,channelUrl:b,lifecycleGeneration:u.current,tracked:!1};s.current=_,t&&(ch(r,_),_.tracked=!0)},onApiResult:(f,p,b)=>{if(!h(m)||!Ot(n,b))return;const _={error:f,messages:p,channelUrl:b,lifecycleGeneration:u.current,tracked:!1};o.current=_,t&&(lh(r,_),_.tracked=!0)},onLocalMessageDeleted:f=>{h(m)&&Ot(n,f.channelUrl)&&io(f,r)}}),[e,m,t,h,n,r])},gh=({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])},fh=({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(b=>u==null?void 0:u(b),()=>{});let m;const h=i.current,g=s.current,f=()=>r.current&&o.current&&i.current===h&&s.current===g,p=b=>f()&&Ot(g,b);try{const b=await c(_=>{if(!p(_.channelUrl)){u==null||u(_);return}m=_.reqId,n.messagePendingStuck.start({requestId:_.reqId,channelUrl:_.channelUrl,messageType:ih(_),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})),b}catch(b){throw m&&(f()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),b}},[n])},ph=({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=ah(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])},Eh=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=Ze();dh({activeChannelUrl:t,statsTrackers:r}),mh({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=hh({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=fh({channelUrl:t,enabled:n,statsTrackers:r}),c=ph({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},ot=()=>Te()._aiAgentSDK.statsTrackers,_h=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=ot(),{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();Me(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},Ch=({enabled:e=!0,channelUrl:t,conversationId:n,messages:r})=>{const{duplicateMessageResponse:s}=ot(),{aiAgentInfo:o}=Ze(),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])},Sh=({enabled:e=!0,channelUrl:t,conversationId:n}={})=>{const{messageLifecycleEvent:r}=ot(),{chatSDK:s,_aiAgentSDK:o}=Te(),{watchBackgrounded:i}=o,{aiAgentInfo:c}=Ze(),u=c==null?void 0:c.userId,d=e&&!!t&&!!u;l.useEffect(()=>{r.setBackgroundedWatcher(i)},[r,i]),ht(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=cn.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!==ke.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}},vh=({enabled:e=!0,channelUrl:t}={})=>{const{renderedContentUnusable:n}=ot(),{aiAgentInfo:r}=Ze(),s=r==null?void 0:r.userId,o=e&&!!t;l.useEffect(()=>{if(o)return cn.subscribe(u=>{u.channelUrl!==t||!(u.source===pe.CollectionEventSource.EVENT_MESSAGE_RECEIVED||u.source===pe.CollectionEventSource.EVENT_MESSAGE_UPDATED)||u.messages.forEach(m=>n.onMessageUpdated({message:m,aiAgentUserId:s}))})},[s,t,o,n]);const i=l.useCallback(u=>{o&&n.onTemplateError({messageId:u})},[o,n]),c=l.useCallback(u=>{o&&n.onFormError({messageId:u})},[o,n]);return{onTemplateError:i,onFormError:c}},bh=({enabled:e=!0,channelUrl:t,conversationId:n}={})=>{const{streamingMessageValidation:r}=ot(),{watchBackgrounded:s}=Te()._aiAgentSDK,{aiAgentInfo:o}=Ze(),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=cn.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 pe.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])},ao=()=>{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 yh(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=Te(),{sdkUser:u}=Ze(),d=ao(),m=ao(),[h,g]=l.useState(void 0),f=qn(),[p,b]=l.useState(void 0),[_,E]=l.useState(!1),y=ce(A=>{if(n&&A.isAIAgent&&!A.conversation){const I=m.next();E(!0),c.initConversationIfNeeded(A,{initialUserMessage:r}).finally(()=>{m.isCurrent(I)&&E(!1)})}});async function T(){var I,k,L,R,M,$;const A=d.next();if(!u){o.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(o.debug("useChannel.getChannel: start"),g(void 0),b(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(A))return;y(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(A))return;($=t.onFetchError)==null||$.call(t,{channelUrl:e,error:N}),N instanceof pe.SendbirdError&&b(N),o.error("useChannel.getChannel: error",N)}}}return l.useEffect(()=>(T(),()=>{d.invalidate()}),[s,u,e,i]),l.useEffect(()=>{n&&h&&y(h)},[n]),ln(s,{async onReconnectSucceeded(){var A;try{if(!h){p&&await T();return}const I=d.current(),k=await h.refresh();if(!d.isCurrent(I)||h.url!==e)return;(A=t.onReconnectSucceeded)==null||A.call(t,h.url),y(k),g(k)}catch(I){o.error("useChannel.onReconnectSucceeded: failed to sync the channel",I)}}}),ht(s,{onChannelChanged:A=>{A.isGroupChannel()&&A.url===e&&(o.debug("useChannel.onChannelChanged: channel changed",A.url),g(A),f())}}),{channel:h,channelRevision:f.revision,channelFetchError:p,getChannel:T,isInitializingConversation:_}}const Ah=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=Vn(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}},Th=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=Vn(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},Ih=()=>{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===pe.ConnectionState.OPEN?"connected":o)})},[t,e]),n},xh=3e4,Mh=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&Fe(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=xh-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 ht(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},Rh=({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=Fe(t,n)&&(ye.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},kh=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=Ze(),i=Ih(),c=Rh({channel:e,lastMessage:Mr(t,[ke.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Mh({shouldApply:!!(e!=null&&e.isAIAgent)&&!mt(e),isBlockedWhileAIResponding:c,lastMessage:Mr(t,[ke.SendingStatus.PENDING,ke.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(Ql(e))return bt.handoff_pending;if(Th(e))return bt.form_active;const d=Ah(e);return d?bt[d]:c||u||r?bt.ai_responding:wh},ut=e=>Object.freeze(e==="ai_responding"?{disabled:!0,disabledBy:e,focusPolicy:"preserve"}:{disabled:!0,disabledBy:e,focusPolicy:"release"}),wh=Object.freeze({disabled:!1,disabledBy:"",focusPolicy:"auto"}),bt=Object.freeze({ai_responding:ut("ai_responding"),unavailable:ut("unavailable"),form_active:ut("form_active"),conversation_closed:ut("conversation_closed"),suggested_replies:ut("suggested_replies"),steward:ut("steward"),system:ut("system"),reconnecting:ut("reconnecting"),handoff_pending:ut("handoff_pending")}),Lh=()=>{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:Oh}=be("AIAgentConversation");function Nh({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=_e,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,initialUserMessage:g,shouldCountNewMessages:f=()=>!1,sortComparator:p}){var Q,ie,te,Se,Oe;const{_aiAgentSDK:b,chatSDK:_,logger:E,dispatcher:y}=Te(),T=()=>{d&&(M==null||M.markAsRead().catch(W=>E.warn("AIAgentConversationContext: markAsRead failed",W)))},A=ot(),I={channelUrl:t,enabled:m},k=Pm({...I,statsTracker:A.conversationNotInteractiveTimeout}),L=$m({...I,scheduleForegroundTask:b.scheduleForegroundTask,statsTracker:A.recoveryNotInteractiveTimeout}),R=_h(I),{channel:M,channelRevision:$,channelFetchError:N,getChannel:ee,isInitializingConversation:oe}=yh(t,{shouldInitializeConversation:h,initialUserMessage:g,onFetchStart:W=>{k.onFetchStart(W),R.onGetChannelStart(W)},onFetchSuccess:W=>{k.onFetchSuccess(W),R.onGetChannelComplete(W)},onFetchError:W=>{k.onFetchError(W),R.onGetChannelError(W)},onReconnectSucceeded:L.onReconnectSucceeded}),q=M==null?void 0:M.url,Y=Sh({enabled:m&&!!(M!=null&&M.isAIAgent)&&M.hasAiBot,channelUrl:q,conversationId:(Q=M==null?void 0:M.conversation)==null?void 0:Q.id}),B=vh({enabled:m,channelUrl:q}),X=Eh({requestedChannelUrl:t,activeChannelUrl:q,statsEnabled:m,statsTrackers:A}),P=Nm(_,M,{replyType:ke.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:f,logger:E,markAsRead:T,sortComparator:p,onChannelDeleted:n,onMessagesReceived:W=>r==null?void 0:r(W),onMessagesUpdated:W=>s==null?void 0:s(W),onCollectionInitializeStart:()=>{R.onCollectionInitializeStart()},onApiResult:(W,ge,Z)=>{R.onCollectionApiResult(W,Z),X.messageCallbacks.onApiResult(W,ge,Z)},onCacheResult:(W,ge,Z)=>{R.onCollectionCacheResult(W,Z),X.messageCallbacks.onCacheResult(W,ge,Z)},onCollectionEvent:W=>{X.messageCallbacks.onCollectionEvent(W),cn.publish(W)},onLocalMessageDeleted:W=>{X.messageCallbacks.onLocalMessageDeleted(W)},onOutgoingMessageStatusChanged:W=>{Y.onOutgoingMessageStatusChanged(W),M&&b.liveMetricManager.track({type:"outgoingMessage",channel:M,message:W})}}),V=Lh(),H=kh({channel:M,messages:P.messages,isStreamAnimating:V.isAnimating,isInitializingConversation:oe});bh({enabled:m,channelUrl:q,conversationId:(ie=M==null?void 0:M.conversation)==null?void 0:ie.id}),Ch({enabled:m,channelUrl:q,conversationId:(te=M==null?void 0:M.conversation)==null?void 0:te.id,messages:P.messages}),gh({enabled:m,channelUrl:q,initialized:P.initialized,inputReady:oh(H),renderedSignal:P.messages,statsTrackers:A}),l.useEffect(()=>{T()},[d,M]);const K=(Se=M==null?void 0:M.conversation)==null?void 0:Se.status;l.useEffect(()=>{K&&(o==null||o(K))},[K,o]),l.useEffect(()=>{const W=async ge=>{const Z=typeof(ge==null?void 0:ge.channelUrl)=="string";M&&Z&&ge.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 y.subscribe(ze.ConversationClose,W),()=>{y.unsubscribe(ze.ConversationClose,W)}},[y,M,E,(Oe=M==null?void 0:M.conversation)==null?void 0:Oe.status,i]);const G=ce(()=>P.loadPrevious()),J=ce(()=>P.loadNext()),ae=ce(async W=>{try{await P.deleteMessage(W)}finally{W.sendingStatus!=="succeeded"&&X.messageCallbacks.onLocalMessageDeleted(W)}}),O=ce(W=>W.isUserMessage()?X.runWithUserTurnStats(ge=>X.runWithPendingStuckStats(Z=>P.resendMessage(W,me=>{ge(me.reqId),Z(me)}),void 0)):X.runWithPendingStuckStats((ge,Z)=>P.resendMessage(W,ge,Z),void 0,{tracksUploadProgress:W.isMultipleFilesMessage()})),ve=ce(()=>P.resetNewMessages()),Ie=ce(async W=>{var Z;if(((Z=M==null?void 0:M.conversation)==null?void 0:Z.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(W=await c(W));const ge=await X.runWithUserTurnStats(me=>X.runWithPendingStuckStats(ue=>P.sendUserMessage(W,Ee=>{me(Ee.reqId),ue(Ee)}),u));return u==null||u(ge),ge}),Le=ce(async W=>{var Z;if(((Z=M==null?void 0:M.conversation)==null?void 0:Z.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(W=await c(W));const ge=await X.runWithPendingStuckStats(me=>P.sendFileMessage(W,me),u);return u==null||u(ge),ge}),x=ce(async W=>{var Z;if(((Z=M==null?void 0:M.conversation)==null?void 0:Z.status)===Ce.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(W=await c(W));const ge=await X.runWithPendingStuckStats((me,ue)=>P.sendMultipleFilesMessage(W,me,ue),u,{tracksUploadProgress:!0});return u==null||u(ge),ge}),w=ce(ee),D=ce(async()=>{$e(M)||await(M==null?void 0:M.closeConversation())}),z=l.useMemo(()=>({_statsEnabled:m,_stats:{onMessageLifecycleAnimationStart:Y.onAnimationStart,onMessageLifecycleAnimationComplete:Y.onAnimationComplete,onRenderedContentTemplateError:B.onTemplateError,onRenderedContentFormError:B.onFormError},conversation:(M==null?void 0:M.conversation)??void 0,actions:{setUserMemoryState:b.setUserMemoryState},channelSource:{channel:M,error:N,refetch:w,closeConversation:D},messageSource:{messages:P.messages,newMessages:P.newMessages,initialized:P.initialized,loadPrevious:G,loadNext:J,deleteMessage:ae,resendMessage:O,resetNewMessages:ve,sendUserMessage:Ie,sendFileMessage:Le,sendMultipleFilesMessage:x},state:{streamAnimation:V,input:H}}),[m,Y.onAnimationStart,Y.onAnimationComplete,B.onTemplateError,B.onFormError,M,$,b,N,w,D,P.messages,P.newMessages,P.initialized,P.collectionRevision,G,J,ae,O,ve,Ie,Le,x,V,H]);return a.createElement(Oh,{value:z},e)}function Dh(e,t,n){var E,y,T,A,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 ee;return(ee=n==null?void 0:n.onListRequestComplete)==null?void 0:ee.call(n,N)}),p=l.useCallback(async N=>{g();try{await N.loadMore(),f()}catch(ee){throw f(ee),ee}},[g,f]),b=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,(T=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:T.join(),(I=(A=t.filter)==null?void 0:A.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:()=>b()}),l.useEffect(()=>{b()},[b]),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}},Ph=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=ot(),{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();Me(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:$h}=be("AIAgentConversationList");function Fh({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=Ph({enabled:n}),d=Dh(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($h,{value:m},r)}function Uh(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:Bh,useContext:Hh}=be("MessageTemplateFetching");function Gh({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 b=d(h).catch(_=>{throw g||i(h,{error:!0}),_}).finally(()=>{g||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=b,b},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=Uh(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(Bh,{value:u},e)}const zh="remove_powered_by",hs=(e,t)=>{var s,o;const{chatSDK:n}=Te(),{aiAgentInfo:r}=Ze();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&&Qr(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(zh)),[i])}throw new Error("Unsupported feature")},Vh={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"},Kh={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}}},qh={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}}},Wh={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}}},Yh={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}}},jh={text:Kh,number:qh,"single-select":Wh,"multi-select":Yh},Xh={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Zi(e){return jh[e.type]||Xh}function co(e){return Zi(e).getValueOrDefault(e)}function Zh(e,t,n={}){const r={...Vh,...n};return Zi(e).validate(e,t,r)}const Jh=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const b={};return e.fields.forEach(_=>{b[_.key]=co(_)}),b}),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 b={};let _=!1;e.fields.forEach(E=>{const y=co(E);JSON.stringify(c[E.key])!==JSON.stringify(y)&&(_=!0),b[E.key]=y}),_&&u(b)}},[d]);const m=(b,_)=>{u(E=>({...E,[b]:_})),i(E=>({...E,[b]:void 0}))},h=e.fields.map(b=>{var y,T,A;const _=c[b.key]??null,E={key:b.key,label:b.label,error:o[b.key],required:b.required};return b.type==="text"?{...E,type:"text",layout:b.layout,value:_,...b.placeholder&&{placeholder:b.placeholder},...((y=b.rules)==null?void 0:y.max_length)&&{maxLength:b.rules.max_length}}:b.type==="number"?{...E,type:"number",layout:b.layout,value:_,...b.placeholder&&{placeholder:b.placeholder},...((T=b.rules)==null?void 0:T.max)&&{max:b.rules.max}}:b.type==="single-select"?{...E,type:"single-select",layout:b.layout,value:_,options:b.options}:b.type==="multi-select"?{...E,type:"multi-select",layout:b.layout,value:_,options:b.options,...((A=b.rules)==null?void 0:A.max_select)&&{maxSelect:b.rules.max_select}}:{...E,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:b=>h.find(_=>_.key===b),updateFieldValue:m,submit:async()=>{const b={};let _=!1;for(const E of e.fields){const y=c[E.key]??null,T=Zh(E,y,n);T.isValid||(b[E.key]=T.error,_=!0)}if(i(b),!_&&r){const E={};e.fields.forEach(y=>{E[y.key]=c[y.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}=Ze(),[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(b=>m(_=>({seq:_.seq+1,response:b})))},[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 b=n.session;try{const E=await c({aiAgentId:r,language:s,country:o,context:i});if(n.session!==b)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",Qh=e=>Qi in e||ea in e,eg=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)||!Qh(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}))};ht(t,{onMetaDataCreated:o,onMetaDataUpdated:o})},tg=e=>{const{chatSDK:t,handlers:n,logger:r}=Te(),{aiAgentInfo:s}=Ze(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!Fe(m,s.userId))return;const g=m.messageId;if(ye.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 ht(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},lo=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}=Ze(),n=ji(e);if($e(e))return null;const r=n.find(i=>lo(i.metaData)!==void 0)??n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?lo(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},ng=250,rg=(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),ng);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},sg=(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},[])},og=(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()}}},ig=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=og(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])},ag=({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])},gs=({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?mt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},uo=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 cg=new Set(["free_text","single_choice"]),lg=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=uo({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=uo({followUpItem:!1}),d=l.useMemo(()=>{var _;const f=o.csat,p=typeof f=="number",b=(_=e.follow_up)==null?void 0:_.find(E=>p?E.scores.includes(f):E.always_visible??!1);if(cg.has(b==null?void 0:b.response_type))return b},[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",b=!((f=e.cre)!=null&&f.required)||typeof o.isResolved=="boolean";if(p&&b)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"}}},ug=({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=qn();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,dg=1500,gr=e=>Math.max(0,e-na),mg=(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,hg=(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,dg);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},gg=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},mo=(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=mo(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=mo(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},fg=({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(y=>{var T;(T=r.current)==null||T.call(r,y)},[]),m=l.useCallback(y=>{const T=e.initialEnabled&&(e.enabled||y<e.textLength),A=T&&e.deferImages,I=T&&e.deferLinks;return!A&&!I?y:ra(e.text.slice(0,y),{hideImages:A,hideLinks:I}).length},[e]),h=l.useCallback((y,T,A=!1)=>{r.current&&(y<=c.lastLength||!A&&T-c.lastReportedAt<Xt||(c.lastLength=y,c.lastReportedAt=T,d(y)))},[d,c]),g=l.useCallback((y,T,A=!1)=>{if(!r.current)return;const I=Math.max(c.lastReportedAt,c.lastCheckedAt);!A&&T-I<Xt||(c.lastCheckedAt=T,h(m(y),T,!0))},[m,h,c]),f=l.useCallback((y,T,A=!1)=>{s.current&&(y<=i.lastLength||!A&&T-i.lastReportedAt<Xt||(i.lastLength=y,i.lastReportedAt=T,s.current(y)))},[i]),p=l.useCallback((y,T,A)=>{const I=y>=T,k=A-i.lastReportedAt>=Xt;if(!I&&!k)return;const L=m(y);f(L,A,I)},[m,i,f]),b=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),_=l.useCallback(y=>{r.current&&(o.current!==null&&y<=o.current||(o.current=y,d(y)))},[d]),E=l.useCallback(({displayedLength:y,streamTextLength:T})=>{const A=u.current;if(u.current={displayedLength:y,streamTextLength:T},!e.initialEnabled||!A||y>A.displayedLength||T<=A.streamTextLength)return;const I=xn();h(T,I,!0),f(T,I,!0)},[u,f,h,e]);return{resetProgress:b,reportVisibleTextProgress:g,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:_,reportMarkdownRevealProgress:E}},pg=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=hg(n,t),g=s.includes("image"),f=s.includes("link"),[p,b]=l.useState(()=>n?h?0:gr(t.length):t.length),_=l.useRef(null),E=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,y=l.useRef({startCalled:!1,completeCalled:!1}).current,T=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,A=ce(()=>o==null?void 0:o()),I=ce(()=>i==null?void 0:i()),k=ce(P=>c==null?void 0:c(P)),L=ce(P=>u==null?void 0:u(P)),{resetProgress:R,reportVisibleTextProgress:M,reportRenderedTextProgress:$,reportNonStreamingVisibleTextProgress:N,reportMarkdownRevealProgress:ee}=fg({trackedRef:T,onVisibleTextProgress:d,onRenderedTextProgress:m}),oe=n,q=p<t.length,Y=T.initialEnabled&&(oe||q);l.useLayoutEffect(()=>{T.prevText=T.text,T.prevEnabled=T.enabled,T.textLength=t.length,T.enabled=n,T.text=t,T.deferImages=g,T.deferLinks=f,T.snapOnDisable=r,T.isGatingStreamingStart=h}),l.useLayoutEffect(()=>{if(!T.initialEnabled)return;y.startCalled||(y.startCalled=!0,A());const P=()=>{b(t.length);const J=xn();M(t.length,J,!0),$(t.length,t.length,J)};if(!T.enabled&&T.snapOnDisable){P();return}const{prevText:V,prevEnabled:H}=T;if(!H){T.resyncLength=t.length,R(),P();return}if(t.length>=V.length?t.startsWith(V):V.startsWith(t)){b(J=>t.length<J?t.length:J);return}const G=Math.max(1,Math.min(p,mg(V,t)));T.resyncLength=G,b(G)},[A,$,M,R,t]),l.useEffect(()=>{if(!T.initialEnabled)return;let P=h?0:gr(t.length),V=h;E.lastUpdate=0,E.startTime=0,E.lastProgressCall=0,R();const H=K=>{T.resyncLength!==null&&(P=T.resyncLength,T.resyncLength=null,E.lastUpdate=0,R(),V=!1),E.lastUpdate===0&&(E.lastUpdate=K,E.startTime=K,E.lastProgressCall=K,P>0&&M(P,K,!0));const G=T.textLength;V&&!T.isGatingStreamingStart&&(P=gr(G),b(P),P>0&&M(P,K,!0),E.lastUpdate=K,V=!1),!T.enabled&&T.snapOnDisable&&P<G&&(P=G,b(P),M(P,K,!0),$(P,G,K));const J=K-E.lastUpdate,ae=K-E.startTime,{speed:O,chunkSize:ve}=gg(ae),Ie=O*ve;!T.isGatingStreamingStart&&J>=Ie&&P<G&&(P=Math.min(P+ve,G),b(P),M(P,K,P>=G),$(P,G,K),E.lastUpdate=K),K-E.lastProgressCall>=Xt&&(E.lastProgressCall=K,I()),(P<G||T.enabled)&&(_.current=requestAnimationFrame(H))};return _.current=requestAnimationFrame(H),()=>{_.current&&cancelAnimationFrame(_.current),y.startCalled&&!y.completeCalled&&(y.completeCalled=!0,k({completed:!1}))}},[k,I,$,M,R]),l.useEffect(()=>{T.initialEnabled&&(n||t.length>0)||(N(t.length),$(t.length,t.length,xn()))},[n,m,d,N,$,t.length,T]),l.useEffect(()=>{const P=T.initialEnabled&&y.startCalled,V=!n,H=(T.resyncLength??p)>=t.length;P&&V&&H&&!y.completeCalled&&(y.completeCalled=!0,k({completed:!0}))},[n,p,k,t.length]);const B=l.useMemo(()=>{let P=t;T.initialEnabled&&(P=h?"":t.slice(0,p));const V=Y&&g,H=Y&&f;return!V&&!H?P:ra(P,{hideImages:V,hideLinks:H})},[t,p,g,f,Y,h]);l.useEffect(()=>{!T.initialEnabled||Y||M(p,xn(),!0)},[p,Y,M]),l.useEffect(()=>{ee({displayedLength:p,streamTextLength:B.length})},[p,ee,B.length]);const X=B.length===0&&Y&&!T.hasRevealed;return l.useLayoutEffect(()=>{!(T.resyncLength!==null&&T.resyncLength!==p)&&B.length>0&&(T.hasRevealed=!0)}),l.useLayoutEffect(()=>(L(X),()=>L(!1)),[L,X]),{streamText:B,isAnimating:Y,isHolding:X}},ho={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Eg=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),_g=(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}},Cg=()=>{const{chatSDK:e}=Te(),[t,n]=l.useState(ho),r=()=>n(ho);return ln(e,{onConnectionDelayed:s=>{s>0?n(Eg(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>_g(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},Sg=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},vg=(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)}},bg=({enabled:e=!0}={})=>{const t=ot();return l.useCallback(({message:n})=>{if(!e)return;const r=n.messageId,o=ye.isStreaming(n)||t.streamStalled.hasPendingStream(r),i=t.userPerceivedResponseTime.hasPendingAIResponse(r);if(!o&&!i)return;let c=!1;const u={};return i&&(u.onVisibleTextProgress=()=>{c||(c=t.userPerceivedResponseTime.markAIResponseVisible(r))}),o&&(u.onRenderedTextProgress=d=>{t.streamStalled.markRenderedProgress({messageId:r,displayedLength:d})}),u},[e,t])},yg=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},fr=5e3,Ag=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=ot(),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])},Tg=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=ot();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Ig=(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===pe.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(),xg="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}},Mg=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}},Rg=(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)},kg=(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},wg=(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},Lg=(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},Og=e=>{let t=0,n="";for(;t<e.length;){const r=kg(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=wg(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=Lg(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)},Ng=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}`}),Dg=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Pg=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),$g=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},Fg=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Ug=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},go=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))},fo=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},Bg=e=>{const t=e.split(`
12
+ `),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=fo(s);if(i.length>0&&o&&go(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=fo(c);if(u.length===0||go(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
13
+ `)},Hg=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Gg=(e,t)=>{const n=e.split(`
14
+ `),r=[];let s=0;for(;s<n.length;){const o=n[s],i=Mg(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(Rg(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},zg=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=xg}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
17
+ `);if(!n)return;const r=[];let s=n;s=Gg(s,t),s=Ug(s);const o=zg(s);s=o.text,r.push(...o.inlineCodes),s=Og(s),s=Ng(s),s=Dg(s),s=Pg(s),s=$g(s),s=Bg(s),s=Hg(s),s=Fg(s);for(let c=0;c<r.length;c++)s=s.replaceAll(sa(c),r[c]);return $t(s)||void 0},Vg=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ve(r)?t.image:sn(r)?t.video:Ti({name:n,mimeType:r})?t.pdf(n):t.document(n)},$n=e=>(e==null?void 0:e.trim())||"",Kg=e=>(e?$t(e):void 0)||void 0,po=30,qg=e=>e.length>po?`${e.slice(0,po)}…`:e,Wg=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=qg($t(n)),c=[t,i].filter(Boolean).join(", ");return o($t(e),$t(c),r,s)},Dr=e=>({text:$n(e),format:"plain"}),Yg=e=>({text:$n(e),format:"markdown"}),jg=({markdownText:e,plainText:t,comparisonText:n})=>{const r=$n(e);return r&&r!==$n(n)?Yg(r):Dr(t)},en=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?ca(t,{codeBlockPlaceholder:s}):Kg(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),Xg=(...e)=>$t(e.filter(Boolean).join(", "))||void 0,Eo=(e,t,n,r)=>{if(!t||Ii(t,n))return e;const s=la(t,r);return s?Xg(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=Vg({name:o,mimeType:e.type},t);return Eo(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 Eo(d,n,c,t.codeBlockPlaceholder)}return la(n,t.codeBlockPlaceholder)},Zg=(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},b=()=>{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=b();M&&_(M)},n)},E=R=>{u=R.text,d=R.dedupeKey??null,e(R.text)},y=(R,M,$,N)=>M!=null&&N!=null?M===N:M==null&&N==null?R!=null&&R===$:!1,T=(R,M,$)=>{if(!R||!M&&(r!=null&&r()))return;const N=$==null?void 0:$.dedupeKey;if(!(h&&y(R,N,u,d)))if(h){if((($==null?void 0:$.mode)??"latestOnly")==="ordered"){const oe=c[c.length-1];if(oe&&y(R,N,oe.text,oe.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)=>{T(R,!1,M)},announceIgnoringSuppression:(R,M)=>{T(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}}},Jg=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Qg=(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(". "),ef=(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}},tf=(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}},nf=(e,t)=>!t||!Xe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),rf=(e,t)=>we.isAdmin(e)?we.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,sf=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,of=e=>e===pe.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===pe.CollectionEventSource.EVENT_MESSAGE_UPDATED,af=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",cf=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},lf=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},uf=({intent:e,strings:t})=>({label:cf(e,t),hint:lf(e,t)}),df="1.43.3",Ue="sb-agent",Ae={ENTRY:`${Ue}-entry`,MODAL_ROOT:`${Ue}-modal-root`,WINDOW:`${Ue}-window`,LAUNCHER:`${Ue}-launcher`,NUDGE_MESSAGE:`${Ue}-nudge-message`,WINDOW_TITLE:`${Ue}-window-title`},da="data-sb-initial-focus",ma="true",mf=`[${da}="${ma}"]`,ha={[da]:ma},fs="data-sb-focus-trap-sentinel",hf="true",ga="data-sb-initial-focus-header",fa="true",gf=`[${ga}="${fa}"]`,pa={[ga]:fa},Ea="data-sb-message-input",_a="true",ff=`textarea[${Ea}="${_a}"]:not(:disabled)`,pf={[Ea]:_a},Ca=1e3,vn=2147483647,It={MODAL:vn-1,TOOLTIP:vn-2,WINDOW:vn-3,LAUNCHER:vn-4},Sa=36,Ef=100,_f=df,va="noopener noreferrer nofollow",Cf=()=>typeof document>"u"||document.visibilityState==="visible",Pr=()=>typeof document<"u"&&document.visibilityState==="hidden",_o=()=>Pr()?"backgrounded":"foregrounded",Sf={getState:_o,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(_o());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function vf(){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 bf(){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 yf={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:yf,dateLocale:tl.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"]),Af='@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:Tf,useContext:ps}=be("AgentUIElementResolver"),If=({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(Tf,{value:s},r)};function _t(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Co=()=>{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:xf,useContext:Es}=be("EscapeDismissStack"),So=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Mf=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Co()),s.current||(s.current=Co());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??_t(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){So(m);return}i.dismissTopmost()&&So(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(xf,{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])},Rf=(e,t)=>{const{register:n}=Es();Ta(e,t,n)},kf=(e,t)=>{const{registerShellDismissHandler:n}=Es();Ta(e,t,n)},Ia=()=>{const{subscribe:e,getOpenCount:t}=Es();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},wf=(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.":""))))})},vo=ba($r.strings),Lf={...vo,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:vo.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:Lf},Of=Object.freeze(Object.defineProperty({__proto__:null,default:Fn},Symbol.toStringTag,{value:"Module"})),Fr=new Map([[un,Fn]]);async function Nf(e){const t=Fr.get(e);if(t)return t;try{if(Aa.has(e)){const{default:n}=await wf(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/qr4Ghr48.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Of),"./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:Df,useContext:le}=be("Localization"),Pf=({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}),Nf(c).then(i))},[e,t,n]),a.createElement(Df,{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",bo=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Un}='${e}'] & { ${r} }`},re={light:bo("light"),dark:bo("dark")},$f=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
- `}),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"})`
66
+ `}),Ff=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);}`,v={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},Uf=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"})),Bf=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"})),Hf=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"})),Gf=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"})),zf=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"})),Vf=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),Kf={close:Uf,send:zf,menu:Gf,expand:Hf,collapse:Bf,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")))},qf=e=>({size:t=24,color:n=v.color.primary.main,flipInRtl:r=!1})=>a.createElement(Yf,{$size:t,$color:n,$rtlFlip:r},a.createElement(At,{errorFallback:a.createElement(jf,null)},a.createElement(e,null))),xa=Object.fromEntries(Object.entries(Kf).map(([e,t])=>[e,qf(t)])),Wf=F.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Yf=S.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,25 +84,25 @@ $2
84
84
  stroke-linejoin: round;
85
85
  }
86
86
 
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)",'[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};`:""}
87
+ ${({$rtlFlip:e})=>e&&Wf};
88
+ `,jf=()=>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:Xf,useContext:Zf}=be("MessengerIcon",{icons:xa}),Jf=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:um(xa,e)}),[e]);return a.createElement(Xf,{value:n},t)},{Provider:Qf,useContext:Ma}=be("MessengerTheme");function ep(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(Jm,{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(tp,{...e}))}function tp({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(Qf,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const np=(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])},rp=(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])},sp=80,op=()=>{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=be("AriaLiveRegion",{announce:_e,announceScreenEntry:_e,announceStatus:_e,announceError:_e,flush:_e,setSuppressionState:_e}),ip=Ra.Provider,_s=Ra.useContext,ap={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},cp=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(_e),s=op(),[o]=l.useState(()=>Zg(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=Qg(f,s.current);i(p)},[i]),d=l.useCallback((f,p)=>{const b=ef(f,s.current),_=(p==null?void 0:p.mode)??Jg(f.event);i(b,{mode:_,dedupeKey:p==null?void 0:p.dedupeKey})},[i]),m=l.useCallback((f,p)=>{const b=tf(f,s.current);o.announceIgnoringSuppression(b),p&&setTimeout(()=>{p.focus()},sp)},[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(ip,{value:g},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:ap}))},ka=be("ConversationAnnouncements",{announcementsEnabled:!0,announce:_e,announceScreenEntry:_e,announceStatus:_e,announceError:_e,setIsSuppressed:_e,setStatusPauseState:_e,flush:_e}),lp=ka.Provider,gt=ka.useContext,up=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=_s(),u=l.useRef([]),d=l.useRef(new Set),m=l.useRef(Symbol("conversation-announcements")),h=l.useCallback(A=>{if(!t||!A){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 A=[...u.current];g(),A.forEach(I=>{i(),s(I.params,I.options)})},[s,t,g,i]),p=l.useCallback((A,I)=>{if(I){d.current.add(A);return}d.current.delete(A),d.current.size===0&&f()},[f]),b=l.useCallback(A=>{t&&n(A)},[n,t]),_=l.useCallback(A=>{t&&r(A)},[r,t]),E=l.useCallback((A,I)=>{if(t){if(d.current.size>0){u.current.push({params:A,options:I});return}s(A,I)}},[s,t]),y=l.useCallback((A,I)=>{t&&o(A,I)},[o,t]);l.useLayoutEffect(()=>(t||(g(),c(m.current,!1)),()=>{g(),c(m.current,!1)}),[t,g,c]);const T=l.useMemo(()=>({announcementsEnabled:t,announce:b,announceScreenEntry:_,announceStatus:E,announceError:y,setIsSuppressed:h,setStatusPauseState:p,flush:i}),[t,i,b,y,_,E,h,p]);return a.createElement(lp,{value:T},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(fs)&&Ft(n))return n;return null},La=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Yn))r.hasAttribute(fs)||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,dp=(e,t,n)=>Oa(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),Cs=e=>rn(e,mf),Na=e=>Cs(e)??rn(e,Yn),mp=e=>{const t=Cs(e);if(t)return t;const n=e.querySelector(gf);return(n?rn(n,wa):null)??rn(e,Yn)},U=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(fp,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),yo=new WeakMap,hp=(e,t)=>{let n=yo.get(t);n||(n=new Map,yo.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},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"})`
90
+ `;return n.set(e,o),o},gp=e=>e?F.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",fp=S.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>hp(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>gp(e)}`;async function Ss(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"]',pp=(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},Ep=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Ur)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Ft(n)),_p=e=>{const t=Na(e)??e;t===e&&Da(e),t.focus()},Da=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Cp=(e,t)=>{const n=La(e);if(!n){Da(e),e.focus();return}n[t].focus()},Ao=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(fs,hf),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Cp(e,t)),n},Sp=(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=pp(i,u);return()=>{u&&Me(()=>{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)||Ep(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,_p(o)};if(n)return Me(c),()=>{i=!0};const u=setTimeout(()=>Me(c),Ca);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=Ao(o,"last"),c=Ao(o,"first"),u=d=>Sp(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}=ps();return jn(n,d),Rf(n,o?r:_e),n?nl.createPortal(a.createElement(vp,{onClick:o?r:void 0,style:e},a.createElement(bp,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},vp=S.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${v.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${It.MODAL};`,bp=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};`,yp=({id:e,children:t})=>a.createElement(Ap,{id:e},t),Ap=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;`,To=(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},Tp=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(yp,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},Io=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ve(t??"")?r.A11Y_FILE_IMAGE(e):sn(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},Ip=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Zt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Ip(e)}),xp=({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()},xo=(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:xp({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},de=()=>{const{stringSet:e}=le(),t=Tp(),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":Io(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=uf({intent:af({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:To(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,...pf},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?Io({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,b=e.A11Y_HINT_SELECT_RATING,_=t(b,`cs${i}`);return{props:{disabled:d,onClick:()=>f(i),...xo(u,d,m,h,g,y=>f(y+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:{...xo(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:To(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=Wg({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}}}}},Mp=({title:e,description:t,highlightedText:n})=>{const r=vg(t,n);return a.createElement(kp,null,a.createElement(wp,null,a.createElement(U,{as:"div",variant:"h1",color:v.themedColor.textHighEmphasis},e),t&&a.createElement(Lp,null,a.createElement(U,{as:"div",variant:"body3",color:v.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(Op,null,r.highlightedText):null,r.afterText))))},Rp=()=>{const{components:e}=Xn.useContext(),{stringSet:t}=le(),{messenger:n}=de(),r=Cg(),s=r.showDescription?Sg(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(St,{portalContainerId:Ae.WINDOW,visible:r.visible,onClose:_e,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Xn=Qe({template:Rp,components:{Dialog:Mp}}),kp=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};`,wp=S.default.div`display:flex;flex-direction:column;`,Lp=S.default.div`margin-top:16px;`,Op=S.default.strong`font-weight:700;`,Np=({url:e})=>Ss(e),{Provider:Dp,Consumer:Pa,useContext:he}=be("Messenger");function Pp({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}=ps(),g=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);kf(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),y=h(Ae.WINDOW);let T=!1;return Me(()=>{var A;T||dp(E,E.activeElement,y)&&((A=h(Ae.LAUNCHER))==null||A.focus())}),()=>{T=!0}},[m.opened,o.rootElement,h]);const{Template:p}=Xn.useContext(),b=l.useMemo(()=>{var _;return{...o.handlers,onClickLink:((_=o.handlers)==null?void 0:_.onClickLink)??Np}},[o.handlers]);return a.createElement(_m,{...o},_=>a.createElement(Dp,{value:{...o,..._,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:b}},a.createElement(p,null),e))}const $a=/iPad|iPhone|iPod/.test(navigator.userAgent),$p=/Android/.test(navigator.userAgent),dn=e=>$a||$p;let Yt=null,pr=null;const Fp=(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)",Re=F.css`&:focus-visible{outline:2px solid ${v.themedColor.primary};outline-offset:2px;}`,Mo=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??Mo(t)??Mo(n),g=u?void 0:t?d:n?m:void 0,f=t&&n?m:void 0,p=()=>{c(),Me(()=>o==null?void 0:o())},b=()=>{c(),Me(()=>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(Up,null,a.createElement(Bp,null,t&&a.createElement("div",{id:d},a.createElement(U,{variant:"h1",color:v.themedColor.textHighEmphasis},t)),n&&a.createElement(Hp,{id:m},a.createElement(U,{variant:"body3",color:v.themedColor.textMidEmphasis},n))),a.createElement(Gp,null,s&&a.createElement(Ro,{onClick:b},a.createElement(U,{variant:"button",color:v.themedColor.textHighEmphasis},s)),a.createElement(Ro,{onClick:p},a.createElement(U,{variant:"button",color:v.themedColor.primary},r)))))},Up=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};`,Bp=S.default.div`margin-bottom:16px;`,Hp=S.default.div`margin-top:16px;`,Gp=S.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,Ro=S.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Re}`,{Provider:zp,useContext:De}=be("MessengerSession"),Vp=l.forwardRef(function({children:e,...t},n){return a.createElement(rh,{ref:n,...t},r=>a.createElement(Kp,{...r},e))}),Kp=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=he(),{userSessionInfo:h,authenticate:g,userSession:f,aiAgentInfo:p,launcherInfo:b}=t,[_,E]=l.useState(!1),y=l.useRef(null);ht(n,{async onUserJoined(A,I){var L,R,M,$;A.conversation&&A.conversation.type===Ce.ConversationType.PROACTIVE&&I.userId===((L=n.currentUser)==null?void 0:L.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",A.url),(M=m.session)==null||M._updateActiveChannel({url:A.url,status:"open",conversationStatus:(R=A.conversation)==null?void 0:R.status}),c.setOpened(!0),qp({sound:document.hidden||!c.opened}),($=y.current)==null||$.call(y,{channel:A}))}}),l.useEffect(()=>{g().then(({launcher:A})=>{A.auto_open&&!dn()&&setTimeout(()=>c.setOpened(!0),500)}).catch(A=>{var I;r.error("messengerSession: failed to initialize",A),(I=u==null?void 0:u.onInitializeFailed)==null||I.call(u,A)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const A=()=>E(!0);return d.subscribe(ze.AnonymousSessionTokenExpired,A),()=>d.unsubscribe(ze.AnonymousSessionTokenExpired,A)},[d]);const T=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!f||!p||!b?null:a.createElement(zp,{value:{...t,userSession:f,aiAgentInfo:{...p,...i==null?void 0:i.bot},launcherInfo:{...b,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:A=>y.current=A}},e,a.createElement(mn,{visible:_,title:"Session timed out",description:"Start a new conversation.",onConfirm:T,onClose:_e}))};function qp({sound:e}){Fp("🔔You have received a new message"),e&&Fa()}const Bn=`@${Ue}-focused-channel`,Ba=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Wp=()=>{try{const e=localStorage.getItem(Bn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},ko=e=>{try{localStorage.setItem(Bn,JSON.stringify({channelUrl:e,tabId:Ba}))}catch{}},wo=()=>{try{const e=localStorage.getItem(Bn);if(!e)return;JSON.parse(e).tabId===Ba&&localStorage.removeItem(Bn)}catch{}},Yp=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>ko(e),r=()=>wo();return document.hasFocus()&&ko(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),wo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Wp()===e}),jp=e=>{const{config:t,chatSDK:n}=he(),{sdkUser:r}=De(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=Yp(e,s);ht(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 Xp(e,t){Ve(e.type)&&!Br.has(e)&&Br.set(e,Ha(t))}async function Zp(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 Jp(e){if("file"in e&&e.file instanceof File&&Ve(e.file.type)){const t=await(Br.get(e.file)??Zp(e.file));return t?new ke.MessageMetaArray({key:bi,value:[t.width,t.height]}):void 0}}const Qp=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=he(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await Jp(s),i={...s,metaArrays:o?[o]:void 0},c=eE(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===ke.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===ke.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},eE=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:tE,useContext:Ga}=be("ConversationScroll"),Lo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},_r=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),Oo=e=>Array.from(e.querySelectorAll(`#${Ue}-message-item`));function nE({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(Lo),[u,d]=l.useState(0),[m,h]=l.useState(0),[g,f]=l.useState(!1),[p,b]=l.useState(!1),[_,E]=l.useState(!0),y=x=>{const w=_r(x);return o.current.distanceFromBottom=w,h(w),w},T=()=>{const x=i.current;x.reconcileTimer&&(clearTimeout(x.reconcileTimer),x.reconcileTimer=null)},A=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:z,shouldRecalc:Q}=c.current,ie=x.clientHeight;if(z>D)return w;const te=R(x,{messageType:"outgoing"});let Se=0;if(te){const Oe=te.message.offsetTop-Er+ie;Se=Math.max(0,Oe-D)}else{const Oe=D-z,W=ie-Er;Se=Math.max(0,Oe-W)}return w===0||Se!==w||Q?(c.current.shouldRecalc=!1,Se):w})},R=l.useCallback((x,w)=>{const{messageType:D="all"}=w??{},z=Oo(x);let Q=z;D==="outgoing"&&(Q=z.filter(ge=>ge.getAttribute("data-layout-id")==="outgoingmessage"));const ie=Q[Q.length-1];if(!ie)return null;const te=x.getBoundingClientRect(),Se=ie.getBoundingClientRect(),Oe=x.scrollTop+(Se.top-te.top),W=Oe+ie.offsetHeight;return{message:ie,scrollTop:Oe,lastMessageBottom:W}},[]),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):y(x),L()},[I,R]),$=l.useCallback(()=>{A(),T(),c.current=Lo,d(0),h(0),E(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[A]),N=l.useCallback((x=!0)=>{const w=o.current.distanceFromBottom>Nt;if(i.current.awayByUser=!1,h(0),!w){Me(()=>{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),T()),Me(()=>{const D=r.current;if(!D){i.current.programmatic=!1,E(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,y(D),E(!0);return}const z=()=>{if(r.current!==D){i.current.programmatic=!1,r.current&&y(r.current),E(!0);return}i.current.programmatic=!1,y(D),E(!0)};if(x&&!i.current.reconcileTimer){const Q=setTimeout(z,500);i.current.reconcileTimer=Q,D.addEventListener("scrollend",()=>{clearTimeout(Q),i.current.reconcileTimer=null,z()},{once:!0})}D.scrollTo({top:D.scrollHeight,behavior:x?"smooth":"auto"}),x||z()})},[]),ee=l.useCallback(()=>{const x=r.current;if(x){if(i.current.awayByUser){y(x);return}N(!1)}},[N]),oe=l.useCallback(()=>{const x=r.current,w=s.current;if(!x||!w.resize)return;const D=new Set(Oo(x));for(const z of w.resizeTargets)D.has(z)||(w.resize.unobserve(z),w.resizeTargets.delete(z));for(const z of D)w.resizeTargets.has(z)||(w.resize.observe(z),w.resizeTargets.add(z))},[]),q=l.useCallback(x=>{A();const w=s.current;typeof ResizeObserver<"u"&&(w.resize=new ResizeObserver(ee),oe());const D=new MutationObserver(()=>{oe(),ee()});w.mutation=D,D.observe(x,{childList:!0})},[A,ee,oe]),Y=l.useCallback(x=>{if(!x){r.current=null,A();return}if(r.current=x,I!=="fixed"){q(x);return}$(),c.current.viewport=x.clientHeight;const w=new MutationObserver(()=>{M()});s.current.mutation=w,w.observe(x,{childList:!0,subtree:!0})},[A,I,M,$,q]),B=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(()=>{b(!1)},500))},[R]),X=(x,w,D)=>{const z=_r(x);if(D&&z>Nt){i.current.programmatic=!1,i.current.awayByUser=!0,T(),y(x),E(!0),o.current.prevScrollTop=w;return}o.current.distanceFromBottom=z},P=(x,w,D)=>{const Q=y(x)<=Nt;w&&!Q&&(i.current.awayByUser=!0,T()),D&&Q&&(i.current.awayByUser=!1)},V=l.useCallback(x=>{const{scrollTop:w}=x.currentTarget,D=o.current.prevScrollTop;i.current.programmatic?X(x.currentTarget,w,w<D):P(x.currentTarget,w<D,w>D),o.current.prevScrollTop=w},[]),H=l.useCallback(()=>{I==="fixed"&&(b(!0),k())},[I]),K=l.useCallback(()=>{I==="fixed"?setTimeout(()=>B(),300):N()},[I,B]),G=l.useCallback(x=>{i.current.streaming=x,I==="fixed"?k():i.current.awayByUser||N()},[I,N]),J=l.useCallback(x=>{f(x),x&&(d(0),I==="fixed"&&A())},[A,I]),ae=l.useCallback(x=>{I==="auto"&&x&&!i.current.awayByUser&&N()},[I,N]),ve=!(m<=Nt)&&!p,Ie=l.useCallback(()=>o.current.distanceFromBottom>Nt,[]),Le=l.useMemo(()=>({ref:Y,state:{bottomSpace:u,isAwayFromBottom:ve,isScrollPositionReconciled:_,shouldCountNewMessages:Ie},props:{onScroll:V},actions:{scrollToBottom:N,onBeforeMessageSend:H,onAfterMessageSend:K,onStreamingUpdate:G,onConversationClosed:J,onTypingIndicatorUpdate:ae}}),[Y,u,ve,_,Ie,V,N,H,K,G,J,ae]);return a.createElement(tE,{value:Le},n)}const{Provider:rE,Context:sE,useContext:xe}=be("Conversation"),oE=({children:e})=>{var s;const{channelSource:t}=xe(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=tg(n);return eg(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)},iE=({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(rE,{value:o},s)},aE=({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);jp(h);const{onBeforeSendMessage:g,onAfterSendMessage:f}=Qp({onScrollAfterSendMessage:()=>{m.actions.onAfterMessageSend()}}),p=l.useCallback(y=>(m.actions.onBeforeMessageSend(),g(y)),[m.actions,g]),b=l.useCallback(y=>{const T=y.some(A=>ye.isStreaming(A));m.actions.onStreamingUpdate(T)},[m.actions.onStreamingUpdate]),_=l.useCallback(y=>{m.actions.onConversationClosed(y===Ce.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),E=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(Nh,{key:h,channelUrl:h,onBeforeSendMessage:p,onAfterSendMessage:f,onMessagesUpdated:b,onMessagesReceived:b,onChannelDeleted:E,onConversationStatusChanged:_,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,shouldCountNewMessages:m.state.shouldCountNewMessages},y=>a.createElement(iE,{context:y,scrollSource:m,goToActiveConversation:E,onNavigateToConversationList:n},a.createElement(oE,null,c)))},za=({children:e,...t})=>{const{config:n}=Te(),{agentPreviewConfigs:r}=he(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(nE,{scrollMode:s,messageStackDirection:o},a.createElement(aE,{...t},e))},vs=l.createContext({onDrop:_e,subscribe:()=>_e}),Hr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(vs.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)},cE=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(vs);l.useEffect(()=>t(e),[e])};Hr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(vs);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const Va=be("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>_e,registerWindowTitlePending:()=>_e}),lE=Va.Provider,Ka=Va.useContext,No=()=>{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]},bs=({children:e})=>{const[t,n]=No(),[r,s]=No(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(lE,{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}},uE=(e,t)=>{const r=(t?rn(e,t):null)??mp(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=Cs(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,uE(e.current,s))};if(r)return Me(d),()=>{u=!0};const m=setTimeout(()=>Me(d),Ca);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},dE=(e,t)=>{const{announcementsEnabled:n}=gt(),{channelSource:r}=xe(),{isWindowNameReady:s}=Zn(),o=Ia(),i=r.channel!=null||r.error!=null;Wa(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?ff:void 0,suppressed:o})},mE=()=>{var s;const{_statsEnabled:e,channelSource:t}=xe(),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)},[]);Ag({channelUrl:n,enabled:e,isInitiallyBackgrounded:Pr,isForegrounded:Cf,subscribeToForegroundState:r})},hE=e=>Ve(e)||sn(e);function gE(e,t){return e.filter(n=>ye.isWelcomeMessage(n,t))}const Ya=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!ye.isWelcomeMessage(r,n):!0),fE=[],ja=()=>{var f,p,b,_;const{agentPreviewConfigs:e={},aiAgentId:t}=he(),{aiAgentInfo:n,userSession:r}=De(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=xe(),u=e.welcomeMessages??fE,d=l.useMemo(()=>Ya(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=mt(s.channel),g=((p=(f=Li(s.channel,r.userId))==null?void 0:f.nickname)==null?void 0:p.trim())||((b=n==null?void 0:n.nickname)==null?void 0:b.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}},pE=(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=>we.isAdmin(g)&&we.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])},EE=()=>{const e=ja();pE(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}),Do=(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}},_E={senderName:!0,body:!0,time:!0},CE=Object.keys(_E),SE=(e,t)=>CE.every(n=>e[n]===t[n]),Po=2e3,$o=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(!we.isAdmin(e)||!we.isCSAT(e))return null;const t=sf(e);return t?`csat:${t}`:null},vE=e=>{const t=new Set;for(const n of e){const r=Za(n);r&&t.add(r)}return t},bE=(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)),Fo=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,Sr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),yE=()=>{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:b}=l.useMemo(()=>{if(!f)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const V=o.flatMap(H=>{const K=nf(H,f);return!K||!("sendingStatus"in H)?[]:[{key:K,sendingStatus:H.sendingStatus}]});return{outgoingMessageStates:V,outgoingMessageStatusSignature:V.map(({key:H,sendingStatus:K})=>`${H}:${K}`).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}),y=l.useRef([]),T=l.useRef(null),A=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",$=()=>{T.current!=null&&(clearTimeout(T.current),T.current=null)},N=(V,H,K)=>{const G=K==null?void 0:K.replaceableForMs;if(V.length===0||!G)return;const J=Date.now();A.current=[...A.current.filter(({replaceableUntil:ae})=>ae>J),{eventKeys:V,parts:H,replaceableUntil:J+G}]},ee=()=>y.current.length>0,oe=()=>{y.current=[]},q=()=>{const[V,...H]=y.current;if(!V)return!1;y.current=H;const{eventKeys:K,parts:G,dedupeKey:J}=V,ae=Ie=>{N(K,Ie,{replaceableForMs:K.length>0?Po:void 0}),e({event:"newMessage",...Ie},J?{dedupeKey:J}:void 0)};if(K.length===0)return ae(G),!0;const O=E.current,ve=bE(O.messages,K);if(ve){const Ie=Do(ve,O.stringSet,O.format);return ae(Ie),!0}return ae(G),!0},Y=()=>{for($();q(););},B=(V=Po)=>{$(),T.current=setTimeout(()=>{if(T.current=null,M())return;const H=Fo(),[K]=y.current;if(!K)return;if(K.focusTarget!==H){y.current=[{...K,focusTarget:H},...y.current.slice(1)],B($o);return}q()&&ee()&&B($o)},V)},X=(V,H,K)=>{const G={eventKeys:H,parts:V,focusTarget:Fo(),dedupeKey:K?K.dedupeKey??void 0:H[0]},J=H.length===0?-1:y.current.findIndex(({eventKeys:ae})=>Cr(ae,H));J>=0?y.current=y.current.map((ae,O)=>O===J?{...G,dedupeKey:K?G.dedupeKey:ae.dedupeKey}:ae):y.current=[...y.current,G],B()},P=(V,H,K)=>{if(V!=="messagesUpdated"||H.length===0)return!1;const G=Date.now(),J=A.current.find(ae=>ae.replaceableUntil>G&&Cr(ae.eventKeys,H));return J?!SE(K,J.parts):!1};l.useEffect(()=>{const V=R.current!==s;(!t||!d||V)&&(L.current=!1,k.current.clear(),oe(),A.current=[],I.current.clear(),$(),V&&(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(!ye.isStreaming(H))return[];const K="sender"in H?H.sender:void 0;return(K==null?void 0:K.userId)===E.current.currentUserId?[]:Gr(H)})),k.current=vE(o))},[e,t,s,d,m,i,c,b]),l.useEffect(()=>{const V=(H,K)=>{const G=E.current,J=Gr(H),ae=Za(H);if(ae!=null){if(k.current.has(ae))return;k.current.add(ae),e({event:"csatDisplayed"});return}if(ye.isStreaming(H)){J.forEach(z=>{I.current.add(z)});return}const O=J.filter(z=>I.current.has(z)),ve=K==="messagesUpdated"&&O.length>0;ve&&O.forEach(z=>{I.current.delete(z)});const Ie=K==="messagesUpdated"&&y.current.some(({eventKeys:z})=>Cr(z,J)),Le=Do(H,G.stringSet,G.format),x=P(K,J,Le);if(!ve&&K!=="messagesAdded"&&!Ie&&!x)return;const w=x?{dedupeKey:null}:void 0;if(ve||M()||Ie){X(Le,[...new Set([...O,...J])],w);return}if(x){X(Le,J,w);return}ee()&&Y();const D=J[0];e({event:"newMessage",...Le},D?{dedupeKey:D}:void 0)};return cn.subscribe(H=>{if(!L.current||H.channelUrl!==s||H.kind==="initialized"||H.kind==="messagesDeleted"||!of(H.source))return;const K=E.current.currentUserId;for(const G of H.messages)G&&rf(G,K)&&V(G,H.kind)})},[e,s]),l.useEffect(()=>{L.current&&(M()||ee()&&B())},[h,g]),l.useEffect(()=>()=>{$()},[]),l.useEffect(()=>{if(!L.current)return;const V=_.current,H=V.outgoingMessageStatuses;V.outgoingMessageStatuses=Sr(p),p.some(({key:G,sendingStatus:J})=>{const ae=H.get(G);return ae!==void 0&&ae!=="failed"&&J==="failed"})&&e({event:"sendFailed"})},[e,b]),l.useEffect(()=>{if(!L.current)return;const V=_.current;i&&!V.isClosed&&e({event:"conversationClosed"}),V.isClosed=i},[e,i]),l.useEffect(()=>{if(!L.current)return;const V=_.current;c&&!V.isHandedOff&&e({event:"agentConnected",agentName:u}),V.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!L.current)return;const V=_.current;m&&h!=="ai_responding"&&(!V.inputDisabled||V.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),V.inputDisabled=m,V.inputDisabledBy=h},[e,m,h])},AE=()=>{const{channelSource:e}=xe(),t=ta(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},TE=e=>{const{announceStatus:t,announcementsEnabled:n}=gt();ig(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},IE=()=>{const e=AE();TE(e)},ne=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=Zf(),o=s[e];return a.createElement(xE,{className:n,"data-testid":`sb-icon-${e}`},a.createElement(o,{size:t,color:r??v.color.primary.main,flipInRtl:Vf.has(e)}))},xE=S.default.span.attrs({"aria-hidden":"true"})`
91
91
  display: inline-flex;
92
92
  &:focus {
93
93
  outline: none;
94
94
  }
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
- background-color: ${b.color.background100};
95
+ `,ME=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(St,{portalContainerId:Ae.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(LE,null,n)),RE=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(kE,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(wE,null,a.createElement(ne,{type:n,size:24,color:v.themedColor.primary})),s),Et=Object.assign(ME,{ActionItem:RE}),kE=S.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?v.themedColor.error:v.themedColor.textHighEmphasis};${Re}`,wE=S.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,LE=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};`,Uo=40,Bo=.9,OE="[data-message-listitem]",NE='input, textarea, select, [role="textbox"], [contenteditable="true"]',DE=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Bo;case"PageUp":return t.clientHeight*-Bo;case"ArrowDown":return n?Uo:void 0;case"ArrowUp":return n?Uo*-1:void 0;default:return}},PE=({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(NE))return;const o=s===r||s.matches(OE),i=DE({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]),$E="[data-message-listitem]",FE=e=>Math.min(Math.max(0,e),1),UE=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest($E),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},BE=({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})},HE=({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,BE({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 y=t.current;if(!y||(i==null||i(E),m.current=y.scrollHeight-y.scrollTop,d.current=y.scrollTop,c.current))return;const T=y.clientHeight*FE(n);if(y.scrollTop<=T){c.current=!0,u.current="top",h.current=UE(y),await o(),c.current=!1;return}if(y.scrollHeight-y.scrollTop-y.clientHeight<=T){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),b=l.useCallback(E=>{const y=t.current;if(!y)return;const T=f.current;if(T!=null){if(T===y.scrollTop){f.current=null;return}f.current=null}const A=g.current;if(A!=null&&A===y.scrollTop){g.current=null,f.current=y.scrollTop,p(E);return}g.current=null,p(E)},[p,t]),_=l.useCallback(E=>{const y=t.current;y&&(g.current=E,f.current=null,y.scrollTop=E,y.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{g.current=null,f.current=null},[]),{handleScroll:b,syncScrollPosition:_}},GE=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:b,loadThreshold:_=.05,onScroll:E=_e,depsForResetScrollPositionToBottom:y,stackDirection:T="top",bottomSpacerHeight:A=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}=HE({depsForResetScrollPositionToBottom:y,listRef:k,loadThreshold:_,messagesLength:r.length,onLoadNext:b,onLoadPrev:p,onScroll:E}),$=PE({listRef:k,syncScrollPosition:M});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(zE,{id:"infinite-list-container"},a.createElement(VE,{id:"infinite-list-inner",ref:L,onScroll:R,onKeyDown:$,role:"list","aria-label":I,tabIndex:0},T==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((N,ee)=>s({message:N,index:ee})),g,A>0&&a.createElement("div",{style:{minHeight:A}})),a.createElement(KE,{id:"infinite-list-overlay-container"},a.createElement(qE,{id:"infinite-list-overlay"},f)))}),zE=S.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,VE=S.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${v.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,KE=S.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,qE=S.default.div`pointer-events:auto;`,it=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?v.themedColor.textDisabled:v.themedColor.textHighEmphasis;return a.createElement(WE,{as:e,disabled:s,...i},a.createElement(ne,{type:t,size:n,color:r??c}),o)},WE=S.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Re}&:disabled{cursor:not-allowed;}`,xt=({className:e,children:t,size:n=26})=>a.createElement(YE,{className:e,$size:n},t??a.createElement(ne,{type:"spinner",size:n})),YE=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);}}`,jE=({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}=he(),h=e.length,g=e[s],f=m.conversation.fileViewer.downloadEnabled,p=h>1,b=(g==null?void 0:g.type)||"",_=Ve(b),E=sn(b),y=!hE(b);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const T=l.useCallback(()=>{s>0&&(o(I=>I-1),c(!1))},[s]),A=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"?T():k.key==="ArrowRight"&&A()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[r,T,A]),!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(XE,null,a.createElement(ZE,null,a.createElement(JE,null,a.createElement(QE,null,a.createElement(U,{variant:"button",maxTextLines:1,color:v.color.ondark.textHighEmphasis},g.name||u.IMAGE_VIEWER__DEFAULT_TITLE),g.timestamp&&a.createElement(U,{variant:"caption2",color:v.color.ondark.textHighEmphasis},d(new Date(g.timestamp),"h:mm a")))),a.createElement(e_,{type:"close",size:18,color:v.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(t_,null,p&&a.createElement(Ho,{$position:"left",type:"chevron-right",size:22,color:v.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(n_,{onClick:I=>I.currentTarget===I.target&&n()},_&&a.createElement(a.Fragment,null,!i&&a.createElement(r_,null,a.createElement(xt,{size:32},a.createElement(ne,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(s_,{src:g.url,alt:g.name||"Image",$loaded:i,onLoad:()=>c(!0)})),E&&a.createElement(o_,{controls:!0},a.createElement("source",{src:g.url,type:b})),y&&a.createElement(i_,null,a.createElement(U,{variant:"h1",color:v.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&a.createElement(Ho,{$position:"right",type:"chevron-right",size:22,color:v.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(a_,null,p&&a.createElement(U,{variant:"body2",color:v.color.ondark.textHighEmphasis},s+1,"/",h),f&&!y&&a.createElement(c_,{forwardedAs:"a",href:g.url,download:g.name||"file",type:"download",size:24,color:v.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},XE=S.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${v.themedColor.bg_50_600};`,ZE=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:${v.color.overlay.dark};`,JE=S.default.div`flex:1;min-width:0;padding-right:8px;`,QE=S.default.div`display:flex;flex-direction:column;gap:2px;`,e_=S.default(it)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Jn=S.default.div`display:flex;align-items:center;justify-content:center;`,t_=S.default(Jn)`flex:1;min-height:0;position:relative;`,n_=S.default(Jn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,r_=S.default(Jn)`position:absolute;inset:0;pointer-events:none;`,s_=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;`,o_=S.default.video`max-width:100%;max-height:100%;object-fit:contain;`,i_=S.default(Jn)`flex-direction:column;gap:16px;`,Ho=S.default(it)`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:${v.color.overlay.dark};&:disabled{opacity:0.3;}`,a_=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:${v.color.overlay.dark};`,c_=S.default(it)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,l_=.75,Ja=6,u_=Ja*2;let zr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(zr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const d_=e=>zr?Array.from(zr.segment(e),t=>t.segment):[...e],m_=e=>{const t=Math.floor(e.length*l_),n=Math.max(0,e.length-Ja);return Math.max(t,n)},Go=(e,t="")=>{if(e.length<u_)return{start:e+t,end:""};const n=d_(e),r=m_(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},h_=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Go(t);const s=t.slice(0,n),o=t.slice(n);return Go(s,o)},Qa=({children:e,"data-testid":t,...n})=>{const{start:r,end:s}=l.useMemo(()=>h_(e),[e]);return s?a.createElement(g_,{"data-testid":t},a.createElement(f_,{...n},r),a.createElement(p_,{...n},s)):a.createElement(U,{"data-testid":t,...n},r)},g_=S.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,f_=S.default(U)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,p_=S.default(U)`flex-shrink:0;white-space:nowrap;`,ys=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=F.useTheme(),{conversation:u}=de(),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(E_,{...d.props,$clickable:!!o},a.createElement(C_,{$bgColor:s??c.base.primary},a.createElement(ne,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(S_,null,a.createElement(Qa,{variant:"button",color:v.themedColor.textHighEmphasis},e),a.createElement(U,{color:v.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},E_=S.default.div`border:none;border-radius:12px;gap:8px;width:${se.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${v.themedColor.textDisabled};background-color:${v.themedColor.bg_50_600};${({$clickable:e})=>e&&__}`,__=F.css`cursor:pointer;${Re}&:hover{background-color:${v.themedColor.bg_100_500};}`,C_=S.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,S_=S.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function v_({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(b_,null,a.createElement(ys,{name:e.name,mimeType:e.type,type:Xr(e.name,e.type),onClick:r}),t)}const b_=S.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,Ke=`${Ue}-incoming-msg`,zo=`${Ue}-marked-text`,y_="masked-text";function A_({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=de(),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(x_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(M_,{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(T_,null,a.createElement(I_,{...d},u(),c.descriptionNode),r)}return null}const T_=S.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,I_=S.default.div`width:${se.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${re.light`
96
+ background-color: ${v.color.background100};
97
97
  `}
98
- ${ne.dark`
99
- background-color: ${b.color.background400};
98
+ ${re.dark`
99
+ background-color: ${v.color.background400};
100
100
  `}
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
- background-color: ${b.color.background100};
101
+ `,x_=S.default.img`width:100%;height:100%;object-fit:cover;`,M_=S.default.video`width:100%;height:100%;object-fit:cover;`,R_=e=>e.startsWith("blob:"),ec=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=de(),s=e.length;if(s===0)return null;const o=fm(s),i=!!n&&!t;return a.createElement(w_,{"data-testid":"sb-image-grid",$width:se.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=pm({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(L_,{key:c.url,"data-testid":"sb-image-grid-item",$clickable:i,$itemSpan:d,$isPending:t,...f.props},a.createElement(k_,{src:c.url,alt:c.name||""}),t&&a.createElement(O_,{"data-testid":"sb-image-grid-dim"}),f.descriptionNode)}))},k_=({src:e,alt:t})=>{const[n,r]=l.useState(()=>R_(e)),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(N_,null,a.createElement(xt,{size:20},a.createElement(ne,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(D_,null,a.createElement(ne,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(P_,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},w_=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;`,L_=S.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${re.light`
102
+ background-color: ${v.color.background100};
103
103
  `}
104
- ${ne.dark`
105
- background-color: ${b.color.background400};
104
+ ${re.dark`
105
+ background-color: ${v.color.background400};
106
106
  `}
107
107
  ${e=>e.$itemSpan&&e.$itemSpan>1&&`
108
108
  grid-column: span ${e.$itemSpan};
@@ -110,7 +110,7 @@ $2
110
110
  `}
111
111
 
112
112
  &:focus-visible {
113
- outline: 2px solid ${b.color.primary.main};
113
+ outline: 2px solid ${v.color.primary.main};
114
114
  outline-offset: -2px;
115
115
  }
116
116
 
@@ -121,19 +121,19 @@ $2
121
121
  }
122
122
  `}
123
123
  }
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
- background-color: ${b.color.background200};
124
+ `,O_=S.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${v.color.overlay.dark};pointer-events:none;`,tc=S.default.div`display:flex;align-items:center;justify-content:center;`,N_=S.default(tc)`position:absolute;inset:0;`,D_=S.default(tc)`position:absolute;inset:0;${re.light`
125
+ background-color: ${v.color.background200};
126
126
  `}
127
- ${ne.dark`
128
- background-color: ${b.color.background500};
127
+ ${re.dark`
128
+ background-color: ${v.color.background500};
129
129
  `}
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`
130
+ `,P_=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;`,$_=({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(F_,null,a.createElement(ec,{images:e,onClickImage:s}),t)},F_=S.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,U_=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs"))).MarkdownText})),Vo=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 B_(e){var s,o;const t=e.maxBodyWidth??se.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(Ko,{...r},e.children):null:a.createElement(Ko,{...r},n.map((i,c)=>i.type==="text"?a.createElement(qo,{key:c,variant:"body3"},a.createElement(At,{fallback:i.value},a.createElement(U_,{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"?Vo?a.createElement(At,{key:c,fallback:a.createElement(qo,{variant:"body3"},i.value)},a.createElement(Vo,{code:i.value,language:i.language})):a.createElement(H_,{key:c},a.createElement("code",null,i.value)):null),e.children)}const Ko=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`
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=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`})`
136
+ `,qo=S.default(U)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,H_=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 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(G_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:nt(n),$backgroundColor:c,style:i,...u},t&&t!==d?a.createElement(z_,{"data-testid":"sb-avatar-image",src:t,alt:"",onLoad:()=>o==null?void 0:o(t),onError:()=>{m(t),s==null||s(t)}}):a.createElement(ne,{type:"user",size:n}))}const G_=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??v.themedColor.bg_100_500};&:focus{outline:none;}${Re}`,z_=S.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,V_=({sender:e,isBotMessage:t})=>{const n=`${Ke}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(K_,{id:n},a.createElement(ne,{type:"delight",size:"100%"})):a.createElement(nc,{id:n,size:se.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},K_=S.default.div`flex-shrink:0;width:${se.AVATAR_SIZE}px;height:${se.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;}}`,q_=({sender:e})=>a.createElement(W_,{id:`${Ke}-sender-name`,variant:"caption1",color:v.themedColor.textMidEmphasis},e.nickname),W_=S.default(U)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Y_=({createdAt:e})=>{const{stringSet:t,format:n}=le();return e?a.createElement(U,{id:`${Ke}-sent-time`,variant:"caption4",color:v.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},rc="(prefers-reduced-motion: reduce)",j_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(rc).matches,sc=()=>{const[e,t]=l.useState(j_);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},X_=({thinkingMessage:e,customStyle:t})=>{const n=sc();return e?a.createElement(Q_,{$prefersReducedMotion:n},a.createElement(eC,null,e),!n&&a.createElement(tC,null)):a.createElement(Z_,{"data-testid":"sb-typing-indicator-dots",$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(J_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},Z_=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};`,J_=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;}`,Q_=S.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
- `,tC=v.default(B).attrs({variant:"body3"})`
148
+ `,eC=S.default(U).attrs({variant:"body3"})`
149
149
  white-space: pre-wrap;
150
150
  word-break: break-word;
151
- color: ${b.themedColor.textHighEmphasis};
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"})`
151
+ color: ${v.themedColor.textHighEmphasis};
152
+ `,tC=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=Ws(e.colors.base.background,.5),n=Ws(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
153
+ `,nC=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Ss(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(rC,{id:`${Ke}-ext-cta-button`,onClick:r},a.createElement(sC,{variant:"button"},n.label))},rC=S.default.button.attrs({type:"button"})`
154
154
  all: unset;
155
155
  display: flex;
156
156
  width: 100%;
@@ -160,14 +160,14 @@ $2
160
160
  cursor: pointer;
161
161
  border-radius: 6px;
162
162
  padding: 8px;
163
- color: ${b.themedColor.textHighEmphasis};
164
- background-color: ${b.color.background50};
165
- ${ne.dark`
166
- background-color: ${b.color.ondark.textDisabled};
163
+ color: ${v.themedColor.textHighEmphasis};
164
+ background-color: ${v.color.background50};
165
+ ${re.dark`
166
+ background-color: ${v.color.ondark.textDisabled};
167
167
  `}
168
168
 
169
- ${ke}
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"})`
169
+ ${Re}
170
+ `,sC=S.default(U)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,oC=e=>a.createElement(a.Fragment,null),iC=({extendedMessagePayload:e,onClickCitation:t=n=>Ss(n.link)})=>{const{stringSet:n}=le(),{theme:r}=Wn(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(aC,{id:`${Ke}-ext-citation`},a.createElement(cC,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(lC,null,s.map((o,i)=>a.createElement(dC,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(ne,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(uC,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},aC=S.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,cC=S.default(U)`opacity:0.5;`,lC=S.default.div`display:flex;flex-direction:column;gap:8px;`,uC=S.default(U)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,dC=S.default.button.attrs({type:"button"})`
171
171
  background: none;
172
172
  border: none;
173
173
  padding: 0;
@@ -182,127 +182,127 @@ $2
182
182
  &:hover {
183
183
  opacity: 0.5;
184
184
  }
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`
185
+ `,mC=e=>a.createElement(a.Fragment,null),Vr=e=>`${e}-filled`,hC=e=>e==="good"?Ce.AIAgentMessageFeedbackRating.GOOD:Ce.AIAgentMessageFeedbackRating.BAD,As=F.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,yn={good:{onlight:v.color.secondary.dark,ondark:v.color.secondary.light},bad:{onlight:v.color.error.dark,ondark:v.color.error.light}},gC={good:v.themedColor.secondary,bad:v.themedColor.error},oc=e=>F.css`color:${yn[e].onlight};border-color:${yn[e].onlight};${re.dark`
186
186
  color: ${yn[e].ondark};
187
187
  border-color: ${yn[e].ondark};
188
188
  `}
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
- outline: 2px solid ${b.themedColor.primary};
189
+ `,fC=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=le(),{conversation:u}=de(),{rootElement:d}=Ma(),m=_t(d),[h,g]=l.useState(r),[f,p]=l.useState(s),[b,_]=l.useState(!1),E=l.useRef(!1),y=h??r??"good",T=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 A=()=>{h&&(o({rating:h,comment:f.trim()||void 0}),t())},I=()=>{t()};if(!e)return null;const k={feedback:T.container()};return a.createElement(St,{portalContainerId:Ae.WINDOW,visible:e,onClose:I,"aria-label":c.FEEDBACK_TITLE},a.createElement(pC,null,a.createElement(EC,null,a.createElement(U,{variant:"h2",color:v.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(_C,null,a.createElement(CC,{...k.feedback.props},["good","bad"].map(L=>{const R=h===L,M=L==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,$=T.button(L,R);return a.createElement(l.Fragment,{key:L},a.createElement(SC,{type:"button",$selected:R,$rating:L,...$.props,onClick:()=>g(L),"data-sb-initial-focus":L===y?"true":void 0},a.createElement(ne,{type:R?Vr(L):L,size:24,color:"currentColor"}),a.createElement(U,{variant:"caption1",color:"currentColor"},M)),$.descriptionNode)}),k.feedback.descriptionNode),i&&a.createElement(vC,null,a.createElement(U,{variant:"caption3",color:v.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(bC,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:f,onChange:L=>p(L.target.value),onFocus:()=>_(E.current),onBlur:()=>_(!1),maxLength:100,$focusVisible:b,"data-focus-visible":b?"true":"false"}))),a.createElement(yC,null,a.createElement(AC,{onClick:I},a.createElement(U,{variant:"button",color:v.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(TC,{onClick:A,disabled:!h},a.createElement(U,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},pC=S.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,EC=S.default.div`padding:24px;`,_C=S.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,CC=S.default.div`display:flex;gap:4px;`,SC=S.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${v.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:${v.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&oc(t)}${As}`,vC=S.default.label`display:flex;flex-direction:column;gap:6px;`,bC=S.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${v.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${v.themedColor.textHighEmphasis};background-color:${v.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${v.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&F.css`
190
+ outline: 2px solid ${v.themedColor.primary};
191
191
  outline-offset: 2px;
192
192
  `}
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
- border: 1px solid ${b.color.background400};
193
+ `,yC=S.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,ic=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;`,AC=S.default(ic)`background-color:transparent;${As}`,TC=S.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};}`,IC=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=le(),{conversation:u}=de(),[d,m]=l.useState(!1),[h,g]=l.useState(!1),[f,p]=l.useState(void 0),[b,_]=l.useState(""),E=l.useRef(null),y=l.useRef(null),T=l.useRef(null),A=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=B=>{B&&Me(()=>{const X=B==="good"?E.current:y.current;X==null||X.focus()})},$=({restoreTrigger:B=!0}={})=>{g(!1),B&&M(T.current)},N=B=>{L==="none"?(p(B),_(""),m(!0)):(T.current=B,g(!0))},ee=()=>{i==null||i(null),$()},oe=()=>{A.current=!0,$({restoreTrigger:!1}),p(k==null?void 0:k.rating),_((k==null?void 0:k.comment)??""),m(!0)},q=B=>{A.current=!1,i==null||i(B),m(!1),M(T.current)},Y=()=>{m(!1),A.current&&(A.current=!1,g(!0))};return t&&L!=="none"?a.createElement(Wo,{role:"presentation",$horizontal:!0},a.createElement(xC,null,a.createElement(ne,{type:Vr(L),size:12,color:gC[L]})),(k==null?void 0:k.comment)&&a.createElement(Yo,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):a.createElement(a.Fragment,null,a.createElement(Wo,{role:"presentation"},a.createElement(MC,{role:"presentation"},["good","bad"].map(B=>{const X=L===B,P=I.button(B,X);return a.createElement(l.Fragment,{key:B},a.createElement(RC,{$selected:X,$rating:B,ref:B==="good"?E:y,...P.props,onClick:()=>N(B)},a.createElement(ne,{type:X?Vr(B):B,size:14,color:"currentColor"})),P.descriptionNode)})),L!=="none"&&(k==null?void 0:k.comment)&&a.createElement(Yo,{variant:"caption2"},k.comment)),a.createElement(Et,{visible:h,onClose:$,...I.optionsBottomSheet().props},a.createElement(Et.ActionItem,{onClick:oe,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(Et.ActionItem,{onClick:ee,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(fC,{visible:d,onClose:Y,isEdit:L!=="none",initialRating:f,initialComment:b,onSubmit:q,isCommentEnabled:s}))},Wo=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:${se.BODY_MAX_WIDTH}px;`,xC=S.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,MC=S.default.div`display:flex;gap:2px;`,RC=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:${v.themedColor.textMidEmphasis};border:1px solid ${v.color.background200};background-color:transparent;${re.dark`
194
+ border: 1px solid ${v.color.background400};
195
195
  `}
196
196
 
197
197
  ${({$selected:e,$rating:t})=>e&&oc(t)}
198
198
 
199
- ${Ts}
200
- `,jo=v.default(B)`color:${b.themedColor.textMidEmphasis};${ne.dark`
201
- color: ${b.themedColor.textHighEmphasis};
199
+ ${As}
200
+ `,Yo=S.default(U)`color:${v.themedColor.textMidEmphasis};${re.dark`
201
+ color: ${v.themedColor.textHighEmphasis};
202
202
  `}
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
- background-color: ${b.color.background50};
203
+ `,Ts=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;${Re}&:disabled{cursor:not-allowed;}`,jo=S.default.button`${Ts};background-color:${v.themedColor.primary};color:${v.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,kC=S.default.button`${Ts};color:${v.themedColor.primary};${re.light`
204
+ background-color: ${v.color.background50};
205
205
  `};
206
- ${ne.dark`
207
- background-color: ${b.color.background700};
206
+ ${re.dark`
207
+ background-color: ${v.color.background700};
208
208
  `};
209
209
 
210
210
  &:hover:not(:disabled) {
211
211
  opacity: 0.9;
212
212
  }
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
- background-color: ${b.color.ondark.textMidEmphasis};
213
+ `,wC=S.default.button`${Ts};background-color:transparent;color:${v.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,LC=e=>{switch(e){case"primary":return jo;case"secondary":return kC;case"clear":return wC;default:return jo}},OC=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);}}`,NC=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return v.themedColor.textHighEmphasisInverse;case"secondary":return v.themedColor.primary;case"clear":return v.themedColor.textHighEmphasis;default:return v.themedColor.textHighEmphasisInverse}},u=LC(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(OC,null,a.createElement(ne,{type:"spinner",size:22,color:c()})):a.createElement(U,{variant:"button",color:c()},e))},DC=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(U,{variant:"caption4",color:v.themedColor.error,className:t,style:n,id:r,role:s},e),PC=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=le();return a.createElement(U,{id:e,variant:"caption3",color:v.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:v.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},$C=({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(GC,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},FC=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;${Re}&::placeholder{color:${v.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,UC=F.css`color:${v.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${re.light`
214
+ background-color: ${v.color.ondark.textMidEmphasis};
215
215
  `}
216
- ${ne.dark`
217
- background-color: ${b.color.onlight.textLowEmphasis};
216
+ ${re.dark`
217
+ background-color: ${v.color.onlight.textLowEmphasis};
218
218
  `}
219
219
 
220
220
  &::placeholder {
221
- color: ${b.themedColor.textLowEmphasis};
221
+ color: ${v.themedColor.textLowEmphasis};
222
222
  }
223
- `,HC=F.css`border:1px solid ${b.themedColor.error};color:${b.themedColor.textHighEmphasis};${ne.light`
224
- background-color: ${b.color.background50};
223
+ `,BC=F.css`border:1px solid ${v.themedColor.error};color:${v.themedColor.textHighEmphasis};${re.light`
224
+ background-color: ${v.color.background50};
225
225
  `}
226
- ${ne.dark`
227
- background-color: ${b.color.onlight.textLowEmphasis};
226
+ ${re.dark`
227
+ background-color: ${v.color.onlight.textLowEmphasis};
228
228
  `}
229
- `,GC=F.css`border:1px solid ${b.themedColor.textDisabled};color:${b.themedColor.textHighEmphasis};${ne.light`
230
- background-color: ${b.color.background50};
229
+ `,HC=F.css`border:1px solid ${v.themedColor.textDisabled};color:${v.themedColor.textHighEmphasis};${re.light`
230
+ background-color: ${v.color.background50};
231
231
  `}
232
- ${ne.dark`
233
- background-color: ${b.color.onlight.textLowEmphasis};
232
+ ${re.dark`
233
+ background-color: ${v.color.onlight.textLowEmphasis};
234
234
  `}
235
235
 
236
236
  &:focus {
237
- border-color: ${b.themedColor.primary};
237
+ border-color: ${v.themedColor.primary};
238
238
  }
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`
239
+ `,GC=S.default.input`${FC}${({$error:e,$submitted:t})=>t?UC:e?BC:HC}`,zC=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}=de(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=zC(e),m=t.some(h=>u.includes(h.value));return a.createElement(KC,{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(JC,{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,b=>{const _=t[b];_&&d(_.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(U,{variant:"caption1",color:VC(f,n)},h.label))}))},VC=(e,t)=>t?e?v.themedColor.textHighEmphasis:v.themedColor.textDisabled:e?v.themedColor.primary:v.themedColor.textMidEmphasis,KC=S.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,qC=F.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,WC=F.css`cursor:default;background-color:${v.color.ondark.textMidEmphasis};color:${v.themedColor.textHighEmphasis};${re.dark`
240
240
  background-color: transparent;
241
241
  border: 1px solid white;
242
242
  color: white;
243
243
  `}
244
- `,jC=F.css`cursor:default;${ne.light`
245
- background-color: ${b.color.ondark.textMidEmphasis};
246
- color: ${b.themedColor.textDisabled};
244
+ `,YC=F.css`cursor:default;${re.light`
245
+ background-color: ${v.color.ondark.textMidEmphasis};
246
+ color: ${v.themedColor.textDisabled};
247
247
  `}
248
- ${ne.dark`
249
- background-color: ${b.color.onlight.textLowEmphasis};
250
- border: 1px solid ${b.color.onlight.textLowEmphasis};
251
- color: ${b.themedColor.textDisabled};
248
+ ${re.dark`
249
+ background-color: ${v.color.onlight.textLowEmphasis};
250
+ border: 1px solid ${v.color.onlight.textLowEmphasis};
251
+ color: ${v.themedColor.textDisabled};
252
252
  `}
253
- `,XC=F.css`cursor:pointer;border:1px solid ${b.themedColor.primary};${ne.light`
254
- background-color: ${b.color.background50};
255
- color: ${b.themedColor.primary};
253
+ `,jC=F.css`cursor:pointer;border:1px solid ${v.themedColor.primary};${re.light`
254
+ background-color: ${v.color.background50};
255
+ color: ${v.themedColor.primary};
256
256
  `}
257
- ${ne.dark`
258
- background-color: ${b.color.onlight.textLowEmphasis};
259
- color: ${b.themedColor.primary};
257
+ ${re.dark`
258
+ background-color: ${v.color.onlight.textLowEmphasis};
259
+ color: ${v.themedColor.primary};
260
260
  `}
261
- `,ZC=F.css`cursor:pointer;border:1px solid ${b.themedColor.textDisabled};${ne.light`
262
- background-color: ${b.color.background50};
263
- color: ${b.themedColor.textMidEmphasis};
261
+ `,XC=F.css`cursor:pointer;border:1px solid ${v.themedColor.textDisabled};${re.light`
262
+ background-color: ${v.color.background50};
263
+ color: ${v.themedColor.textMidEmphasis};
264
264
  `}
265
- ${ne.dark`
266
- background-color: ${b.color.onlight.textLowEmphasis};
267
- color: ${b.themedColor.textMidEmphasis};
265
+ ${re.dark`
266
+ background-color: ${v.color.onlight.textLowEmphasis};
267
+ color: ${v.themedColor.textMidEmphasis};
268
268
  `}
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}
269
+ `,ZC=F.css`border-color:${v.themedColor.error}!important;`,JC=S.default.button`${qC}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?WC:YC;const r=e?jC:XC;return n?F.css`
270
+ ${r} ${ZC}
271
271
  `:r}}
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
- background-color: ${b.color.ondark.textMidEmphasis};
272
+ `,QC=e=>a.createElement(ac,{...e,multiple:!1}),eS=e=>a.createElement(ac,{...e,multiple:!0}),tS=S.default.div`width:100%;height:1px;background-color:${v.themedColor.textDisabled};`,nS=({className:e})=>a.createElement(tS,{className:e}),rS=({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(oS,{...g}):a.createElement(sS,{...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;${Re}&::placeholder{color:${v.themedColor.textLowEmphasis};}`,lc=F.css`color:${v.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${re.light`
273
+ background-color: ${v.color.ondark.textMidEmphasis};
274
274
  `}
275
- ${ne.dark`
276
- background-color: ${b.color.onlight.textLowEmphasis};
275
+ ${re.dark`
276
+ background-color: ${v.color.onlight.textLowEmphasis};
277
277
  `}
278
278
 
279
279
  &::placeholder {
280
- color: ${b.themedColor.textLowEmphasis};
280
+ color: ${v.themedColor.textLowEmphasis};
281
281
  }
282
- `,uc=F.css`border:1px solid ${b.themedColor.error};color:${b.themedColor.textHighEmphasis};${ne.light`
283
- background-color: ${b.color.background50};
282
+ `,uc=F.css`border:1px solid ${v.themedColor.error};color:${v.themedColor.textHighEmphasis};${re.light`
283
+ background-color: ${v.color.background50};
284
284
  `}
285
- ${ne.dark`
286
- background-color: ${b.color.onlight.textLowEmphasis};
285
+ ${re.dark`
286
+ background-color: ${v.color.onlight.textLowEmphasis};
287
287
  `}
288
- `,dc=F.css`border:1px solid ${b.themedColor.textDisabled};color:${b.themedColor.textHighEmphasis};${ne.light`
289
- background-color: ${b.color.background50};
288
+ `,dc=F.css`border:1px solid ${v.themedColor.textDisabled};color:${v.themedColor.textHighEmphasis};${re.light`
289
+ background-color: ${v.color.background50};
290
290
  `}
291
- ${ne.dark`
292
- background-color: ${b.color.onlight.textLowEmphasis};
291
+ ${re.dark`
292
+ background-color: ${v.color.onlight.textLowEmphasis};
293
293
  `}
294
294
 
295
295
  &:focus {
296
- border-color: ${b.themedColor.primary};
296
+ border-color: ${v.themedColor.primary};
297
297
  }
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`
298
+ `,sS=S.default.input`${cc};height:36px;${({$error:e,$submitted:t})=>t?lc:e?uc:dc}`,oS=S.default.textarea`${cc};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?lc:e?uc:dc}`,iS=({children:e,className:t,style:n})=>a.createElement(U,{variant:"button",color:v.themedColor.textHighEmphasis,className:t,style:n},e),Ne={Title:iS,Label:PC,ErrorLabel:DC,Separator:nS,Button:NC,TextInput:rS,NumberInput:$C,SingleSelect:QC,MultiSelect:eS},aS=1,cS=new Set(["text","number","single-select","multi-select"]),lS=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,uS=e=>{var T;const t=(T=e.extendedMessagePayload)==null?void 0:T.form;if(!lS)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=le(),{onFormError:r}=e,{conversation:s}=de(),[o,i]=l.useState({submitting:!1,canceling:!1}),[c,u]=l.useState({visible:!1}),{state:d,fields:m,submit:h,cancel:g,updateFieldValue:f}=Jh(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:A=>{var I;return(I=e.onSubmitForm)==null?void 0:I.call(e,{key:t.key,data:A})},onCancel:()=>{var A;return(A=e.onCancelForm)==null?void 0:A.call(e,{key:t.key})}}),p=d==="submitted",b=async()=>{i(A=>({...A,submitting:!0}));try{await h()}catch(A){u({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{i(A=>({...A,submitting:!1}))}},_=async()=>{i(A=>({...A,canceling:!0}));try{await g()}catch(A){u({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{i(A=>({...A,canceling:!1}))}},E=l.useMemo(()=>t.version<=aS&&t.fields.every(A=>cS.has(A.type)),[t.version,t.fields]),y=l.useMemo(()=>E?d==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}:{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED},[E,d,e.isHandedOff,e.isConversationClosed]);return l.useEffect(()=>{E||r==null||r()},[E,r]),d==="canceled"?null:y.visible?a.createElement(l.Fragment,null,a.createElement(Xo,{id:`${Ke}-ext-form`,$maxWidth:e.maxBodyWidth??se.BODY_MAX_WIDTH},a.createElement(Ne.Title,null,t.title),a.createElement(dS,null,m.map(A=>a.createElement(mS,{key:A.key},a.createElement(Ne.Label,{style:{marginBottom:"6px"},required:A.required},A.label),A.type==="text"&&a.createElement(Ne.TextInput,{value:A.value||"",placeholder:A.placeholder,onChange:I=>f(A.key,I),disabled:p,error:!!A.error,submitted:p,variant:A.layout==="multiline"?"multi-line":"single-line",maxLength:A.maxLength,...s.form.textInput(A.label,A.required??!1,p).props}),A.type==="number"&&a.createElement(Ne.NumberInput,{value:A.value||null,placeholder:A.placeholder,onChange:I=>f(A.key,I),disabled:p,error:!!A.error,submitted:p,max:A.max,...s.form.numberInput(A.label,A.required??!1,p).props}),A.type==="single-select"&&a.createElement(Ne.SingleSelect,{options:A.options.map(I=>({label:I,value:I})),value:A.value||"",onChange:I=>f(A.key,I),submitted:p,groupLabel:A.label}),A.type==="multi-select"&&a.createElement(Ne.MultiSelect,{options:A.options.map(I=>({label:I,value:I})),value:A.value||[],onChange:I=>f(A.key,I),submitted:p,maxSelect:A.maxSelect,groupLabel:A.label}),A.error&&a.createElement(Ne.ErrorLabel,{style:{marginTop:"4px"}},A.error)))),a.createElement(Ne.Separator,null),a.createElement(hS,null,a.createElement(Ne.Button,{variant:p?"clear":"primary",...s.form.button(p?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:b,disabled:p||o.canceling,loading:o.submitting},p?n.SUBMITTED:n.BUTTON__SUBMIT),d!=="submitted"&&a.createElement(Ne.Button,{variant:"secondary",...s.form.button(n.BUTTON__CANCEL).props,onClick:_,disabled:o.submitting,loading:o.canceling},n.BUTTON__CANCEL))),a.createElement(mn,{...c,onClose:()=>u({visible:!1,title:""})})):a.createElement(Xo,{id:`${Ke}-ext-form`,$maxWidth:e.maxBodyWidth??se.BODY_MAX_WIDTH},a.createElement(U,{variant:"body3"},y.reason),y.cancelable&&a.createElement(Ne.Button,{variant:"primary",...s.form.button(n.BUTTON__CANCEL).props,onClick:_,loading:o.canceling},n.BUTTON__CANCEL))},Xo=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`
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
- `,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"})`
305
+ `,dS=S.default.div`display:flex;flex-direction:column;gap:12px;`,mS=S.default.div`display:flex;flex-direction:column;`,hS=S.default.div`display:flex;flex-direction:column;gap:8px;`,gS=e=>a.createElement(a.Fragment,null),Zo=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,fS=e=>{const{onTemplateError:t}=e,n=l.useCallback(()=>{t==null||t()},[t]);return Zo?a.createElement(At,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:n},a.createElement(Zo,{...e})):null},pS=e=>a.createElement(a.Fragment,null),ES=({data:e,extendedMessagePayload:t,onClickSuggestedReply:n,onConfirmTicketClosure:r,suggestedRepliesDirection:s="vertical"})=>{const{conversation:o}=de(),{stringSet:i}=le(),[c,u]=l.useState(!1),[d,m]=l.useState(!1),h=l.useRef(!1),{suggestedReplies:g}=o,f=cm({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=b=>{if(b.action==="confirmTicketClosure"){if(h.current||!r)return;h.current=!0,r({ticketId:b.ticketId,confirmed:b.confirmed}).catch(()=>{h.current=!1,m(!0)});return}n&&(n({reply:b.label}),u(!0))};return a.createElement(a.Fragment,null,a.createElement(_S,{id:`${Ke}-ext-suggested-replies`,role:"presentation",$type:s},f.map((b,_)=>{const E=g.item(b.label,_);return a.createElement(l.Fragment,{key:_},a.createElement(CS,{$type:s,...E.props,onClick:()=>p(b)},a.createElement(SS,{variant:"body3"},b.label)),E.descriptionNode)})),a.createElement(mn,{visible:d,title:i.PLACE_HOLDER__WRONG,description:i.DESK__TICKET_CLOSURE_ERROR_MESSAGE,onClose:()=>m(!1)}))},_S=S.default.div`margin:16px 0;padding:0 ${se.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?vS:bS};`,CS=S.default.button.attrs({type:"button"})`
306
306
  all: unset;
307
307
  box-sizing: border-box;
308
308
  padding: 8px 12px;
@@ -312,85 +312,85 @@ $2
312
312
  border-radius: 20px / clamp(20px, 5%, 100px);
313
313
  cursor: pointer;
314
314
  word-break: break-word;
315
- color: ${b.color.primary.main};
316
- border: 1px solid ${b.color.primary.main};
317
- background-color: ${b.themedColor.bg_50_600};
315
+ color: ${v.color.primary.main};
316
+ border: 1px solid ${v.color.primary.main};
317
+ background-color: ${v.themedColor.bg_50_600};
318
318
 
319
319
  &:hover {
320
- background-color: ${b.themedColor.bg_100_500};
320
+ background-color: ${v.themedColor.bg_100_500};
321
321
  }
322
322
 
323
- ${ke}
323
+ ${Re}
324
324
 
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"})`
325
+ ${({$type:e,theme:t})=>F.css`${e==="vertical"?yS:AS};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
326
+ `,SS=S.default(U)`color:inherit;`,vS=F.css`flex-direction:column;align-items:flex-end;`,bS=F.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,yS=F.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,AS=F.css`white-space:nowrap;`,TS=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})},IS=Object.freeze({}),xS=e=>{var A,I,k,L,R;const{components:t}=Ct.useContext(),{streamText:n,isAnimating:r,isHolding:s}=pg({text:e.message,enabled:e.isStreaming,snapOnDisable:((A=e.extendedMessagePayload)==null?void 0:A.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?IS:e.extendedMessagePayload},i=!!o.isTyping,c=!!o.isSenderAvatarVisible,u=Vn(o.extendedMessagePayload),d=u.hasCTAButton,m=u.hasChallenge,h=u.hasCitations,g=u.hasForm,f=u.hasMessageTemplate,p=!!o.createdAt,b=d||h,_=o.groupType==="top"||o.groupType==="single",E=o.groupType==="bottom"||o.groupType==="single",y=c?se.AVATAR_SIZE:0,T=b&&a.createElement(l.Fragment,null,d&&a.createElement(RS,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...o})),h&&a.createElement(t.Citation,{...o}));return a.createElement(MS,{$marginBottom:i?0:Kn(o.groupType)},_&&a.createElement(kS,null,c&&a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(t.Prechecks,{...o}),a.createElement(LS,null,a.createElement(vr,{$extraStartPadding:y},i?a.createElement(t.TypingIndicator,{...o}):a.createElement(t.MessageBody,{...o},T)),f&&a.createElement(Jo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(vr,{$extraStartPadding:y},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:y},a.createElement(t.TypingIndicator,{...o}))})),a.createElement(t.CustomMessageTemplate,{...o}),m&&a.createElement(t.Challenge,{...o}),g&&a.createElement(Jo,{$extraStartPadding:y},a.createElement(t.Form,{...o}))),a.createElement(t.MessageLogs,{...o}),E&&p&&a.createElement(wS,{$extraStartPadding:y+8},a.createElement(t.SentTime,{...o})),a.createElement(l.Fragment,null,!i&&a.createElement(hn,{$extraStartPadding:y+8},a.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},Ct=Qe({template:xS,components:{SenderName:q_,SenderAvatar:V_,SentTime:Y_,MessageBody:TS,TextMessageBody:B_,MediaMessageBody:A_,FileMessageBody:v_,MultipleFilesMessageBody:$_,TypingIndicator:X_,SuggestedReplies:ES,MessageTemplate:fS,CustomMessageTemplate:mC,Challenge:oC,CTAButton:nC,Citation:iC,Form:uS,Feedback:IC,MessageLogs:gS,Prechecks:pS}}),MS=S.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=v.default.div.attrs({role:"presentation"})`
331
+ `,hn=S.default.div.attrs({role:"presentation"})`
332
332
  display: flex;
333
333
  align-self: stretch;
334
334
  justify-content: flex-start;
335
- ${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
335
+ ${({$startPadding:e=se.HORIZONTAL_PADDING,$endPadding:t=se.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
336
336
  padding-inline: ${e+n}px ${t}px;
337
337
  `}
338
- `,wS=v.default.div.attrs({role:"presentation"})`
338
+ `,RS=S.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
- `,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"})`
343
+ `,kS=S.default(hn)`display:flex;flex-direction:row;align-items:center;gap:8px;`,vr=S.default(hn)`display:flex;`,wS=S.default(hn)`margin-top:${se.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Jo=S.default(hn).attrs({role:"presentation"})`
344
344
  display: flex;
345
- ${({$startPadding:e=re.HORIZONTAL_PADDING,$endPadding:t=re.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
345
+ ${({$startPadding:e=se.HORIZONTAL_PADDING,$endPadding:t=se.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
346
346
  padding-inline: ${e+n}px ${t}px;
347
347
  `}
348
- `,NS=v.default.div.attrs({role:"presentation"})`
348
+ `,LS=S.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
- gap: ${re.GAP_GROUPED}px;
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
- background-color: ${b.color.background100};
354
+ gap: ${se.GAP_GROUPED}px;
355
+ `;function OS({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(NS,null,a.createElement(ys,{name:e.name,mimeType:e.type,type:Xr(e.name,e.type),onClick:s}),t)}const NS=S.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${se.GAP_GROUPED}px;`,Hn=new WeakMap;function Is(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 DS({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=de(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?Is(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}),b={...p.props,$ratio:c,$clickable:!!f};return a.createElement(PS,null,a.createElement($S,{...b},!h&&a.createElement(xt,{size:26},a.createElement(ne,{type:"spinner",color:"textLowEmphasis",size:26})),m?a.createElement(FS,{$loaded:h,src:m,alt:"image-message",onLoad:()=>g(!0)}):null,p.descriptionNode),o)}const PS=S.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${se.GAP_GROUPED}px;`,$S=S.default.div`width:${se.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;${re.light`
356
+ background-color: ${v.color.background100};
357
357
  `}
358
- ${ne.dark`
359
- background-color: ${b.color.background400};
358
+ ${re.dark`
359
+ background-color: ${v.color.background400};
360
360
  `}
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`
361
+ `,FS=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 US(e){return typeof e=="object"&&e!==null&&"url"in e}const BS=({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:Is(g),type:g.type,name:g instanceof File?g.name:""}:US(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(HS,null,a.createElement(ec,{images:c,isPending:u,onClickImage:d?m:void 0}),o)},HS=S.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${se.GAP_GROUPED}px;`,mc=({children:e})=>a.createElement("span",{id:zo,className:zo,"aria-label":y_},e),hc="✱",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??""}})}}},GS=e=>{const t=new RegExp(`(\`+)[^\`]+?\\1|(${hc}+)`,"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(mc,{key:i.start},i.text)),o=i.end);return o<n&&s.push(e.slice(o,n)),s},zS=e=>{const t=GS(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 VS(e){var n,r;const t=l.useMemo(()=>zS(e.message),[e.message]);return a.createElement(KS,{$maxWidth:e.maxBodyWidth??se.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(qS,{variant:"body3"},t))}const KS=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`
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
- `,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
- background-color: ${b.color.background500};
368
+ `,qS=S.default(U)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,WS=({sendingStatus:e})=>{const t=F.useTheme();switch(e){case"pending":return a.createElement(YS,{size:16},a.createElement(ne,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(ne,{type:"error",color:v.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(ne,{type:"done",color:v.themedColor.secondary,size:16}))}},YS=S.default(xt)`margin-bottom:2px;width:16px;height:16px;`,jS=({createdAt:e})=>{const{stringSet:t,format:n}=le();return e?a.createElement(U,{variant:"caption4",color:v.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},XS=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())},ZS=e=>a.createElement(a.Fragment,null),JS=e=>{const{components:t}=Gt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(QS,{$marginBottom:Kn(e.groupType)},a.createElement(ev,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(tv,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Gt=Qe({template:JS,components:{SendingStatus:WS,SentTime:jS,MessageBody:XS,TextMessageBody:VS,MediaMessageBody:DS,FileMessageBody:OS,MultipleFilesMessageBody:BS,MessageLogs:ZS}}),QS=S.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
369
+ `,gc=S.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=se.HORIZONTAL_PADDING,$endPadding:t=se.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
370
+ `,ev=S.default(gc)``,tv=S.default(gc)`margin-top:${se.BODY_TIME_GAP}px;`,nv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),rv=e=>e.messageType!=="admin"?null:a.createElement(iv,null,a.createElement(sv,{forwardedAs:"div",variant:"caption2",color:v.themedColor.textMidEmphasis},a.createElement(At,{fallback:e.message},a.createElement(ov,{onClickLink:e.onClickLink},e.message)))),sv=S.default(U)`&&{line-height:${4/3};}`,ov=S.default(nv)`&& p{font-size:inherit;line-height:inherit;}&& a{font-weight:inherit;}`,iv=S.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${se.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,av=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,fc=({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(av({direction:g,currentIndex:h,totalCount:e.length}))}})}},cv=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},lv=({event:e,onClick:t,onArrowNavigate:n})=>{if(uv(e))return;const r=cv(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},uv=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",xs=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?v.themedColor.primary:r?v.themedColor.textDisabled:v.themedColor.textLowEmphasis,m=t?v.themedColor.textHighEmphasis:r?v.themedColor.textLowEmphasis:v.themedColor.textHighEmphasis;return a.createElement(hv,{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=>lv({event:h,onClick:e,onArrowNavigate:c})},a.createElement(dv,{"aria-hidden":"true"},a.createElement(ne,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(mv,{"aria-hidden":"true",variant:o,color:m},n))});xs.displayName="Radio";const dv=S.default.div`width:20px;height:20px;`,mv=S.default(U)`line-height:20px;word-break:break-word;`,hv=S.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Re}&[aria-disabled='false']{cursor:pointer;}`,gv=({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=fc({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(fv,null,a.createElement(Ne.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(pv,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(xs,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},fv=S.default.div`display:flex;flex-direction:column;gap:8px;`,pv=S.default.div`display:flex;flex-direction:column;gap:8px;`,Ev=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=le(),{conversation:i}=de(),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=fc({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(_v,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(Cv,{...h.radioGroupProps(e.question)},m.map((g,f)=>a.createElement(xs,{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(Sv,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},_v=S.default.div`display:flex;flex-direction:column;gap:8px;`,Cv=S.default.div`display:flex;flex-direction:column;gap:8px;`,Sv=S.default(Ne.ErrorLabel)``,vv=({value:e,selected:t})=>a.createElement(bv,{$selected:t,"aria-hidden":"true"},yv[e-1]),bv=S.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,yv=[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)"}))))],Av=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=de(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(Iv,null,a.createElement(U,{variant:"caption3",color:v.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(xv,{...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(Mv,{key:d,type:"button",...f.props},a.createElement(Tv,{value:m,selected:s||h,src:u}),!!c&&a.createElement(U,{"aria-hidden":"true",color:h?v.themedColor.textHighEmphasis:v.themedColor.textLowEmphasis,variant:"caption3"},c),f.descriptionNode)})))},Tv=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(vv,{value:e,selected:n}):a.createElement(kv,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(Rv,null,o)},Iv=S.default.div`display:flex;flex-direction:column;gap:8px;`,xv=S.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Mv=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;${Re}&:not(:disabled):hover span{color:${v.themedColor.textHighEmphasis};}`,Rv=S.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${v.color.background200};${re.dark`
371
+ background-color: ${v.color.background500};
372
372
  `}
373
373
  }
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
- background-color: ${b.color.onlight.textDisabled};
374
+ `,kv=S.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,wv=({csatPayload:e})=>a.createElement(U,{variant:"button",color:v.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}=lg({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(Lv,null,a.createElement(wv,{...f}),t===st.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(gv,{...f,defaultValue:o,value:i.isResolved,onChange:p=>c({isResolved:p})}),a.createElement(Av,{...f,value:i.csat,onChange:p=>c({csat:p})}),m&&a.createElement(Ev,{...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})))},Lv=S.default.div`display:flex;flex-direction:column;gap:12px;`,Ov=e=>{const{stringSet:t}=le();return nu(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})},Nv=()=>{const{stringSet:e}=le();return a.createElement(U,{variant:"body2",color:v.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},Dv=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Me(e)},[]),t),Pv=e=>{const{conversation:t}=de();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=qn(),m=Ov(n==null?void 0:n.csat),h=l.useRef(null),g=l.useRef(null),[f,p]=l.useState(!1),b=l.useRef(!1),_=l.useCallback(()=>{Me(()=>{var I;return(I=g.current)==null?void 0:I.focus()})},[]),{isExpiredNow:E,isRenderableCSAT:y}=ug({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:f});if(ag({csat:o,csatPayload:m,isRenderableCSAT:y,isExpiredNow:E,announceStatus:e.announceStatus,onSubmittedAnnounced:_}),!y||!m)return null;const T=()=>{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},A=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($v,{ref:h},!o&&E?a.createElement(Nv,null):a.createElement(A,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:I,params:k,validateParams:L})=>I==="submitted"?a.createElement(Uv,{ref:g,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(U,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(Dv,{onMount:s},a.createElement(Fv,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(b.current)return;const R=Oi(c);if(!R&&L()){b.current=!0,p(!0);try{await r(k)}catch(M){throw b.current=!1,p(!1),M}}else d(),R||Me(()=>{var M;(M=e.announceError)==null||M.call(e,{type:"csatFormError"},T())})}},a.createElement(U,{variant:"button"},m.csat_submit_label)))}))},$v=S.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,Fv=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;${Re}&:hover{background-color:${v.color.primary.dark};}`,Uv=S.default.div`width:100%;box-sizing:border-box;color:${v.themedColor.textHighEmphasis};background-color:${v.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${re.dark`
375
+ background-color: ${v.color.onlight.textDisabled};
376
376
  `}
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
- background-color: ${b.color.background50};
377
+ `,Bv=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(Hv,{$marginBottom:Kn(e.groupType)},n)},Qn=Qe({template:Bv,components:{AdminMessage:rv,CSATMessage:Pv}}),Hv=S.default.div`padding-inline:${se.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Ms=({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(qv,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(U,{variant:"button",color:(d==null?void 0:d.negativeText)??v.themedColor.textHighEmphasis},s)):null,f=h?a.createElement(Wv,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(U,{variant:"button",color:(d==null?void 0:d.positiveText)??v.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(Gv,null,a.createElement(zv,null,a.createElement(U,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??v.themedColor.textHighEmphasis},e)),a.createElement(Vv,null,a.createElement(U,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??v.themedColor.textMidEmphasis},n)),a.createElement(Kv,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,g,f):a.createElement(a.Fragment,null,f,g)))},Gv=S.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,zv=S.default.div`padding:24px 24px 16px;`,Vv=S.default.div`padding-inline:24px;`,Kv=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;`,qv=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;}`,Wv=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??v.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,An=16,Yv=({status:e})=>e===wn.COMPLETED?a.createElement(ne,{type:"done-circle",size:An,color:v.themedColor.textHighEmphasis}):e===wn.CANCELED?a.createElement(ne,{type:"stop-circle",size:An,color:v.themedColor.textLowEmphasis}):a.createElement(xt,{size:An},a.createElement(ne,{type:"spinner",size:An,color:v.themedColor.textHighEmphasis})),pc=24,jv=8,Xv=40,Zv=({task:e,isFirst:t,isLast:n})=>a.createElement(Jv,{role:"listitem"},a.createElement(Qv,null,a.createElement(ti,{$hidden:t}),a.createElement(eb,null,a.createElement(Yv,{status:e.status})),a.createElement(ti,{$hidden:n})),a.createElement(tb,null,a.createElement(U,{as:"div",variant:"body3",color:e.status===wn.CANCELED?v.themedColor.textLowEmphasis:v.themedColor.textHighEmphasis},e.user_facing_title))),Jv=S.default.div`display:flex;gap:4px;`,Qv=S.default.div`display:flex;flex-direction:column;align-items:center;width:${pc}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,${v.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,eb=S.default.div`display:flex;height:${pc}px;align-items:center;justify-content:center;`,tb=S.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${Xv}px;padding-block:${jv}px;`,nb=({steward:e,onCancelSteward:t})=>{const{logger:n}=he(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=ml(e.status);return a.createElement(rb,{$marginBottom:Kn("single")},a.createElement(sb,null,a.createElement(ob,null,a.createElement(ib,null,a.createElement(U,{as:"div",variant:"caption1",color:v.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(U,{as:"div",variant:"caption4",color:v.themedColor.textLowEmphasis},e.description)),c&&a.createElement(ub,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(ne,{type:"stop",size:16,color:o?v.themedColor.textDisabled:v.themedColor.textHighEmphasis}))),a.createElement(ab,null),e.tasks.length===0?u!==Qt.IN_PROGRESS?null:a.createElement(lb,null,a.createElement(xt,{size:16},a.createElement(ne,{type:"spinner",size:16,color:v.themedColor.textHighEmphasis}))):a.createElement(cb,{role:"list"},e.tasks.map((d,m)=>a.createElement(Zv,{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(Ms,{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)}}})))},rb=S.default.div`display:flex;flex-direction:column;margin:0 ${se.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
378
+ `,sb=S.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${v.themedColor.bg_300_500};background-color:${v.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,ob=S.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,ib=S.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,ab=S.default.div`height:1px;margin-block:12px;background-color:${v.themedColor.bg_200_400};`,cb=S.default.div`display:flex;flex-direction:column;`,lb=S.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,ub=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:${v.themedColor.textHighEmphasis};background-color:${v.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,db=({className:e,label:t,onClick:n})=>{const{colors:r}=F.useTheme(),{conversation:s}=de(),o={newMessages:s.newMessagesButton()};return a.createElement(mb,{className:e,onClick:n,...o.newMessages.props},a.createElement(U,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(ne,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},mb=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;}${Re}`,Rs=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(gb,{className:n},t&&a.createElement(ne,{type:t,size:e,color:v.themedColor.textLowEmphasis}),r&&a.createElement(U,{variant:"body1",color:v.themedColor.textMidEmphasis},r),s),hb=S.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,gb=S.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,fb=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(Rs,{icon:t,label:e,...r},n&&a.createElement(pb,{onClick:n.onClick,label:n.label??"Retry"})),pb=({label:e,onClick:t})=>{const{conversation:n}=de();return a.createElement(Eb,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(ne,{type:"refresh",size:20}),a.createElement(U,{variant:"button",color:v.color.primary.main},e))},Eb=S.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Re}`,_b=({iconSize:e=48,className:t})=>a.createElement(xt,{size:e,className:t}),Cb=({label:e="No channels",icon:t="chat",...n})=>a.createElement(Rs,{icon:t,label:e,...n}),Sb=({label:e="No messages",icon:t="message",...n})=>a.createElement(Rs,{icon:t,label:e,...n}),vb=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(hb,{"data-testid":`sb-placeholder-${e.type}`},n)},er=Qe({template:vb,components:{Loading:_b,Error:fb,NoChannels:Cb,NoMessages:Sb}}),tn=e=>{const{Template:t}=er.useContext();return a.createElement(t,{...e})},bb=[0,150,450];function yb({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=bb.map(c=>setTimeout(()=>{Me(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const Ab=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=le();return a.createElement(Tb,{id:`${Ue}-date-separator`,role:n,style:r,className:e},a.createElement(U,{variant:"caption4",color:v.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},Tb=S.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Ib=({className:e,style:t,onClick:n})=>{const{conversation:r}=de(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(xb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(ne,{size:24,type:"chevron-down",color:v.color.primary.main}),s.scrollToBottom.descriptionNode??null)},xb=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);${re.light`
379
+ background-color: ${v.color.background50};
380
380
  &:hover {
381
- background-color: ${b.color.background100};
381
+ background-color: ${v.color.background100};
382
382
  }
383
383
  &:active {
384
- background-color: ${b.color.background200};
384
+ background-color: ${v.color.background200};
385
385
  }
386
386
  `}
387
- ${ne.dark`
388
- background-color: ${b.color.background400};
387
+ ${re.dark`
388
+ background-color: ${v.color.background400};
389
389
  &:hover {
390
- background-color: ${b.color.background500};
390
+ background-color: ${v.color.background500};
391
391
  }
392
392
  &:active {
393
- background-color: ${b.color.background700};
393
+ background-color: ${v.color.background700};
394
394
  }
395
395
  `}
396
396
 
@@ -398,45 +398,45 @@ $2
398
398
  outline: none;
399
399
  }
400
400
 
401
- ${ke}
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
- background-color: ${b.color.background700};
404
- border-color: ${b.color.ondark.textLowEmphasis};
401
+ ${Re}
402
+ `,Mb=()=>null,tr=Qe({template:Mb,components:{DateSeparator:Ab,ScrollToBottomButton:Ib}}),Rb=()=>{const{stringSet:e,format:t}=le(),{agentPreviewConfigs:n={},aiAgentId:r}=he(),{aiAgentInfo:s}=De(),{messageSource:o}=xe(),{Template:i}=Ct.useContext(),{components:c}=tr.useContext(),u=n.welcomeMessages??[],d=o.messages,m=gE(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 b=p===u.length-1,_=m.length!==d.length,E=u.length===1?"single":p===0?"top":b||_?"bottom":"middle",y=(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(y,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:y,extendedMessagePayload:{suggested_replies:f.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:b&&!_,isBotMessage:!0,onClickSuggestedReply:async({reply:T})=>{o.sendUserMessage({message:T})}}))}))}},kb=()=>{const{messageSource:e,scrollSource:t}=xe();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",wb=({style:e})=>{const{stringSet:t}=le(),{handlers:n}=he(),{conversation:r}=de();return hs("powered-by")?a.createElement(Lb,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(Ob,{variant:"caption2",forwardedAs:"a",href:ni,...r.poweredByLink().props,rel:va,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:ni})}},"Sendbird")):null},Lb=S.default(U)`color:${v.themedColor.textLowEmphasis};text-align:center;`,Ob=S.default(U)`color:${v.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,Nb=()=>{var c;const{stringSet:e}=le(),{conversation:t}=de(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=xe(),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(Db,null,a.createElement(Pb,{variant:"button",color:v.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},Db=S.default.div`display:flex;justify-content:center;margin-bottom:16px;`,Pb=S.default(U)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${v.color.background50};border:1px solid ${v.color.onlight.textDisabled};${re.dark`
403
+ background-color: ${v.color.background700};
404
+ border-color: ${v.color.ondark.textLowEmphasis};
405
405
  `}
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`
406
+ `,$b=({statsCallbacks:e,...t})=>(yg(e),a.createElement(nb,{...t})),Fb=(e,t,n)=>t&&ye.isWelcomeMessage(e,n)&&ye.isWelcomeMessage(t,n)?!1:!rl.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Ub=()=>{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}=de().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:g,handlers:f,state:p,_aiAgentSDK:b}=he(),{userSession:_,aiAgentInfo:E,connectionError:y}=De(),{_statsEnabled:T,_stats:A,conversation:I,channelSource:k,messageSource:L,scrollSource:R,state:{input:M,streamAnimation:$}}=xe(),{filteredMessages:N,shouldShowOriginalDate:ee,renderAgentPreviewWelcomeMessages:oe}=Rb(),q=bg({enabled:T}),Y=rg(ta(k.channel),Ml(N,_.userId)),[B,X]=l.useState(null),[P,V]=l.useState(null),H=$e(k.channel)?void 0:Y??$.heldTypingInfo;l.useEffect(()=>{R.actions.onTypingIndicatorUpdate(!!H)},[!!H,R.actions.onTypingIndicatorUpdate]),kb(),yb({enabled:L.initialized&&L.messages.length>0});const K=O=>{var ve;return hl(O,{aiAgentInfo:E,members:(ve=k.channel)==null?void 0:ve.members})},G=O=>{if(O.sendingStatus==="failed"&&!M.disabled)return()=>V(O)},J=({message:O,index:ve})=>{const Ie=gl(O),Le=N[ve-1],x=N[ve+1],w=N[N.length-1],D=O===w,z=Fe(O,E.userId),Q=!(E.isUserFeedbackEnabled&&z&&!ye.isWelcomeMessage(O)),ie=fl(O,Le,x,Q),te=Fb(O,Le,E.userId)&&ee(ve),Se=Pe=>{X({files:Pe.files.map(et=>({...et,timestamp:O.createdAt})),index:Pe.index})},Oe=Pe=>{Se({files:[Pe],index:0})},W=te?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:O.createdAt}):null,ge={data:O.data,maxBodyWidth:p.expanded?se.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:O.extendedMessagePayload,createdAt:O.createdAt,groupType:ie,onClickMedia:Oe,onClickMediaFiles:Se,onClickFile:f.onClickLink,onClickCTA:f.onClickLink,onClickCitation:Pe=>f.onClickLink({url:Pe.link}),onClickLink:f.onClickLink},Z=()=>{if(we.isOutgoing(O,_.userId))return"outgoingmessage";if(we.isIncoming(O,_.userId))return"incomingmessage"},me=O.createdAt!=null&&O.createdAt!==0?o(O.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ue=(()=>{var et;const Pe=(et=O.message)==null?void 0:et.trim();return O.isFileMessage()||O.isMultipleFilesMessage()?Dr(ua(O,Xa(s))):Pe?jg({markdownText:Pe}):Dr("")})(),Ee=(()=>{if(we.isAdmin(O))return en({message:ue.text,messageFormat:ue.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(we.isOutgoing(O,_.userId))return en({sender:s.A11Y_MESSAGE_SENDER_YOU,message:ue.text,messageFormat:"plain",time:me,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(we.isIncoming(O,_.userId))return en({sender:K(O).nickname,message:ue.text,messageFormat:ue.format,time:me,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),Be=(()=>{var Pe,et;if(we.isAdmin(O))return we.isCSAT(O)?I?a.createElement(n,{...ge,...I,isResolvedWhenDeterminedByUser:eu(I),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async at=>{var ct;await((ct=k.channel)==null?void 0:ct.submitCSAT(at))},onScrollToBottom:()=>R.actions.scrollToBottom()}):null:a.createElement(n,{...ge,messageType:"admin",message:O.message});if(we.isSteward(O)){const at=q({message:O});return a.createElement($b,{steward:O.extendedMessagePayload.steward,statsCallbacks:at,onCancelSteward:async()=>{await g.aiAgent.cancelStewardTask({channelUrl:O.channelUrl,messageId:O.messageId})}})}if(we.isOutgoing(O,_.userId)){const at={...ge,message:O.message,sender:K(O),sendingStatus:O.sendingStatus,onClickFailedMessage:G(O)};if(O.isUserMessage())return a.createElement(e,{messageType:"user",...at});if(O.isFileMessage()){const[ct,ft]=((Pe=O.metaArrays.find(fe=>fe.key===bi))==null?void 0:Pe.value)??[];return a.createElement(e,{messageType:"file",file:O,metadata:{aspectRatio:ct&&ft?`${ct}/${ft}`:"1/1",localFile:(et=O.messageParams)==null?void 0:et.file},...at})}if(O.isMultipleFilesMessage()){const{files:ct,metadata:ft}=ei(O);return a.createElement(e,{messageType:"multipleFiles",files:ct,metadata:ft,...at})}}if(we.isIncoming(O,_.userId)){const at=ye.isStreaming(O),ct=q({message:O}),ft={...ge,onTemplateError:()=>A.onRenderedContentTemplateError(O.messageId),onFormError:()=>A.onRenderedContentFormError(O.messageId),statsCallbacks:ct,sender:K(O),message:O.message,suggestedRepliesVisible:D,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:z,isStreaming:at,isHandedOff:mt(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 b.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:lt}=fe.internalData;Ge==="message.send"&&(lt!=null&&lt.message)&&L.sendUserMessage({message:lt.message})}},onFeedbackUpdate:fe=>{const Ge={messageId:O.messageId,channelUrl:O.channelUrl};if(!fe)return g.aiAgent.deleteMessageFeedback(Ge);const lt={...Ge,rating:hC(fe.rating),comment:fe.comment};return ye.hasFeedback(O)?g.aiAgent.updateMessageFeedback(lt):g.aiAgent.createMessageFeedback(lt)},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:lt,data:Jc})=>g.aiAgent.sendChallengeAction({channelUrl:O.channelUrl,key:fe,requestId:Ge,action:lt,data:Jc}),onStreamAnimationStart:()=>{$.start(O.messageId),A.onMessageLifecycleAnimationStart(O.messageId)},onStreamAnimationProgress:()=>{R.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:({completed:fe})=>{$.stop(O.messageId),R.actions.onStreamingUpdate(!1),A.onMessageLifecycleAnimationComplete(O.messageId,fe)},onStreamAnimationHoldChange:fe=>{fe?$.holdStart(O.messageId,{user:K(O),isBot:z}):$.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),Je=u.item({label:Ee,holding:He});return a.createElement(l.Fragment,{key:Ie},W,a.createElement("div",{id:`${Ue}-message-item`,...Je.props,"data-message-listitem":"","data-layout-id":Z()},Be))};return a.createElement(Bb,{id:`${Ue}-message-list`},a.createElement(GE,{ref:R.ref,onScroll:R.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:N,renderMessage:J,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:!!(y||k.error),LoadingComponent:a.createElement(tn,{type:"loading"}),EmptyComponent:(()=>{const O=oe();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:(y==null?void 0:y.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(wb,{style:{marginTop:16}}),oe()),messageBottomArea:a.createElement(a.Fragment,null,H&&a.createElement("div",{id:`${Ue}-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(Nb,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&R.state.isAwayFromBottom&&L.newMessages.length>0&&a.createElement(Hb,{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}}))}),B&&a.createElement(jE,{files:B.files,initialIndex:B.index,onClose:()=>X(null),visible:!0}),P&&a.createElement(Et,{visible:!0,onClose:()=>V(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(Et.ActionItem,{onClick:()=>{L.resendMessage(P),V(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(Et.ActionItem,{destructive:!0,onClick:()=>{L.deleteMessage(P),V(null)}},s.FAILED_MESSAGE_REMOVE)))},Bb=S.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,Hb=S.default(db)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,Gb=()=>a.createElement(Ub,null),ri={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Ec=({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:b="#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(ne,{size:16,type:"actionbook",color:p})),a.createElement(Tn,{$clickable:!!o,$highlightColor:_,variant:"body2",color:b,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(ne,{size:16,type:"function",color:p})),a.createElement(Gn,null,a.createElement(Tn,{$clickable:!!i,$highlightColor:_,variant:"body2",color:b,onClick:()=>i==null?void 0:i(E),maxTextLines:1},E.name),c&&a.createElement(zb,{role:"button",onClick:()=>c==null?void 0:c(E)},a.createElement(U,{variant:"body2",color:_},"View details"),a.createElement(ne,{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(ne,{size:16,type:ri[E.source_type]??ri.snippet,color:p}),sourceType:E.source_type})),a.createElement(Tn,{$clickable:!!u,$highlightColor:_,variant:"body2",color:b,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(ne,{size:16,type:"template",color:p})),a.createElement(Tn,{$clickable:!!d,$highlightColor:_,variant:"body2",color:b,onClick:()=>d==null?void 0:d(E),maxTextLines:1},E.name))),!!(s!=null&&s.length)&&a.createElement(Vb,null,a.createElement(jt,null,a.createElement(ne,{size:16,type:"activity",color:p})),a.createElement(Kb,{variant:"body2",color:b},s.map(E=>E.replace(/_/g," ")).join(" · "))),h)},_c=S.default(U)`font-weight:400;`,Tn=S.default(_c)`${({$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=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
- background-color: ${b.color.background50};
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;`,zb=S.default(Gn)`cursor:pointer;gap:4px;`,Rn=S.default(Gn)`flex-direction:row;align-items:center;`,Vb=S.default(Rn)`align-items:flex-start;max-width:100%;`,Kb=S.default(_c)`min-width:0;`,si=S.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,qb=e=>{const t=e.replace(/[_-]+/g," ").trim().toLowerCase();return t?t.charAt(0).toUpperCase()+t.slice(1):""},Cc=({prechecks:e,maxBodyWidth:t})=>{const{theme:n}=Wn();return e.length===0?null:a.createElement(Wb,{id:`${Ke}-ext-prechecks`},a.createElement(Yb,{$maxWidth:t??se.BODY_MAX_WIDTH},e.map(r=>a.createElement(jb,{key:r.key},a.createElement(Xb,{type:"done-circle",size:16,color:v.themedColor.secondary}),a.createElement(U,{variant:"caption2",color:n.colors.messageIncoming.text},qb(r.key))))))},Wb=S.default.div`align-self:stretch;padding-block-end:8px;padding-inline-start:${se.HORIZONTAL_PADDING+se.AVATAR_SIZE}px;padding-inline-end:${se.HORIZONTAL_PADDING}px;`,Yb=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};`,jb=S.default.div`display:flex;align-items:center;gap:6px;min-width:0;overflow-wrap:anywhere;`,Xb=S.default(ne)`flex-shrink:0;`,Sc=be("DashboardTester"),Zb=Sc.Provider;function Jb({testerType:e,origin:t,children:n}){return a.createElement(Zb,{value:{testerType:e,origin:t}},e&&a.createElement(Qb,null),n)}const vc=Sc.useContext,Qb=()=>a.createElement(a.Fragment,null,a.createElement(Ct.Prechecks,{component:ey}),a.createElement(Ct.MessageLogs,{component:oi}),a.createElement(Gt.MessageLogs,{component:oi})),ey=({extendedMessagePayload:e={},maxBodyWidth:t})=>a.createElement(Cc,{prechecks:e.prechecks??[],maxBodyWidth:t}),oi=({extendedMessagePayload:e={}})=>{const{handlers:t}=he(),{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(ty,null,a.createElement(ny,{$width:4}),a.createElement(Ec,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:v.themedColor.textHighEmphasis,textColor:v.themedColor.textHighEmphasis,barColor:v.themedColor.textDisabled},topContent:a.createElement(U,{variant:"caption4",color:v.themedColor.textLowEmphasis},"Only visible in the tester")}))},ty=S.default.div`display:flex;gap:16px;margin:6px ${se.HORIZONTAL_PADDING}px 4px ${se.HORIZONTAL_PADDING+se.AVATAR_SIZE}px;align-self:stretch;`,ny=S.default.div`width:${({$width:e})=>e}px;background-color:${v.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,ry=()=>{var s;const{origin:e}=vc(),{appId:t,aiAgentId:n}=Te(),{channelSource:r}=xe();return(s=r.channel)!=null&&s.conversation?a.createElement(sy,null,a.createElement(Kr,{style:{gap:4}},a.createElement(ne,{color:v.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(U,{as:"i",color:v.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(Kr,{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(U,{variant:"body3",color:v.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:v.themedColor.primary}},"conversation link")),a.createElement(ne,{color:v.themedColor.primary,size:14,type:"copy"}))):null},Kr=S.default.div`display:flex;justify-content:center;align-items:center;`,sy=S.default(Kr)`flex-direction:column;padding-block:16px;background-color:${v.themedColor.bg_100_500};gap:8px;`,oy=(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}},bc=l.createContext(void 0),iy=({children:e})=>{var ee,oe;const{chatSDK:t}=he(),{createAttachmentRules:n}=De(),{stringSet:r}=le(),{channelSource:s,state:o}=xe(),[i,c]=l.useState([]),{announceError:u}=_s(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(ee=t.appInfo)==null?void 0:ee.uploadSizeLimit}),g=((oe=o==null?void 0:o.input)==null?void 0:oe.disabled)??!1,f=h.isEnabled(),p=h.maxAttachmentCount,b=()=>m(null),_=q=>m(q),E=()=>{_({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString())})},y=q=>{_({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",q.toString())}),u({type:"fileSizeExceeded",maxSizeMB:q})},T=q=>{_({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",q.toString())})},A=q=>q.map(Y=>{const B=Is(Y);return Xp(Y,B),{file:Y,preview:{url:B,type:Y.type,name:Y.name}}}),I=q=>{c(Y=>[...Y,...q])},k=q=>{c(Y=>(Y.forEach(B=>Qo(B.file)),q))},L=q=>{const{passed:Y,failedBySize:B,failedByType:X}=oy(q,h),P=B.length+X.length,V=q.length===1?B[0]:void 0;return V?y(h.getUploadSizeLimitInMB(V.type)):P>0&&T(P),Y},R=q=>{const Y=L(q.files);if(Y.length===0)return;const B=A(Y);q.type==="append"?I(B):k(B)},M=q=>{if(!f||g||!mm(q))return;const Y=gm({currentFiles:i.map(({file:B})=>B),incomingFiles:q,maxAttachmentCount:p});switch(Y.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(Y.action)});return;case"apply":R(Y.action);return}},$=q=>{c(Y=>{var X;const B=(X=Y[q])==null?void 0:X.file;return B&&Qo(B),Y.filter((P,V)=>V!==q)})},N=()=>{c([])};return a.createElement(bc.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:b}))},ks=()=>{const e=l.useContext(bc);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function ay({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 cy({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 ly=()=>{const{announceError:e}=gt();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},uy=1e3,dy=(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]),sg(t,u,{enabled:o,idleMs:uy})},my=({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}}},hy=S.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,gy=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;}`,fy=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;${re.light`
414
+ background-color: ${v.color.background50};
415
415
  `}
416
- ${ne.dark`
417
- background-color: ${b.color.background500};
416
+ ${re.dark`
417
+ background-color: ${v.color.background500};
418
418
  `}
419
419
  path {
420
- fill: ${b.themedColor.textMidEmphasis};
420
+ fill: ${v.themedColor.textMidEmphasis};
421
421
  }
422
422
 
423
423
  &:hover {
424
424
  path {
425
- fill: ${b.themedColor.textHighEmphasis};
425
+ fill: ${v.themedColor.textHighEmphasis};
426
426
  }
427
427
  }
428
428
 
429
429
  &:focus-visible {
430
430
  opacity: 1;
431
- outline: 2px solid ${b.color.primary.main};
431
+ outline: 2px solid ${v.color.primary.main};
432
432
  outline-offset: 2px;
433
433
  }
434
434
 
435
435
  circle {
436
- stroke: ${b.themedColor.bg_50_600};
436
+ stroke: ${v.themedColor.bg_50_600};
437
437
  }
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
- outline: 2px solid ${b.themedColor.primary};
438
+ `,py=()=>{const e=dn(),{conversation:t}=de(),{files:n,removeFile:r,isFileUploadEnabled:s}=ks();return s&&n.length>0?a.createElement(hy,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(ys,{name:c,mimeType:i,type:Xr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(gy,{key:u},a.createElement(fy,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(ne,{type:"close-filled",color:v.themedColor.textMidEmphasis})),m)})):null},Ey={textArea:F.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},yc=S.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Re}`,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:${Sa}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${$a&&Ey.textArea};${({$focusVisible:e})=>e&&F.css`
439
+ outline: 2px solid ${v.themedColor.primary};
440
440
  outline-offset: 2px;
441
441
  `}
442
442
 
@@ -447,22 +447,22 @@ $2
447
447
  &:disabled {
448
448
  cursor: not-allowed;
449
449
  &::placeholder {
450
- color: ${b.themedColor.textDisabled};
450
+ color: ${v.themedColor.textDisabled};
451
451
  }
452
452
  }
453
453
 
454
- ${({$blocked:e})=>e&&F.css`cursor:not-allowed;&::placeholder{color:${b.themedColor.textDisabled};}`}
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
- color: ${b.color.information.light};
454
+ ${({$blocked:e})=>e&&F.css`cursor:not-allowed;&::placeholder{color:${v.themedColor.textDisabled};}`}
455
+ `,_y=S.default.input`display:none;`;S.default.div`display:flex;align-items:center;gap:24px;`;const Cy=S.default(yc)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${v.themedColor.bg_100_500};path{fill:${v.themedColor.textHighEmphasis};}}&:active{background-color:${v.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}=de(),{config:r}=he(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=ks(),g=m.includes(Ir),f=g?["image/*"]:m.filter(ui),p=g?[Ir]:m.filter(L=>!ui(L)),b=r.conversation.input.gallery.photoEnabled,_=r.conversation.input.fileEnabled,E=()=>g||f.length>0,y=()=>g||p.length>0,T=L=>{const R=L.currentTarget.files;R&&u(Array.from(R)),L.target.value=""},A=()=>{c(!0)},I=l.useMemo(()=>{const L=[];return b&&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(!y()){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,b,_]);if(!d)return null;const k={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(Cy,{...k.attach.props,disabled:e,onClick:A},a.createElement(ne,{type:"add",color:e?v.themedColor.textDisabled:v.color.primary.main,size:20}),k.attach.descriptionNode),I.map(L=>a.createElement(_y,{key:L.type,type:"file",ref:L.inputRef,multiple:L.type==="image",onChange:T,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))))},Sy=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=le(),{conversation:s}=de(),{rootElement:o}=he(),i=_t(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=my({focusRoot:i}),{channelSource:m,messageSource:h,state:g}=xe(),{files:f,addFiles:p,clearFiles:b}=ks(),_=ly(),{focusPolicy:E,disabled:y,disabledBy:T}=g.input,A=E==="preserve",I=E==="release",k=(()=>{if(!y)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(T){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}})();cE({onDropFiles:G=>{p(G)}}),cy({blurred:I,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),dy(m.channel,t,!y);const L=t.trim().length>0,R=f.length>0,M=!y&&(L||R),$={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()};l.useLayoutEffect(()=>{if(!e.current)return;e.current.style.height="";const G=Math.min(Ef,e.current.scrollHeight);Sa<G&&(e.current.style.height=`${G}px`)},[t,I]);const N=()=>{b(),n("")},ee=()=>{var G;d(),(G=e.current)==null||G.focus()},{requestRestore:oe,cancelRestore:q}=ay({elementRef:e,ready:A,onRestore:d}),Y=G=>{q(),_(G)},B=()=>{q()},X=async G=>{try{await G(),B()}catch{Y(e.current)}},P=async()=>{if(y)return;const G=t.trim();if(!G&&!f.length)return;const J=[...f];if(oe(),N(),ee(),J.length===0){await X(()=>h.sendUserMessage({message:G}));return}if(J.length===1)await X(()=>h.sendFileMessage({message:G,file:J[0].file}));else{const ae=J.map(({file:O})=>({file:O}));await X(()=>h.sendMultipleFilesMessage({message:G,fileInfoList:ae}))}},V=G=>{const J=Array.from(G.clipboardData.files);J.length>0&&(G.preventDefault(),p(J))},H=G=>{G.key!=="Enter"||G.nativeEvent.isComposing||G.shiftKey||(G.preventDefault(),P())},K=G=>{y||n(G.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:y}),a.createElement(ii,null,a.createElement(py,null),a.createElement(ai,null,a.createElement(ci,{ref:e,rows:1,...$.input.props,readOnly:A,"aria-disabled":A?"true":void 0,value:t,placeholder:k,maxLength:5e3,$blocked:y,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:H,onChange:K,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:V}))),M&&a.createElement(yc,{...$.send.props,onClick:()=>P()},a.createElement(ne,{type:"send",color:v.color.primary.main,size:20}),$.send.descriptionNode))},vy=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:${v.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${re.light`
456
+ color: ${v.color.information.light};
457
457
  `};
458
- ${ne.dark`
459
- color: ${b.color.information.main};
458
+ ${re.dark`
459
+ color: ${v.color.information.main};
460
460
  `};
461
461
  }
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
- box-shadow: 0 0 0 2px ${b.color.background500};
462
+ `,by=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),yy=()=>{const{aiAgentInfo:e,userSession:t}=De(),{handlers:n}=he(),{messageSource:r,channelSource:s}=xe(),[o,i]=l.useState(null),c=hs("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>Fe(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(vy,{"data-testid":"sb-special-notice"},a.createElement(At,{fallback:e.specialNotice},a.createElement(by,{onClickLink:n.onClickLink},e.specialNotice)))},Ay=()=>a.createElement(Ty,null,a.createElement(yy,null),a.createElement(iy,null,a.createElement(Sy,null))),Ty=S.default.div`z-index:0;border:none;width:100%;`,Iy=()=>{var s;const{testerType:e}=vc(),{channelSource:t}=xe(),n=$e(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(ry,null):a.createElement(Ay,null)},Ac=({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(xy,{...s},a.createElement(My,null,n==="center"&&t&&a.createElement(Ry,{$sideWidth:Math.max(c,d)},a.createElement(ky,null,t)),a.createElement(wy,null,a.createElement(Ly,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Ny,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Oy,{ref:i},r))))},xy=S.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${v.themedColor.textDisabled};`,My=S.default.div`position:relative;height:56px;padding:11px 12px;`,Ry=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;`,ky=S.default.div`max-width:100%;overflow:hidden;`,wy=S.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Ly=S.default.div`flex-shrink:0;display:flex;align-items:center;`,Oy=S.default.div`flex-shrink:0;display:flex;align-items:center;`,Ny=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,Dy=()=>{const{state:e}=he(),{messenger:t}=de(),n=zt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},Py=()=>{const{enableCloseConversationButton:e,dispatcher:t}=he(),{channelSource:n}=xe(),{conversation:r}=de(),s=n.channel,o=zt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!Qr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(dt.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(it,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},$y=()=>{const{state:e,enableExpandButton:t}=he(),{messenger:n}=de(),r=zt();return t?a.createElement(it,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Fy=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(qr,null,t,a.createElement(Hy,{$position:n},a.createElement(Gy,{variant:"caption1"},e),a.createElement(Uy,{$position:n}))),Uy=({$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:v.themedColor.textHighEmphasis})),By={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%);`},qr=S.default.div`position:relative;`,Hy=S.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${It.TOOLTIP};${({$position:e})=>By[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${qr}:hover &,${qr}:focus-within &{opacity:1;}`,Gy=S.default(U)`padding:6px 8px;background:${v.themedColor.textHighEmphasis};color:${v.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,zy=2e3,mi=0,Vy=1500,In=Symbol("header-focus-status-pause"),hi="data-sb-header-focus-protected",Ky="[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)},qy=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),kn(e)},Wy=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)})},Yy=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(Ky),!1),ws=()=>{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()+Vy,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(()=>{qy(u),e(In,!1)},zy)},[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||!Yy(f))return;const b=Wy(d);d.focus({preventScroll:!0}),b()},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}},jy=()=>{const{logger:e}=he(),{stringSet:t}=le(),{channelSource:n}=xe(),{conversation:r}=de(),s=n.channel,o=zt(),i=hs("handoff-button",s),c=!Qr(s)||mt(s),[u,d]=l.useState(!1),m=ws(),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(Fy,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(it,{...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(Ms,{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})))},Xy=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/TEfZbcKQ.cjs")).then(e=>({default:e.MarkdownText}))),Zy=()=>{const{logger:e,_aiAgentSDK:t}=he(),{stringSet:n}=le(),{memoryInfo:r,sdkUser:s}=De(),{actions:o}=xe(),{conversation:i}=de(),c=zt(20),u=ws(),[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),b=(y,T,A)=>{t.liveMetricManager.track({type:"memory",variant:y,action:T,deleteOnOff:A})},_=()=>m(null),E=async y=>{if(!f.current){f.current=!0,g(!1);try{await o.setUserMemoryState({enabled:y}),_()}catch(T){e.error("memoryIndicator.setUserMemoryState: error",T),g(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,r.showIndicator&&a.createElement(a.Fragment,null,a.createElement(tA,{...p.props,as:"button",type:"button",onClick:()=>m({...r}),...u,$size:c},a.createElement(ne,{type:"memory",size:c,color:v.themedColor.textHighEmphasis}),a.createElement(nA,{$enabled:r.enabled})),p.descriptionNode),d&&a.createElement(Jy,{memoryInfo:d,onClose:_,onSetEnabled:E,trackMemory:b}),a.createElement(mn,{visible:h,title:n.PLACE_HOLDER__WRONG,description:n.MEMORY__ERROR_MESSAGE,onClose:()=>g(!1)}))},Jy=({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=dm(e),d=u==="consent",m=l.useRef(!1),h=l.useRef(!1),g=y=>{y!=="shown"&&(h.current=!0),r(u,y,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:b}=p,_=o.memoryDialog;return a.createElement(St,{visible:!0,portalContainerId:Ae.WINDOW,onClose:f,cancelable:!d,"aria-labelledby":i,"aria-describedby":c},a.createElement(Ms,{title:s.MEMORY__DIALOG_TITLE,titleId:i,description:a.createElement(Qy,null,p.body),descriptionId:c,negativeText:p.negativeText,positiveText:p.positiveText,buttonLayout:d?"horizontal":"vertical-full-width",onCancel:b&&(()=>{g("cancel"),b()}),onConfirm:()=>{g("confirm"),p.onConfirm()},styles:{titleColor:_.titleText,positiveBackground:_.positiveBackground,positiveText:_.positiveText,positiveBorderColor:_.positiveBorderColor,negativeBackground:_.negativeBackground,negativeText:_.negativeText,negativeBorderColor:_.negativeBorderColor}}))},Qy=({children:e})=>{const{handlers:t}=he();return a.createElement(rA,null,a.createElement(At,{fallback:e},a.createElement(Xy,{onClickLink:t.onClickLink},e)))},eA=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;`,tA=S.default.button`${eA};cursor:pointer;${Re}`,nA=S.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?v.themedColor.secondary:v.color.background300};box-shadow:0 0 0 2px ${v.color.background50};${re.dark`
463
+ box-shadow: 0 0 0 2px ${v.color.background500};
464
464
  `}
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})`
465
+ `,rA=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;}`,sA=()=>{const{conversation:e}=de(),{onNavigateToConversationList:t}=xe();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(it,{...n.menu.props,...ha,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Tc=({channel:e,size:t=40,skeletonColor:n=v.themedColor.bg_100_500})=>{const{userSession:r,aiAgentInfo:s}=De(),{fallbackIcon:o,url:i}=gs({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(ne,{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;`,oA=e=>{const{channelSource:t}=xe(),{aiAgentInfo:n,userSession:r}=De(),{conversation:s}=de(),{config:o}=Te(),{announcementsEnabled:i}=gt(),c=F.useTheme(),u=t.channel,d=gs({channel:u,userSession:r,aiAgentInfo:n}),m=e.title??d.title,h=o.conversation.header.avatarEnabled,g=ws(),f=qa({enabled:i,label:m}),p={title:s.header.title(m,{active:f.enabled,titleId:f.id,initialFocus:!1})};return a.createElement(iA,null,h&&a.createElement(Tc,{channel:u,size:34,skeletonColor:c.colors.conversation.headerProfileSkeleton}),a.createElement(aA,{...p.title.props,...g},m))},iA=S.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,aA=S.default(U).attrs({variant:"h2",color:v.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
- `,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`
477
+ `,cA=e=>{const{components:t}=Mt.useContext();return a.createElement(Ac,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:pa})},lA=()=>{const{components:e}=Mt.useContext();return a.createElement(e.MenuButton,null)},uA=()=>{const{components:e}=Mt.useContext();return a.createElement(e.Title,null)},dA=()=>{const{components:e}=Mt.useContext();return a.createElement(hA,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:cA,components:{StartArea:lA,TitleArea:uA,EndArea:dA,MenuButton:sA,Title:oA,MemoryIndicator:Zy,HandoffButton:jy,ConversationCloseButton:Py,ExpandButton:$y,CloseButton:Dy}}),mA=()=>{const{Template:e}=Mt.useContext();return a.createElement(e,{titleAlign:"start"})},hA=S.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Ic=({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(up,{announcementsEnabled:c},a.createElement(gA,null),a.createElement(fA,null),a.createElement(pA,{style:m,dragHandlers:p,initialFocusTarget:d},a.createElement(f,null)),e))))},gA=()=>(mE(),null),fA=()=>(IE(),EE(),yE(),null),pA=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return dE(s,n),a.createElement(_A,{ref:s,style:e,...t},r)},EA=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:EA,components:{Header:mA,Body:Gb,Footer:Iy}}),_A=S.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,xc=be("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:_e}),CA=xc.Provider,Ls=xc.useContext,SA=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=_s(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(CA,{value:s},e)},{Provider:vA,Context:bA,useContext:gn}=be("ConversationList");function Mc({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=_e,children:s}){return a.createElement(Fh,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(vA,{value:{...o,onOpenConversationView:r}},s))}const yA=e=>{const{announcementsEnabled:t}=Ls(),{listSource:n}=gn(),r=Ia();Wa(e,{enabled:t,ready:n.initialized,suppressed:r})},AA=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=Ls(),{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])},TA=({channel:e})=>a.createElement(Tc,{channel:e}),Wr=99,IA=e=>{var _,E;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=le(),{userSession:o,aiAgentInfo:i}=De(),{conversationList:c}=de(),u=gs({channel:t,userSession:o,aiAgentInfo:i}),d=sm(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=im(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,b=c.item({agent:g,status:f,lastMessage:d,time:m,unreadCount:h,onActivate:p});return a.createElement(xA,{"data-testid":"sb-conversation-list-item",$clickable:!!p,...b.props},a.createElement(MA,null,a.createElement(TA,{...e})),a.createElement(RA,null,a.createElement(kA,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:v.themedColor.textHighEmphasis},d):a.createElement(U,{"data-testid":"sb-conversation-list-item-preview",variant:"subtitle1",color:v.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(wA,null,$e(t)&&a.createElement(a.Fragment,null,a.createElement(U,{"data-testid":"sb-conversation-list-item-ended",variant:"caption1",color:v.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(LA,null)),a.createElement(U,{"data-testid":"sb-conversation-list-item-time",variant:"caption2",color:v.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(OA,{"data-testid":"sb-conversation-list-item-unread-badge",$count:h},a.createElement(U,{variant:"caption3",color:v.themedColor.textHighEmphasisInverse},h<=Wr?h:`${Wr}+`))),b.descriptionNode)},Os=Qe({template:IA,components:{}}),xA=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"};`,MA=S.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,RA=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 ${v.themedColor.textDisabled};`,kA=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;`,wA=S.default.div`display:flex;align-items:center;gap:6px;`,LA=S.default.div`width:2px;height:2px;border-radius:1px;background-color:${v.themedColor.textLowEmphasis};`,OA=S.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${v.themedColor.error};${({$count:e})=>e<=Wr&&F.css`
478
478
  width: 20px;
479
479
  `}
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`
480
+ `,NA=({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(DA,{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(PA,{key:d,role:"listitem"},u)}))},DA=S.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,PA=S.default.div`flex-shrink:0;`,$A=()=>{const{stringSet:e}=le(),{listSource:t,onOpenConversationView:n}=gn(),{Template:r}=Os.useContext();return t.initialized?t.channels.length===0?a.createElement(tn,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(NA,{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"})},FA=()=>{const{stringSet:e}=le(),{_aiAgentSDK:t}=Te(),{language:n,countryCode:r,context:s}=he(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=De(),{onOpenConversationView:u}=gn(),{conversationList:d}=de(),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(UA,{...d.footer.button({onActivate:m}).props},a.createElement(BA,{variant:"h1"},e.TALK_TO_AGENT))},UA=S.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,BA=S.default(U)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,HA=()=>{const{state:e}=he(),{messenger:t}=de(),n=zt(),r=()=>{e.setOpened(!1)};return a.createElement(it,{...t.closeButton().props,type:"close",size:n,onClick:r})},GA=()=>{const{stringSet:e}=le(),{announcementsEnabled:t}=Ls(),{conversationList:n}=de(),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(zA,{forwardedAs:"h2",variant:"h2",color:v.themedColor.textHighEmphasis,...o.title.props},r)},zA=S.default(U)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,VA=e=>{const{components:t}=Vt.useContext();return a.createElement(Ac,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:pa})},KA=()=>null,qA=()=>{const{components:e}=Vt.useContext();return a.createElement(e.Title,null)},WA=()=>{const{components:e}=Vt.useContext();return a.createElement(e.CloseButton,null)},Vt=Qe({template:VA,components:{StartArea:KA,TitleArea:qA,EndArea:WA,Title:GA,CloseButton:HA}}),YA=()=>{const{Template:e}=Vt.useContext();return a.createElement(e,{titleAlign:"start"})},jA=()=>(AA(),null),Rc=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=rr.useContext();return a.createElement(Mc,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(SA,{announcementsEnabled:s},a.createElement(jA,null),a.createElement(XA,{style:i},a.createElement(c,null)),n))},XA=({style:e,children:t})=>{const n=l.useRef(null);return yA(n),a.createElement(JA,{ref:n,style:e},t)},ZA=()=>{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:ZA,components:{Header:YA,Body:$A,Footer:FA}}),JA=S.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,QA=F.css`:where(#${Ae.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,eT=[QA,$f,Ff],tT=(e,...t)=>F.createGlobalStyle(e,...eT,...t),nT=tT``,rT=rm(nr,Ct,Gt,Qn,tr,rr,Mt,Os,Vt,er,Xn),sT=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function kc({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){rp(sT?Af:"",t);const[g,f]=l.useState(null),p=l.useCallback(E=>{f(y=>y===E?y:E)},[]),b=m??g,_=a.createElement(F.StyleSheetManager,{target:t},a.createElement(ep,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(Mf,{rootElement:t,boundaryElement:b},a.createElement(Gh,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(Pf,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(Jf,{icons:u},a.createElement(rT,null,a.createElement(If,{entryElement:b,modalRootElement:h,rootElement:t},i),a.createElement(nT,null))))))));return m?_:a.createElement("div",{ref:p,style:{display:"contents"}},_)}const oT=()=>{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}},Ns=l.forwardRef(function({rootElement:t=document.body,logLevel:n=pe.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var _,E,y;Jt.level!==n&&(Jt.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:g,setModalRootElement:f}=oT();np("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const p=ya(r),b=Aa.has(p)?p:un;return a.createElement("div",{ref:g,id:Ae.ENTRY,lang:b,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(kc,{logger:Jt,rootElement:t,appearance:(_=u.agentPreviewConfigs)==null?void 0:_.appearance,stringSet:u.stringSet,language:b,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(Pp,{rootElement:t,language:r,logger:Jt,dispatcher:wc,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:(y=u.agentPreviewConfigs)==null?void 0:y.agentVersion,...u},a.createElement(Vp,{ref:d,userSessionInfo:s},a.createElement(Jb,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(cp,null,o))))),a.createElement("div",{ref:f,id:Ae.MODAL_ROOT,dir:u.dir}))}),Jt=new Ni(pe.LogLevel.WARN),wc=new wi(Jt),zn=()=>{const[e,t]=l.useState(null),n=l.useCallback(r=>t(()=>r),[]);return[e,n]},{Provider:iT,useContext:fn}=be("PageChildren"),Lc=({children:e})=>{const[t,n]=zn(),[r,s]=zn(),[o,i]=l.useState(null),[c,u]=l.useState(null);return a.createElement(iT,{value:{conversationComponent:t,setConversationComponent:n,conversationChildren:o,setConversationChildren:i,conversationListComponent:r,setConversationListComponent:s,conversationListChildren:c,setConversationListChildren:u}},e)},aT=48,cT=2/3,pi=12;function Oc({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=aT,hasUnread:g=!1}){const f=sc(),p=d&&!f,b=Nr(m),_=Math.round(h*cT);return a.createElement(dT,{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(mT,{$isOpened:n,$animated:p,$fillColor:b,$iconSize:_,$prefersReducedMotion:f},a.createElement(Ei.Open,{url:c,isDefaultIcon:i==="default_icon",size:_})),a.createElement(hT,{$isOpened:n,$animated:p,$fillColor:b,$iconSize:_,$prefersReducedMotion:f},a.createElement(Ei.Close,{size:_})),g&&a.createElement(gT,null),t)}const lT=F.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,uT=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%)"};}}`,Nc=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
- `,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"})`
490
+ `,dT=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:${Ua};${({$animated:e})=>e&&lT}`,Dc=S.default.span.attrs({"aria-hidden":"true"})`
491
491
  position: absolute;
492
492
  width: 100%;
493
493
  height: 100%;
@@ -497,23 +497,23 @@ $2
497
497
  display: flex;
498
498
  justify-content: center;
499
499
  align-items: center;
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"})`
500
+ `,mT=S.default(Dc)`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)")};${uT}${Nc}`,hT=S.default(Dc)`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)")};${Nc}`,gT=S.default.span.attrs({"aria-hidden":"true"})`
501
501
  position: absolute;
502
502
  top: 1px;
503
503
  inset-inline-end: 1px;
504
504
  width: ${pi}px;
505
505
  height: ${pi}px;
506
506
  border-radius: 50%;
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 $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`
507
+ background-color: ${v.themedColor.error};
508
+ `,Ei={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(ne,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(ne,{size:e,type:"chevron-down"})};function Pc({opened:e,setOpened:t,className:n,size:r,entryPoint:s="Conversation",activeRoute:o}){const{colors:i}=F.useTheme(),{chatSDK:c,config:u,dir:d}=he(),{resolveElement:m}=ps(),{launcher:h}=de(),{launcherInfo:g}=De(),f=u.launcher.unreadBadgeEnabled,p=Xi(),b=Ig(c,{enabled:f,opened:e,filter:p}),_=(o??s)==="ConversationList",E={launcher:h.button({isOpened:e,opensConversationList:_})},y=()=>{Me(()=>{const I=m(Ae.WINDOW),k=I?Na(I):null;k==null||k.focus()})},T=()=>{Me(()=>{var I;(I=m(Ae.LAUNCHER))==null||I.focus()})},A=()=>{const I=!e;t(I),I?y():T()};return a.createElement(Oc,{dir:d,className:n,isOpened:e,onClick:A,type:g.type,imageUrl:g.imageUrl,backgroundColor:i.base.primary,size:r,hasUnread:f&&!e&&b,...E.launcher.props},E.launcher.descriptionNode)}const $c=()=>(Tg("launcher_toggle"),null),Fc=l.createContext(null);function sr(){const e=l.useContext(Fc);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Uc({children:e}){const t=sr();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}function Bc({children:e}){return a.createElement(a.Fragment,null,e)}const fT=F.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,pT=F.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,ET=F.css`animation-name:${fT};animation-duration:0.3s;animation-fill-mode:forwards;`,_T=F.css``,CT=F.css`animation-name:${pT};animation-duration:0.3s;animation-fill-mode:forwards;`,ST=F.css`visibility:hidden;`,vT=S.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return ET;case"entered":return _T;case"exiting":return CT;case"exited":return ST;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===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}`};
511
+ `;function Pt({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((E,y)=>{r(T=>[...T,E]),g(T=>({...T,[E]:!0})),y!=null&&y.reset&&_(T=>({...T,[E]:(T[E]||0)+1})),p(T=>({...T,[E]:"entering"})),setTimeout(()=>{p(T=>({...T,[E]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(E=>{if(E.length<=1)return E;const y=E[E.length-1];return p(T=>({...T,[y]:"exiting"})),setTimeout(()=>{p(T=>({...T,[y]:"exited"})),r(T=>T.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===Uc),[t]),d=l.useMemo(()=>l.Children.toArray(t).filter(E=>E.type===Bc),[t]),m=l.useMemo(()=>{const E={};return u.forEach(y=>{const{id:T,lazy:A,children:I}=y.props;E[T]={lazy:A,element:typeof I=="function"?I(c):I}}),E},[u,c]),[h,g]=l.useState(()=>{const E={};return Object.entries(m).forEach(([y,{lazy:T}])=>{T===!1&&(E[y]=!0)}),E[e]=!0,E}),[f,p]=l.useState(()=>{const E={};return Object.keys(m).forEach(y=>{y===e?E[y]="entered":E[y]="exited"}),E}),[b,_]=l.useState({});return a.createElement(Fc.Provider,{value:c},d,a.createElement(bT,null,Object.keys(m).map(E=>{var I;if(!h[E])return null;const y=f[E]||"exited",T=E===s,A=`${E}-${b[E]||0}`;return a.createElement(vT,{key:A,$transitionState:y,$active:T,"aria-hidden":T?void 0:!0,inert:T?void 0:!0},(I=m[E])==null?void 0:I.element)})))}const bT=S.default.div`position:relative;width:100%;height:100%;`;Pt.Screen=Uc;Pt.Effect=Bc;const Ye={conv:"conv",convList:"conv-list"},yT=e=>e===Ye.convList?"ConversationList":"Conversation",Hc=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,nudgeConversation:s,onActiveRouteChange:o})=>{const{conversationComponent:i,conversationChildren:c,conversationListComponent:u,conversationListChildren:d}=fn(),m=i??Ic,h=u??Rc,[g,f]=l.useState(),p=(()=>{switch(t){case"Conversation":return Ye.conv;case"ConversationList":return Ye.convList;default:return Ye.conv}})(),b=a.createElement(a.Fragment,null,a.createElement(AT,{onOpenConversationView:(_,E)=>{r(E),f(void 0),_.navigate(Ye.conv)}}),a.createElement(IT,{onActiveRouteChange:o}));return a.createElement(Pt,{initialId:p},a.createElement(Pt.Effect,null,a.createElement(TT,{nudgeConversation:s,onNavigate:_=>{f("messageInput"),_.navigate(Ye.conv)}})),a.createElement(Pt.Screen,{id:Ye.conv},({navigation:_,activeScreenId:E})=>{const y=E===Ye.conv,T=e&&y;return a.createElement(a.Fragment,null,b,a.createElement(m,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{f(void 0),_.navigate(Ye.convList)},announcementsEnabled:T,conversationStatsEnabled:T,shouldMarkAsRead:T,shouldInitializeConversation:T,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 y=E===Ye.convList,T=e&&y;return a.createElement(a.Fragment,null,b,a.createElement(h,{announcementsEnabled:T,conversationListStatsEnabled:T,onOpenConversationView:(A,I,k)=>{r(A),f(k==null?void 0:k.initialFocusTarget),_.navigate(Ye.conv)}},d))}))},AT=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=De(),{navigation:n}=sr();return t(({channel:r})=>{e(n,r.url)}),null},TT=({nudgeConversation:e,onNavigate:t})=>{const{navigation:n}=sr();return l.useEffect(()=>{e&&t(n)},[e]),null},IT=({onActiveRouteChange:e})=>{const{activeScreenId:t}=sr();return l.useEffect(()=>{e==null||e(yT(t))},[t,e]),null},Ds=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Ae.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},xT=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(bs,null,a.createElement(MT,{isExpanded:e,isOpened:t,launcher:r},n)),MT=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=he(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Zn();return jn(t,o,{nameReady:c}),a.createElement(RT,null,a.createElement(kT,{ref:o,dir:s,id:Ae.WINDOW,...Ds(t,i),$isExpanded:e,$isOpened:t},n),r)},RT=S.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,kT=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&&LT};${({$isExpanded:e})=>e&&wT};`,wT=F.css`width:743px;height:723px;`,LT=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;`,OT=({isMessengerOpened:e,onConversationStarted:t,className:n})=>{const r=Ji({isMessengerOpened:e,onConversationStarted:t});return a.createElement(Gc,{...r,className:n})},Gc=({nudgeMessage:e,nudgeMessageKey:t,dismissNudgeMessage:n,startNudgeConversation:r,className:s})=>{const{stringSet:o}=le(),{dir:i}=he();return e?a.createElement(DT,{key:t,id:Ae.NUDGE_MESSAGE,className:s,dir:i},a.createElement(PT,{onClick:r},a.createElement($T,{variant:"body3",color:v.themedColor.textHighEmphasis,maxTextLines:2},e.message)),a.createElement(FT,{type:"close",size:16,"aria-label":o.A11Y_DISMISS_NUDGE_MESSAGE,onClick:n})):null},zc=12,NT=F.keyframes`from{opacity:0;transform:scale(0.8);}`,DT=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:${zc}px;background-color:${v.themedColor.bg_50_600};box-shadow:${Ua};animation-name:${NT};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;}`,PT=S.default.button`all:unset;flex:1;min-width:0;cursor:pointer;text-align:start;${Re}&::after{content:'';position:absolute;inset:0;border-radius:${zc}px;}`,$T=S.default(U)`line-height:20px;overflow-wrap:anywhere;white-space:pre-line;`,FT=S.default(it)`position:relative;margin:-4px;`,UT=1e3*60,Vc=()=>{const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=he();return l.useEffect(()=>{if(!r)return;if(t.opened){e.connectionState===pe.ConnectionState.CLOSED&&(e.reconnect(),n.debug("SDKInactivityTimeout: reconnected"));return}const s=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("SDKInactivityTimeout: disconnected")},UT);return n.debug("SDKInactivityTimeout: schedule disconnect"),()=>clearTimeout(s)},[r,e,t.opened,n]),null},BT=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(Ns,{enableExpandButton:!dn(),ref:r,...n},a.createElement(Pa,null,({state:m})=>a.createElement(Lc,null,a.createElement(Vc,null),a.createElement($c,null),a.createElement(xT,{isExpanded:m.expanded,isOpened:m.opened,launcher:a.createElement(a.Fragment,null,a.createElement(OT,{isMessengerOpened:m.opened,onConversationStarted:h=>{o(h.channelUrl),c(h),m.setOpened(!0)}}),a.createElement(Pc,{opened:m.opened,setOpened:m.setOpened,entryPoint:n.entryPoint,activeRoute:u}))},a.createElement(Hc,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,nudgeConversation:i,onActiveRouteChange:d})),e)))}),{Provider:HT,useContext:Kt}=be("FixedMessengerStyle"),GT=({children:e,isOpened:t,zIndex:n=It.WINDOW})=>a.createElement(bs,null,a.createElement(zT,{isOpened:t,zIndex:n},e)),zT=({children:e,isOpened:t,zIndex:n=It.WINDOW})=>{const{dir:r,rootElement:s}=he(),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(VT,{ref:i,id:Ae.WINDOW,dir:r,...Ds(t,c),$visible:t,$zIndex:n},e)},VT=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 Kc(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 Yr={position:"fixed",zIndex:It.LAUNCHER};function qc(e,t,n,r=0){return F.css`&&{position:${Yr.position};z-index:${Yr.zIndex};${Wc(e,t,n,r)};}`}function Wc(e,t,n,r=0){return F.css(Kc(e,t,n,r))}function Yc(e,t,n,r,s){return{...Yr,direction:s,...Kc(e,t,n,r)}}function KT(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Kt();return a.createElement(qT,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const qT=S.default(Pc)`${({$horizontal:e,$vertical:t,$margin:n})=>qc(e,t,n)};`,jc=be("FixedMessengerSlots"),WT=jc.Provider,or=jc.useContext,YT=({children:e})=>{const[t,n]=zn(),[r,s]=zn();return a.createElement(WT,{value:{launcherComponent:t,setLauncherComponent:n,nudgeMessageComponent:r,setNudgeMessageComponent:s}},e)},jT=({isExpanded:e,isOpened:t,children:n})=>a.createElement(bs,null,a.createElement(XT,{isExpanded:e,isOpened:t},n)),XT=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=he(),{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(ZT,{ref:u,dir:r,id:Ae.WINDOW,...Ds(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},ZT=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})=>Wc(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&&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;
517
+ ${({$isOpened:e})=>e&&QT};
518
+ ${({$isExpanded:e})=>e&&JT};
519
+ `,JT=F.css`width:743px;height:723px;`,QT=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;`,eI=8,Xc=e=>e+eI,tI=e=>{const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Kt();return a.createElement(nI,{...e,$horizontal:t,$vertical:n,$margin:r,$launcherSize:s})},nI=S.default(Gc)`${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>qc(e,t,n,Xc(r))};`,Zc={top:24,bottom:24,start:24,end:24},rI=e=>{const{launcherComponent:t}=or(),{horizontal:n,vertical:r,margin:s,launcherSize:o}=Kt(),{dir:i}=he();if(t){const c=Yc(n,r,s,0,i);return a.createElement(t,{...e,size:o,style:c})}return a.createElement(KT,{...e})},sI=({isMessengerOpened:e,onConversationStarted:t})=>{const{nudgeMessageComponent:n}=or(),{horizontal:r,vertical:s,margin:o,launcherSize:i}=Kt(),{dir:c}=he(),u=Ji({isMessengerOpened:e,onConversationStarted:t});if(n){const{nudgeMessageKey:d,...m}=u,h=Yc(r,s,o,Xc(i),c);return a.createElement(n,{key:d,...m,style:h})}return a.createElement(tI,{...u})},oI=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(Zc),[b,_]=l.useState(48),E=dn(),y=E?GT:jT,{horizontal:T,vertical:A}=l.useMemo(()=>{const[I,k]=h.split("-");return{horizontal:I==="start"?"start":"end",vertical:k==="top"?"top":"bottom"}},[h]);return a.createElement(Ns,{enableExpandButton:!E,ref:s,...r},a.createElement(Pa,null,({state:I})=>a.createElement(HT,{value:{horizontal:T,vertical:A,margin:f,launcherSize:b,setPosition:g,setMargin:p,setLauncherSize:_}},a.createElement(Lc,null,a.createElement(YT,null,a.createElement(Vc,null),a.createElement($c,null),a.createElement(y,{isExpanded:I.expanded,isOpened:I.opened},a.createElement(Hc,{isOpened:I.opened,entryPoint:n,selectedChannelUrl:o,setSelectedChannelUrl:i,nudgeConversation:c,onActiveRouteChange:m})),a.createElement(rI,{opened:I.opened,setOpened:I.setOpened,entryPoint:n,activeRoute:d}),a.createElement(sI,{isMessengerOpened:I.opened,onConversationStarted:k=>{i(k.channelUrl),u(k),I.setOpened(!0)}}),e)))))}),iI=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({...Zc,...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])},aI=({component:e})=>(qt(or().setLauncherComponent,e),null),cI=({component:e})=>(qt(or().setNudgeMessageComponent,e),null),lI=({component:e})=>(qt(fn().setConversationComponent,e),null),uI=({component:e})=>(qt(fn().setConversationListComponent,e),null),dI=({children:e})=>(qt(fn().setConversationChildren,e),null),mI=({children:e})=>(qt(fn().setConversationListChildren,e),null),hI=Object.assign(oI,{Style:iI,Launcher:aI,NudgeMessage:cI,Conversation:lI,ConversationChildren:dI,ConversationList:uI,ConversationListChildren:mI}),gI=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(pe.SendbirdPlatform.JS,{deviceOSPlatform:Rl()?pe.DeviceOsPlatform.MOBILE_WEB:pe.DeviceOsPlatform.WEB,messengerVersion:_f,keyValueStorage:bf(),networkStateAdapter:vf(),foregroundStateAdapter:Sf});exports.ANCHOR_REL=va;exports.AgentProviderContainer=Ns;exports.AgentUIProviderContainer=kc;exports.AnonymousSessionInfo=Rr;exports.CSATType=st;exports.Commands=dt;exports.ConnectionDelayLayout=Xn;exports.Conversation=Ic;exports.ConversationContext=sE;exports.ConversationContextProvider=za;exports.ConversationHeaderLayout=Mt;exports.ConversationLayout=nr;exports.ConversationList=Rc;exports.ConversationListContext=bA;exports.ConversationListContextProvider=Mc;exports.ConversationListHeaderLayout=Vt;exports.ConversationListItemLayout=Os;exports.ConversationListLayout=rr;exports.DefaultMessenger=BT;exports.DeskTicketPriority=us;exports.DeskTicketStatus=ls;exports.FixedMessenger=hI;exports.ID_INCOMING=Ke;exports.IncomingMessageLayout=Ct;exports.LauncherBase=Oc;exports.LogLevel=ns;exports.MARK_CHAR=hc;exports.ManualSessionInfo=Di;exports.MaskedText=mc;exports.MessageListUILayout=tr;exports.MessageLogs=Ec;exports.OutgoingMessageLayout=Gt;exports.PlaceholderLayout=er;exports.Prechecks=Cc;exports.SystemMessageLayout=Qn;exports.createMarkdownPreprocessor=Il;exports.cssVars=v;exports.flattenObject=Pd;exports.mapCommonStringsToReactFormat=ba;exports.messengerDispatcher=wc;exports.noop=_e;exports.parseToMessageTemplate=Ui;exports.parseToUITemplate=Nd;exports.pickColorByTheme=Dd;exports.replaceVariablesAsync=Fd;exports.replaceVariablesSync=$d;exports.useAIAgentContext=Te;exports.useConversationContext=xe;exports.useConversationListContext=gn;exports.useLocalizationContext=le;exports.useMessageTemplateFetchingContext=Hh;exports.useMessengerContext=he;exports.useMessengerSessionContext=De;exports.useMessengerThemeContext=Ma;exports.useRefreshActiveChannel=gI;