@brainfish-ai/components 0.32.0 → 0.32.2

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.
@@ -366,15 +366,15 @@ declare type MarkdownTextBlock = {
366
366
  text: string;
367
367
  };
368
368
 
369
- declare type NextBestAction = {
369
+ export declare type NextBestAction = {
370
370
  id?: string;
371
371
  label: string;
372
372
  type: NextBestActionType;
373
373
  icon?: string | UrlString;
374
- value: any;
374
+ value: NextBestActionValue[NextBestActionType];
375
375
  };
376
376
 
377
- declare enum NextBestActionType {
377
+ export declare enum NextBestActionType {
378
378
  Link = "link",
379
379
  Email = "email",
380
380
  Phone = "phone",
@@ -388,6 +388,20 @@ declare enum NextBestActionType {
388
388
  WebhookHandoff = "webhook_handoff"
389
389
  }
390
390
 
391
+ export declare type NextBestActionValue = {
392
+ link: UrlString;
393
+ email: string;
394
+ phone: string;
395
+ callback: string;
396
+ function: string;
397
+ zendesk_chat: string;
398
+ zendesk_messenger: string;
399
+ intercom_chat: string;
400
+ freshdesk: string;
401
+ zendesk_sunshine_chat: string;
402
+ webhook_handoff: string;
403
+ };
404
+
391
405
  declare type NoArticlesFound = {
392
406
  type: typeof AnswersActions.NO_ARTICLES_FOUND;
393
407
  payload: {
@@ -510,4 +524,6 @@ export declare const useChatSearch: () => ChatSearchContextProps;
510
524
 
511
525
  export declare const useIsChatSearchDirty: () => boolean;
512
526
 
527
+ export declare const validateUrlString: (value: string) => UrlString;
528
+
513
529
  export { }
@@ -14,26 +14,26 @@ return e.createElement(zt,{block:t});default:return null}}function Sr({text:t,cl
14
14
  return e.createElement(ae,{text:t,className:r})}const Pr={xs:{container:"size-12",spinner:"size-3",close:"top-0.5 right-0.5 p-0.5",closeIcon:"size-2"},sm:{container:"size-16",spinner:"size-4",close:"top-0.5 right-0.5 p-0.5",closeIcon:"size-2.5"},md:{container:"size-20",spinner:"size-5",close:"top-1 right-1 p-1",closeIcon:"size-3"}};function Tr({items:t,size:r="sm",onRemove:n,className:a}){if(0===t.length)return null;const s=Pr[r];/* @__PURE__ */
15
15
  return e.createElement("div",{className:Z("flex gap-2 overflow-x-auto",a)},t.map(t=>/* @__PURE__ */e.createElement("div",{key:t.id,className:Z("relative group rounded-lg overflow-hidden flex-shrink-0",s.container)},/* @__PURE__ */e.createElement("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:Z(!t.url&&"pointer-events-none")},
16
16
  /* @__PURE__ */e.createElement("img",{src:t.src,alt:t.alt||"Attachment",className:"w-full h-full object-cover"})),"uploading"===t.status&&/* @__PURE__ */e.createElement("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40"},/* @__PURE__ */e.createElement("div",{className:Z("animate-spin rounded-full border-[2.5px] border-black/30 border-t-white",s.spinner)})),n&&/* @__PURE__ */e.createElement("button",{onClick:()=>n(t.id),className:Z("absolute rounded-full opacity-0","group-hover:opacity-100 transition-opacity duration-200","hover:bg-black/70 bg-black/50",s.close)},
17
- /* @__PURE__ */e.createElement(b,{className:Z("text-white",s.closeIcon),"aria-label":"Remove attachment"})))))}const Ar=d(v);function Rr({groups:t,onGroupSelect:r}){return t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full px-4 py-3"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground mb-2 text-right"},"Please select an option"),/* @__PURE__ */e.createElement("div",{className:"flex flex-wrap justify-end gap-2"},t.map((t,n)=>/* @__PURE__ */e.createElement(Ar,{key:t.id,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:.05*n},onClick:()=>r(t),variant:"outline",className:"border-border font-normal h-auto rounded-full px-4 py-1.5 text-sm"},t.name)))):null}var jr=/* @__PURE__ */(e=>(e.CallPhone="call_phone",e.OpenUrl="open_url",e.SendEmail="send_email",e.RunCallback="run_callback",e.LaunchIntercomChat="launch_intercom_chat",e.LaunchZendeskChat="launch_zendesk_chat",e.LaunchZendeskMessenger="launch_zendesk_messenger",e.LaunchFreshdesk="launch_freshdesk",e.LaunchSupportTicketForm="launch_support_ticket_form",e.LaunchZendeskSunshineChat="launch_zendesk_sunshine_chat",e.LaunchWebhookHandoff="launch_webhook_handoff",e))(jr||{}),Or=/* @__PURE__ */(e=>(e.Link="link",e.Email="email",e.Phone="phone",e.Callback="callback",e.Function="function",e.ZendeskChat="zendesk_chat",e.ZendeskMessenger="zendesk_messenger",e.IntercomChat="intercom_chat",e.Freshdesk="freshdesk",e.ZendeskSunshineChat="zendesk_sunshine_chat",e.WebhookHandoff="webhook_handoff",e))(Or||{});const Dr=d(v),zr=()=>{window.Brainfish?.HelpWidget?.close&&window.Brainfish.HelpWidget.close()},Lr=({icon:t,label:r,index:n,onClick:a,showArrowOut:s=!1,asChild:o=!1,children:i})=>/* @__PURE__ */e.createElement(Dr,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.1*n},className:"w-full text-left h-12 text-base [&_svg]:size-6",variant:"ghost",onClick:a,asChild:o},o?i:/* @__PURE__ */e.createElement(e.Fragment,null,t&&/* @__PURE__ */e.createElement(se,{iconName:t}),/* @__PURE__ */e.createElement("span",{className:"flex-grow"},r),s&&/* @__PURE__ */e.createElement(se,{iconName:"ArrowSquareOut"}))),Fr=({href:t,icon:r,label:n,index:a,onClick:s})=>/* @__PURE__ */e.createElement(Lr,{icon:r,label:n,index:a,onClick:s,asChild:!0},/* @__PURE__ */e.createElement("a",{href:t,target:"_blank",rel:"noopener noreferrer"},r&&/* @__PURE__ */e.createElement(se,{iconName:r}),/* @__PURE__ */e.createElement("span",{className:"flex-grow"},n),/* @__PURE__ */e.createElement(se,{iconName:"ArrowSquareOut"}))),Ur=({nextBestActions:t,onActionClick:r})=>t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-full"},
18
- /* @__PURE__ */e.createElement("div",{className:"rounded-lg overflow-hidden bg-card border divide-y divide-dark-300"},t.map((t,n)=>{const a=e=>{r(t,e)},s=`${t.label}-${n}`.replace(/\s+/g,"-");switch(t.type){case Or.Email:/* @__PURE__ */
19
- return e.createElement(Fr,{key:s,href:`mailto:${t.value}`,icon:t.icon,label:t.label,index:n,onClick:()=>a()});case Or.Link:/* @__PURE__ */
20
- return e.createElement(Fr,{key:s,href:L(t.value),icon:t.icon,label:t.label,index:n,onClick:()=>a()});case Or.Phone:/* @__PURE__ */
21
- return e.createElement(Fr,{key:s,href:`tel:${t.value}`,icon:t.icon,label:t.label,index:n,onClick:()=>a()});case Or.ZendeskChat:/* @__PURE__ */
22
- return e.createElement(Lr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.zE?(zr(),window.zE("webWidget","open"),a(!0)):(console.error("Zendesk Chat is not loaded. Make sure you've included the Zendesk Chat script in your website."),a(!1))}});case Or.ZendeskMessenger:/* @__PURE__ */
23
- return e.createElement(Lr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.zE?(zr(),window.zE("messenger","open"),a(!0)):(console.error("Zendesk Messenger is not loaded. Make sure you've included the Zendesk Messenger script in your website."),a(!1))}});case Or.IntercomChat:/* @__PURE__ */
24
- return e.createElement(Lr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.Intercom?(zr(),window.Intercom("show"),a(!0)):(console.error("Intercom is not loaded. Make sure you've included the Intercom script in your website."),a(!1))}});case Or.Freshdesk:/* @__PURE__ */
25
- return e.createElement(Lr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.fcWidget?(zr(),setTimeout(()=>{window.fcWidget.open(),window.fcWidget.show()},300),a(!0)):(console.error("Freshdesk is not loaded. Make sure you've included the Freshdesk script in your website."),a(!1))}});case Or.ZendeskSunshineChat:case Or.WebhookHandoff:/* @__PURE__ */
26
- return e.createElement(Lr,{key:s,icon:"CalendarBlank",label:t.label,index:n,onClick:()=>a()});default:/* @__PURE__ */
27
- return e.createElement(Lr,{key:s,icon:"ArrowCircleRight",label:t.label,index:n,onClick:()=>a(),showArrowOut:!0})}}))):null,Qr=({actions:r,nextBestActions:n,isLastAnswer:a,handleActionClick:s,searchQueryId:o,searchIntentId:i,question:c,answer:l})=>{const d=r&&r.length>0,u=n&&a&&n.length>0,[m]=t(d||u);if(!m)return null;let p=[];if(d&&(p=r.map(e=>{const t={...e,searchIntentId:i},r=(e=>{const t={[jr.CallPhone]:{type:Or.Phone,icon:"Phone",getValue:e=>e.action?.options?.phoneNumber||e.id,getLabel:e=>e.action?.options?.title||e.type},[jr.SendEmail]:{type:Or.Email,icon:"EnvelopeSimple",getValue:e=>e.action?.options?.to||e.id,getLabel:e=>e.action?.options?.title||e.type},[jr.OpenUrl]:{type:Or.Link,icon:"Link",getValue:e=>e.action?.options?.url||e.id,getLabel:e=>e.action?.options?.title||e.type},[jr.RunCallback]:{type:Or.Callback,icon:"Sparkle",getValue:e=>JSON.stringify({actionId:e.id,searchIntentId:e.searchIntentId}),getLabel:e=>e.action?.options?.title||"Run Action"},[jr.LaunchZendeskChat]:{type:Or.ZendeskChat,icon:"ChatCircleDots",getValue:e=>e.action?.options?.embedKey||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[jr.LaunchZendeskMessenger]:{type:Or.ZendeskMessenger,icon:"ChatCircleDots",getValue:e=>e.action?.options?.embedKey||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[jr.LaunchIntercomChat]:{type:Or.IntercomChat,icon:"ChatCircleDots",getValue:e=>e.action?.options?.appId||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[jr.LaunchFreshdesk]:{type:Or.Freshdesk,icon:"ChatCircleDots",getValue:e=>e.action?.options?.token||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[jr.LaunchSupportTicketForm]:{type:Or.Link,icon:"Notepad",getValue:e=>e.action?.options?.formUrl||e.id,getLabel:e=>e.action?.options?.title||"Submit a ticket"},[jr.LaunchZendeskSunshineChat]:{type:Or.ZendeskSunshineChat,icon:"CalendarBlank",getValue:e=>JSON.stringify({actionId:e.id,requireConfirmation:Boolean(e.action?.options?.requireConfirmation)}),getLabel:e=>e.action?.options?.title||"Speak to an expert"},[jr.LaunchWebhookHandoff]:{type:Or.WebhookHandoff,icon:"CalendarBlank",getValue:e=>JSON.stringify({actionId:e.id,requireConfirmation:Boolean(e.action?.options?.requireConfirmation)}),getLabel:e=>e.action?.options?.title||"Talk to a human"}},r=t[e.type]||{type:Or.Link,icon:"Link",getValue:e=>e.action?.options?.url||e.id,getLabel:e=>e.action?.options?.title||e.type};return r})(t);return{id:e.id,label:r.getLabel(t),type:r.type,icon:r.icon,value:r.getValue(t)}})),u){const e=n.filter(e=>!p.some(t=>t.type===e.type));p=p.concat(e)}/* @__PURE__ */
28
- return e.createElement("div",{className:"p-4"},/* @__PURE__ */e.createElement(Ur,{nextBestActions:p,onActionClick:(e,t)=>{e&&s?.({action:e,searchQueryId:o||"",query:c,answer:l,success:t})}}))};function Mr({index:r,blocks:n=[],question:a,searchResults:s,state:o="completed",searchQueryId:i,searchIntentId:c,hideCitations:l=!1,feedback:d,onFeedback:u,disableFeedback:m=!1,textConfig:p={},redirectRules:w,attachments:b=[],actions:k,handleActionClick:N,nextBestActions:C,isLastAnswer:I,onFeedbackReasonSubmit:S,hasError:P=!1,knowledgeSourceGroups:T,onKnowledgeGroupSelect:A,statusMessage:R}){const[j,O]=t(!1),[D,z]=t(!1),F=Qt(n),U="awaiting-knowledge-group"===o,Q=("fetching-search-results"===o||"fetching-stream"===o)&&(1===n.length||Boolean(R)),M="fetching-search-results"===o,V="completed"===o,q=P&&V,K=R??p.loadingAnswerText,B=M?p.loadingSearchText:K,H=Q&&Boolean(R);/* @__PURE__ */
17
+ /* @__PURE__ */e.createElement(b,{className:Z("text-white",s.closeIcon),"aria-label":"Remove attachment"})))))}const Ar=d(v);function Rr({groups:t,onGroupSelect:r}){return t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full px-4 py-3"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground mb-2 text-right"},"Please select an option"),/* @__PURE__ */e.createElement("div",{className:"flex flex-wrap justify-end gap-2"},t.map((t,n)=>/* @__PURE__ */e.createElement(Ar,{key:t.id,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:.05*n},onClick:()=>r(t),variant:"outline",className:"border-border font-normal h-auto rounded-full px-4 py-1.5 text-sm"},t.name)))):null}var jr=/* @__PURE__ */(e=>(e.CallPhone="call_phone",e.OpenUrl="open_url",e.SendEmail="send_email",e.RunCallback="run_callback",e.LaunchIntercomChat="launch_intercom_chat",e.LaunchZendeskChat="launch_zendesk_chat",e.LaunchZendeskMessenger="launch_zendesk_messenger",e.LaunchFreshdesk="launch_freshdesk",e.LaunchSupportTicketForm="launch_support_ticket_form",e.LaunchZendeskSunshineChat="launch_zendesk_sunshine_chat",e.LaunchWebhookHandoff="launch_webhook_handoff",e))(jr||{});const Or=e=>{if(!(e=>/^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i.test(e))(e))throw new Error(`Invalid URL: ${e}`);return e};var Dr=/* @__PURE__ */(e=>(e.Link="link",e.Email="email",e.Phone="phone",e.Callback="callback",e.Function="function",e.ZendeskChat="zendesk_chat",e.ZendeskMessenger="zendesk_messenger",e.IntercomChat="intercom_chat",e.Freshdesk="freshdesk",e.ZendeskSunshineChat="zendesk_sunshine_chat",e.WebhookHandoff="webhook_handoff",e))(Dr||{});const zr=d(v),Lr=()=>{window.Brainfish?.HelpWidget?.close&&window.Brainfish.HelpWidget.close()},Fr=({icon:t,label:r,index:n,onClick:a,showArrowOut:s=!1,asChild:o=!1,children:i})=>/* @__PURE__ */e.createElement(zr,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.1*n},className:"w-full text-left h-12 text-base [&_svg]:size-6",variant:"ghost",onClick:a,asChild:o},o?i:/* @__PURE__ */e.createElement(e.Fragment,null,t&&/* @__PURE__ */e.createElement(se,{iconName:t}),/* @__PURE__ */e.createElement("span",{className:"flex-grow"},r),s&&/* @__PURE__ */e.createElement(se,{iconName:"ArrowSquareOut"}))),Ur=({href:t,icon:r,label:n,index:a,onClick:s})=>/* @__PURE__ */e.createElement(Fr,{icon:r,label:n,index:a,onClick:s,asChild:!0},/* @__PURE__ */e.createElement("a",{href:t,target:"_blank",rel:"noopener noreferrer"},r&&/* @__PURE__ */e.createElement(se,{iconName:r}),/* @__PURE__ */e.createElement("span",{className:"flex-grow"},n),/* @__PURE__ */e.createElement(se,{iconName:"ArrowSquareOut"}))),Qr=({nextBestActions:t,onActionClick:r})=>t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-full"},
18
+ /* @__PURE__ */e.createElement("div",{className:"rounded-lg overflow-hidden bg-card border divide-y divide-dark-300"},t.map((t,n)=>{const a=e=>{r(t,e)},s=`${t.label}-${n}`.replace(/\s+/g,"-");switch(t.type){case Dr.Email:/* @__PURE__ */
19
+ return e.createElement(Ur,{key:s,href:`mailto:${t.value}`,icon:t.icon,label:t.label,index:n,onClick:()=>a()});case Dr.Link:/* @__PURE__ */
20
+ return e.createElement(Ur,{key:s,href:L(t.value),icon:t.icon,label:t.label,index:n,onClick:()=>a()});case Dr.Phone:/* @__PURE__ */
21
+ return e.createElement(Ur,{key:s,href:`tel:${t.value}`,icon:t.icon,label:t.label,index:n,onClick:()=>a()});case Dr.ZendeskChat:/* @__PURE__ */
22
+ return e.createElement(Fr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.zE?(Lr(),window.zE("webWidget","open"),a(!0)):(console.error("Zendesk Chat is not loaded. Make sure you've included the Zendesk Chat script in your website."),a(!1))}});case Dr.ZendeskMessenger:/* @__PURE__ */
23
+ return e.createElement(Fr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.zE?(Lr(),window.zE("messenger","open"),a(!0)):(console.error("Zendesk Messenger is not loaded. Make sure you've included the Zendesk Messenger script in your website."),a(!1))}});case Dr.IntercomChat:/* @__PURE__ */
24
+ return e.createElement(Fr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.Intercom?(Lr(),window.Intercom("show"),a(!0)):(console.error("Intercom is not loaded. Make sure you've included the Intercom script in your website."),a(!1))}});case Dr.Freshdesk:/* @__PURE__ */
25
+ return e.createElement(Fr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.fcWidget?(Lr(),setTimeout(()=>{window.fcWidget.open(),window.fcWidget.show()},300),a(!0)):(console.error("Freshdesk is not loaded. Make sure you've included the Freshdesk script in your website."),a(!1))}});case Dr.ZendeskSunshineChat:case Dr.WebhookHandoff:/* @__PURE__ */
26
+ return e.createElement(Fr,{key:s,icon:"CalendarBlank",label:t.label,index:n,onClick:()=>a()});default:/* @__PURE__ */
27
+ return e.createElement(Fr,{key:s,icon:"ArrowCircleRight",label:t.label,index:n,onClick:()=>a(),showArrowOut:!0})}}))):null,Mr=({actions:r,nextBestActions:n,isLastAnswer:a,handleActionClick:s,searchQueryId:o,searchIntentId:i,question:c,answer:l})=>{const d=r&&r.length>0,u=n&&a&&n.length>0,[m]=t(d||u);if(!m)return null;let p=[];if(d&&(p=r.map(e=>{const t={...e,searchIntentId:i},r=(e=>{const t={[jr.CallPhone]:{type:Dr.Phone,icon:"Phone",getValue:e=>e.action?.options?.phoneNumber||e.id,getLabel:e=>e.action?.options?.title||e.type},[jr.SendEmail]:{type:Dr.Email,icon:"EnvelopeSimple",getValue:e=>e.action?.options?.to||e.id,getLabel:e=>e.action?.options?.title||e.type},[jr.OpenUrl]:{type:Dr.Link,icon:"Link",getValue:e=>e.action?.options?.url||e.id,getLabel:e=>e.action?.options?.title||e.type},[jr.RunCallback]:{type:Dr.Callback,icon:"Sparkle",getValue:e=>JSON.stringify({actionId:e.id,searchIntentId:e.searchIntentId}),getLabel:e=>e.action?.options?.title||"Run Action"},[jr.LaunchZendeskChat]:{type:Dr.ZendeskChat,icon:"ChatCircleDots",getValue:e=>e.action?.options?.embedKey||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[jr.LaunchZendeskMessenger]:{type:Dr.ZendeskMessenger,icon:"ChatCircleDots",getValue:e=>e.action?.options?.embedKey||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[jr.LaunchIntercomChat]:{type:Dr.IntercomChat,icon:"ChatCircleDots",getValue:e=>e.action?.options?.appId||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[jr.LaunchFreshdesk]:{type:Dr.Freshdesk,icon:"ChatCircleDots",getValue:e=>e.action?.options?.token||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[jr.LaunchSupportTicketForm]:{type:Dr.Link,icon:"Notepad",getValue:e=>e.action?.options?.formUrl||e.id,getLabel:e=>e.action?.options?.title||"Submit a ticket"},[jr.LaunchZendeskSunshineChat]:{type:Dr.ZendeskSunshineChat,icon:"CalendarBlank",getValue:e=>JSON.stringify({actionId:e.id,requireConfirmation:Boolean(e.action?.options?.requireConfirmation)}),getLabel:e=>e.action?.options?.title||"Speak to an expert"},[jr.LaunchWebhookHandoff]:{type:Dr.WebhookHandoff,icon:"CalendarBlank",getValue:e=>JSON.stringify({actionId:e.id,requireConfirmation:Boolean(e.action?.options?.requireConfirmation)}),getLabel:e=>e.action?.options?.title||"Talk to a human"}},r=t[e.type]||{type:Dr.Link,icon:"Link",getValue:e=>e.action?.options?.url||e.id,getLabel:e=>e.action?.options?.title||e.type};return r})(t);return{id:e.id,label:r.getLabel(t),type:r.type,icon:r.icon,value:r.getValue(t)}})),u){const e=n.filter(e=>!p.some(t=>t.type===e.type));p=p.concat(e)}/* @__PURE__ */
28
+ return e.createElement("div",{className:"p-4"},/* @__PURE__ */e.createElement(Qr,{nextBestActions:p,onActionClick:(e,t)=>{e&&s?.({action:e,searchQueryId:o||"",query:c,answer:l,success:t})}}))};function Vr({index:r,blocks:n=[],question:a,searchResults:s,state:o="completed",searchQueryId:i,searchIntentId:c,hideCitations:l=!1,feedback:d,onFeedback:u,disableFeedback:m=!1,textConfig:p={},redirectRules:w,attachments:b=[],actions:k,handleActionClick:N,nextBestActions:C,isLastAnswer:I,onFeedbackReasonSubmit:S,hasError:P=!1,knowledgeSourceGroups:T,onKnowledgeGroupSelect:A,statusMessage:R}){const[j,O]=t(!1),[D,z]=t(!1),F=Qt(n),U="awaiting-knowledge-group"===o,Q=("fetching-search-results"===o||"fetching-stream"===o)&&(1===n.length||Boolean(R)),M="fetching-search-results"===o,V="completed"===o,q=P&&V,K=R??p.loadingAnswerText,B=M?p.loadingSearchText:K,H=Q&&Boolean(R);/* @__PURE__ */
29
29
  return e.createElement("div",{className:"rounded-lg relative mx-auto overflow-hidden bg-card border border-primary","data-name":"SearchResults","data-index":r},
30
30
  /* @__PURE__ */e.createElement("div",{className:"px-4 pt-4 pb-2"},/* @__PURE__ */e.createElement("div",{className:"flex items-start justify-between gap-2 min-h-9"},/* @__PURE__ */e.createElement("h2",{className:"leading-normal font-semibold m-0 text-foreground self-center text-lg"},a),V&&!q&&/* @__PURE__ */e.createElement(h,null,/* @__PURE__ */e.createElement(f,null,/* @__PURE__ */e.createElement(g,{asChild:!0},/* @__PURE__ */e.createElement(v,{variant:"ghost",size:"icon",onClick:()=>{(async()=>{try{await navigator.clipboard.writeText(F)}catch(e){console.warn("Clipboard API failed, using fallback:",e);const r=document.createElement("textarea");r.value=F,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.focus(),r.select();try{document.execCommand("copy")}catch(t){console.error("Fallback: Oops, unable to copy",t)}document.body.removeChild(r)}O(!0),setTimeout(()=>O(!1),2e3)})()},className:"-mt-1 flex-shrink-0"},j?/* @__PURE__ */e.createElement(E,{className:"text-feedback-positive",weight:"bold"}):/* @__PURE__ */e.createElement($,{className:"text-secondary-foreground",weight:"bold"}))),/* @__PURE__ */e.createElement(y,null,/* @__PURE__ */e.createElement("p",null,j?"Copied!":"Copy"))))),/* @__PURE__ */e.createElement(Tr,{items:b.map((e,t)=>({id:`${t}`,src:e.url,url:e.url,alt:e.filename})),size:"xs",className:"mt-2"})),Q&&/* @__PURE__ */e.createElement("div",{className:"px-4 pt-0 pb-2"},/* @__PURE__ */e.createElement(Sr,{text:B??""})),U&&T&&A?/* @__PURE__ */e.createElement(Rr,{groups:T,onGroupSelect:A}):/* @__PURE__ */e.createElement("div",{className:"flex flex-col"},!H&&n?.map((t,r)=>/* @__PURE__ */e.createElement("div",{key:r,className:Z("px-4 pt-0 pb-2 border-b last:border-b-0 border-dashed",q&&"text-muted-foreground")},
31
- /* @__PURE__ */e.createElement(Ir,{block:t,redirectRules:w,state:o})))),V&&!q&&/* @__PURE__ */e.createElement(Qr,{actions:k,nextBestActions:C,isLastAnswer:I,handleActionClick:N,searchQueryId:i||"",searchIntentId:c,question:a,answer:F}),V&&!m&&!q&&/* @__PURE__ */e.createElement("div",{className:"p-4 pt-0"},/* @__PURE__ */e.createElement(le,{feedback:d,onFeedback:e=>{u&&i&&u(e)},textConfig:p,disabled:m,feedbackReasonLength:500,feedbackReasonPlaceholder:"What could we have done better? Your feedback is valuable to us...",onFeedbackReasonSubmit:S,feedbackReasonThankYouText:"Thank you for your feedback!"})),!l&&s&&s.length>0&&/* @__PURE__ */e.createElement("div",{className:"overflow-hidden bg-card border-dashed border-0 border-t-2"},/* @__PURE__ */e.createElement(oe,{open:D,onOpenChange:z,className:"w-full"},/* @__PURE__ */e.createElement("div",null,/* @__PURE__ */e.createElement(ie,{asChild:!0},/* @__PURE__ */e.createElement(v,{variant:"secondary",className:"w-full justify-between h-11","data-name":"RelatedSources"},/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2"},/* @__PURE__ */e.createElement("span",{className:"font-medium truncate text-base"},"Sources")),/* @__PURE__ */e.createElement(x,{className:"size-4 flex-shrink-0 transition-transform duration-200 text-secondary-foreground "+(D?"rotate-180":""),weight:"bold"}),/* @__PURE__ */e.createElement("span",{className:"sr-only"},"Toggle")))),/* @__PURE__ */e.createElement(ce,{className:"divide-y divide-dark-300 overflow-hidden CollapsibleContent"},s.map(t=>/* @__PURE__ */e.createElement("a",{key:t.id,href:L(t.url),target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-3 transition-colors duration-200 hover:bg-accent bg-card text-foreground"},
31
+ /* @__PURE__ */e.createElement(Ir,{block:t,redirectRules:w,state:o})))),V&&!q&&/* @__PURE__ */e.createElement(Mr,{actions:k,nextBestActions:C,isLastAnswer:I,handleActionClick:N,searchQueryId:i||"",searchIntentId:c,question:a,answer:F}),V&&!m&&!q&&/* @__PURE__ */e.createElement("div",{className:"p-4 pt-0"},/* @__PURE__ */e.createElement(le,{feedback:d,onFeedback:e=>{u&&i&&u(e)},textConfig:p,disabled:m,feedbackReasonLength:500,feedbackReasonPlaceholder:"What could we have done better? Your feedback is valuable to us...",onFeedbackReasonSubmit:S,feedbackReasonThankYouText:"Thank you for your feedback!"})),!l&&s&&s.length>0&&/* @__PURE__ */e.createElement("div",{className:"overflow-hidden bg-card border-dashed border-0 border-t-2"},/* @__PURE__ */e.createElement(oe,{open:D,onOpenChange:z,className:"w-full"},/* @__PURE__ */e.createElement("div",null,/* @__PURE__ */e.createElement(ie,{asChild:!0},/* @__PURE__ */e.createElement(v,{variant:"secondary",className:"w-full justify-between h-11","data-name":"RelatedSources"},/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2"},/* @__PURE__ */e.createElement("span",{className:"font-medium truncate text-base"},"Sources")),/* @__PURE__ */e.createElement(x,{className:"size-4 flex-shrink-0 transition-transform duration-200 text-secondary-foreground "+(D?"rotate-180":""),weight:"bold"}),/* @__PURE__ */e.createElement("span",{className:"sr-only"},"Toggle")))),/* @__PURE__ */e.createElement(ce,{className:"divide-y divide-dark-300 overflow-hidden CollapsibleContent"},s.map(t=>/* @__PURE__ */e.createElement("a",{key:t.id,href:L(t.url),target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-3 transition-colors duration-200 hover:bg-accent bg-card text-foreground"},
32
32
  /* @__PURE__ */e.createElement("span",{className:"flex-grow truncate"},t.title),
33
- /* @__PURE__ */e.createElement(_,{className:"size-4 flex-shrink-0 text-secondary-foreground",weight:"bold"})))))))}const Vr=d(v);function qr({questions:t,onQuestionClick:r}){return t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-full"},
34
- /* @__PURE__ */e.createElement("div",{className:"rounded-lg overflow-hidden bg-card border"},/* @__PURE__ */e.createElement("h3",{className:"px-4 py-3 border-b border-b-dark-300 font-bold"},"Follow-up questions"),t.map((t,n)=>n<3?/* @__PURE__ */e.createElement(Vr,{key:n,initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.1*n},onClick:()=>r(t),variant:"ghost",className:"w-full text-left"},
33
+ /* @__PURE__ */e.createElement(_,{className:"size-4 flex-shrink-0 text-secondary-foreground",weight:"bold"})))))))}const qr=d(v);function Kr({questions:t,onQuestionClick:r}){return t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-full"},
34
+ /* @__PURE__ */e.createElement("div",{className:"rounded-lg overflow-hidden bg-card border"},/* @__PURE__ */e.createElement("h3",{className:"px-4 py-3 border-b border-b-dark-300 font-bold"},"Follow-up questions"),t.map((t,n)=>n<3?/* @__PURE__ */e.createElement(qr,{key:n,initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.1*n},onClick:()=>r(t),variant:"ghost",className:"w-full text-left"},
35
35
  /* @__PURE__ */e.createElement("span",{className:"flex-grow"},t),
36
- /* @__PURE__ */e.createElement(k,{className:"",weight:"bold"})):null))):null}function Kr({questions:r,activeIndex:n,onNavigate:a,offset:s}){const[i,c]=t(n);o(()=>{c(n)},[n]);const l=r.length,m=(()=>{const e=[];let t=null;const r=r=>{null!==t&&r-t>1&&e.push("ellipsis"),e.push(r),t=r};r(0);for(let a=Math.max(1,n-2);a<=Math.min(l-2,n+2);a++)r(a);return l>1&&r(l-1),e})();/* @__PURE__ */
36
+ /* @__PURE__ */e.createElement(k,{className:"",weight:"bold"})):null))):null}function Br({questions:r,activeIndex:n,onNavigate:a,offset:s}){const[i,c]=t(n);o(()=>{c(n)},[n]);const l=r.length,m=(()=>{const e=[];let t=null;const r=r=>{null!==t&&r-t>1&&e.push("ellipsis"),e.push(r),t=r};r(0);for(let a=Math.max(1,n-2);a<=Math.min(l-2,n+2);a++)r(a);return l>1&&r(l-1),e})();/* @__PURE__ */
37
37
  return e.createElement("nav",{"aria-label":"Question timeline navigation",className:"fixed left-4 top-1/2 -translate-y-1/2 z-40 flex flex-col gap-3",style:{...s?{left:`${s}px`}:{}}},
38
38
  /* @__PURE__ */e.createElement(d.div,{className:"flex flex-col items-center space-y-3",role:"list",initial:!1,animate:{y:0},transition:{type:"spring",stiffness:300,damping:30}},
39
39
  /* @__PURE__ */e.createElement(u,null,m.map((t,s)=>{if("ellipsis"===t)/* @__PURE__ */
@@ -41,14 +41,14 @@ return e.createElement(d.div,{key:`ellipsis-${s}`,className:"h-8 flex items-cent
41
41
  /* @__PURE__ */e.createElement(N,{className:"size-4 text-foreground"}));const o=t,c=r[o];/* @__PURE__ */
42
42
  return e.createElement(d.div,{key:o,className:"relative group isolate",role:"listitem",initial:{opacity:0,y:i>n?-20:20},animate:{opacity:1,y:0},exit:{opacity:0,y:i>n?20:-20},transition:{duration:.2},layout:!0},
43
43
  /* @__PURE__ */e.createElement(h,{delayDuration:100},/* @__PURE__ */e.createElement(f,null,/* @__PURE__ */e.createElement(g,{asChild:!0},/* @__PURE__ */e.createElement("button",{onClick:()=>a(o),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||a(o)},className:Z("flex items-center justify-center size-8 rounded-full transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 hover:opacity-90 cursor-pointer ring-primary ",o===n?"bg-primary text-primary-foreground":"bg-stone-300 text-zinc-800"),"aria-label":`Navigate to question ${o+1}: ${c}`,"aria-current":o===n?"step":void 0},o+1)),/* @__PURE__ */e.createElement(y,{side:"right",sideOffset:8,bgColor:"--bfc-card",className:"max-w-[300px] text-card-foreground border-foreground/35"},
44
- /* @__PURE__ */e.createElement("p",{className:"break-words leading-relaxed"},c)))))}))))}function Br({value:t,loading:r,disabled:n,onToggle:a}){/* @__PURE__ */
45
- return e.createElement("div",{className:"flex items-center gap-2"},/* @__PURE__ */e.createElement(ue,{id:"include-page",checked:t,onCheckedChange:a,disabled:r||n}),/* @__PURE__ */e.createElement("label",{htmlFor:"include-page",className:"text-sm text-foreground flex items-center gap-2"},"Include page",r&&/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-3 border-2 border-t-transparent border-primary"})))}const Hr=e.forwardRef(({query:r,onQueryChange:n,onSearch:a,textConfig:s,collections:c=[],currentCollectionId:l,onCollectionChange:m,allowedRegions:p=[],onRegionChange:h,apiKey:f,fetchRegionConfig:g,enableFileAttachment:y=!1,attachedFiles:w=[],isUploading:b=!1,onAddFiles:E,onRemoveFile:$,isSearching:x=!1,autocompleteSuggestions:_=[],onAutocompleteSuggestionSelect:N,isAgentAssist:A=!1,includePageEnabled:R=!1,includePageLoading:j=!1,includePageDisabled:O=!1,onIncludePageToggle:D},z)=>{const L=i(null),[F,U]=t(!1),[Q,M]=t(!1),V=he("showIncludePageToggle",!1),q=[{value:"all",label:"All regions",icon:/* @__PURE__ */e.createElement(C,{className:"size-4"})},...p.map(t=>{const r=de(t);return{value:t,label:r?.name||t,icon:/* @__PURE__ */e.createElement("img",{alt:`${r?.name||t}`,src:`https://purecatamphetamine.github.io/country-flag-icons/3x2/${t}.svg`,className:"w-5"})}})],K=e.useCallback(async t=>{if(!f||!g)return console.warn("No apiKey or fetchRegionConfig provided, falling back to current collections"),c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}));try{const r=await g(f,t);return(r?.settings?.collections||[]).map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}))}catch(r){return console.error("Error fetching collections for region:",r),c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}))}},[f,g,c]);o(()=>{const e=e=>{e.target.closest(".suggestions-dropdown")||U(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),o(()=>{r.trim()&&U(!0)},[r]);const B=F&&r.trim()&&_.length>0,H={hidden:{opacity:0,x:-4},visible:{opacity:1,x:0,transition:{duration:.2}}};/* @__PURE__ */
44
+ /* @__PURE__ */e.createElement("p",{className:"break-words leading-relaxed"},c)))))}))))}function Hr({value:t,loading:r,disabled:n,onToggle:a}){/* @__PURE__ */
45
+ return e.createElement("div",{className:"flex items-center gap-2"},/* @__PURE__ */e.createElement(ue,{id:"include-page",checked:t,onCheckedChange:a,disabled:r||n}),/* @__PURE__ */e.createElement("label",{htmlFor:"include-page",className:"text-sm text-foreground flex items-center gap-2"},"Include page",r&&/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-3 border-2 border-t-transparent border-primary"})))}const Gr=e.forwardRef(({query:r,onQueryChange:n,onSearch:a,textConfig:s,collections:c=[],currentCollectionId:l,onCollectionChange:m,allowedRegions:p=[],onRegionChange:h,apiKey:f,fetchRegionConfig:g,enableFileAttachment:y=!1,attachedFiles:w=[],isUploading:b=!1,onAddFiles:E,onRemoveFile:$,isSearching:x=!1,autocompleteSuggestions:_=[],onAutocompleteSuggestionSelect:N,isAgentAssist:A=!1,includePageEnabled:R=!1,includePageLoading:j=!1,includePageDisabled:O=!1,onIncludePageToggle:D},z)=>{const L=i(null),[F,U]=t(!1),[Q,M]=t(!1),V=he("showIncludePageToggle",!1),q=[{value:"all",label:"All regions",icon:/* @__PURE__ */e.createElement(C,{className:"size-4"})},...p.map(t=>{const r=de(t);return{value:t,label:r?.name||t,icon:/* @__PURE__ */e.createElement("img",{alt:`${r?.name||t}`,src:`https://purecatamphetamine.github.io/country-flag-icons/3x2/${t}.svg`,className:"w-5"})}})],K=e.useCallback(async t=>{if(!f||!g)return console.warn("No apiKey or fetchRegionConfig provided, falling back to current collections"),c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}));try{const r=await g(f,t);return(r?.settings?.collections||[]).map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}))}catch(r){return console.error("Error fetching collections for region:",r),c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}))}},[f,g,c]);o(()=>{const e=e=>{e.target.closest(".suggestions-dropdown")||U(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),o(()=>{r.trim()&&U(!0)},[r]);const B=F&&r.trim()&&_.length>0,H={hidden:{opacity:0,x:-4},visible:{opacity:1,x:0,transition:{duration:.2}}};/* @__PURE__ */
46
46
  return e.createElement("div",{className:"relative w-full","data-name":"PrimarySearch"},/* @__PURE__ */e.createElement("div",{className:Z("relative w-full overflow-hidden bg-background border border-border transition-all",B?"rounded-t-md":"rounded-md",Q&&y&&"ring-2 ring-primary"),onDrop:e=>{if(e.preventDefault(),M(!1),!y||!E)return;const t=Array.from(e.dataTransfer.files);t.length>0&&E(t)},onDragOver:e=>{e.preventDefault(),y&&M(!0)},onDragLeave:()=>{M(!1)},onPaste:e=>{if(!y||!E)return;const t=Array.from(e.clipboardData.files);t.length>0&&(e.preventDefault(),E(t))}},Q&&y&&/* @__PURE__ */e.createElement("div",{className:"absolute inset-0 z-10 flex items-center justify-center rounded-md",style:{backgroundColor:"color-mix(in srgb, var(--bfc-card) 90%, transparent)"}},
47
47
  /* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-muted-foreground"},"Drop images here to attach")),y&&/* @__PURE__ */e.createElement(Tr,{items:w.map(e=>({id:e.id,src:e.preview,url:e.publicUrl,status:e.status})),size:"md",onRemove:$,className:"pt-3 px-3 bg-card"}),
48
48
  /* @__PURE__ */e.createElement("div",{className:"p-3 flex items-center bg-card","data-name":"search-input"},/* @__PURE__ */e.createElement(S,{className:"h-5 w-5 mr-2 text-muted-foreground","aria-hidden":!0,role:"presentation"}),/* @__PURE__ */e.createElement("textarea",{ref:z,value:r,onChange:e=>{var t;n(e.target.value),(t=e.target).style.height="auto",t.style.height=`${t.scrollHeight}px`},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||b||(e.preventDefault(),a())},onFocus:()=>U(!0),placeholder:s.searchPlaceholder,className:Z("w-full resize-none !outline-none text-base py-1 min-h-9","overflow-hidden border-none bg-transparent shadow-none","placeholder:text-gray-400 text-dark-900 !ring-0"),rows:1}),x&&/* @__PURE__ */e.createElement("div",{className:"flex items-center justify-center ml-2"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 border-2 border-t-transparent border-primary"}))),!B&&/* @__PURE__ */e.createElement("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border"},/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2"},y&&/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement("input",{type:"file",ref:L,accept:"image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:e=>{e.target.files&&E?.(Array.from(e.target.files)),e.target.value=""}}),/* @__PURE__ */e.createElement(v,{variant:"ghost",size:"icon",className:"rounded-md size-8 hover:bg-opacity-80 disabled:opacity-50",onClick:()=>L.current?.click(),disabled:w.length>=5,"aria-label":s.attachImageText},
49
49
  /* @__PURE__ */e.createElement(P,{weight:"regular",className:"size-4 text-secondary-foreground"}))),/* @__PURE__ */e.createElement("div",{className:"flex gap-1","data-name":"collections-dropdown"},p.length>0&&c.length>0?
50
50
  /* @__PURE__ */e.createElement(pe,{firstLevelItems:q,fetchSecondLevelItems:K,onSelectionChange:(e,t)=>{e&&h&&h(e.value),t&&m&&m(t.value)},firstLevelLabel:"Region",secondLevelLabel:"Collection",firstLevelPlaceholder:"All documents",className:"min-w-[200px]",displayLabel:!1}):c.length>0?
51
- /* @__PURE__ */e.createElement(me,{options:c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})})),value:"all"===l?void 0:l,defaultValueLabel:"All documents",placeholder:"Select collection",noResultsLabel:"No collections found",dropdownWidth:200,onChange:e=>m?.(e)}):null),A&&D&&V&&/* @__PURE__ */e.createElement(Br,{value:R,loading:j,disabled:O,onToggle:D})),/* @__PURE__ */e.createElement("div",{className:"flex items-center","data-name":"search-button"},/* @__PURE__ */e.createElement(v,{size:"sm",disabled:!r||x||b,"aria-disabled":!r||x||b,className:"rounded-md size-8 disabled:opacity-50 bg-primary",onClick:a},x?/* @__PURE__ */e.createElement("div",{className:"flex items-center",role:"status","aria-live":"polite"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 border-2 border-t-transparent border-white","aria-hidden":"true"}),/* @__PURE__ */e.createElement("span",{className:"sr-only"},"Loading")):/* @__PURE__ */e.createElement(T,{className:"text-primary-foreground",size:16,weight:"bold","aria-label":"Submit question"}))))),/* @__PURE__ */e.createElement(u,{mode:"wait"},B&&/* @__PURE__ */e.createElement(d.div,{variants:{hidden:{opacity:0,scale:.95,transformOrigin:"top"},visible:{opacity:1,scale:1,transition:{type:"spring",stiffness:500,damping:30,mass:.5}},exit:{opacity:0,scale:.95,transition:{duration:.15,ease:"easeOut"}}},initial:"hidden",animate:"visible",exit:"exit",className:Z("suggestions-dropdown absolute","left-0 right-0 z-50","overflow-hidden bg-card","border-border border border-t-0 rounded-b-md shadow-md -mt-px","md:relative")},
51
+ /* @__PURE__ */e.createElement(me,{options:c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})})),value:"all"===l?void 0:l,defaultValueLabel:"All documents",placeholder:"Select collection",noResultsLabel:"No collections found",dropdownWidth:200,onChange:e=>m?.(e)}):null),A&&D&&V&&/* @__PURE__ */e.createElement(Hr,{value:R,loading:j,disabled:O,onToggle:D})),/* @__PURE__ */e.createElement("div",{className:"flex items-center","data-name":"search-button"},/* @__PURE__ */e.createElement(v,{size:"sm",disabled:!r||x||b,"aria-disabled":!r||x||b,className:"rounded-md size-8 disabled:opacity-50 bg-primary",onClick:a},x?/* @__PURE__ */e.createElement("div",{className:"flex items-center",role:"status","aria-live":"polite"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 border-2 border-t-transparent border-white","aria-hidden":"true"}),/* @__PURE__ */e.createElement("span",{className:"sr-only"},"Loading")):/* @__PURE__ */e.createElement(T,{className:"text-primary-foreground",size:16,weight:"bold","aria-label":"Submit question"}))))),/* @__PURE__ */e.createElement(u,{mode:"wait"},B&&/* @__PURE__ */e.createElement(d.div,{variants:{hidden:{opacity:0,scale:.95,transformOrigin:"top"},visible:{opacity:1,scale:1,transition:{type:"spring",stiffness:500,damping:30,mass:.5}},exit:{opacity:0,scale:.95,transition:{duration:.15,ease:"easeOut"}}},initial:"hidden",animate:"visible",exit:"exit",className:Z("suggestions-dropdown absolute","left-0 right-0 z-50","overflow-hidden bg-card","border-border border border-t-0 rounded-b-md shadow-md -mt-px","md:relative")},
52
52
  /* @__PURE__ */e.createElement(d.div,{variants:H},r.trim()&&/* @__PURE__ */e.createElement("div",{role:"option","aria-selected":!1,tabIndex:0,className:Z("px-4 py-3","cursor-pointer","flex items-center gap-3","transition-colors duration-200","hover:bg-dark-100/50 text-foreground bg-dark-200","border-b border border-border"),onClick:()=>{a(),U(!1)},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),a(),U(!1))}},
53
53
  /* @__PURE__ */e.createElement(S,{className:"size-4 flex-shrink-0 text-secondary-foreground"}),
54
54
  /* @__PURE__ */e.createElement("span",{className:"text-[15px]"},r),
@@ -56,41 +56,41 @@ return e.createElement("div",{className:"relative w-full","data-name":"PrimarySe
56
56
  /* @__PURE__ */e.createElement(d.div,{variants:{visible:{transition:{staggerChildren:.03,delayChildren:.05}}},initial:"hidden",animate:"visible"},_.map(t=>/* @__PURE__ */e.createElement(d.div,{key:t.id,variants:H,role:"option","aria-selected":!1,tabIndex:0,className:"px-4 py-3 cursor-pointer flex items-center gap-3 transition-colors duration-200 hover:bg-dark-300 text-foreground",onClick:()=>{N?.(t),U(!1)},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),N?.(t),U(!1))}},
57
57
  /* @__PURE__ */e.createElement(S,{className:"size-4 flex-shrink-0 text-secondary-foreground"}),
58
58
  /* @__PURE__ */e.createElement("span",{className:"text-[15px]"},t.question),
59
- /* @__PURE__ */e.createElement("div",{className:"ml-auto flex items-center"},/* @__PURE__ */e.createElement(k,{className:"size-4 text-secondary-foreground"}))))))))});Hr.displayName="PrimarySearch";const Gr="_followUpSearchBar_x7ads_1",Wr=e.forwardRef(({initialQuery:r="",onQueryChange:n,isSearching:a,handleFollowUpSearch:s,textConfig:c,enableFileAttachment:l=!1,attachedFiles:u=[],isUploading:m=!1,onAddFiles:p,onRemoveFile:h,disabled:f=!1},g)=>{const[y,w]=t(r),[b,E]=t(!1),$=i(null),x=i(null);o(()=>{$.current&&($.current.style.height="inherit",$.current.style.height=`${$.current.scrollHeight}px`)},[y]),o(()=>{w(r)},[r]);const _=f||a||!y.trim()||m;/* @__PURE__ */
60
- return e.createElement(d.footer,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:Gr},
59
+ /* @__PURE__ */e.createElement("div",{className:"ml-auto flex items-center"},/* @__PURE__ */e.createElement(k,{className:"size-4 text-secondary-foreground"}))))))))});Gr.displayName="PrimarySearch";const Wr="_followUpSearchBar_x7ads_1",Jr=e.forwardRef(({initialQuery:r="",onQueryChange:n,isSearching:a,handleFollowUpSearch:s,textConfig:c,enableFileAttachment:l=!1,attachedFiles:u=[],isUploading:m=!1,onAddFiles:p,onRemoveFile:h,disabled:f=!1},g)=>{const[y,w]=t(r),[b,E]=t(!1),$=i(null),x=i(null);o(()=>{$.current&&($.current.style.height="inherit",$.current.style.height=`${$.current.scrollHeight}px`)},[y]),o(()=>{w(r)},[r]);const _=f||a||!y.trim()||m;/* @__PURE__ */
60
+ return e.createElement(d.footer,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:Wr},
61
61
  /* @__PURE__ */e.createElement("div",{className:"container flex items-center justify-center p-3"},/* @__PURE__ */e.createElement("div",{className:Z("relative flex w-full flex-col rounded bg-card border border-dark-400",b&&l&&"ring-2 ring-primary"),onDrop:e=>{if(e.preventDefault(),E(!1),!l||!p)return;const t=Array.from(e.dataTransfer.files);t.length>0&&p(t)},onDragOver:e=>{e.preventDefault(),l&&E(!0)},onDragLeave:()=>{E(!1)},onPaste:e=>{if(!l||!p)return;const t=Array.from(e.clipboardData.files);t.length>0&&(e.preventDefault(),p(t))}},b&&l&&/* @__PURE__ */e.createElement("div",{className:"absolute inset-0 z-10 flex items-center justify-center rounded",style:{backgroundColor:"color-mix(in srgb, var(--bfc-card) 90%, transparent)"}},
62
62
  /* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-muted-foreground"},"Drop images here to attach")),l&&/* @__PURE__ */e.createElement(Tr,{items:u.map(e=>({id:e.id,src:e.preview,url:e.publicUrl,status:e.status})),size:"sm",onRemove:h,className:"pt-2 px-2"}),
63
63
  /* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2 px-2"},l&&/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement("input",{type:"file",ref:x,accept:"image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:e=>{e.target.files&&p?.(Array.from(e.target.files)),e.target.value=""}}),/* @__PURE__ */e.createElement(v,{variant:"ghost",size:"icon",className:"rounded-md size-7 hover:bg-opacity-80 disabled:opacity-50 shrink-0",onClick:()=>x.current?.click(),disabled:f||u.length>=5,"aria-label":c.attachImageText},
64
- /* @__PURE__ */e.createElement(P,{weight:"regular",className:"size-4 text-secondary-foreground"}))),!l&&/* @__PURE__ */e.createElement("div",{className:"size-6 flex flex-shrink-0 justify-center items-center"},/* @__PURE__ */e.createElement(S,{className:"size-5 text-secondary-foreground"})),/* @__PURE__ */e.createElement(W,{ref:e=>{$.current=e,"function"==typeof g?g(e):g&&"current"in g&&(g.current=e)},value:y,onChange:e=>{w(e.target.value)},onBlur:()=>{y!==r&&n(y)},onKeyDown:e=>{if("Enter"===e.key&&!e.shiftKey&&!_){e.preventDefault();const t=y;n(t),s(t),w("")}},placeholder:c.followUpPlaceholder,disabled:f,className:"min-h-11 w-full resize-none border-0 shadow-none bg-transparent px-0 py-2.5 focus:outline-none focus:ring-0 focus-visible:ring-0 disabled:opacity-50 disabled:cursor-not-allowed",rows:1}),/* @__PURE__ */e.createElement(v,{type:"button",size:"icon",disabled:_,onClick:()=>{const e=y;n(e),s(e),w("")},className:Z("size-8 shrink-0 rounded",y?"bg-primary text-primary-foreground":"bg-dark-400 text-white")},a?/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 sm:size-5 border-2 border-dark/40 !border-t-foreground"}):/* @__PURE__ */e.createElement(T,{className:"size-6"}))))))});Wr.displayName="FollowUpSearchBar";const Jr=()=>{const{showResults:e,answers:t}=Nr();return Boolean(e||t.length>0)};function Zr({headerText:t,onToggleSizeButtonClick:r,onBackButtonClick:n,onCloseWidgetClick:a,isSearchWidget:s,onHistoryButtonClick:o,onHistoryBackClick:i,showHistory:c,hasUnreadConversations:l,className:u,showHistoryButton:m,...p}){const h=Jr(),[f,g]=e.useState(!1),{isSearching:y,showMobileCloseWidgetButton:w}=Nr();/* @__PURE__ */
64
+ /* @__PURE__ */e.createElement(P,{weight:"regular",className:"size-4 text-secondary-foreground"}))),!l&&/* @__PURE__ */e.createElement("div",{className:"size-6 flex flex-shrink-0 justify-center items-center"},/* @__PURE__ */e.createElement(S,{className:"size-5 text-secondary-foreground"})),/* @__PURE__ */e.createElement(W,{ref:e=>{$.current=e,"function"==typeof g?g(e):g&&"current"in g&&(g.current=e)},value:y,onChange:e=>{w(e.target.value)},onBlur:()=>{y!==r&&n(y)},onKeyDown:e=>{if("Enter"===e.key&&!e.shiftKey&&!_){e.preventDefault();const t=y;n(t),s(t),w("")}},placeholder:c.followUpPlaceholder,disabled:f,className:"min-h-11 w-full resize-none border-0 shadow-none bg-transparent px-0 py-2.5 focus:outline-none focus:ring-0 focus-visible:ring-0 disabled:opacity-50 disabled:cursor-not-allowed",rows:1}),/* @__PURE__ */e.createElement(v,{type:"button",size:"icon",disabled:_,onClick:()=>{const e=y;n(e),s(e),w("")},className:Z("size-8 shrink-0 rounded",y?"bg-primary text-primary-foreground":"bg-dark-400 text-white")},a?/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 sm:size-5 border-2 border-dark/40 !border-t-foreground"}):/* @__PURE__ */e.createElement(T,{className:"size-6"}))))))});Jr.displayName="FollowUpSearchBar";const Zr=()=>{const{showResults:e,answers:t}=Nr();return Boolean(e||t.length>0)};function Xr({headerText:t,onToggleSizeButtonClick:r,onBackButtonClick:n,onCloseWidgetClick:a,isSearchWidget:s,onHistoryButtonClick:o,onHistoryBackClick:i,showHistory:c,hasUnreadConversations:l,className:u,showHistoryButton:m,...p}){const h=Zr(),[f,g]=e.useState(!1),{isSearching:y,showMobileCloseWidgetButton:w}=Nr();/* @__PURE__ */
65
65
  return e.createElement("div",{className:Z("w-full px-3 py-4 flex items-center justify-between","bg-primary h-14 leading-6","md:hidden","@3xl:bg-transparent @3xl:h-auto @3xl:leading-normal","@3xl:justify-center @3xl:space-y-4 @3xl:p-0",s?"hidden bg-transparent":"",u),...p},
66
66
  /* @__PURE__ */e.createElement(d.h2,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.3},className:Z("m-0 text-primary-foreground @3xl:text-foreground flex gap-1 items-center font-bold text-base",s?"":"@3xl:text-5xl")},(c||h)&&/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:c?i:n,"aria-label":"Go back",className:Z("shrink-0 text-primary-foreground",s?"":"@3xl:hidden"),disabled:y},
67
67
  /* @__PURE__ */e.createElement(A,null)),
68
68
  /* @__PURE__ */e.createElement("span",null,c?"History":t)),
69
69
  /* @__PURE__ */e.createElement("div",{className:"@3xl:hidden shrink-0","data-name":"HeaderButtons"},!w&&/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:()=>{g(e=>!e),r()},"aria-label":f?"Collapse widget":"Expand widget",className:"text-primary-foreground device-touch:hidden device-desktop:inline-flex device-desktop-touch:inline-flex"},f?/* @__PURE__ */e.createElement(R,null):/* @__PURE__ */e.createElement(j,null)),m&&/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:o,"aria-label":"Conversation history",className:"relative text-primary-foreground"},
70
70
  /* @__PURE__ */e.createElement(O,null),l&&!c&&/* @__PURE__ */e.createElement("span",{className:"absolute top-1 right-1 size-2 rounded-full bg-red-500"})),/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:a,"aria-label":"Close widget",className:"text-primary-foreground"},
71
- /* @__PURE__ */e.createElement(b,null))))}const Xr={headerText:"How can we help you today?",searchPlaceholder:"Ask a question or type a search term here ...",attachImageText:"Attach image",allDocumentsText:"All documents",loadingSearchText:"Searching for relevant content...",loadingAnswerText:"Crafting a response...",errorText:"Sorry, we were unable to process the request right now. Please try again in a moment.",followUpPlaceholder:"Type your response or follow-up",positiveAnswerText:"Helpful",negativeAnswerText:"Not helpful",uncertaintyFallbackText:{en:"Sorry, I can't find a clear answer to your question. Please try rephrasing or check the related sources below.",es:"Lo siento, no puedo encontrar una respuesta clara. Intente reformular la pregunta o consulte las fuentes relacionadas.",fr:"Désolé, je ne trouve pas de réponse claire. Essayez de reformuler ou consultez les sources connexes.",de:"Entschuldigung, ich finde keine klare Antwort. Versuchen Sie es anders zu formulieren oder sehen Sie sich die verwandten Quellen an.",it:"Mi dispiace, non trovo una risposta chiara. Prova a riformulare o consulta le fonti correlate.",pt:"Desculpe, não encontro uma resposta clara. Tente reformular ou consulte as fontes relacionadas.",nl:"Sorry, ik kan geen duidelijk antwoord vinden. Probeer het anders te formuleren of bekijk de gerelateerde bronnen.",pl:"Przepraszam, nie znajduję jasnej odpowiedzi. Spróbuj przeformułować pytanie lub sprawdź powiązane źródła.",ru:"Извините, я не могу найти четкого ответа. Попробуйте переформулировать или ознакомьтесь со связанными источниками.",ja:"申し訳ありませんが、明確な回答が見つかりません。質問の言い換えや、関連ソースをご確認ください。",ko:"죄송합니다. 명확한 답변을 찾을 수 없습니다. 질문을 다시 작성하거나 관련 소스를 확인해 주세요.",zh:"抱歉,找不到明确的答案。请尝试重新表述或查看相关来源。","zh-TW":"抱歉,找不到明確的答案。請嘗試重新表述或查看相關來源。"}},Yr=({loadConversationEndpoint:e,headers:t,mergedTextConfig:n})=>{const{setIsLoadingConversation:a,setShowResults:s,answerListDispatch:o,conversationId:i,setConversationId:c,clearConversationId:l,setLoadError:d}=Nr(),u=r(r=>{if(!e)return;a(!0),a(!0),s(!0);const i=new AbortController;return ge({endpoint:e,conversationId:r,headers:t,signal:i.signal}).then(({data:e})=>{const t=e.map(e=>({id:e.searchQueryId,state:"completed",question:e.question,isUncertain:X(e.answer).uncertain,searchQueryId:e.searchQueryId,searchIntentId:e.searchIntentId,blocks:e.answer.split("---").map(e=>Ft({text:e.trim()}))}));o((({answers:e})=>({type:Vt,payload:{answers:e}}))({answers:t})),c(r),s(!0)}).catch(e=>{console.error("Error loading conversation:",e),o(cr()),l(),s(!1),d(n.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment.")}).finally(()=>{a(!1)}),()=>i.abort("Conversation loader aborted")},[e,a,s,t,o,c,d,n.errorText]);return ne(()=>{let e;return i&&(console.log("loading conversation",i),e=u(i)),()=>e?.()}),{loadConversationById:u}},en={"image/jpeg":"image","image/png":"image","image/gif":"image","image/webp":"image"};let tn=0;function rn({toasts:t,onDismiss:r}){/* @__PURE__ */
71
+ /* @__PURE__ */e.createElement(b,null))))}const Yr={headerText:"How can we help you today?",searchPlaceholder:"Ask a question or type a search term here ...",attachImageText:"Attach image",allDocumentsText:"All documents",loadingSearchText:"Searching for relevant content...",loadingAnswerText:"Crafting a response...",errorText:"Sorry, we were unable to process the request right now. Please try again in a moment.",followUpPlaceholder:"Type your response or follow-up",positiveAnswerText:"Helpful",negativeAnswerText:"Not helpful",uncertaintyFallbackText:{en:"Sorry, I can't find a clear answer to your question. Please try rephrasing or check the related sources below.",es:"Lo siento, no puedo encontrar una respuesta clara. Intente reformular la pregunta o consulte las fuentes relacionadas.",fr:"Désolé, je ne trouve pas de réponse claire. Essayez de reformuler ou consultez les sources connexes.",de:"Entschuldigung, ich finde keine klare Antwort. Versuchen Sie es anders zu formulieren oder sehen Sie sich die verwandten Quellen an.",it:"Mi dispiace, non trovo una risposta chiara. Prova a riformulare o consulta le fonti correlate.",pt:"Desculpe, não encontro uma resposta clara. Tente reformular ou consulte as fontes relacionadas.",nl:"Sorry, ik kan geen duidelijk antwoord vinden. Probeer het anders te formuleren of bekijk de gerelateerde bronnen.",pl:"Przepraszam, nie znajduję jasnej odpowiedzi. Spróbuj przeformułować pytanie lub sprawdź powiązane źródła.",ru:"Извините, я не могу найти четкого ответа. Попробуйте переформулировать или ознакомьтесь со связанными источниками.",ja:"申し訳ありませんが、明確な回答が見つかりません。質問の言い換えや、関連ソースをご確認ください。",ko:"죄송합니다. 명확한 답변을 찾을 수 없습니다. 질문을 다시 작성하거나 관련 소스를 확인해 주세요.",zh:"抱歉,找不到明确的答案。请尝试重新表述或查看相关来源。","zh-TW":"抱歉,找不到明確的答案。請嘗試重新表述或查看相關來源。"}},en=({loadConversationEndpoint:e,headers:t,mergedTextConfig:n})=>{const{setIsLoadingConversation:a,setShowResults:s,answerListDispatch:o,conversationId:i,setConversationId:c,clearConversationId:l,setLoadError:d}=Nr(),u=r(r=>{if(!e)return;a(!0),a(!0),s(!0);const i=new AbortController;return ge({endpoint:e,conversationId:r,headers:t,signal:i.signal}).then(({data:e})=>{const t=e.map(e=>({id:e.searchQueryId,state:"completed",question:e.question,isUncertain:X(e.answer).uncertain,searchQueryId:e.searchQueryId,searchIntentId:e.searchIntentId,blocks:e.answer.split("---").map(e=>Ft({text:e.trim()}))}));o((({answers:e})=>({type:Vt,payload:{answers:e}}))({answers:t})),c(r),s(!0)}).catch(e=>{console.error("Error loading conversation:",e),o(cr()),l(),s(!1),d(n.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment.")}).finally(()=>{a(!1)}),()=>i.abort("Conversation loader aborted")},[e,a,s,t,o,c,d,n.errorText]);return ne(()=>{let e;return i&&(console.log("loading conversation",i),e=u(i)),()=>e?.()}),{loadConversationById:u}},tn={"image/jpeg":"image","image/png":"image","image/gif":"image","image/webp":"image"};let rn=0;function nn({toasts:t,onDismiss:r}){/* @__PURE__ */
72
72
  return e.createElement("div",{className:"fixed top-4 left-4 right-4 z-50 flex flex-col gap-2 pointer-events-none"},/* @__PURE__ */e.createElement(u,null,t.map(t=>/* @__PURE__ */e.createElement(d.div,{key:t.id,initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.2},className:"pointer-events-auto flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-3 text-sm text-foreground shadow-lg"},
73
73
  /* @__PURE__ */e.createElement("span",{className:"flex-1"},t.message),
74
74
  /* @__PURE__ */e.createElement("button",{onClick:()=>r(t.id),className:"shrink-0 rounded-full p-0.5 hover:bg-muted transition-colors","aria-label":"Dismiss"},
75
- /* @__PURE__ */e.createElement(Ie,{className:"size-3.5"}))))))}const nn=()=>/* @__PURE__ */e.createElement(d.div,{key:"loading",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"w-full flex items-center justify-center py-20","data-name":"loading"},
76
- /* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center gap-4"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-8 border-2 border-t-transparent border-primary"}),/* @__PURE__ */e.createElement("p",{className:"text-sm text-secondary-foreground"},"Loading conversation...")));function an({isHandoff:t,agentAvatarUrl:r}){return t?r?/* @__PURE__ */e.createElement("img",{src:r,className:"h-8 w-8 shrink-0 rounded-full object-cover",alt:"Agent avatar"}):/* @__PURE__ */e.createElement(D,{size:32,className:"text-primary"}):/* @__PURE__ */e.createElement(Se,{className:"border border-neutral-200 rounded-full"})}function sn({item:t,onSelect:r}){/* @__PURE__ */
75
+ /* @__PURE__ */e.createElement(Ie,{className:"size-3.5"}))))))}const an=()=>/* @__PURE__ */e.createElement(d.div,{key:"loading",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"w-full flex items-center justify-center py-20","data-name":"loading"},
76
+ /* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center gap-4"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-8 border-2 border-t-transparent border-primary"}),/* @__PURE__ */e.createElement("p",{className:"text-sm text-secondary-foreground"},"Loading conversation...")));function sn({isHandoff:t,agentAvatarUrl:r}){return t?r?/* @__PURE__ */e.createElement("img",{src:r,className:"h-8 w-8 shrink-0 rounded-full object-cover",alt:"Agent avatar"}):/* @__PURE__ */e.createElement(D,{size:32,className:"text-primary"}):/* @__PURE__ */e.createElement(Se,{className:"border border-neutral-200 rounded-full"})}function on({item:t,onSelect:r}){/* @__PURE__ */
77
77
  return e.createElement("button",{onClick:()=>r({conversationId:t.conversationId,isHandoff:t.isHandoff??!1,isCompleted:"completed"===t.status}),className:Z("w-full flex items-center gap-3 p-3 rounded-lg bg-card text-left","hover:bg-accent transition-colors","border-l-4 border-transparent hover:border-primary/40")},
78
- /* @__PURE__ */e.createElement("div",{className:"relative shrink-0"},/* @__PURE__ */e.createElement(an,{isHandoff:t.isHandoff,agentAvatarUrl:t.agentAvatarUrl}),t.hasUnread&&/* @__PURE__ */e.createElement("span",{className:"absolute top-0 right-0 size-2 rounded-full bg-red-500"})),
79
- /* @__PURE__ */e.createElement("div",{className:"flex flex-col min-w-0"},/* @__PURE__ */e.createElement("span",{className:"text-sm font-medium truncate"},t.title),/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground truncate"},t.subtitle?`${t.subtitle} replied • ${t.timestamp}`:t.timestamp)))}function on({title:t,items:r,onSelect:n,isReadOnly:a=!1}){return 0===r.length?null:/* @__PURE__ */e.createElement("section",null,/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2 mb-2"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground"},t),a&&/* @__PURE__ */e.createElement("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-muted text-muted-foreground"},"View only")),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2"},r.map(t=>/* @__PURE__ */e.createElement(sn,{key:t.conversationId,item:t,onSelect:n}))))}function cn(){/* @__PURE__ */
80
- return e.createElement("div",{className:"w-full flex items-center gap-3 p-3 rounded-lg bg-card animate-pulse"},/* @__PURE__ */e.createElement("div",{className:"size-8 rounded-full bg-muted shrink-0"}),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 flex-1 min-w-0"},/* @__PURE__ */e.createElement("div",{className:"h-3.5 bg-muted rounded w-3/4"}),/* @__PURE__ */e.createElement("div",{className:"h-3 bg-muted rounded w-1/2"})))}const ln=()=>{};function dn({conversations:t,isLoading:r,onSelectConversation:n}){const a=n??ln,s=t.filter(e=>"active"===e.status),o=t.filter(e=>"completed"===e.status);return r?/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 px-3 py-4 overflow-hidden"},/* @__PURE__ */e.createElement("div",{className:"h-4 w-16 bg-muted rounded animate-pulse mb-2"}),[...Array(3)].map((t,r)=>/* @__PURE__ */e.createElement(cn,{key:r}))):/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-4 px-3 py-4 min-h-full"},/* @__PURE__ */e.createElement(on,{title:"Active",items:s,onSelect:a}),/* @__PURE__ */e.createElement(on,{title:"Previous",items:o,onSelect:a,isReadOnly:!0}),0===t.length&&/* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center justify-center gap-3 mt-16 text-center px-6"},/* @__PURE__ */e.createElement(Se,{size:40,className:"text-muted-foreground opacity-40"}),/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-foreground"},"No Threads yet"),/* @__PURE__ */e.createElement("p",{className:"text-xs text-muted-foreground"},"Start a conversation and it will appear here.")))}function un({onStartNewConversation:t,message:r="This conversation is closed. Messages are read-only."}){/* @__PURE__ */
78
+ /* @__PURE__ */e.createElement("div",{className:"relative shrink-0"},/* @__PURE__ */e.createElement(sn,{isHandoff:t.isHandoff,agentAvatarUrl:t.agentAvatarUrl}),t.hasUnread&&/* @__PURE__ */e.createElement("span",{className:"absolute top-0 right-0 size-2 rounded-full bg-red-500"})),
79
+ /* @__PURE__ */e.createElement("div",{className:"flex flex-col min-w-0"},/* @__PURE__ */e.createElement("span",{className:"text-sm font-medium truncate"},t.title),/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground truncate"},t.subtitle?`${t.subtitle} replied • ${t.timestamp}`:t.timestamp)))}function cn({title:t,items:r,onSelect:n,isReadOnly:a=!1}){return 0===r.length?null:/* @__PURE__ */e.createElement("section",null,/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2 mb-2"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground"},t),a&&/* @__PURE__ */e.createElement("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-muted text-muted-foreground"},"View only")),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2"},r.map(t=>/* @__PURE__ */e.createElement(on,{key:t.conversationId,item:t,onSelect:n}))))}function ln(){/* @__PURE__ */
80
+ return e.createElement("div",{className:"w-full flex items-center gap-3 p-3 rounded-lg bg-card animate-pulse"},/* @__PURE__ */e.createElement("div",{className:"size-8 rounded-full bg-muted shrink-0"}),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 flex-1 min-w-0"},/* @__PURE__ */e.createElement("div",{className:"h-3.5 bg-muted rounded w-3/4"}),/* @__PURE__ */e.createElement("div",{className:"h-3 bg-muted rounded w-1/2"})))}const dn=()=>{};function un({conversations:t,isLoading:r,onSelectConversation:n}){const a=n??dn,s=t.filter(e=>"active"===e.status),o=t.filter(e=>"completed"===e.status);return r?/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 px-3 py-4 overflow-hidden"},/* @__PURE__ */e.createElement("div",{className:"h-4 w-16 bg-muted rounded animate-pulse mb-2"}),[...Array(3)].map((t,r)=>/* @__PURE__ */e.createElement(ln,{key:r}))):/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-4 px-3 py-4 min-h-full"},/* @__PURE__ */e.createElement(cn,{title:"Active",items:s,onSelect:a}),/* @__PURE__ */e.createElement(cn,{title:"Previous",items:o,onSelect:a,isReadOnly:!0}),0===t.length&&/* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center justify-center gap-3 mt-16 text-center px-6"},/* @__PURE__ */e.createElement(Se,{size:40,className:"text-muted-foreground opacity-40"}),/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-foreground"},"No Threads yet"),/* @__PURE__ */e.createElement("p",{className:"text-xs text-muted-foreground"},"Start a conversation and it will appear here.")))}function mn({onStartNewConversation:t,message:r="This conversation is closed. Messages are read-only."}){/* @__PURE__ */
81
81
  return e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:"bg-card shadow-top-soft"},
82
- /* @__PURE__ */e.createElement("div",{className:"container flex flex-col items-center justify-center p-3 gap-2 text-center"},/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground"},r),/* @__PURE__ */e.createElement("p",{className:"m-0 text-sm font-medium text-foreground"},"Still need help?"),/* @__PURE__ */e.createElement("button",{type:"button",onClick:t,className:"h-8 rounded-md px-4 text-sm bg-primary text-primary-foreground"},"Start new conversation")))}const mn="enableHistoryTab",pn=[p],hn=[m],fn={p:({children:t})=>/* @__PURE__ */e.createElement("span",null,t)},gn=c(({suggestions:n=[],collections:a=[],selectedCollectionId:s,onCollectionChange:c,selectedRegion:m,onRegionChange:p,apiKey:h,fetchRegionConfig:f,searchEndpoint:g,answerStreamEndpoint:y,uploadEndpoint:v,feedbackEndpoint:w,feedbackReasonEndpoint:b,loadConversationEndpoint:E,autocompleteEndpoint:$,disableFollowUpQuestions:x=!1,enableFileAttachment:_=!1,disableFeedback:k=!1,disclaimer:N,offset:C=0,headers:I,textConfig:S={},followUpQuestionsEndpoint:P,className:T,onToggleSizeButtonClick:A,trackEvent:R,onCloseWidget:j,isWidgetMode:O=!0,nextBestActions:D,bodyActionButtons:z,onNextBestActionClick:L,userData:U,redirectRules:Q,secretAttributes:M,allowedRegions:V,style:q,isSearchWidget:K=!1,isAgentAssist:B=!1,hideCitations:H=!1,conversationInlineSlot:G,liveHumanAgentChatSlot:W,reconnectHandoff:J,resetHandoff:Y,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,knowledgeSourceGroups:ne},ae)=>{const{answers:oe,answerListDispatch:ie,query:ce,setQuery:le,followUpQuery:de,setFollowUpQuery:ue,isSearching:me,setIsSearching:pe,showResults:fe,setShowResults:ge,activeAnswerIndex:Ie,setActiveAnswerIndex:Se,conversationId:Ae,setConversationId:Re,clearConversationId:je,isLoadingConversation:Oe,setShowMobileCloseWidgetButton:De}=Nr(),ze={...Xr,...S},Le=he("enableFileAttachment",!1),Fe=_||Le,Ue=he(mn,!1),{toasts:Qe,showToast:Me,dismissToast:Ve}=function(e=3e3){const[n,a]=t([]),s=i(0),o=r(t=>{const r=++s.current;a(e=>[...e,{id:r,message:t}]),setTimeout(()=>{a(e=>e.filter(e=>e.id!==r))},e)},[e]),c=r(e=>{a(t=>t.filter(t=>t.id!==e))},[]);return{toasts:n,showToast:o,dismissToast:c}}(),qe=r(()=>{let e=Ae;return e||(e=ye(),Re(e)),e},[Ae,Re]),{attachedFiles:Ke,isUploading:Be,addFiles:He,removeFile:Ge,clearAttachedFiles:We,getUploadedAttachments:Je}=function({uploadEndpoint:e,headers:n,getConversationId:a,onError:s}){const[o,i]=t([]),c=r(e=>{i(t=>{const r=t.find(t=>t.id===e);return r&&URL.revokeObjectURL(r.preview),t.filter(t=>t.id!==e)})},[]),l=r(t=>{if(0===t.length)return;const r=t.filter(e=>en[e.type]?!(e.size>10485760&&(s?.(`Image "${e.name}" exceeds the 10MB size limit.`),1)):(s?.("Image type is not supported. Please use JPEG, PNG, GIF, or WebP."),!1)),c=5-o.length;if(0===c)return void s?.("Maximum 5 images reached.");const l=r.slice(0,c);if(0===l.length)return;if(l.length<r.length&&s?.("Maximum 5 images. Some images were not attached."),!e)return console.error("[useFileAttachment] uploadEndpoint is not configured — file attachment is unavailable."),void s?.("Something went wrong. Please try again later.");const d=l.map(e=>({id:"file-"+ ++tn,file:e,preview:URL.createObjectURL(e),status:"uploading",attachmentType:en[e.type]}));i(e=>[...e,...d]);const u=a();d.forEach(t=>{(async()=>{try{const{publicUrl:r}=await ve({endpoint:e,conversationId:u,file:t.file,headers:n});i(e=>e.map(e=>e.id===t.id?{...e,status:"uploaded",publicUrl:r}:e))}catch(r){console.error("Upload failed:",r),s?.(`Failed to upload "${t.file.name}". Please try again.`),i(e=>{const r=e.find(e=>e.id===t.id);return r&&URL.revokeObjectURL(r.preview),e.filter(e=>e.id!==t.id)})}})()})},[o,e,n,a,s]),d=r(()=>{o.forEach(e=>URL.revokeObjectURL(e.preview)),i([])},[o]),u=r(()=>o.filter(e=>"uploaded"===e.status&&e.publicUrl).map(e=>({type:e.attachmentType,url:e.publicUrl,filename:e.file.name})),[o]),m=o.some(e=>"uploading"===e.status);return{attachedFiles:o,isUploading:m,addFiles:l,removeFile:c,clearAttachedFiles:d,getUploadedAttachments:u}}({uploadEndpoint:v,headers:I,getConversationId:qe,onError:Me}),[Ze,Xe]=t(s),[Ye,et]=t(m),[tt,rt]=t(!0),nt=i(null),at=i(null),st=i(null),ot=i([]),it=i(null),ct=i(null),lt=i(null),dt=i(null),ut=i(null),{suggestions:mt}=$e({query:ce,endpoint:$||"",allowedRegions:V,collectionId:Ze,headers:I,conversationId:Ae,delay:300}),{loadConversationById:pt}=Yr({loadConversationEndpoint:E,headers:I,mergedTextConfig:ze}),{showHistory:ht,setShowHistory:ft,conversations:gt,isLoadingHistory:yt,hasUnreadConversations:vt,isViewOnly:wt,setIsViewOnly:bt,handleSelectConversation:Et,completeActiveConversations:$t}=function({enabled:e=!1,conversationHistoryEndpoint:n,markConversationReadEndpoint:a,markConversationCompletedEndpoint:s,headers:c,userData:l,currentConversationId:d,loadConversationById:u,reconnectHandoff:m,resetHandoff:p}){const[h,f]=t(!1),[g,y]=t([]),[v,w]=t(!1),[b,E]=t(!1),$=i(null),x=i(c);x.current=c;const _=g.some(e=>e.hasUnread),k=l?.userId,N=c?.["x-bf-fingerprint"],C=!(!k&&!N);o(()=>{if(!e||!n||!C)return;let t=!1;return we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}),()=>{t=!0}},[n,C,k,N]),o(()=>{if(!(e&&h&&n&&C))return;let t=!1;return w(!0),we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}).finally(()=>{t||w(!1)}),()=>{t=!0}},[e,h,n,C,k,N]);const I=r(({conversationId:e,isHandoff:t,isCompleted:r})=>{d&&!b&&($.current=d),u(e),E(r),t?m?.(e):p?.(),a&&be({endpoint:a,conversationId:e,headers:x.current}).catch(()=>{}),f(!1)},[e,d,b,u,m,p,a]),S=r(()=>{if(!s)return;const e=g.filter(e=>"active"===e.status).map(e=>e.conversationId),t=new Set([$.current,b?null:d,...e].filter(e=>!!e));y(e=>e.map(e=>t.has(e.conversationId)?{...e,status:"completed"}:e)),t.forEach(e=>{Ee({endpoint:s,conversationId:e,headers:x.current}).catch(()=>{})}),$.current=null},[s,d,b,g]);return{showHistory:h,setShowHistory:f,conversations:g,isLoadingHistory:v,hasUnreadConversations:_,isViewOnly:b,setIsViewOnly:E,handleSelectConversation:I,completeActiveConversations:S}}({enabled:Ue,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,headers:I,userData:U??void 0,currentConversationId:Ae,loadConversationById:pt,reconnectHandoff:J,resetHandoff:Y}),{scrollToLastAnswer:xt,scrollToAnswer:_t}=((e,t,r)=>({scrollToLastAnswer:()=>{requestAnimationFrame(()=>{const r=e.current?.[e.current.length-1],n=t.current;if(r&&n){const e=r.getBoundingClientRect(),t=n.getBoundingClientRect(),a=n.scrollTop+(e.top-t.top)-80;n.scrollTo({top:a,behavior:"smooth"})}})},scrollToAnswer:r=>{requestAnimationFrame(()=>{const n=e.current?.[r],a=t.current;if(n&&a){const e=n.getBoundingClientRect(),t=a.getBoundingClientRect(),r=a.scrollTop+(e.top-t.top)-80;a.scrollTo({top:r,behavior:"smooth"})}})},scrollToBottom:()=>{setTimeout(()=>{r?.current&&t.current&&r.current.scrollIntoView({behavior:"smooth",block:"end"})},200)}}))(ot,it,dt),{subscribeToStateChanges:kt}=(()=>{const e=i([]),{showResults:t,answers:r,isLoadingConversation:n,loadError:a}=Nr();return o(()=>{const s={showResults:t,answers:r,isLoading:n,error:a};e.current.forEach(e=>e(s))},[t,r,n,a]),{subscribeToStateChanges:s=>(e.current.push(s),s({showResults:t,answers:r,isLoading:n,error:a}),()=>{e.current=e.current.filter(e=>e!==s)})}})(),{includePageEnabled:Nt,includePageLoading:Ct,includePageDisabled:It,handleIncludePageToggle:St,fetchPageContext:Pt}=(({isAgentAssist:e,apiKey:n,trackEvent:a})=>{const[s,i]=t(!1),[c,l]=t(!1),[d,u]=t(!1),m=r((e,t=5e3)=>new Promise((r,a)=>{const s=ye();let o;const i=e=>{e.data.requestId===s&&(clearTimeout(o),window.removeEventListener("message",i),r(e.data))};o=setTimeout(()=>{window.removeEventListener("message",i),a(new Error("Request timeout"))},t),window.addEventListener("message",i),window.parent.postMessage({...e,requestId:s,widgetKey:n},"*")}),[n]),p=r(async e=>{l(!0);try{if(e){if(!(await m({type:"REQUEST_PAGE_PERMISSION"})).granted)throw a?.("Include Page Permission Denied",{}),new Error("Permission denied");window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!0,widgetKey:n},"*"),a?.("Include Page Enabled",{}),i(!0)}else window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!1,widgetKey:n},"*"),a?.("Include Page Disabled",{}),i(!1)}catch(t){console.error("Failed to toggle include page:",t),i(!1)}finally{l(!1)}},[n,m,a]),h=r(async(t,r)=>{if(s&&e&&!d)try{l(!0);const e=await m({type:"REQUEST_PAGE_CONTENT"},5e3);return e.success&&e.content?(a?.("Page Content Included",{conversationId:t,searchQuery:r,contentLength:e.content.length}),[{type:"text",text:`I am currently viewing this web page:\n\n${e.content}`}]):void 0}catch(n){return console.error("Failed to fetch page content:",n),void a?.("Page Content Fetch Failed",{conversationId:t,searchQuery:r})}finally{l(!1)}},[s,e,d,m,a]);return o(()=>{if(!e)return;const t=e=>{const t=e.data;"INCLUDE_PAGE_STATE"===t.type&&(i(t.enabled||!1),u(t.disabled||!1))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e]),{includePageEnabled:s,includePageLoading:c,includePageDisabled:d,handleIncludePageToggle:p,fetchPageContext:h}})({isAgentAssist:B,apiKey:h??"unknown",trackEvent:R}),Tt=async({reader:e,searchQueryId:t,conversationId:r,onFirstEvent:n})=>{ut.current=e;let a="";try{let s,o,i=!1,c=!0,l=!1;for(;({done:i,value:o}=await e.read()),!i&&ut.current===e;){c&&(c=!1,n?.());const e=(new TextDecoder).decode(o).split(/\n\n/).filter(e=>e.startsWith("data: ")).map(e=>e.replace(/^data: /,"").trim());for(const n of e)try{if("[DONE]"===n)continue;const e=JSON.parse(n);if("status-message"===e.type&&ie(gr({message:e.message})),"answer-text-chunk"===e.type){a+=e.content,ie(dr({text:e.content}));const t=X(a);if(l=t.uncertain,l){const e=ze.uncertaintyFallbackText?.[t.language??"en"]??a??"I don't know.";ie(pr({uncertaintyText:e}))}}"answer-error"===e.type&&ie(ur({error:ze.errorText||e.message})),"action-buttons"===e.type&&(s=e.searchIntentId,ie(vr({searchIntentId:s,actions:e.actions}))),"get-action-inputs"===e.type&&(s=e.searchIntentId,ie(yr({searchIntentId:e.searchIntentId,inputs:e.inputs,actionId:e.actionId,schema:e.schema,initialValues:e.values,onSubmit:async n=>{if("client_execution"===e.actionType){const o=await(a=e.actionKey,s=n,new Promise(e=>{const t=crypto.randomUUID(),r=n=>{n.data.messageId===t&&"CLIENT_EXECUTION_RESULT"===n.data.type&&(window.removeEventListener("message",r),e(n.data.result))};window.addEventListener("message",r),window.parent.postMessage({type:"CLIENT_EXECUTION",messageId:t,actionKey:a,inputs:s},"*"),setTimeout(()=>{window.removeEventListener("message",r),e({success:!1,reason:`Client Action handler with key ${a} timed out`})},5e3)}));return jt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,results:o})}var a,s;return"run_workflow"===e.actionType?(ie(hr()),ie(gr({message:ze.loadingAnswerText})),At({searchQueryId:t,conversationId:r,parameters:n})):Rt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,parameters:n})}}))),"citations"===e.type&&ie(lr({searchQueryId:t,results:e.data,state:"completed"}))}catch{console.warn("Failed to parse answer stream block")}}return{answer:a,searchIntentId:s,isUncertain:l}}catch(s){if(ut.current!==e)return{answer:"",searchIntentId:void 0,isUncertain:!1};throw s}finally{ut.current===e&&(ut.current=null,e.releaseLock())}},At=async({searchQueryId:e,conversationId:t,context:r,attachments:n,parameters:a})=>{try{const s=(async(e,t)=>{if(P&&!x)try{return await Ce({endpoint:P,searchQueryId:e,headers:I,conversationId:t})}catch(r){return void console.error("Error fetching follow-up questions:",r)}})(e),o=await Ne({endpoint:y,headers:I,body:{type:"generate-for-query",conversationId:t,searchQueryId:e,profileId:U?.userId,...r&&{context:r},...n?.length&&{attachments:n},...a&&{parameters:a}}}),i=o.body?.getReader();if(!i)return;const{answer:c,searchIntentId:l,isUncertain:d}=await Tt({reader:i,searchQueryId:e,conversationId:t,onFirstEvent:()=>{R?.("First Streamed Answer Chunk Received",{conversationId:t,searchQueryId:e})}});if(!c)return;s.then(e=>{e&&e.length>0&&!l&&ie((({questions:e,index:t})=>({type:Wt,payload:{questions:e,index:t}}))({questions:e}))}),R?.(d?"Answer Not Found":"Answer Found",{conversationId:t,searchQueryId:e})}catch(s){console.error("Error generating answer for query:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr())}},Rt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,parameters:a})=>{ie(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"invoke-action",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,parameters:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr()),pe(!1)}},jt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,results:a})=>{ie(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"client-execution-result",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,results:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr()),pe(!1)}},Ot=async({searchQuery:e,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,knowledgeGroupCollectionIds:s})=>{const o=s??Ze,i=await ke({endpoint:g,query:e,collectionId:o,headers:I,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,source:B?"agent_assist":void 0});if(0!==i.results.length||i.isAgenticResponse)return ie(lr({searchQueryId:i.searchQueryId,results:i.results})),i.searchQueryId;R?.("No Articles Found",{conversationId:t,searchQuery:e})},Dt=async({searchQuery:e=ce.trim(),event:t})=>{if(!e)return;const r=Ae||ye();Re(r);const n=Je();We(),pe(!0),ge(!0),Se(oe.length),xt(),ie((({id:e,query:t,attachments:r})=>({type:Kt,payload:{id:e,query:t,attachments:r}}))({query:e,attachments:n})),await Promise.resolve(),lt.current?.focus();const a=await Pt(r,e);if(ne&&ne.length>0&&!nt.current)return at.current={searchQuery:e,conversationId:r,attributes:{...U},secretAttributes:M,allowedRegions:V,pageContext:a??void 0,fileAttachments:n.length>0?n:void 0},ie((({index:e}={})=>({type:sr,payload:{index:e}}))()),void pe(!1);try{const s={...U},o=nt.current?.collectionIds,i=await Ot({searchQuery:e,conversationId:r,attributes:s,secretAttributes:M,allowedRegions:V,knowledgeGroupCollectionIds:o});i?(t&&R?.(t.name,{conversationId:r,searchQuery:e,searchQueryId:i,...t.metaData}),await At({searchQueryId:i,conversationId:r,context:a,attachments:n.length>0?n:void 0})):ie(fr())}catch(s){console.error("Error generating answer:",s),t&&R?.(`${t.name} - Search Error`,{conversationId:r,searchQuery:e,...t.metaData}),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}},zt=async e=>{nt.current=e;const t=at.current;if(t){at.current=null,ie((({index:e}={})=>({type:or,payload:{index:e}}))()),pe(!0);try{const r=await Ot({searchQuery:t.searchQuery,conversationId:t.conversationId,attributes:t.attributes,secretAttributes:t.secretAttributes,allowedRegions:t.allowedRegions,knowledgeGroupCollectionIds:e.collectionIds});r?(R?.("Knowledge Group Selected",{conversationId:t.conversationId,searchQuery:t.searchQuery,searchQueryId:r,knowledgeGroupId:e.id,knowledgeGroupName:e.name}),await At({searchQueryId:r,conversationId:t.conversationId,context:t.pageContext,attachments:t.fileAttachments})):ie(fr())}catch(r){console.error("Error generating answer after group selection:",r),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}}},Lt=e=>{if($t(),bt(!1),Y?.(),ut.current){const e=ut.current;ut.current=null,function(e){try{e.cancel().catch(e=>{console.warn("Error cancelling stream reader:",e)});try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}catch(r){console.warn("Error cancelling stream reader:",r);try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}}(e)}pe(!1),le(""),ue(""),ge(!1),ie(cr()),Se(0),We(),je(),nt.current=null,at.current=null,R?.("New Thread Created",{oldConversationId:Ae}),st.current&&(st.current.style.height="auto"),e&&(le(e),Dt({searchQuery:e,event:{name:"New Thread Created with Query"}}))};l(ae,()=>({createNewThread:Lt,showFollowUpThread:e=>{rt(e)},subscribeToStateChanges:kt,focusSearchField:()=>ct.current?.focus()||lt.current?.focus(),showCloseButton:(e=!0)=>{De(e)},loadConversation:pt})),o(()=>{Xe(s)},[s]),o(()=>{et(m)},[m]);const Ft=async(e,t,r)=>{if(w){ie((({feedback:e,index:t})=>({type:Xt,payload:{feedback:e,index:t}}))({feedback:e,index:r}));try{await _e({endpoint:w,searchQueryId:t,response:e,headers:I,conversationId:Ae}),R?.("accept"===e?"Answer Accepted":"Answer Rejected",{conversationId:Ae,searchQueryId:t})}catch(n){console.error("Error sending feedback:",n),ie((({index:e}={})=>({type:Yt,payload:{index:e}}))({index:r}))}}},Ut=async e=>{const t=void 0!==e?e:de;t.trim()&&(le(t),ue(""),await Dt({searchQuery:t,event:{name:"Follow-up Search Field Submitted"}}))};o(()=>{const e=()=>{new URLSearchParams(window.location.search).get("conversation")||(le(""),ue(""),ge(!1),ie(cr()),Se(0),We(),st.current&&(st.current.style.height="auto"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);const Mt=e=>{R?.("Follow-up Question Clicked",{conversationId:Ae,question:e}),Dt({searchQuery:e,event:{name:"Follow-up Question Clicked"}})},Vt=({action:e,searchQueryId:t,query:r,answer:n})=>{R?.("Next Best Action Clicked",{conversationId:Ae,searchQueryId:t,action:e.label});const a=((e,t)=>({conversationId:t,messages:e.map(e=>({question:e.question,answer:Qt(e.blocks)}))}))(oe,Ae);L?.({action:e,searchQueryId:t,query:r,answer:n,conversation:a})};return o(()=>{const e=it.current;if(!e||!K)return;let t=0,r=null;const n=()=>{const r=(()=>{const t=e.firstElementChild,r=t?.scrollHeight??e.scrollHeight,n=document.querySelector('[data-name="BrandFooter"]')?.clientHeight??0,a=document.querySelector('[data-name="Header"]')?.clientHeight??0,s=fe&&tt?70:0,o=document.querySelector('[data-name="ChatSearch"]')?.clientHeight??0,i=r+n+s+a+32;return fe?Math.max(i,o):i})();r>0&&r!==t&&(t=r,window.parent.postMessage({type:"RESIZE_IFRAME",height:r,widgetKey:h},"*"))},a=setTimeout(n,100),s=new ResizeObserver(()=>{null!==r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{n(),r=null})}),o=e.firstElementChild;return o&&s.observe(o),s.observe(e),()=>{clearTimeout(a),null!==r&&cancelAnimationFrame(r),s.disconnect()}},[K,h,fe,tt]),/* @__PURE__ */e.createElement("div",{className:Z("w-full relative h-dvh flex flex-col justify-between @container","md:h-auto md:p-4 md:bg-dark-100",T),"data-name":"ChatSearch",style:q},
83
- /* @__PURE__ */e.createElement(rn,{toasts:Qe,onDismiss:Ve}),(O||!fe)&&/* @__PURE__ */e.createElement(Zr,{showHistoryButton:Ue,isSearchWidget:K,"data-name":"Header",headerText:ze.headerText,onToggleSizeButtonClick:()=>{A?.()},onBackButtonClick:()=>{Lt()},onCloseWidgetClick:()=>j?.(),showHistory:ht,hasUnreadConversations:vt,onHistoryButtonClick:()=>ft(!0),onHistoryBackClick:()=>ft(!1),className:Z("@3xl:mb-4",{"!block":fe&&K})}),
82
+ /* @__PURE__ */e.createElement("div",{className:"container flex flex-col items-center justify-center p-3 gap-2 text-center"},/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground"},r),/* @__PURE__ */e.createElement("p",{className:"m-0 text-sm font-medium text-foreground"},"Still need help?"),/* @__PURE__ */e.createElement("button",{type:"button",onClick:t,className:"h-8 rounded-md px-4 text-sm bg-primary text-primary-foreground"},"Start new conversation")))}const pn="enableHistoryTab",hn=[p],fn=[m],gn={p:({children:t})=>/* @__PURE__ */e.createElement("span",null,t)},yn=c(({suggestions:n=[],collections:a=[],selectedCollectionId:s,onCollectionChange:c,selectedRegion:m,onRegionChange:p,apiKey:h,fetchRegionConfig:f,searchEndpoint:g,answerStreamEndpoint:y,uploadEndpoint:v,feedbackEndpoint:w,feedbackReasonEndpoint:b,loadConversationEndpoint:E,autocompleteEndpoint:$,disableFollowUpQuestions:x=!1,enableFileAttachment:_=!1,disableFeedback:k=!1,disclaimer:N,offset:C=0,headers:I,textConfig:S={},followUpQuestionsEndpoint:P,className:T,onToggleSizeButtonClick:A,trackEvent:R,onCloseWidget:j,isWidgetMode:O=!0,nextBestActions:D,bodyActionButtons:z,onNextBestActionClick:L,userData:U,redirectRules:Q,secretAttributes:M,allowedRegions:V,style:q,isSearchWidget:K=!1,isAgentAssist:B=!1,hideCitations:H=!1,conversationInlineSlot:G,liveHumanAgentChatSlot:W,reconnectHandoff:J,resetHandoff:Y,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,knowledgeSourceGroups:ne},ae)=>{const{answers:oe,answerListDispatch:ie,query:ce,setQuery:le,followUpQuery:de,setFollowUpQuery:ue,isSearching:me,setIsSearching:pe,showResults:fe,setShowResults:ge,activeAnswerIndex:Ie,setActiveAnswerIndex:Se,conversationId:Ae,setConversationId:Re,clearConversationId:je,isLoadingConversation:Oe,setShowMobileCloseWidgetButton:De}=Nr(),ze={...Yr,...S},Le=he("enableFileAttachment",!1),Fe=_||Le,Ue=he(pn,!1),{toasts:Qe,showToast:Me,dismissToast:Ve}=function(e=3e3){const[n,a]=t([]),s=i(0),o=r(t=>{const r=++s.current;a(e=>[...e,{id:r,message:t}]),setTimeout(()=>{a(e=>e.filter(e=>e.id!==r))},e)},[e]),c=r(e=>{a(t=>t.filter(t=>t.id!==e))},[]);return{toasts:n,showToast:o,dismissToast:c}}(),qe=r(()=>{let e=Ae;return e||(e=ye(),Re(e)),e},[Ae,Re]),{attachedFiles:Ke,isUploading:Be,addFiles:He,removeFile:Ge,clearAttachedFiles:We,getUploadedAttachments:Je}=function({uploadEndpoint:e,headers:n,getConversationId:a,onError:s}){const[o,i]=t([]),c=r(e=>{i(t=>{const r=t.find(t=>t.id===e);return r&&URL.revokeObjectURL(r.preview),t.filter(t=>t.id!==e)})},[]),l=r(t=>{if(0===t.length)return;const r=t.filter(e=>tn[e.type]?!(e.size>10485760&&(s?.(`Image "${e.name}" exceeds the 10MB size limit.`),1)):(s?.("Image type is not supported. Please use JPEG, PNG, GIF, or WebP."),!1)),c=5-o.length;if(0===c)return void s?.("Maximum 5 images reached.");const l=r.slice(0,c);if(0===l.length)return;if(l.length<r.length&&s?.("Maximum 5 images. Some images were not attached."),!e)return console.error("[useFileAttachment] uploadEndpoint is not configured — file attachment is unavailable."),void s?.("Something went wrong. Please try again later.");const d=l.map(e=>({id:"file-"+ ++rn,file:e,preview:URL.createObjectURL(e),status:"uploading",attachmentType:tn[e.type]}));i(e=>[...e,...d]);const u=a();d.forEach(t=>{(async()=>{try{const{publicUrl:r}=await ve({endpoint:e,conversationId:u,file:t.file,headers:n});i(e=>e.map(e=>e.id===t.id?{...e,status:"uploaded",publicUrl:r}:e))}catch(r){console.error("Upload failed:",r),s?.(`Failed to upload "${t.file.name}". Please try again.`),i(e=>{const r=e.find(e=>e.id===t.id);return r&&URL.revokeObjectURL(r.preview),e.filter(e=>e.id!==t.id)})}})()})},[o,e,n,a,s]),d=r(()=>{o.forEach(e=>URL.revokeObjectURL(e.preview)),i([])},[o]),u=r(()=>o.filter(e=>"uploaded"===e.status&&e.publicUrl).map(e=>({type:e.attachmentType,url:e.publicUrl,filename:e.file.name})),[o]),m=o.some(e=>"uploading"===e.status);return{attachedFiles:o,isUploading:m,addFiles:l,removeFile:c,clearAttachedFiles:d,getUploadedAttachments:u}}({uploadEndpoint:v,headers:I,getConversationId:qe,onError:Me}),[Ze,Xe]=t(s),[Ye,et]=t(m),[tt,rt]=t(!0),nt=i(null),at=i(null),st=i(null),ot=i([]),it=i(null),ct=i(null),lt=i(null),dt=i(null),ut=i(null),{suggestions:mt}=$e({query:ce,endpoint:$||"",allowedRegions:V,collectionId:Ze,headers:I,conversationId:Ae,delay:300}),{loadConversationById:pt}=en({loadConversationEndpoint:E,headers:I,mergedTextConfig:ze}),{showHistory:ht,setShowHistory:ft,conversations:gt,isLoadingHistory:yt,hasUnreadConversations:vt,isViewOnly:wt,setIsViewOnly:bt,handleSelectConversation:Et,completeActiveConversations:$t}=function({enabled:e=!1,conversationHistoryEndpoint:n,markConversationReadEndpoint:a,markConversationCompletedEndpoint:s,headers:c,userData:l,currentConversationId:d,loadConversationById:u,reconnectHandoff:m,resetHandoff:p}){const[h,f]=t(!1),[g,y]=t([]),[v,w]=t(!1),[b,E]=t(!1),$=i(null),x=i(c);x.current=c;const _=g.some(e=>e.hasUnread),k=l?.userId,N=c?.["x-bf-fingerprint"],C=!(!k&&!N);o(()=>{if(!e||!n||!C)return;let t=!1;return we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}),()=>{t=!0}},[n,C,k,N]),o(()=>{if(!(e&&h&&n&&C))return;let t=!1;return w(!0),we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}).finally(()=>{t||w(!1)}),()=>{t=!0}},[e,h,n,C,k,N]);const I=r(({conversationId:e,isHandoff:t,isCompleted:r})=>{d&&!b&&($.current=d),u(e),E(r),t?m?.(e):p?.(),a&&be({endpoint:a,conversationId:e,headers:x.current}).catch(()=>{}),f(!1)},[e,d,b,u,m,p,a]),S=r(()=>{if(!s)return;const e=g.filter(e=>"active"===e.status).map(e=>e.conversationId),t=new Set([$.current,b?null:d,...e].filter(e=>!!e));y(e=>e.map(e=>t.has(e.conversationId)?{...e,status:"completed"}:e)),t.forEach(e=>{Ee({endpoint:s,conversationId:e,headers:x.current}).catch(()=>{})}),$.current=null},[s,d,b,g]);return{showHistory:h,setShowHistory:f,conversations:g,isLoadingHistory:v,hasUnreadConversations:_,isViewOnly:b,setIsViewOnly:E,handleSelectConversation:I,completeActiveConversations:S}}({enabled:Ue,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,headers:I,userData:U??void 0,currentConversationId:Ae,loadConversationById:pt,reconnectHandoff:J,resetHandoff:Y}),{scrollToLastAnswer:xt,scrollToAnswer:_t}=((e,t,r)=>({scrollToLastAnswer:()=>{requestAnimationFrame(()=>{const r=e.current?.[e.current.length-1],n=t.current;if(r&&n){const e=r.getBoundingClientRect(),t=n.getBoundingClientRect(),a=n.scrollTop+(e.top-t.top)-80;n.scrollTo({top:a,behavior:"smooth"})}})},scrollToAnswer:r=>{requestAnimationFrame(()=>{const n=e.current?.[r],a=t.current;if(n&&a){const e=n.getBoundingClientRect(),t=a.getBoundingClientRect(),r=a.scrollTop+(e.top-t.top)-80;a.scrollTo({top:r,behavior:"smooth"})}})},scrollToBottom:()=>{setTimeout(()=>{r?.current&&t.current&&r.current.scrollIntoView({behavior:"smooth",block:"end"})},200)}}))(ot,it,dt),{subscribeToStateChanges:kt}=(()=>{const e=i([]),{showResults:t,answers:r,isLoadingConversation:n,loadError:a}=Nr();return o(()=>{const s={showResults:t,answers:r,isLoading:n,error:a};e.current.forEach(e=>e(s))},[t,r,n,a]),{subscribeToStateChanges:s=>(e.current.push(s),s({showResults:t,answers:r,isLoading:n,error:a}),()=>{e.current=e.current.filter(e=>e!==s)})}})(),{includePageEnabled:Nt,includePageLoading:Ct,includePageDisabled:It,handleIncludePageToggle:St,fetchPageContext:Pt}=(({isAgentAssist:e,apiKey:n,trackEvent:a})=>{const[s,i]=t(!1),[c,l]=t(!1),[d,u]=t(!1),m=r((e,t=5e3)=>new Promise((r,a)=>{const s=ye();let o;const i=e=>{e.data.requestId===s&&(clearTimeout(o),window.removeEventListener("message",i),r(e.data))};o=setTimeout(()=>{window.removeEventListener("message",i),a(new Error("Request timeout"))},t),window.addEventListener("message",i),window.parent.postMessage({...e,requestId:s,widgetKey:n},"*")}),[n]),p=r(async e=>{l(!0);try{if(e){if(!(await m({type:"REQUEST_PAGE_PERMISSION"})).granted)throw a?.("Include Page Permission Denied",{}),new Error("Permission denied");window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!0,widgetKey:n},"*"),a?.("Include Page Enabled",{}),i(!0)}else window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!1,widgetKey:n},"*"),a?.("Include Page Disabled",{}),i(!1)}catch(t){console.error("Failed to toggle include page:",t),i(!1)}finally{l(!1)}},[n,m,a]),h=r(async(t,r)=>{if(s&&e&&!d)try{l(!0);const e=await m({type:"REQUEST_PAGE_CONTENT"},5e3);return e.success&&e.content?(a?.("Page Content Included",{conversationId:t,searchQuery:r,contentLength:e.content.length}),[{type:"text",text:`I am currently viewing this web page:\n\n${e.content}`}]):void 0}catch(n){return console.error("Failed to fetch page content:",n),void a?.("Page Content Fetch Failed",{conversationId:t,searchQuery:r})}finally{l(!1)}},[s,e,d,m,a]);return o(()=>{if(!e)return;const t=e=>{const t=e.data;"INCLUDE_PAGE_STATE"===t.type&&(i(t.enabled||!1),u(t.disabled||!1))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e]),{includePageEnabled:s,includePageLoading:c,includePageDisabled:d,handleIncludePageToggle:p,fetchPageContext:h}})({isAgentAssist:B,apiKey:h??"unknown",trackEvent:R}),Tt=async({reader:e,searchQueryId:t,conversationId:r,onFirstEvent:n})=>{ut.current=e;let a="";try{let s,o,i=!1,c=!0,l=!1;for(;({done:i,value:o}=await e.read()),!i&&ut.current===e;){c&&(c=!1,n?.());const e=(new TextDecoder).decode(o).split(/\n\n/).filter(e=>e.startsWith("data: ")).map(e=>e.replace(/^data: /,"").trim());for(const n of e)try{if("[DONE]"===n)continue;const e=JSON.parse(n);if("status-message"===e.type&&ie(gr({message:e.message})),"answer-text-chunk"===e.type){a+=e.content,ie(dr({text:e.content}));const t=X(a);if(l=t.uncertain,l){const e=ze.uncertaintyFallbackText?.[t.language??"en"]??a??"I don't know.";ie(pr({uncertaintyText:e}))}}"answer-error"===e.type&&ie(ur({error:ze.errorText||e.message})),"action-buttons"===e.type&&(s=e.searchIntentId,ie(vr({searchIntentId:s,actions:e.actions}))),"get-action-inputs"===e.type&&(s=e.searchIntentId,ie(yr({searchIntentId:e.searchIntentId,inputs:e.inputs,actionId:e.actionId,schema:e.schema,initialValues:e.values,onSubmit:async n=>{if("client_execution"===e.actionType){const o=await(a=e.actionKey,s=n,new Promise(e=>{const t=crypto.randomUUID(),r=n=>{n.data.messageId===t&&"CLIENT_EXECUTION_RESULT"===n.data.type&&(window.removeEventListener("message",r),e(n.data.result))};window.addEventListener("message",r),window.parent.postMessage({type:"CLIENT_EXECUTION",messageId:t,actionKey:a,inputs:s},"*"),setTimeout(()=>{window.removeEventListener("message",r),e({success:!1,reason:`Client Action handler with key ${a} timed out`})},5e3)}));return jt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,results:o})}var a,s;return"run_workflow"===e.actionType?(ie(hr()),ie(gr({message:ze.loadingAnswerText})),At({searchQueryId:t,conversationId:r,parameters:n})):Rt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,parameters:n})}}))),"citations"===e.type&&ie(lr({searchQueryId:t,results:e.data,state:"completed"}))}catch{console.warn("Failed to parse answer stream block")}}return{answer:a,searchIntentId:s,isUncertain:l}}catch(s){if(ut.current!==e)return{answer:"",searchIntentId:void 0,isUncertain:!1};throw s}finally{ut.current===e&&(ut.current=null,e.releaseLock())}},At=async({searchQueryId:e,conversationId:t,context:r,attachments:n,parameters:a})=>{try{const s=(async(e,t)=>{if(P&&!x)try{return await Ce({endpoint:P,searchQueryId:e,headers:I,conversationId:t})}catch(r){return void console.error("Error fetching follow-up questions:",r)}})(e),o=await Ne({endpoint:y,headers:I,body:{type:"generate-for-query",conversationId:t,searchQueryId:e,profileId:U?.userId,...r&&{context:r},...n?.length&&{attachments:n},...a&&{parameters:a}}}),i=o.body?.getReader();if(!i)return;const{answer:c,searchIntentId:l,isUncertain:d}=await Tt({reader:i,searchQueryId:e,conversationId:t,onFirstEvent:()=>{R?.("First Streamed Answer Chunk Received",{conversationId:t,searchQueryId:e})}});if(!c)return;s.then(e=>{e&&e.length>0&&!l&&ie((({questions:e,index:t})=>({type:Wt,payload:{questions:e,index:t}}))({questions:e}))}),R?.(d?"Answer Not Found":"Answer Found",{conversationId:t,searchQueryId:e})}catch(s){console.error("Error generating answer for query:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr())}},Rt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,parameters:a})=>{ie(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"invoke-action",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,parameters:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr()),pe(!1)}},jt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,results:a})=>{ie(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"client-execution-result",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,results:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr()),pe(!1)}},Ot=async({searchQuery:e,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,knowledgeGroupCollectionIds:s})=>{const o=s??Ze,i=await ke({endpoint:g,query:e,collectionId:o,headers:I,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,source:B?"agent_assist":void 0});if(0!==i.results.length||i.isAgenticResponse)return ie(lr({searchQueryId:i.searchQueryId,results:i.results})),i.searchQueryId;R?.("No Articles Found",{conversationId:t,searchQuery:e})},Dt=async({searchQuery:e=ce.trim(),event:t})=>{if(!e)return;const r=Ae||ye();Re(r);const n=Je();We(),pe(!0),ge(!0),Se(oe.length),xt(),ie((({id:e,query:t,attachments:r})=>({type:Kt,payload:{id:e,query:t,attachments:r}}))({query:e,attachments:n})),await Promise.resolve(),lt.current?.focus();const a=await Pt(r,e);if(ne&&ne.length>0&&!nt.current)return at.current={searchQuery:e,conversationId:r,attributes:{...U},secretAttributes:M,allowedRegions:V,pageContext:a??void 0,fileAttachments:n.length>0?n:void 0},ie((({index:e}={})=>({type:sr,payload:{index:e}}))()),void pe(!1);try{const s={...U},o=nt.current?.collectionIds,i=await Ot({searchQuery:e,conversationId:r,attributes:s,secretAttributes:M,allowedRegions:V,knowledgeGroupCollectionIds:o});i?(t&&R?.(t.name,{conversationId:r,searchQuery:e,searchQueryId:i,...t.metaData}),await At({searchQueryId:i,conversationId:r,context:a,attachments:n.length>0?n:void 0})):ie(fr())}catch(s){console.error("Error generating answer:",s),t&&R?.(`${t.name} - Search Error`,{conversationId:r,searchQuery:e,...t.metaData}),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}},zt=async e=>{nt.current=e;const t=at.current;if(t){at.current=null,ie((({index:e}={})=>({type:or,payload:{index:e}}))()),pe(!0);try{const r=await Ot({searchQuery:t.searchQuery,conversationId:t.conversationId,attributes:t.attributes,secretAttributes:t.secretAttributes,allowedRegions:t.allowedRegions,knowledgeGroupCollectionIds:e.collectionIds});r?(R?.("Knowledge Group Selected",{conversationId:t.conversationId,searchQuery:t.searchQuery,searchQueryId:r,knowledgeGroupId:e.id,knowledgeGroupName:e.name}),await At({searchQueryId:r,conversationId:t.conversationId,context:t.pageContext,attachments:t.fileAttachments})):ie(fr())}catch(r){console.error("Error generating answer after group selection:",r),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}}},Lt=e=>{if($t(),bt(!1),Y?.(),ut.current){const e=ut.current;ut.current=null,function(e){try{e.cancel().catch(e=>{console.warn("Error cancelling stream reader:",e)});try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}catch(r){console.warn("Error cancelling stream reader:",r);try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}}(e)}pe(!1),le(""),ue(""),ge(!1),ie(cr()),Se(0),We(),je(),nt.current=null,at.current=null,R?.("New Thread Created",{oldConversationId:Ae}),st.current&&(st.current.style.height="auto"),e&&(le(e),Dt({searchQuery:e,event:{name:"New Thread Created with Query"}}))};l(ae,()=>({createNewThread:Lt,showFollowUpThread:e=>{rt(e)},subscribeToStateChanges:kt,focusSearchField:()=>ct.current?.focus()||lt.current?.focus(),showCloseButton:(e=!0)=>{De(e)},loadConversation:pt})),o(()=>{Xe(s)},[s]),o(()=>{et(m)},[m]);const Ft=async(e,t,r)=>{if(w){ie((({feedback:e,index:t})=>({type:Xt,payload:{feedback:e,index:t}}))({feedback:e,index:r}));try{await _e({endpoint:w,searchQueryId:t,response:e,headers:I,conversationId:Ae}),R?.("accept"===e?"Answer Accepted":"Answer Rejected",{conversationId:Ae,searchQueryId:t})}catch(n){console.error("Error sending feedback:",n),ie((({index:e}={})=>({type:Yt,payload:{index:e}}))({index:r}))}}},Ut=async e=>{const t=void 0!==e?e:de;t.trim()&&(le(t),ue(""),await Dt({searchQuery:t,event:{name:"Follow-up Search Field Submitted"}}))};o(()=>{const e=()=>{new URLSearchParams(window.location.search).get("conversation")||(le(""),ue(""),ge(!1),ie(cr()),Se(0),We(),st.current&&(st.current.style.height="auto"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);const Mt=e=>{R?.("Follow-up Question Clicked",{conversationId:Ae,question:e}),Dt({searchQuery:e,event:{name:"Follow-up Question Clicked"}})},Vt=({action:e,searchQueryId:t,query:r,answer:n})=>{R?.("Next Best Action Clicked",{conversationId:Ae,searchQueryId:t,action:e.label});const a=((e,t)=>({conversationId:t,messages:e.map(e=>({question:e.question,answer:Qt(e.blocks)}))}))(oe,Ae);L?.({action:e,searchQueryId:t,query:r,answer:n,conversation:a})};return o(()=>{const e=it.current;if(!e||!K)return;let t=0,r=null;const n=()=>{const r=(()=>{const t=e.firstElementChild,r=t?.scrollHeight??e.scrollHeight,n=document.querySelector('[data-name="BrandFooter"]')?.clientHeight??0,a=document.querySelector('[data-name="Header"]')?.clientHeight??0,s=fe&&tt?70:0,o=document.querySelector('[data-name="ChatSearch"]')?.clientHeight??0,i=r+n+s+a+32;return fe?Math.max(i,o):i})();r>0&&r!==t&&(t=r,window.parent.postMessage({type:"RESIZE_IFRAME",height:r,widgetKey:h},"*"))},a=setTimeout(n,100),s=new ResizeObserver(()=>{null!==r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{n(),r=null})}),o=e.firstElementChild;return o&&s.observe(o),s.observe(e),()=>{clearTimeout(a),null!==r&&cancelAnimationFrame(r),s.disconnect()}},[K,h,fe,tt]),/* @__PURE__ */e.createElement("div",{className:Z("w-full relative h-dvh flex flex-col justify-between @container","md:h-auto md:p-4 md:bg-dark-100",T),"data-name":"ChatSearch",style:q},
83
+ /* @__PURE__ */e.createElement(nn,{toasts:Qe,onDismiss:Ve}),(O||!fe)&&/* @__PURE__ */e.createElement(Xr,{showHistoryButton:Ue,isSearchWidget:K,"data-name":"Header",headerText:ze.headerText,onToggleSizeButtonClick:()=>{A?.()},onBackButtonClick:()=>{Lt()},onCloseWidgetClick:()=>j?.(),showHistory:ht,hasUnreadConversations:vt,onHistoryButtonClick:()=>ft(!0),onHistoryBackClick:()=>ft(!1),className:Z("@3xl:mb-4",{"!block":fe&&K})}),
84
84
  /* @__PURE__ */e.createElement(Pe,{className:"w-full relative h-auto flex-grow [&>[data-radix-scroll-area-viewport]>div:first-child]:!block",ref:it},
85
- /* @__PURE__ */e.createElement(u,null,ht?/* @__PURE__ */e.createElement(dn,{conversations:gt,isLoading:yt,onSelectConversation:Et}):Oe?/* @__PURE__ */e.createElement(nn,null):fe?/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"results",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.5},className:"w-full max-w-[100vw] space-y-4 p-3 md:p-0"},oe.map((t,r)=>/* @__PURE__ */e.createElement(d.div,{key:r,ref:e=>ot.current[r]=e,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.1*r},className:"space-y-4 last:!mb-8"},
86
- /* @__PURE__ */e.createElement(Mr,{index:r,blocks:t.blocks,question:t.question,attachments:t.attachments,state:t.state,searchResults:t.searchResults,searchQueryId:t.searchQueryId,searchIntentId:t.searchIntentId,hideCitations:H,feedback:t.feedback,onFeedback:e=>{Ft(e,t.searchQueryId,r)},disableFeedback:k,textConfig:ze,redirectRules:Q,nextBestActions:D,actions:t.actions,handleActionClick:Vt,isLastAnswer:r===oe.length-1,onFeedbackReasonSubmit:e=>{(async(e,t)=>{if(b)try{await xe({endpoint:b,searchQueryId:t,reason:e,headers:I})}catch(r){console.error("Error sending feedback reason:",r)}})(e,t.searchQueryId)},hasError:t.hasError,statusMessage:t.statusMessage,knowledgeSourceGroups:ne,onKnowledgeGroupSelect:e=>{zt(e)}}),r===oe.length-1&&!x&&t.followUpQuestions&&"completed"===t.state&&!t.hasError&&/* @__PURE__ */e.createElement(qr,{questions:t.followUpQuestions,onQuestionClick:Mt}))))):/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"search",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:"w-full md:space-y-4"},
85
+ /* @__PURE__ */e.createElement(u,null,ht?/* @__PURE__ */e.createElement(un,{conversations:gt,isLoading:yt,onSelectConversation:Et}):Oe?/* @__PURE__ */e.createElement(an,null):fe?/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"results",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.5},className:"w-full max-w-[100vw] space-y-4 p-3 md:p-0"},oe.map((t,r)=>/* @__PURE__ */e.createElement(d.div,{key:r,ref:e=>ot.current[r]=e,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.1*r},className:"space-y-4 last:!mb-8"},
86
+ /* @__PURE__ */e.createElement(Vr,{index:r,blocks:t.blocks,question:t.question,attachments:t.attachments,state:t.state,searchResults:t.searchResults,searchQueryId:t.searchQueryId,searchIntentId:t.searchIntentId,hideCitations:H,feedback:t.feedback,onFeedback:e=>{Ft(e,t.searchQueryId,r)},disableFeedback:k,textConfig:ze,redirectRules:Q,nextBestActions:D,actions:t.actions,handleActionClick:Vt,isLastAnswer:r===oe.length-1,onFeedbackReasonSubmit:e=>{(async(e,t)=>{if(b)try{await xe({endpoint:b,searchQueryId:t,reason:e,headers:I})}catch(r){console.error("Error sending feedback reason:",r)}})(e,t.searchQueryId)},hasError:t.hasError,statusMessage:t.statusMessage,knowledgeSourceGroups:ne,onKnowledgeGroupSelect:e=>{zt(e)}}),r===oe.length-1&&!x&&t.followUpQuestions&&"completed"===t.state&&!t.hasError&&/* @__PURE__ */e.createElement(Kr,{questions:t.followUpQuestions,onQuestionClick:Mt}))))):/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"search",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:"w-full md:space-y-4"},
87
87
  /* @__PURE__ */e.createElement("div",{className:Z("pb-4",K?"bg-transparent p-3 md:p-0":"px-3 bg-primary md:p-0 md:bg-transparent")},
88
88
  /* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.4}},
89
- /* @__PURE__ */e.createElement(Hr,{ref:ct,query:ce,onQueryChange:e=>{var t;le(e),st.current&&((t=st.current).style.height="auto",t.style.height=`${t.scrollHeight}px`)},onSearch:()=>{(async(e=ce.trim())=>{await Dt({searchQuery:e,event:{name:"Primary Field Search Submitted"}})})()},textConfig:ze,collections:a,currentCollectionId:Ze,onCollectionChange:e=>{Xe(e),c?.(e)},allowedRegions:V,currentRegion:Ye,onRegionChange:e=>{et(e),p?.(e),R?.("Region Changed",{region:e,conversationId:Ae})},apiKey:h,fetchRegionConfig:f,enableFileAttachment:Fe,attachedFiles:Ke,isUploading:Be,onAddFiles:He,onRemoveFile:Ge,isSearching:me,autocompleteSuggestions:mt,onAutocompleteSuggestionSelect:e=>{Dt({searchQuery:e.question,event:{name:"Autocomplete Suggestion Clicked"}})},isAgentAssist:B,includePageEnabled:Nt,includePageLoading:Ct,includePageDisabled:It,onIncludePageToggle:St}))),
90
- /* @__PURE__ */e.createElement(Te,{suggestions:n,onQuestionClick:e=>{if(e.conversationId)return R?.("Recent Conversation Clicked",{conversationId:Ae,question:e.question}),void pt(e.conversationId);Dt({searchQuery:e.question,event:{name:"Suggested Question Clicked"}})},title:ze.suggestionsTitle}),O&&z&&z.length>0&&/* @__PURE__ */e.createElement("div",{className:"mt-4 mb-4 px-3 @3xl:px-0"},/* @__PURE__ */e.createElement("div",{className:"space-y-3"},/* @__PURE__ */e.createElement(Ur,{nextBestActions:z||[],onActionClick:e=>Vt({action:e,searchQueryId:"",query:"",answer:""})})))))),fe&&oe.length>1&&/* @__PURE__ */e.createElement("div",{className:"hidden lg:block"},/* @__PURE__ */e.createElement(Kr,{questions:oe.map(e=>e.question),activeIndex:Ie,onNavigate:e=>{Se(e),_t(e)},offset:C})),N&&O&&!(fe&&tt)&&/* @__PURE__ */e.createElement("div",{"data-name":"disclaimer",className:Z("mt-2 px-3 @3xl:px-0 text-xs text-dark-500 flex items-center gap-1 justify-center text-center w-full md:static md:mt-4 md:text-left md:flex md:gap-4 leading-5",K?"static mb-2 md:text-left [&>svg]:flex-shrink-0":"absolute bottom-12")},
89
+ /* @__PURE__ */e.createElement(Gr,{ref:ct,query:ce,onQueryChange:e=>{var t;le(e),st.current&&((t=st.current).style.height="auto",t.style.height=`${t.scrollHeight}px`)},onSearch:()=>{(async(e=ce.trim())=>{await Dt({searchQuery:e,event:{name:"Primary Field Search Submitted"}})})()},textConfig:ze,collections:a,currentCollectionId:Ze,onCollectionChange:e=>{Xe(e),c?.(e)},allowedRegions:V,currentRegion:Ye,onRegionChange:e=>{et(e),p?.(e),R?.("Region Changed",{region:e,conversationId:Ae})},apiKey:h,fetchRegionConfig:f,enableFileAttachment:Fe,attachedFiles:Ke,isUploading:Be,onAddFiles:He,onRemoveFile:Ge,isSearching:me,autocompleteSuggestions:mt,onAutocompleteSuggestionSelect:e=>{Dt({searchQuery:e.question,event:{name:"Autocomplete Suggestion Clicked"}})},isAgentAssist:B,includePageEnabled:Nt,includePageLoading:Ct,includePageDisabled:It,onIncludePageToggle:St}))),
90
+ /* @__PURE__ */e.createElement(Te,{suggestions:n,onQuestionClick:e=>{if(e.conversationId)return R?.("Recent Conversation Clicked",{conversationId:Ae,question:e.question}),void pt(e.conversationId);Dt({searchQuery:e.question,event:{name:"Suggested Question Clicked"}})},title:ze.suggestionsTitle}),O&&z&&z.length>0&&/* @__PURE__ */e.createElement("div",{className:"mt-4 mb-4 px-3 @3xl:px-0"},/* @__PURE__ */e.createElement("div",{className:"space-y-3"},/* @__PURE__ */e.createElement(Qr,{nextBestActions:z||[],onActionClick:e=>Vt({action:e,searchQueryId:"",query:"",answer:""})})))))),fe&&oe.length>1&&/* @__PURE__ */e.createElement("div",{className:"hidden lg:block"},/* @__PURE__ */e.createElement(Br,{questions:oe.map(e=>e.question),activeIndex:Ie,onNavigate:e=>{Se(e),_t(e)},offset:C})),N&&O&&!(fe&&tt)&&/* @__PURE__ */e.createElement("div",{"data-name":"disclaimer",className:Z("mt-2 px-3 @3xl:px-0 text-xs text-dark-500 flex items-center gap-1 justify-center text-center w-full md:static md:mt-4 md:text-left md:flex md:gap-4 leading-5",K?"static mb-2 md:text-left [&>svg]:flex-shrink-0":"absolute bottom-12")},
91
91
  /* @__PURE__ */e.createElement(se,{iconName:"Info",className:"size-4"}),
92
- /* @__PURE__ */e.createElement(F,{className:"[&_a]:underline [&_a:hover]:no-underline",remarkPlugins:pn,rehypePlugins:hn,components:fn},N)),null!=G&&fe&&!ht&&/* @__PURE__ */e.createElement("div",{className:"-mt-6 w-full max-w-[100vw] px-3 pb-0 pt-0 text-foreground md:px-0"},G),
92
+ /* @__PURE__ */e.createElement(F,{className:"[&_a]:underline [&_a:hover]:no-underline",remarkPlugins:hn,rehypePlugins:fn,components:gn},N)),null!=G&&fe&&!ht&&/* @__PURE__ */e.createElement("div",{className:"-mt-6 w-full max-w-[100vw] px-3 pb-0 pt-0 text-foreground md:px-0"},G),
93
93
  /* @__PURE__ */e.createElement("div",{ref:dt})),fe&&tt&&!wt&&!W&&!ht&&(()=>{const t=oe.some(e=>"awaiting-knowledge-group"===e.state);/* @__PURE__ */
94
- return e.createElement(Wr,{ref:lt,initialQuery:de,onQueryChange:ue,isSearching:me,handleFollowUpSearch:Ut,textConfig:ze,enableFileAttachment:Fe,attachedFiles:Ke,isUploading:Be,onAddFiles:He,onRemoveFile:Ge,disabled:t})})(),fe&&wt&&!W&&!ht&&/* @__PURE__ */e.createElement(un,{onStartNewConversation:()=>Lt()}),!ht&&W)});gn.displayName="ChatSearch";const yn=c(({featureFlags:t,...r},n)=>/* @__PURE__ */e.createElement(fe,{flags:t},/* @__PURE__ */e.createElement(kr,{searchPath:r.searchPath,contentTypeEndpoint:r.contentTypeEndpoint,widgetKey:r.apiKey},
95
- /* @__PURE__ */e.createElement(gn,{...r,ref:n}))));yn.displayName="ChatSearch";export{yn as C,un as R,kr as a,Jr as b,Nr as u};
96
- //# sourceMappingURL=ChatSearch.DLxjq2j8.js.map
94
+ return e.createElement(Jr,{ref:lt,initialQuery:de,onQueryChange:ue,isSearching:me,handleFollowUpSearch:Ut,textConfig:ze,enableFileAttachment:Fe,attachedFiles:Ke,isUploading:Be,onAddFiles:He,onRemoveFile:Ge,disabled:t})})(),fe&&wt&&!W&&!ht&&/* @__PURE__ */e.createElement(mn,{onStartNewConversation:()=>Lt()}),!ht&&W)});yn.displayName="ChatSearch";const vn=c(({featureFlags:t,...r},n)=>/* @__PURE__ */e.createElement(fe,{flags:t},/* @__PURE__ */e.createElement(kr,{searchPath:r.searchPath,contentTypeEndpoint:r.contentTypeEndpoint,widgetKey:r.apiKey},
95
+ /* @__PURE__ */e.createElement(yn,{...r,ref:n}))));vn.displayName="ChatSearch";export{vn as C,Dr as N,mn as R,kr as a,Zr as b,Nr as u,Or as v};
96
+ //# sourceMappingURL=ChatSearch.EPCaUj3O.js.map