@smart-cloud/ai-kit-ui 1.3.11 → 1.3.12

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.
@@ -566,7 +566,6 @@
566
566
  border-top: 1px solid var(--ai-kit-color-border-light);
567
567
  background: var(--ai-kit-chat-surface-subtle);
568
568
  margin-top: auto;
569
- z-index: 1;
570
569
  }
571
570
 
572
571
  /* Responsive tweaks */
package/dist/index.cjs CHANGED
@@ -28,4 +28,4 @@ Guidelines:
28
28
  - caption: optional context users might see below the image; keep short.
29
29
  - description: 1\u20132 short sentences; can include context/usage if known.
30
30
  `+(de?`
31
- Follow these additional instructions: ${de}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),_=await z.run(async({signal:te,onStatus:oe})=>(await(0,j.prompt)({messages:q,images:[Ne],outputLanguage:"en",responseConstraint:dr},{signal:te,onStatus:oe,context:P,modeOverride:o,onDeviceTimeoutOverride:a})).result);if(!_){U("");return}let re=(N&&N!=="auto"?N:null)||yt(),Y=xt(_).trim();try{J("Translating result...");let te=await z.run(async({signal:oe})=>await gr(Y,re,{signal:oe,context:P,modeOverride:o,onDeviceTimeoutOverride:a,silent:!0}));U(te)}catch(te){U(Y),console.warn("AI Kit: failed to parse SEO JSON",te)}break}}}catch(w){xe(w instanceof Error?w.message:r.I18n.get("An unknown error occurred."))}J(void 0)}},[H,z,de,me,N,Re,Fe,P,g,Le,ut,he,Te]),et=(0,B.useCallback)(async()=>{await ze("backend-only")},[ze]),ft=(0,B.useCallback)(o=>{switch(g){case"proofread":return(0,c.jsx)(rt.IconCircleDashedCheck,{className:o});case"translate":return(0,c.jsx)(rt.IconLanguage,{className:o});case"summarize":return(0,c.jsx)(rt.IconSum,{className:o});case"rewrite":case"write":return(0,c.jsx)(rt.IconPencilCode,{className:o});case"generateImageMetadata":case"generatePostMetadata":return(0,c.jsx)(rt.IconSeo,{className:o});default:return(0,c.jsx)(j.AiKitFeatureIcon,{mode:g,className:o})}},[g]),Je=(0,B.useCallback)(()=>{switch(g){case"proofread":return z.lastSource?r.I18n.get("Proofread again"):r.I18n.get("Proofread");case"translate":return z.lastSource?r.I18n.get("Translate again"):r.I18n.get("Translate");case"rewrite":return z.lastSource?r.I18n.get("Rewrite again"):r.I18n.get("Rewrite");case"summarize":return z.lastSource?r.I18n.get("Summarize again"):r.I18n.get("Summarize");default:return z.lastSource?r.I18n.get("Regenerate"):r.I18n.get("Generate")}},[H,z.lastSource,g]),tt=(0,B.useCallback)(()=>{switch(g){case"proofread":return r.I18n.get("Proofread on Backend");case"translate":return r.I18n.get("Translate on Backend");case"rewrite":return r.I18n.get("Rewrite on Backend");case"summarize":return r.I18n.get("Summarize on Backend");default:return r.I18n.get("Regenerate on Backend")}},[H,g]),je=(0,B.useCallback)(async()=>{ue(!1),U(null),xe(null),K.current=!1,z.reset(),G||ke()},[ke,K,z,G]),De=(0,B.useCallback)(async()=>{z.busy&&z.cancel()},[z.busy]);(0,B.useEffect)(()=>{!ye||!m||!he||z.busy||E||K.current||(K.current=!0,queueMicrotask(()=>{ze(fe)}))},[z.busy,K,ye,he,m,E,ze,fe]),(0,B.useEffect)(()=>{Te&&g!=="proofread"&&(he||(_e(!0),K.current=!0))},[Te,he,g]),(0,B.useEffect)(()=>{let o=!0;return(async()=>{try{await(0,j.waitForAiKitReady)();let w=await ua();o&&$e(w)}catch(w){console.error(w),o&&$e(!1)}})(),()=>{o=!1}},[]);let We=(0,B.useMemo)(()=>{let o=[];if(g==="translate"){let w=j.LANGUAGE_OPTIONS.find(q=>q.value===ut)?.label;o.push(r.I18n.get("Input language")+": "+(w?r.I18n.get(w):"auto"))}if(N&&W?.outputLanguage){let w=j.LANGUAGE_OPTIONS.find(q=>q.value===N)?.label;o.push(r.I18n.get("Output language")+": "+(w?r.I18n.get(w):N))}return g==="summarize"&&Le&&W?.type&&o.push(r.I18n.get("Type")+": "+r.I18n.get(Le)),(g==="write"||g==="rewrite")&&Fe&&W?.tone&&o.push(r.I18n.get("Tone")+": "+r.I18n.get(Fe)),(g==="write"||g==="rewrite"||g==="summarize")&&me&&W?.length&&o.push(r.I18n.get("Length")+": "+r.I18n.get(me)),de?.trim()&&W?.instructions&&o.push(r.I18n.get("Instructions")+": \u2713"),o.length?o.join(" \u2022 "):r.I18n.get("No overrides")},[H,g,ut,N,Le,Fe,me,de]),ge={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},Qe=f==="modal"?b.Modal.Root:b.Group,Ee=f==="modal"?b.Modal.Content:b.Group,Kt=f==="modal"?b.Modal.Body:b.Group,Ut=L==="collapse"?b.Collapse:b.Stack,gt=L==="horizontal"?b.Group:b.Stack;return(0,B.useEffect)(()=>{if(!(f!=="modal"||!ye))return document.body.style.overflow="hidden",document.body.onkeydown=o=>{o.key==="Escape"&&(o.preventDefault(),je())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[je,f]),(0,c.jsxs)(c.Fragment,{children:[G&&(0,c.jsx)(b.Button,{leftSection:ie&&(se?(0,c.jsx)("span",{dangerouslySetInnerHTML:{__html:se}}):ft()),className:ce?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:ye,onClick:()=>ue(!0),"data-ai-kit-open-button":!0,children:ce&&r.I18n.get(ne||St)}),ye&&(0,c.jsxs)(Qe,{opened:!0,className:"ai-feature-root",onClose:je,padding:"md",gap:"md",size:"md",portalProps:f==="modal"?{target:be,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Z,"data-ai-kit-variation":f,children:[f==="modal"&&(0,c.jsx)(b.Modal.Overlay,{}),(0,c.jsxs)(Ee,{w:"100%",style:{left:0},children:[f==="modal"&&(0,c.jsxs)(b.Modal.Header,{style:{zIndex:1e3},children:[ft("ai-feature-title-icon"),(0,c.jsx)(b.Modal.Title,{children:r.I18n.get(St)}),(0,c.jsx)(b.Modal.CloseButton,{})]}),(0,c.jsx)(Kt,{w:"100%",style:{zIndex:1001},children:(0,c.jsxs)(Lt,{enabled:f!=="modal",working:z.busy,variation:f,children:[(0,c.jsxs)(b.Stack,{gap:"sm",mb:"sm",p:"sm",children:[Oe&&(0,c.jsx)(b.Alert,{color:"red",children:r.I18n.get(Oe)}),Te&&g!=="proofread"&&(0,c.jsxs)(b.Paper,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":L,children:[(0,c.jsxs)(b.Group,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:L==="collapse"?()=>_e(o=>!o):void 0,children:[L==="collapse"&&(0,c.jsxs)(b.Stack,{gap:0,children:[(0,c.jsx)(b.Text,{size:"sm",fw:600,style:{lineHeight:1.1},children:r.I18n.get("Options")}),(0,c.jsx)(b.Text,{size:"xs",c:"dimmed",style:{marginTop:2},children:We})]}),L==="collapse"&&(0,c.jsx)(b.Button,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:o=>{o.stopPropagation(),_e(w=>!w)},children:wt?r.I18n.get("Hide"):r.I18n.get("Show")})]}),(0,c.jsxs)(Ut,{in:wt,children:[L==="collapse"&&(0,c.jsx)(b.Divider,{my:"sm"}),(0,c.jsxs)(gt,{gap:"xs",justify:"space-between",children:[g==="write"&&W?.text&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The topic or subject for the AI to write about."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.TextInput,{size:"xs",className:"ai-feature-option",styles:ge,disabled:z.busy,label:r.I18n.get("Topic"),description:L!=="horizontal"?r.I18n.get("The topic or subject for the AI to write about."):void 0,value:Re||"",onChange:o=>{let w=o.target.value;we(w),D?.({text:w})}})}),(g==="write"||g==="rewrite"||g==="generateImageMetadata"||g==="generatePostMetadata")&&W?.instructions&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("Additional instructions to guide the AI."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.TextInput,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Instructions"),description:L!=="horizontal"?r.I18n.get("Additional instructions to guide the AI."):void 0,value:de||"",onChange:o=>{let w=o.target.value;st(w),D?.({instructions:w})}})}),g==="translate"&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The language of the input text."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",styles:ge,className:"ai-feature-option",label:r.I18n.get("Input language"),description:L!=="horizontal"?r.I18n.get("The language of the input text."):void 0,data:[{value:"auto",label:r.I18n.get("Auto-detect")},...j.LANGUAGE_OPTIONS.map(o=>({value:o.value,label:r.I18n.get(o.label)})).sort((o,w)=>o.label.localeCompare(w.label))],value:ut||"auto",onChange:o=>{let w=o;pt(w),lt(void 0),D?.({inputLanguage:w})}})}),W?.outputLanguage&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",styles:ge,className:"ai-feature-option",label:r.I18n.get("Output language"),description:L!=="horizontal"?r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[g==="rewrite"?{value:"auto",label:r.I18n.get("Auto-detect")}:void 0].filter(Boolean),...j.LANGUAGE_OPTIONS.map(o=>({value:o.value,label:r.I18n.get(o.label)})).sort((o,w)=>o.label.localeCompare(w.label))],value:N||bn.settings.defaultOutputLanguage||(g==="rewrite"?"auto":""),onChange:o=>{let w=o;dt(w),lt(void 0),D?.({outputLanguage:w})}})}),g==="summarize"&&W?.type&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The summary style to generate."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Type"),description:L!=="horizontal"?r.I18n.get("The summary style to generate."):void 0,data:[{value:"headline",label:r.I18n.get("Headline")},{value:"key-points",label:r.I18n.get("Key Points")},{value:"teaser",label:r.I18n.get("Teaser")},{value:"tldr",label:r.I18n.get("TL;DR")}],value:Le||"key-points",onChange:o=>{let w=o;zt(w),D?.({type:w})}})}),(g==="write"||g==="rewrite")&&W?.tone&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The tone or style for the AI to use."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Tone"),description:L!=="horizontal"?r.I18n.get("The tone or style for the AI to use."):void 0,data:g==="write"?[{value:"neutral",label:r.I18n.get("Neutral")},{value:"formal",label:r.I18n.get("Formal")},{value:"casual",label:r.I18n.get("Casual")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"more-formal",label:r.I18n.get("More formal")},{value:"more-casual",label:r.I18n.get("More casual")}],value:Fe||(g==="write"?"neutral":"as-is"),onChange:o=>{let w=o;pe(w),D?.({tone:w})}})}),(g==="write"||g==="rewrite"||g==="summarize")&&W?.length&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The target output length."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Length"),description:L!=="horizontal"?r.I18n.get("The target output length."):void 0,data:g==="write"||g==="summarize"?[{value:"short",label:r.I18n.get("Short")},{value:"medium",label:r.I18n.get("Medium")},{value:"long",label:r.I18n.get("Long")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"shorter",label:r.I18n.get("Shorter")},{value:"longer",label:r.I18n.get("Longer")}],value:me||(g==="rewrite"?"as-is":"short"),onChange:o=>{let w=o;Ze(w),D?.({length:w})}})}),g==="summarize"||g==="write"||g==="rewrite"&&W?.outputFormat&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The format for the generated output."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Output format"),description:L!=="horizontal"?r.I18n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:r.I18n.get("Plain Text")},{value:"markdown",label:r.I18n.get("Markdown")},{value:"html",label:r.I18n.get("HTML")}],value:F||"markdown",onChange:o=>{let w=o;ht(w),D?.({outputFormat:w})}})})]})]})]}),z.busy&&ct&&(0,c.jsx)(Lt,{enabled:f==="modal",working:!0,variation:f,children:(0,c.jsxs)(b.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,c.jsx)(b.Loader,{size:"sm"}),(0,c.jsx)(b.Input.Label,{className:"ai-feature-status-text",children:ct})]})}),E&&(0,c.jsxs)(b.Stack,{mt:"md",children:[g==="proofread"&&(E.corrections.length===0?(0,c.jsx)(b.Alert,{color:"green",children:r.I18n.get("No issues found. Your text looks great!")}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("p",{style:{marginTop:0,opacity:.85},children:r.I18n.get("Hover highlights to see explanations.")}),(0,c.jsx)(gn,{original:Re,corrections:E.corrections}),E.correctedInput?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("h4",{style:{marginTop:16,marginBottom:8},children:r.I18n.get("Corrected")}),(0,c.jsx)(b.Group,{c:"pre",className:"ai-feature-generated-content",children:E.correctedInput})]}):null]})),g==="generateImageMetadata"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Alt Text"),description:r.I18n.get("The alt text for the image."),value:E.alt_text||"",onChange:o=>U({...E,alt_text:o.target.value})}),(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the image."),value:E.title||"",onChange:o=>U({...E,title:o.target.value})}),(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Caption"),description:r.I18n.get("The caption for the image."),value:E.caption||"",onChange:o=>U({...E,caption:o.target.value})}),(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Description"),description:r.I18n.get("The description for the image."),value:E.description||"",onChange:o=>U({...E,description:o.target.value})})]}),g==="generatePostMetadata"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the post."),value:E.title||"",onChange:o=>U({...E,title:o.target.value})}),(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Excerpt"),description:r.I18n.get("The excerpt for the post."),value:E.excerpt||"",onChange:o=>U({...E,excerpt:o.target.value})})]}),g!=="proofread"&&g!=="generateImageMetadata"&&g!=="generatePostMetadata"&&typeof E=="string"&&(0,c.jsx)(yn,{value:E,editable:!!l,onChange:o=>{U(o)}})]}),E===""&&(0,c.jsx)(yn,{value:E,editable:!1})]}),(0,c.jsxs)(b.Group,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[z.busy&&(0,c.jsx)(b.Button,{variant:"outline",size:"sm",onClick:De,"data-ai-kit-cancel-button":!0,children:r.I18n.get("Cancel")}),!z.busy&&(0,c.jsx)(b.Button,{variant:"filled",size:"sm",disabled:!he,onClick:()=>ze(),"data-ai-kit-generate-button":!0,children:Je()}),!z.busy&&z.lastSource==="on-device"&&it&&Ue&&(0,c.jsx)(b.Button,{variant:"filled",size:"sm",disabled:!he,onClick:et,"data-ai-kit-regenerate-on-backend-button":!0,children:tt()}),!z.busy&&T&&(0,c.jsx)(b.Button,{variant:"outline",size:"sm",disabled:!E||g==="proofread"&&E.corrections.length===0,onClick:async()=>{T(F==="html"?await ea(E):E),je()},"data-ai-kit-accept-button":!0,children:r.I18n.get(le)}),(0,c.jsx)(b.Button,{variant:"default",size:"sm",onClick:je,"data-ai-kit-close-button":!0,children:r.I18n.get("Close")})]}),(0,c.jsx)(Jt,{variation:f})]})})]})]})]})};function yn(e){let{value:n,editable:m,onChange:l}=e;return m?(0,c.jsxs)(b.Stack,{p:0,gap:"sm",children:[(0,c.jsx)(b.Input.Label,{children:r.I18n.get("Generated content")}),(0,c.jsx)(b.Textarea,{value:n,onChange:a=>l?.(a.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),(0,c.jsx)(b.Input.Label,{children:r.I18n.get("Preview")}),(0,c.jsx)(b.Stack,{className:"ai-feature-generated-content ai-feature-preview",children:(0,c.jsx)(ma.default,{remarkPlugins:[pa.default],children:n})})]}):(0,c.jsx)(b.Stack,{className:"ai-feature-generated-content",children:n?(0,c.jsx)(ma.default,{remarkPlugins:[pa.default],children:n}):(0,c.jsx)(b.Alert,{color:"yellow",children:r.I18n.get("No content generated.")})})}var An=At(pr);var k=require("@mantine/core"),ve=require("@tabler/icons-react"),Et=require("@smart-cloud/ai-kit-core"),Tn=require("@wordpress/data"),S=require("aws-amplify/utils"),i=require("react"),wn=Ye(require("react-markdown"),1),Sn=Ye(require("remark-gfm"),1);var hr="ai-kit-chatbot-attachments",ot="attachments";var ha=null;function fr(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function ta(){if(!fr())return null;ha||(ha=new Promise(e=>{try{let n=window.indexedDB.open(hr,1);n.onerror=()=>e(null),n.onblocked=()=>e(null),n.onupgradeneeded=()=>{let m=n.result;m.objectStoreNames.contains(ot)||m.createObjectStore(ot,{keyPath:"id"})},n.onsuccess=()=>e(n.result)}catch(n){console.warn("[AiChatbot] IndexedDB is not available",n),e(null)}}));try{return await ha}catch(e){return console.warn("[AiChatbot] Failed to open attachment store",e),null}}async function fa(e,n){let m=await ta();return m?new Promise((l,a)=>{try{let f=m.transaction(ot,e),I=f.objectStore(ot),G=n(I);f.oncomplete=()=>l(G),f.onerror=()=>a(f.error),f.onabort=()=>a(f.error)}catch(f){a(f)}}).catch(l=>(console.warn("[AiChatbot] Attachment store transaction failed",l),null)):null}async function ka(e,n,m){await Ar();let l={id:e,blob:n,name:m.name,type:m.type,size:m.size,createdAt:Date.now()};return await fa("readwrite",f=>(f.put(l),e))}async function ba(e){let n=await ta();return n?new Promise((m,l)=>{try{let a=n.transaction(ot,"readonly"),f=a.objectStore(ot).get(e);f.onsuccess=()=>{let I=f.result;m(I??null)},f.onerror=()=>l(f.error),a.onabort=()=>l(a.error)}catch(a){l(a)}}).catch(m=>(console.warn("[AiChatbot] Failed to load attachment",m),null)):null}async function kr(e){await fa("readwrite",n=>{n.delete(e)})}async function aa(){await fa("readwrite",e=>{e.clear()})}async function ya(e){let n=await ta();n&&await new Promise((m,l)=>{try{let a=n.transaction(ot,"readwrite"),f=a.objectStore(ot),I=f.getAllKeys();I.onsuccess=()=>{let G=I.result;for(let ce of G){let ie=String(ce);e.has(ie)||f.delete(ce)}},I.onerror=()=>l(I.error),a.oncomplete=()=>m(),a.onerror=()=>l(a.error),a.onabort=()=>l(a.error)}catch(a){l(a)}}).catch(m=>{console.warn("[AiChatbot] Failed to cleanup attachments",m)})}var br=50*1024*1024;async function yr(){let e=await ta();return e?new Promise((n,m)=>{try{let l=e.transaction(ot,"readonly"),a=l.objectStore(ot).getAll();a.onsuccess=()=>{let f=a.result||[];n(f)},a.onerror=()=>m(a.error),l.onerror=()=>m(l.error),l.onabort=()=>m(l.error)}catch(l){m(l)}}).catch(n=>(console.warn("[AiChatbot] Failed to get all attachments",n),[])):[]}async function Ar(){let e=await yr();if(e.length===0)return;let n=e.sort((f,I)=>f.createdAt-I.createdAt),m=n.reduce((f,I)=>f+I.size,0),l=[],a=0;for(;m>br&&a<n.length;){let f=n[a];f&&(l.push(f.id),m-=f.size),a++}for(let f of l)await kr(f);l.length>0&&console.log(`[AiChatbot] Deleted ${l.length} old attachment(s) to enforce storage quota`)}var s=require("react/jsx-runtime");S.I18n.putVocabularies(bt);var na=1440*60*1e3,Aa=!1,vr=1,Tr="localstorage",Mt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,oa={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function vt(e){return`${e}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var wr=4,Sr=5*1024*1024,Rr=e=>{let n=(e?.name||"").toString(),m=(e?.code||"").toString(),l=(e?.message||"").toString();return n==="AbortError"||m==="ABORT_ERR"||/abort|aborted|cancel/i.test(l)},Ir=(e,n)=>{if(!e)return null;let m=e.step,l=S.I18n.get((e.message??"").trim()),a=typeof e.progress=="number"?e.progress:null,f=a==null?null:Math.round(a*100);switch(m){case"decide":return l||S.I18n.get("Checking capabilities...");case"on-device:init":return l||S.I18n.get("Initializing on-device AI...");case"on-device:download":return f==null?l||S.I18n.get("Downloading model..."):l||`${S.I18n.get("Downloading model...")} ${f}%`;case"on-device:ready":return l||S.I18n.get("On-device model ready...");case"on-device:run":return l||S.I18n.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return S.I18n.get(n.assistantThinkingLabel??oa.assistantThinkingLabel);case"done":return l||S.I18n.get("Done.");case"error":return l||S.I18n.get("An error occurred.");default:return l||null}};function va(e){if(typeof window>"u")return null;try{return e==="localstorage"?window.localStorage:e==="sessionstorage"?window.sessionStorage:null}catch{return null}}var Dt=e=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(e)}catch{return null}},ra=e=>{if(e&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(e)}catch{}},Rn=e=>{!e||e.length===0||e.forEach(n=>ra(n.objectUrl))},vn=e=>{e.forEach(n=>Rn(n.attachments))},zr=e=>{let{rootElement:n,store:m,previewMode:l,title:a,openButtonTitle:f,openButtonIcon:I,showOpenButtonTitle:G=!0,showOpenButtonIcon:ce=!0,colorMode:ie,language:ne,onClose:se,context:Ue,placeholder:le,maxImages:L,maxImageBytes:g,historyStorage:P=Tr,emptyHistoryAfterDays:fe=vr,labels:Z,openButtonIconLayout:ae="top",openButtonPosition:ke="bottom-right"}=e,T=(0,i.useMemo)(()=>({...oa,...Z||{}}),[Z]),D=It(),[H,be]=(0,i.useState)(""),[W,Te]=(0,i.useState)([]),[M,J]=(0,i.useState)(null),[ye,ue]=(0,i.useState)(!1),[wt,_e]=(0,i.useState)(0),it=(0,i.useRef)(null),$e=(0,i.useRef)([]),Oe=(0,i.useRef)(null),xe=(0,i.useRef)(null),E=(0,i.useRef)(null),[U,Re]=(0,i.useState)([]),[we,Ne]=(0,i.useState)(null),[de,st]=(0,i.useState)(!1),[Ie,lt]=(0,i.useState)(!1),[ut,pt]=(0,i.useState)(!1),[F,ht]=(0,i.useState)(!1),[N,dt]=(0,i.useState)(!0),[me,Ze]=(0,i.useState)(null),[Fe,pe]=(0,i.useState)(!1),[Le,zt]=(0,i.useState)(null),[K,St]=(0,i.useState)(null),[Bt,Pe]=(0,i.useState)(!1),[he,z]=(0,i.useState)(null),ct=(0,i.useRef)(he);(0,i.useEffect)(()=>{ct.current=he},[he]);let ze=(0,i.useRef)(null),et=(0,i.useRef)(!1),[ft,Je]=(0,i.useState)(null),tt=(0,i.useRef)(null),je=(0,i.useRef)(null),De=(0,i.useRef)(null),We=(0,i.useRef)(null),ge=(0,i.useCallback)(t=>{t.forEach(d=>ra(d.objectUrl))},[]),Qe=(0,i.useCallback)(()=>{ge(re.current),Te([]),tt.current&&(tt.current.value="")},[ge]),Ee=(0,i.useCallback)(()=>{Y.current&&ra(Y.current.objectUrl),J(null),$e.current=[],_e(0)},[]),Kt=(0,i.useCallback)(async()=>{try{be(""),Ee();let t=await navigator.mediaDevices.getUserMedia({audio:!0}),d=new MediaRecorder(t,{mimeType:"audio/webm"}),v=new AudioContext,u=v.createMediaStreamSource(t),C=v.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.8,u.connect(C),Oe.current=v,xe.current=C;let R=new Uint8Array(C.fftSize),O=()=>{if(!xe.current)return;xe.current.getByteTimeDomainData(R);let ee=0;for(let Ge=0;Ge<R.length;Ge++){let Rt=(R[Ge]-128)/128;ee+=Rt*Rt}let Ce=Math.sqrt(ee/R.length),Ke=Math.min(100,Ce*200);_e(Ke),E.current=requestAnimationFrame(O)};O(),$e.current=[];let V=Date.now();d.ondataavailable=ee=>{ee.data.size>0&&$e.current.push(ee.data)},d.onstop=()=>{let ee=new Blob($e.current,{type:"audio/webm"}),Ce=(Date.now()-V)/1e3,Ke=Dt(ee);Ke&&J({id:vt("composer-audio"),blob:ee,objectUrl:Ke,duration:Ce}),t.getTracks().forEach(Ge=>Ge.stop()),E.current&&(cancelAnimationFrame(E.current),E.current=null),Oe.current&&(Oe.current.close(),Oe.current=null),xe.current=null,_e(0)},it.current=d,d.start(),ue(!0)}catch(t){console.error("Failed to start recording:",t)}},[Ee]),Ut=(0,i.useCallback)(()=>{it.current&&ye&&(it.current.stop(),ue(!1))},[ye]);(0,i.useEffect)(()=>()=>{E.current&&cancelAnimationFrame(E.current),Oe.current&&Oe.current.close(),Ee()},[Ee]);let[gt,o]=(0,i.useState)(null),w=(0,i.useRef)(H),q=(0,i.useRef)(U),_=(0,i.useRef)(gt),re=(0,i.useRef)(W),Y=(0,i.useRef)(M);(0,i.useEffect)(()=>{w.current=H},[H]),(0,i.useEffect)(()=>{re.current=W},[W]),(0,i.useEffect)(()=>{Y.current=M},[M]),(0,i.useEffect)(()=>{q.current=U},[U]),(0,i.useEffect)(()=>{_.current=gt},[gt]),(0,i.useEffect)(()=>{ne&&S.I18n.setLanguage(ne||"en")},[ne]);let te=(0,Tn.useSelect)(()=>(0,Et.getStoreSelect)(m).isShowChatbotPreview()),oe=(0,i.useMemo)(()=>Math.max(0,L??wr),[L]),qe=(0,i.useMemo)(()=>Math.max(0,g??Sr),[g]),h=U.length>0,A=(0,i.useMemo)(()=>D.busy&&he==="chat",[D.busy,he]),Q=(0,i.useMemo)(()=>A?!1:H.trim().length>0||M!==null,[H,A,M]),X=(0,i.useMemo)(()=>{let t=f||T.askMeLabel;return S.I18n.get(t)},[f,T.askMeLabel,ne]),Se=(0,i.useMemo)(()=>{let t=a||T.modalTitle;return S.I18n.get(t)},[a,T.modalTitle,ne]),Be=(0,i.useMemo)(()=>{let t=le||T.placeholder;return S.I18n.get(t)},[le,T.placeholder,ne]),at=(0,i.useMemo)(()=>{let t="ai-docs-ask",d=`ai-open-btn--${ke}`;return`${t} ${d}`},[ke]),Ae=(0,i.useCallback)(()=>{let t=We.current;if(t)try{let d=window.innerHeight||document.documentElement.clientHeight,v=360,u=1e3,C=Math.floor(d*.8),R=Math.max(v,Math.min(C,u));t.style.height=`${R}px`}catch{}},[]),mt=(0,i.useCallback)(()=>{let t=K;t&&window.setTimeout(()=>{try{t.scrollTop=t.scrollHeight}catch{}},50)},[K]),Ft=(0,i.useCallback)(()=>{ht(!1),Ie&&lt(!1),pt(!1),se?.()},[Ie,se]);(0,i.useEffect)(()=>{if(F)return Ae(),window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[F,Ae]),(0,i.useEffect)(()=>{if(!(!F||!Ie))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[F,Ie,Ft]);let Ct=(0,i.useMemo)(()=>W.map(t=>({id:t.id,url:t.objectUrl,title:t.file.name})),[W]);(0,i.useEffect)(()=>{h||dt(!0)},[h]),(0,i.useEffect)(()=>()=>{ge(re.current)},[ge]),(0,i.useEffect)(()=>{let t=K;if(!t)return;let d=()=>{let v=t.scrollHeight-(t.scrollTop+t.clientHeight);dt(v<20)};return t.addEventListener("scroll",d),()=>{t.removeEventListener("scroll",d)}},[F,K]),(0,i.useEffect)(()=>{if(!N)return;let t=K;t&&t.scrollHeight>t.clientHeight&&(t.scrollTop=t.scrollHeight)},[U,D.busy,N,K]),(0,i.useEffect)(()=>{F||Ze(null)},[F]);let Ot=(0,i.useMemo)(()=>D.busy?Ir(D.statusEvent,T)||S.I18n.get("Working\u2026"):null,[D.busy,D.statusEvent,ne,T]),Mn=(0,i.useMemo)(()=>{for(let t=U.length-1;t>=0;t--){let d=U[t];if(d.role==="user"&&d.clientStatus==="canceled")return d.id}return null},[U]),Nt=(0,i.useCallback)(t=>{Re(d=>{let v=[...d].map((R,O)=>({m:R,i:O})).reverse().find(R=>R.m.role==="user"&&R.m.clientStatus==="pending")?.i;if(v==null)return d;let u=d.slice(),C=u[v];return u[v]={...C,clientStatus:t??void 0},u})},[Re]),Wt=(0,i.useCallback)(()=>{if(!(!D.busy||ct.current!=="chat")){et.current=!0;try{D.cancel()}catch{}Nt("canceled"),z(null),Ne(null),mt()}},[D,Nt,mt]),Dn=(0,i.useCallback)(t=>{let d=re.current,v=Array.from(t.target.files||[]),u=Math.max(0,oe-d.length);if(u===0){t.currentTarget.value="";return}let C=[];for(let R of v){if(C.length>=u)break;let O=/image\/(jpeg|png|gif|webp)/i.test(R.type),V=R.size<=qe,ee=[...d,...C].some(Ke=>Ke.file.name===R.name&&Ke.file.size===R.size&&Ke.file.lastModified===R.lastModified);if(!O||!V||ee)continue;let Ce=Dt(R);Ce&&C.push({id:vt("composer-image"),file:R,objectUrl:Ce})}C.length&&Te(R=>[...R,...C]),t.currentTarget.value=""},[oe,qe]),En=(0,i.useCallback)(t=>{Te(d=>{if(t<0||t>=d.length)return d;let v=d[t];return v&&ra(v.objectUrl),d.filter((u,C)=>C!==t)})},[]),kt=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(we)return kt.current&&(window.clearTimeout(kt.current),kt.current=null),kt.current=window.setTimeout(()=>{Ne(null),kt.current=null},6e3),()=>{kt.current&&(window.clearTimeout(kt.current),kt.current=null)}},[we]);let Ta=(0,i.useCallback)(async(t,d)=>{let v=P!=="nostorage",u=[];if(t.length>0){let C=await Promise.all(t.map(async R=>{let O=vt("attachment-image"),V;if(v)try{V=await ka(O,R.file,{name:R.file.name,type:R.file.type,size:R.file.size})??void 0}catch(Ce){console.warn("[AiChatbot] Failed to persist image",Ce)}let ee=Dt(R.file);return{id:O,name:R.file.name,type:R.file.type||"application/octet-stream",size:R.file.size,blobId:V,objectUrl:ee??void 0,blob:R.file,mediaType:"image"}}));u.push(...C.filter(Boolean))}if(d){let C=vt("attachment-audio"),R;if(v)try{R=await ka(C,d.blob,{name:`audio-${Date.now()}.webm`,type:d.blob.type,size:d.blob.size})??void 0}catch(V){console.warn("[AiChatbot] Failed to persist audio",V)}let O=Dt(d.blob);u.push({id:C,name:`audio-${Date.now()}.webm`,type:d.blob.type||"audio/webm",size:d.blob.size,blobId:R,objectUrl:O??void 0,blob:d.blob,duration:d.duration,mediaType:"audio"})}return u},[P]),wa=(0,i.useCallback)(async t=>{let d=[];for(let v of t){let u;if(v.attachments&&v.attachments.length>0){u=[];for(let C of v.attachments){let R;if(C.blobId)try{R=(await ba(C.blobId))?.blob??void 0}catch(V){console.warn("[AiChatbot] Failed to hydrate attachment",V)}if(!R)continue;let O=R?Dt(R):null;u.push({...C,objectUrl:O??void 0,blob:R??void 0})}}d.push({...v,attachments:u})}return d},[]),Sa=(0,i.useCallback)(async t=>{if(!t||t.length===0){Qe();return}let d=[];for(let v of t){let u=v.blob;if(!u&&v.blobId)try{u=(await ba(v.blobId))?.blob??void 0}catch(O){console.warn("[AiChatbot] Failed to reload attachment",O)}if(!u)continue;let C=u instanceof File?u:new File([u],v.name||"attachment",{type:v.type||u.type||"application/octet-stream"}),R=Dt(C);if(R&&(d.push({id:vt("composer-image"),file:C,objectUrl:R}),d.length>=oe))break}if(d.length===0){Qe();return}Te(v=>(ge(v),d)),tt.current&&(tt.current.value="")},[Qe,ge,oe]),ia=(0,i.useCallback)((t,d)=>{t&&Ze({url:t,title:d})},[]),Bn=(0,i.useCallback)(()=>{Ze(null)},[]),Ra=(0,i.useCallback)(()=>{vn(q.current),Qe(),Ee(),Re([]),Ne(null),De.current=null,o(null),dt(!0),st(!1);let t=va(P);if(t)try{t.removeItem(Mt)}catch{}aa()},[Qe,Ee,P]),Kn=(0,i.useCallback)(()=>{st(!0)},[]),Un=(0,i.useCallback)(()=>{D.busy&&ct.current==="chat"&&Wt(),Ra()},[D.busy,Wt,Ra]),Ia=(0,i.useCallback)(()=>{st(!1)},[]),za=(0,i.useCallback)(async(t,d)=>{if(!D.busy)try{let v=De.current&&Date.now()-De.current.storedAt<fe*na?De.current.id:void 0;if(!v)return;z("feedback"),Ne(null),await D.run(async({signal:u,onStatus:C})=>(await(0,Et.sendFeedbackMessage)({sessionId:v,feedbackMessageId:t,feedbackType:d},{signal:u,onStatus:C,context:Ue}),null)),Ne(null)}catch(v){let u=v?.message?.trim()||S.I18n.get("An error occurred.");Ne(u),console.error("Failed to send feedback",v)}finally{z(v=>v==="feedback"?null:v)}},[D,ne]),Ca=(0,i.useCallback)((t,d)=>{Re(v=>v.map(u=>u.id!==t||u.role!=="assistant"?u:u.feedback===d?{...u,feedback:void 0}:{...u,feedback:d})),za(t,d)},[za]),qt=(0,i.useCallback)(async()=>{let t=w.current.trim(),d=Y.current;if(!t&&!d||D.busy)return;et.current=!1,Ne(null),z("chat");let v=[...re.current],u=await Ta(v,d),C=vt("user"),R=Date.now(),O={id:C,role:"user",content:t||(d?"[Audio message]":""),createdAt:R,clientStatus:"pending",attachments:u.length?u:void 0};be(""),Qe(),Ee(),Re(V=>[...V,O]),F||ht(!0),mt();try{let V=De.current&&Date.now()-De.current.storedAt<fe*na?De.current.id:void 0,ee=await D.run(async({signal:Ke,onStatus:Ge})=>await(0,Et.sendChatMessage)({sessionId:V,message:t||void 0,audio:d?.blob,images:v.map(_n=>_n.file)},{signal:Ke,onStatus:Ge,context:Ue}));if(et.current){Nt("canceled");return}if(!ee)throw new Error(S.I18n.get(D.error??T.emptyResponseLabel));ee.sessionId&&(De.current={id:ee.sessionId,storedAt:Date.now()});let Ce={id:ee.metadata?.messageId||vt("assistant"),role:"assistant",content:ee.result||"",citations:ee.citations,createdAt:Date.now()};Re(Ke=>[...Ke.map(Rt=>Rt.id===C?{...Rt,clientStatus:void 0}:Rt),Ce]),o(R)}catch(V){if(console.error("Error during ask()",V),et.current||Rr(V)){Nt("canceled");return}let ee=V?.message?.trim()||S.I18n.get(T.unexpectedErrorLabel);Re(Ce=>[...Ce.map(Ge=>Ge.id===C?{...Ge,clientStatus:void 0}:Ge),{id:vt("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${ee}`,createdAt:Date.now()}]),o(R)}finally{z(V=>V==="chat"?null:V),et.current=!1,je.current&&je.current.focus(),mt()}},[D,Ta,Qe,Ee,F,mt,Nt,T.emptyResponseLabel,T.unexpectedErrorLabel,ne]),On=(0,i.useCallback)(t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Q&&qt())},[qt,Q]),Nn=(0,i.useCallback)(()=>{ht(!0)},[]);(0,i.useEffect)(()=>()=>{ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null)},[]);let jn=(0,i.useCallback)(()=>{lt(t=>{let d=!t;return ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null),d?(pt(!0),requestAnimationFrame(()=>{ze.current=requestAnimationFrame(()=>{pt(!1),ze.current=null})})):pt(!1),d})},[]),Gn=(0,i.useCallback)(t=>{be(t.content),(async()=>(await Sa(t.attachments),Re(d=>d.filter(v=>v.id!==t.id)),Rn(t.attachments),queueMicrotask(()=>je.current?.focus())))()},[Sa]),xa=(0,i.useMemo)(()=>ce?I?(0,s.jsx)("img",{src:I,className:"ai-open-btn-icon",alt:S.I18n.get(T.askMeLabel||X)}):(0,s.jsx)(ve.IconMessage,{size:18}):null,[ce,I,T,X,ne]),Hn=(0,i.useMemo)(()=>{let t=xa,d=G?(0,s.jsx)(k.Text,{inherit:!0,children:X}):null;if(!ce&&!d)return null;if(!ce)return d;if(!G)return t;switch(ae){case"top":return(0,s.jsxs)(k.Stack,{gap:4,align:"center",children:[t,d]});case"bottom":return(0,s.jsxs)(k.Stack,{gap:4,align:"center",children:[d,t]});case"right":return(0,s.jsxs)(k.Group,{gap:6,align:"center",children:[d,t]});default:return(0,s.jsxs)(k.Group,{gap:6,align:"center",children:[t,d]})}},[xa,ce,G,X,ae]),Fn=(0,i.useMemo)(()=>A,[A]),Wn=(0,i.useMemo)(()=>!A,[A]),qn=(0,i.useMemo)(()=>we||(h?S.I18n.get(T.readyLabel):S.I18n.get(T.readyEmptyLabel)),[we,h,T.readyLabel,T.readyEmptyLabel,ne]),Yn=(0,i.useMemo)(()=>A?S.I18n.get(T.cancelLabel):S.I18n.get(T.sendLabel),[A,T.cancelLabel,T.sendLabel,ne]),Vn=(0,i.useMemo)(()=>A?(0,s.jsx)(ve.IconPlayerStop,{size:18}):(0,s.jsx)(ve.IconSend,{size:18}),[A]),Jn=(0,i.useCallback)(()=>{if(A){Wt();return}qt()},[A,Wt,qt]);return(0,i.useEffect)(()=>{if(!F||!Le||!K)return;let t=()=>{let V=window.getComputedStyle(K).overflowY,ee=V==="auto"||V==="scroll",Ce=Math.ceil(K.scrollHeight),Ke=Math.floor(K.clientHeight),Ge=Ce>Ke;return ee&&Ge},d=!1,v=O=>{if(!t())return;O.preventDefault();let V=K.scrollHeight-K.clientHeight;K.scrollTop=Math.max(0,Math.min(V,K.scrollTop+O.deltaY))},u=()=>{let O=t();Pe(O),O!==d&&(d=O,d?Le.addEventListener("wheel",v,{passive:!1}):Le.removeEventListener("wheel",v))};u();let C=new ResizeObserver(u);C.observe(K);let R=new MutationObserver(u);return R.observe(K,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",u),()=>{d&&Le.removeEventListener("wheel",v),C.disconnect(),R.disconnect(),window.removeEventListener("resize",u)}},[F,Le,K]),(0,i.useEffect)(()=>{let t=!1,d=va(P);if(!d){P==="nostorage"&&aa(),pe(!0);return}return(async()=>{try{let v=d.getItem(Mt);if(!v){pe(!0);return}let u=JSON.parse(v),C=typeof u?.lastUserSentAt=="number"?u.lastUserSentAt:null;if(!C||Date.now()-C>fe*na){d.removeItem(Mt),await aa(),pe(!0);return}let O=(Array.isArray(u.messages)?u.messages:[]).map(ee=>ee?.role==="user"&&ee.clientStatus==="pending"?{...ee,clientStatus:"canceled"}:ee),V=await wa(O);if(t){vn(V);return}Re(V),o(C),u.session&&u.session.id&&(De.current=u.session)}catch(v){console.warn("[AiChatbot] Failed to load history",v);try{d.removeItem(Mt)}catch{}}finally{t||pe(!0)}})(),()=>{t=!0}},[P,fe,wa]),(0,i.useEffect)(()=>{if(!Fe)return;let t=va(P);if(!t)return;let d=_.current;if(!d)return;if(Date.now()-d>fe*na){try{t.removeItem(Mt)}catch{}ya(new Set);return}let v=U.map(({attachments:R,...O})=>({...O,attachments:R?.map(({objectUrl:V,blob:ee,...Ce})=>Ce)})),u={version:1,lastUserSentAt:d,session:De.current,messages:v};try{t.setItem(Mt,JSON.stringify(u))}catch{}let C=new Set;v.forEach(R=>{R.attachments?.forEach(O=>{O.blobId&&C.add(O.blobId)})}),ya(C)},[Fe,U,gt,P,fe]),l&&!te||!l&&te?null:(0,s.jsxs)(k.Group,{className:at,children:[!F&&(0,s.jsx)(k.Button,{variant:"filled",className:G?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:Nn,"aria-label":X,title:X,"data-ai-kit-open-button":!0,children:Hn}),F&&(0,s.jsx)(k.Modal.Root,{ref:We,opened:F,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:Ft,className:at+" ai-chat-container"+(Ie?" maximized":"")+(Ie&&ut?" ai-max-enter":""),portalProps:{target:n,reuseTargetNode:!0},"data-ai-kit-theme":ie,"data-ai-kit-variation":"modal",children:(0,s.jsxs)("div",{className:"ai-chat-container-internal",ref:zt,children:[(0,s.jsxs)(k.Modal.Header,{className:"ai-chat-header-bar",children:[(0,s.jsx)(k.Modal.Title,{className:"ai-chat-title",children:Se}),(0,s.jsxs)(k.Group,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&(0,s.jsx)(k.ActionIcon,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:jn,title:Ie?S.I18n.get(T.restoreSizeLabel):S.I18n.get(T.maximizeLabel),"aria-label":Ie?S.I18n.get(T.restoreSizeLabel):S.I18n.get(T.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Ie?(0,s.jsx)(ve.IconMinimize,{size:16}):(0,s.jsx)(ve.IconMaximize,{size:16})}),(0,s.jsx)(k.Modal.CloseButton,{"aria-label":S.I18n.get(T.closeChatLabel)})]})]}),(0,s.jsxs)(k.Modal.Body,{className:"ai-chat-scroll",ref:St,"data-scrollable":Bt?"true":"false",children:[U.map(t=>{let d=t.role==="user",v=d&&t.clientStatus==="canceled"&&t.id===Mn;return(0,s.jsx)(k.Group,{justify:d?"flex-end":"flex-start",className:"ai-chat-row "+t.role,onMouseEnter:()=>Je(t.id),onMouseLeave:()=>Je(u=>u===t.id?null:u),children:(0,s.jsxs)(k.Stack,{gap:4,w:"100%",style:{alignItems:d?"flex-end":"flex-start"},children:[(0,s.jsxs)(k.Stack,{className:"ai-chat-bubble",children:[(0,s.jsxs)(k.Text,{className:"ai-chat-header",children:[(0,s.jsx)(k.Text,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:d?S.I18n.get(T.userLabel):S.I18n.get(T.assistantLabel)}),"\xA0",(0,s.jsx)(k.Text,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(t.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),t.role==="assistant"?(0,s.jsx)(wn.default,{remarkPlugins:[Sn.default],children:t.content}):(0,s.jsx)(k.Text,{size:"sm",miw:"100px",children:t.content})]}),t.attachments&&t.attachments.length>0&&(0,s.jsxs)(k.Stack,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).length>0&&(0,s.jsx)(k.Group,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).map(u=>(0,s.jsx)("button",{type:"button",className:"thumb",style:{backgroundImage:u.objectUrl?`url(${u.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>ia(u.objectUrl,u.name),disabled:!u.objectUrl,title:u.name||S.I18n.get("View image"),"aria-label":u.name||S.I18n.get("View image"),children:!u.objectUrl&&(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:S.I18n.get("Image no longer available")})},u.id))}),t.attachments.filter(u=>u.mediaType==="audio"||!u.mediaType&&u.type.startsWith("audio/")).map(u=>(0,s.jsx)(k.Box,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:u.objectUrl?(0,s.jsxs)(k.Stack,{gap:"xs",children:[(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:u.objectUrl,preload:"metadata"}),u.duration&&(0,s.jsxs)(k.Text,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(u.duration),"s"]})]}):(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:S.I18n.get("Audio no longer available")})},u.id))]}),v&&(0,s.jsxs)(k.Group,{justify:"flex-end",gap:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:S.I18n.get(T.notSentLabel)})}),ft===t.id&&(0,s.jsx)(k.ActionIcon,{size:"sm",variant:"subtle",onClick:()=>Gn(t),title:S.I18n.get(T.editLabel),"aria-label":S.I18n.get(T.editLabel),"data-ai-kit-edit-button":!0,children:(0,s.jsx)(ve.IconPencil,{size:14})})]}),t.citations&&t.citations.length>0&&(0,s.jsxs)(k.Stack,{className:"ai-citations",children:[(0,s.jsx)(k.Text,{fw:"bold",size:"sm",mb:"xs",children:S.I18n.get(T.referencesLabel)}),(0,s.jsx)(k.List,{spacing:"xs",size:"sm",children:t.citations.map((u,C)=>{let R=u.sourceUrl||u.url,O=u.title||R||`${S.I18n.get(T.referenceLabel)} #${C+1}`;return(0,s.jsxs)(k.List.Item,{children:[R?(0,s.jsx)(k.Anchor,{href:R,target:"_blank",rel:"noreferrer",children:O}):(0,s.jsx)(k.Text,{children:O}),u.snippet?(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",mt:4,children:u.snippet}):null]},C)})})]}),t.role==="assistant"&&(0,s.jsxs)(k.Group,{className:"ai-feedback",gap:"xs",children:[(0,s.jsx)(k.Button,{className:t.feedback==="accepted"?"active":void 0,onClick:()=>Ca(t.id,"accepted"),"aria-label":S.I18n.get(T.acceptResponseLabel),disabled:D.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),(0,s.jsx)(k.Button,{type:"button",className:t.feedback==="rejected"?"active":void 0,onClick:()=>Ca(t.id,"rejected"),"aria-label":S.I18n.get(T.rejectResponseLabel),disabled:D.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},t.id)}),Fn&&(0,s.jsx)(k.Group,{justify:"flex-start",className:"ai-chat-row assistant status",children:(0,s.jsxs)(k.Stack,{className:"ai-chat-bubble typing",children:[Ot?(0,s.jsx)(k.Text,{size:"sm",c:"dimmed",children:(0,s.jsx)("em",{children:Ot})}):null,(0,s.jsxs)("div",{className:"typing-indicator",children:[(0,s.jsx)("span",{}),(0,s.jsx)("span",{}),(0,s.jsx)("span",{})]})]})})]}),Wn&&(0,s.jsx)(k.Group,{className:"ai-status-line",children:(0,s.jsx)(k.Text,{className:"ai-status-text",children:(0,s.jsx)("em",{children:qn})})}),(0,s.jsxs)(k.Stack,{className:"ai-box ai-box-open",children:[(0,s.jsxs)(k.Modal,{opened:de,onClose:Ia,centered:!0,title:S.I18n.get("Reset conversation"),style:{position:"fixed"},left:0,children:[(0,s.jsx)(k.Text,{size:"sm",children:S.I18n.get("Are you sure you want to reset the conversation?")}),(0,s.jsxs)(k.Group,{justify:"flex-end",mt:"md",children:[(0,s.jsx)(k.Button,{variant:"default",onClick:Ia,"data-ai-kit-no-button":!0,children:S.I18n.get("No")}),(0,s.jsx)(k.Button,{color:"var(--ai-kit-color-danger, red)",onClick:Un,disabled:!h&&!A,"data-ai-kit-yes-button":!0,children:S.I18n.get("Yes")})]})]}),(0,s.jsx)(k.Group,{children:(0,s.jsx)(k.Textarea,{className:"ai-message",ref:je,placeholder:Be,value:H,onChange:t=>{be(t.target.value),M&&Ee()},onKeyDown:On,rows:3,disabled:ye||!!M})}),Aa&&ye&&(0,s.jsxs)(k.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:S.I18n.get("Recording...")})}),(0,s.jsx)("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:(0,s.jsx)("div",{style:{width:`${wt}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Aa&&M&&!ye&&(0,s.jsxs)(k.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsxs)("em",{children:[S.I18n.get("Audio recorded")," (",Math.round(M.duration),"s)"]})}),(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:M.objectUrl})]}),(0,s.jsxs)(k.Group,{className:"ai-actions",justify:"space-between",w:"100%",children:[(0,s.jsx)(k.Group,{justify:"flex-start",children:(0,s.jsx)(k.Button,{variant:"light",leftSection:(0,s.jsx)(ve.IconTrash,{size:18}),onClick:Kn,disabled:!h&&!A,"data-ai-kit-reset-button":!0,children:S.I18n.get(T.resetLabel)})}),(0,s.jsxs)(k.Group,{justify:"flex-end",children:[Aa&&(0,s.jsx)(s.Fragment,{children:M?(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(ve.IconX,{size:18}),onClick:Ee,disabled:A,title:S.I18n.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:S.I18n.get("Clear")}):(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(ve.IconMicrophone,{size:18}),onClick:ye?Ut:Kt,disabled:A,title:ye?S.I18n.get("Stop recording"):S.I18n.get("Record audio"),color:ye?"red":void 0,"data-ai-kit-microphone-button":!0,children:ye?S.I18n.get("Stop"):S.I18n.get("Record")})}),oe>0&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(ve.IconPaperclip,{size:18}),onClick:()=>tt.current?.click(),disabled:W.length>=oe||A||ye||!!M,title:S.I18n.get(T.addImageLabel),"data-ai-kit-add-image-button":!0,children:S.I18n.get(T.addLabel)}),(0,s.jsx)(k.Input,{ref:tt,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:Dn})]}),(0,s.jsx)(k.Button,{leftSection:Vn,variant:"filled",onClick:Jn,disabled:!A&&!Q,"data-ai-kit-send-button":!0,children:Yn})]})]}),Ct.length>0&&(0,s.jsx)(k.Group,{className:"ai-thumbs",mt:"xs",gap:"xs",children:Ct.map(({url:t,title:d},v)=>(0,s.jsx)("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:t?`url(${t})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":d||S.I18n.get("View image"),onClick:()=>ia(t,d),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),ia(t,d))},children:(0,s.jsx)(k.Button,{variant:"white",onClick:u=>{u.stopPropagation(),En(v)},"aria-label":S.I18n.get(T.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:S.I18n.get(T.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},W[v]?.id??v))})]})]})}),(0,s.jsx)(k.Modal,{opened:!!me,onClose:Bn,centered:!0,size:"auto",title:me?.title||S.I18n.get("Image preview"),children:me&&(0,s.jsx)("img",{src:me.url,alt:me.title||S.I18n.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},In=At(zr,{showOpenButton:!0,variation:"modal"});var y=require("@mantine/core"),Tt=require("@smart-cloud/ai-kit-core"),$=require("aws-amplify/utils"),x=require("react"),Cn=Ye(require("react-markdown"),1),xn=Ye(require("rehype-raw"),1),Ln=Ye(require("remark-gfm"),1),Ve=require("@tabler/icons-react");var p=require("react/jsx-runtime");$.I18n.putVocabularies(bt);var zn=!1;function Cr(e){let n=e?.citations?.docs??[],m=e?.citations?.chunks??[],l=new Map;for(let a of n)l.set(a.docId,{doc:a,chunks:[]});for(let a of m){let f=l.get(a.docId);f?f.chunks.push(a):l.set(a.docId,{doc:{docId:a.docId},chunks:[a]})}return Array.from(l.values())}var xr=e=>{let{autoRun:n=!0,context:m,title:l,showOpenButton:a=!1,openButtonTitle:f,showOpenButtonTitle:I=!0,openButtonIcon:G,showOpenButtonIcon:ce=!0,searchButtonIcon:ie,showSearchButtonTitle:ne=!0,showSearchButtonIcon:se=!0,showSources:Ue=!0,topK:le=10,getSearchText:L,enableUserFilters:g=!1,availableCategories:P,availableTags:fe,variation:Z,rootElement:ae,colorMode:ke,language:T,onClose:D,onClickDoc:H}=e,[be,W]=(0,x.useState)(!a),[Te,M]=(0,x.useState)(""),[J,ye]=(0,x.useState)(!1),[ue,wt]=(0,x.useState)(null),[_e,it]=(0,x.useState)(0),$e=(0,x.useRef)(null),Oe=(0,x.useRef)([]),xe=(0,x.useRef)(null),E=(0,x.useRef)(null),[U,Re]=(0,x.useState)(!1),[we,Ne]=(0,x.useState)([]),[de,st]=(0,x.useState)([]),[Ie,lt]=(0,x.useState)([]),[ut,pt]=(0,x.useState)(""),[F,ht]=(0,x.useState)(null),[N,dt]=(0,x.useState)(!1),me=(0,x.useRef)(null),Ze=(0,x.useRef)(null),Fe=1440*60*1e3,{busy:pe,error:Le,statusEvent:zt,result:K,run:St,cancel:Bt,reset:Pe}=It(),he=(0,x.useRef)(!1),z=(0,x.useRef)([]),ct=K?.sessionId,ze=K?.citations?.docs??[],et=K?.citations?.chunks??[],ft=K?.citations?.anchors??[],Je=K?.result??"",tt=(0,x.useMemo)(()=>{if(se)return ie?.trim()?(0,p.jsx)("img",{src:ie,alt:"",style:{width:18,height:18,objectFit:"contain"}}):(0,p.jsx)(Ve.IconSearch,{size:18})},[ie,se]),je=(0,x.useMemo)(()=>(T&&$.I18n.setLanguage(T||"en"),$.I18n.get(l||"Search with AI-Kit")),[T]),De=(0,x.useMemo)(()=>zt?$.I18n.get("Searching\u2026"):null,[T,zt]),We=(0,x.useMemo)(()=>Te||L,[Te,L]),ge=(0,x.useMemo)(()=>{if(pe||!be)return!1;let h=typeof We=="function"?We():We;return!!(h&&h.trim().length>0||ue)},[We,pe,ue,be]),Qe=(0,x.useMemo)(()=>{if(!F)return!1;let h=Object.keys(F.allowedCategories).length>0,A=F.allowedTags.length>0;return h||A},[F]),Ee=(0,x.useMemo)(()=>we.length===0||!F?[]:we.flatMap(h=>F.allowedCategories[h]||[]).filter((h,A,Q)=>Q.indexOf(h)===A),[we,F]),Kt=(0,x.useCallback)(async()=>{try{M("");let h=await navigator.mediaDevices.getUserMedia({audio:!0}),A=new MediaRecorder(h,{mimeType:"audio/webm"}),Q=new AudioContext,X=Q.createMediaStreamSource(h),Se=Q.createAnalyser();Se.fftSize=2048,Se.smoothingTimeConstant=.8,X.connect(Se),xe.current=Q,E.current=Se;let Be=new Uint8Array(Se.fftSize),at=()=>{if(!E.current)return;E.current.getByteTimeDomainData(Be);let Ae=0;for(let Ct=0;Ct<Be.length;Ct++){let Ot=(Be[Ct]-128)/128;Ae+=Ot*Ot}let mt=Math.sqrt(Ae/Be.length),Ft=Math.min(100,mt*200);it(Ft),me.current=requestAnimationFrame(at)};at(),Oe.current=[],A.ondataavailable=Ae=>{Ae.data.size>0&&Oe.current.push(Ae.data)},A.onstop=()=>{let Ae=new Blob(Oe.current,{type:"audio/webm"});wt(Ae),h.getTracks().forEach(mt=>mt.stop()),me.current&&(cancelAnimationFrame(me.current),me.current=null),xe.current&&(xe.current.close(),xe.current=null),E.current=null,it(0)},$e.current=A,A.start(),ye(!0)}catch(h){console.error("Failed to start recording:",h)}},[]),Ut=(0,x.useCallback)(()=>{$e.current&&J&&($e.current.stop(),ye(!1))},[J]),gt=(0,x.useCallback)(()=>{wt(null),Oe.current=[],it(0),Ze.current=null},[]);(0,x.useEffect)(()=>()=>{me.current&&cancelAnimationFrame(me.current),xe.current&&xe.current.close()},[]),(0,x.useEffect)(()=>{if(!g)return;if(P||fe){ht({allowedCategories:P||{},allowedTags:fe||[]});return}(async()=>{dt(!0);try{let A=await(0,Tt.resolveBackend)();if(!A.available){console.error("Backend not available for metadata options");return}let Q={feature:"prompt",source:"backend",mode:"backend-only",onDeviceAvailable:!1,backendAvailable:A.available,backendTransport:A.transport,backendApiName:A.apiName,backendBaseUrl:A.baseUrl,reason:A.reason??""},X=await(0,Tt.dispatchBackend)(Q,m??"frontend","/kb/metadata-options","GET",null,{});ht({allowedCategories:X.allowedCategories||{},allowedTags:X.allowedTags||[]})}catch(A){console.error("Failed to load metadata options:",A)}finally{dt(!1)}})()},[g,P,fe,m]);let o=(0,x.useCallback)(async()=>{let h;if(!ue){if(h=typeof We=="function"?We():We,!h)return;M(h)}console.log("Starting search with query:",h,"and audio:",ue);let A=Date.now(),Q=ue&&Ze.current?.blob===ue&&A-Ze.current.uploadTimestamp<Fe;ue&&!Q?(Ze.current={blob:ue,uploadTimestamp:A},console.log("Audio cache updated for new recording")):Q&&console.log("Reusing cached audio (no re-upload needed within",Math.round((Fe-(A-Ze.current.uploadTimestamp))/1e3),"seconds)"),Pe(),await St(async({signal:X,onStatus:Se})=>await(0,Tt.sendSearchMessage)({sessionId:ct,...h&&{query:h},...ue&&{audio:ue},topK:le,...g&&{userSelectedCategories:we},...g&&de.length>0&&{userSelectedSubcategories:de},...g&&Ie.length>0&&{userSelectedTags:Ie}},{signal:X,onStatus:Se,context:m}))},[m,We,ue,St,Pe,le,ct,g,we,de,Ie]),w=(0,x.useCallback)(async()=>{W(!1),Pe(),a||D()},[D,Pe,he,a]);(0,x.useEffect)(()=>{!n||!ge||pe||he.current||(he.current=!0,queueMicrotask(()=>{o()}))},[pe,he,ge,n,o]),(0,x.useEffect)(()=>{ge||(he.current=!0)},[ge]),(0,x.useEffect)(()=>{let h=z.current,A=we;(h.length!==A.length||!A.every(X=>h.includes(X)))&&h.length>0&&Pe(),z.current=[...A]},[we,Pe]);let q=(0,x.useMemo)(()=>Cr(K),[K]),_=(0,x.useMemo)(()=>{let h=new Map;return ze.forEach((A,Q)=>{A?.docId&&h.set(A.docId,Q+1)}),h},[ze]),re=(0,x.useMemo)(()=>{let h=new Map;return et.forEach(A=>{A?.chunkId&&A?.docId&&h.set(A.chunkId,A.docId)}),h},[et]),Y=(0,x.useMemo)(()=>{if(!Je)return"";if(!ft.length||_.size===0)return Je;let h=[...ft].filter(X=>Array.isArray(X?.chunkIds)&&X?.span?.end!==void 0).sort((X,Se)=>{let Be=X.span?.end??0,at=Se.span?.end??0;return Be-at}),A=0,Q=[];for(let X of h){let Se=X.span?.end;if(typeof Se!="number"||Se<A)continue;let Be=Array.from(new Set((X.chunkIds??[]).map(Ae=>Ae?re.get(Ae):void 0).map(Ae=>Ae?_.get(Ae):void 0).filter(Ae=>typeof Ae=="number")));if(!Be.length)continue;let at=Math.min(Se,Je.length);Q.push(Je.slice(A,at)),Q.push(`<sup>${Be.join(",")}</sup>`),A=at}return Q.push(Je.slice(A)),Q.join("")},[ft,Je]),te=Z==="modal"?y.Modal.Root:y.Group,oe=Z==="modal"?y.Modal.Content:y.Group,qe=Z==="modal"?y.Modal.Body:y.Group;return(0,x.useEffect)(()=>{if(!(Z!=="modal"||!be))return document.body.style.overflow="hidden",document.body.onkeydown=h=>{h.key==="Escape"&&(h.preventDefault(),w())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[w,Z,be]),(0,p.jsxs)(p.Fragment,{children:[a&&(0,p.jsx)(y.Button,{leftSection:ce&&(G?(0,p.jsx)("span",{dangerouslySetInnerHTML:{__html:G}}):(0,p.jsx)(Ve.IconSearch,{size:18})),className:I?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:be,onClick:()=>W(!0),"data-ai-kit-open-button":!0,children:I&&$.I18n.get(f||je)}),be&&(0,p.jsxs)(te,{opened:!0,className:"doc-search-root",onClose:w,padding:"md",gap:"md",size:"xl",portalProps:Z==="modal"?{target:ae,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":ke,"data-ai-kit-variation":Z,children:[Z==="modal"&&(0,p.jsx)(y.Modal.Overlay,{}),(0,p.jsxs)(oe,{w:"100%",style:{left:0,...Z==="modal"&&!K?.result&&{overflow:"visible"}},children:[Z==="modal"&&(0,p.jsxs)(y.Modal.Header,{style:{zIndex:1e3},children:[(0,p.jsx)(Tt.AiKitDocSearchIcon,{className:"doc-search-title-icon"}),(0,p.jsx)(y.Modal.Title,{children:$.I18n.get(je)}),(0,p.jsx)(y.Modal.CloseButton,{})]}),(0,p.jsx)(qe,{w:"100%",style:{zIndex:1001,...Z==="modal"&&!K?.result&&{overflow:"visible"}},children:(0,p.jsx)(Lt,{enabled:Z!=="modal",working:pe,variation:Z,children:(0,p.jsx)(y.Paper,{shadow:"sm",radius:"md",p:"md",children:(0,p.jsxs)(y.Stack,{gap:"sm",children:[Z!=="modal"&&(0,p.jsxs)(y.Group,{justify:"space-between",children:[(0,p.jsx)(y.Title,{order:4,style:{margin:0},children:$.I18n.get(je)}),a&&(0,p.jsx)(y.Button,{variant:"subtle",color:"gray",size:"xs",onClick:w,style:{minWidth:32,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":$.I18n.get("Close"),children:(0,p.jsx)(Ve.IconX,{size:18,style:{color:ke==="dark"?"var(--mantine-color-dark-1)":"var(--mantine-color-gray-7)"}})})]}),(0,p.jsxs)(y.Group,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[(0,p.jsx)(y.TextInput,{style:{flex:1},value:Te,onChange:h=>{M(h.currentTarget.value),ue&&gt()},placeholder:ue?$.I18n.get("Audio recorded"):$.I18n.get("Search the documentation\u2026"),disabled:pe||J||!!ue,onKeyDown:h=>{h.key==="Enter"&&ge&&(h.preventDefault(),o())}}),zn&&(0,p.jsx)(p.Fragment,{children:ue?(0,p.jsx)(y.Button,{variant:"outline",size:"sm",color:"red",onClick:gt,disabled:pe,title:$.I18n.get("Clear audio"),children:(0,p.jsx)(Ve.IconMicrophoneOff,{size:18})}):(0,p.jsx)(y.Button,{variant:J?"filled":"outline",size:"sm",color:J?"red":"gray",onClick:J?Ut:Kt,disabled:pe,title:J?$.I18n.get("Stop recording"):$.I18n.get("Record audio"),style:J?{transform:`scale(${1+_e/300})`,transition:"transform 0.1s ease-out"}:void 0,children:(0,p.jsx)(Ve.IconMicrophone,{size:18})})}),(0,p.jsx)(y.Button,{variant:"filled",size:"sm",leftSection:tt,onClick:()=>{o()},disabled:!ge,className:ne?"doc-search-button":"doc-search-button-no-title",children:ne?$.I18n.get("Search"):null}),pe?(0,p.jsx)(y.Button,{variant:"outline",size:"sm",onClick:Bt,children:$.I18n.get("Stop")}):null]}),!pe&&!Le&&!K?.result?(0,p.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:$.I18n.get("Enter a search query to start.")}):null,g&&F&&Qe&&(0,p.jsxs)(y.Stack,{gap:"xs",children:[(0,p.jsx)(y.Button,{variant:"subtle",size:"xs",onClick:()=>Re(!U),leftSection:U?(0,p.jsx)(Ve.IconChevronDown,{size:14}):(0,p.jsx)(Ve.IconChevronRight,{size:14}),style:{alignSelf:"flex-start"},children:$.I18n.get("Filters")}),(0,p.jsx)(y.Collapse,{in:U,children:(0,p.jsxs)(y.Stack,{gap:"md",children:[Object.keys(F.allowedCategories).length>0&&(0,p.jsxs)("div",{children:[(0,p.jsx)(y.Text,{size:"sm",fw:500,mb:"xs",children:$.I18n.get("Categories")}),(0,p.jsx)(y.Group,{gap:"md",children:Object.keys(F.allowedCategories).map(h=>(0,p.jsx)(y.Checkbox,{label:$.I18n.get(h),checked:we.includes(h),onChange:A=>{if(A.currentTarget.checked)Ne([...we,h]);else{Ne(we.filter(X=>X!==h));let Q=F.allowedCategories[h]||[];st(de.filter(X=>!Q.includes(X)))}},disabled:pe||N},h))})]}),Ee.length>0&&(0,p.jsxs)("div",{children:[(0,p.jsx)(y.Text,{size:"sm",fw:500,mb:"xs",children:$.I18n.get("Subcategories")}),(0,p.jsx)(y.Group,{gap:"md",children:Ee.map(h=>(0,p.jsx)(y.Checkbox,{label:$.I18n.get(h),checked:de.includes(h),onChange:A=>{A.currentTarget.checked?st([...de,h]):st(de.filter(Q=>Q!==h))},disabled:pe||N},h))})]}),F.allowedTags.length>0&&(0,p.jsx)(y.MultiSelect,{label:$.I18n.get("Tags"),placeholder:$.I18n.get("Select or type tags..."),data:F.allowedTags.map(h=>({value:h,label:$.I18n.get(h)})),value:Ie,onChange:lt,searchValue:ut,onSearchChange:pt,disabled:pe||N,searchable:!0,clearable:!0,maxDropdownHeight:200,limit:20})]})})]}),zn&&(0,p.jsxs)(p.Fragment,{children:[J&&(0,p.jsxs)(y.Stack,{gap:"xs",children:[(0,p.jsxs)(y.Text,{size:"xs",c:"dimmed",children:[$.I18n.get("Recording...")," \u{1F3A4}"]}),(0,p.jsx)(y.Progress,{value:_e,size:"sm",color:"red",animated:!0,striped:!0})]}),ue&&!J&&(0,p.jsxs)(y.Stack,{gap:"xs",children:[(0,p.jsx)(y.Text,{size:"xs",c:"dimmed",children:$.I18n.get("Recorded audio:")}),(0,p.jsx)("audio",{controls:!0,src:URL.createObjectURL(ue),className:"ai-kit-audio-player"})]})]}),Le?(0,p.jsx)(y.Alert,{color:"red",title:$.I18n.get("Error"),children:Le}):null,pe&&De&&(0,p.jsx)(Lt,{enabled:Z==="modal",working:!0,variation:Z,children:(0,p.jsxs)(y.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,p.jsx)(y.Loader,{size:"sm"}),(0,p.jsx)(y.Text,{size:"sm",c:"dimmed",children:De})]})}),K?.result?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(y.Divider,{}),(0,p.jsxs)(y.Stack,{gap:"xs","data-doc-search-result":!0,children:[(0,p.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:$.I18n.get("AI Summary")}),(0,p.jsx)(Cn.default,{remarkPlugins:[Ln.default],rehypePlugins:[xn.default],"data-doc-search-result-content":!0,children:Y||Je})]})]}):null,Ue&&(K?.citations?.docs?.length||K?.citations?.chunks?.length)?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(y.Divider,{}),(0,p.jsxs)(y.Stack,{gap:"sm","data-doc-search-sources":!0,children:[(0,p.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:$.I18n.get("Sources")}),q.map(({doc:h})=>{let A=h.sourceUrl?.trim()||void 0,Q=h.docId?_.get(h.docId):void 0,X=h.title?.trim()||h.docId,Se=(0,p.jsxs)(y.Text,{fw:600,style:{display:"inline"},children:[Q?`${Q}. `:"",X]});return(0,p.jsx)(y.Paper,{withBorder:!0,radius:"md",p:"sm",children:(0,p.jsx)(y.Stack,{gap:"xs",children:(0,p.jsx)(y.Group,{justify:"space-between",align:"flex-start",children:(0,p.jsxs)(y.Stack,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[A?(0,p.jsx)(y.Anchor,{href:A,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Be=>{H&&(Be.preventDefault(),H?.(h))},"data-doc-search-source-title":!0,children:Se}):Se,(0,p.jsx)(y.Anchor,{href:A,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Be=>{H&&(Be.preventDefault(),H?.(h))},"data-doc-search-source-url":!0,children:h.sourceUrl}),h.author?(0,p.jsx)(y.Text,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:h.author}):null,h.description?(0,p.jsx)(y.Text,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:h.description}):null]})})})},h.docId)})]})]}):null,(0,p.jsx)(Jt,{variation:Z})]})})})})]})]})]})},Pn=At(xr);0&&(module.exports={AiChatbot,AiFeature,DEFAULT_CHATBOT_LABELS,DocSearch,isBackendConfigured,markdownToHtml,readDefaultOutputLanguage,stripCodeFence,translations,useAiRun,withAiKitShell});
31
+ Follow these additional instructions: ${de}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),_=await z.run(async({signal:te,onStatus:oe})=>(await(0,j.prompt)({messages:q,images:[Ne],outputLanguage:"en",responseConstraint:dr},{signal:te,onStatus:oe,context:P,modeOverride:o,onDeviceTimeoutOverride:a})).result);if(!_){U("");return}let re=(N&&N!=="auto"?N:null)||yt(),Y=xt(_).trim();try{J("Translating result...");let te=await z.run(async({signal:oe})=>await gr(Y,re,{signal:oe,context:P,modeOverride:o,onDeviceTimeoutOverride:a,silent:!0}));U(te)}catch(te){U(Y),console.warn("AI Kit: failed to parse SEO JSON",te)}break}}}catch(w){xe(w instanceof Error?w.message:r.I18n.get("An unknown error occurred."))}J(void 0)}},[H,z,de,me,N,Re,Fe,P,g,Le,ut,he,Te]),et=(0,B.useCallback)(async()=>{await ze("backend-only")},[ze]),ft=(0,B.useCallback)(o=>{switch(g){case"proofread":return(0,c.jsx)(rt.IconCircleDashedCheck,{className:o});case"translate":return(0,c.jsx)(rt.IconLanguage,{className:o});case"summarize":return(0,c.jsx)(rt.IconSum,{className:o});case"rewrite":case"write":return(0,c.jsx)(rt.IconPencilCode,{className:o});case"generateImageMetadata":case"generatePostMetadata":return(0,c.jsx)(rt.IconSeo,{className:o});default:return(0,c.jsx)(j.AiKitFeatureIcon,{mode:g,className:o})}},[g]),Je=(0,B.useCallback)(()=>{switch(g){case"proofread":return z.lastSource?r.I18n.get("Proofread again"):r.I18n.get("Proofread");case"translate":return z.lastSource?r.I18n.get("Translate again"):r.I18n.get("Translate");case"rewrite":return z.lastSource?r.I18n.get("Rewrite again"):r.I18n.get("Rewrite");case"summarize":return z.lastSource?r.I18n.get("Summarize again"):r.I18n.get("Summarize");default:return z.lastSource?r.I18n.get("Regenerate"):r.I18n.get("Generate")}},[H,z.lastSource,g]),tt=(0,B.useCallback)(()=>{switch(g){case"proofread":return r.I18n.get("Proofread on Backend");case"translate":return r.I18n.get("Translate on Backend");case"rewrite":return r.I18n.get("Rewrite on Backend");case"summarize":return r.I18n.get("Summarize on Backend");default:return r.I18n.get("Regenerate on Backend")}},[H,g]),je=(0,B.useCallback)(async()=>{ue(!1),U(null),xe(null),K.current=!1,z.reset(),G||ke()},[ke,K,z,G]),De=(0,B.useCallback)(async()=>{z.busy&&z.cancel()},[z.busy]);(0,B.useEffect)(()=>{!ye||!m||!he||z.busy||E||K.current||(K.current=!0,queueMicrotask(()=>{ze(fe)}))},[z.busy,K,ye,he,m,E,ze,fe]),(0,B.useEffect)(()=>{Te&&g!=="proofread"&&(he||(_e(!0),K.current=!0))},[Te,he,g]),(0,B.useEffect)(()=>{let o=!0;return(async()=>{try{await(0,j.waitForAiKitReady)();let w=await ua();o&&$e(w)}catch(w){console.error(w),o&&$e(!1)}})(),()=>{o=!1}},[]);let We=(0,B.useMemo)(()=>{let o=[];if(g==="translate"){let w=j.LANGUAGE_OPTIONS.find(q=>q.value===ut)?.label;o.push(r.I18n.get("Input language")+": "+(w?r.I18n.get(w):"auto"))}if(N&&W?.outputLanguage){let w=j.LANGUAGE_OPTIONS.find(q=>q.value===N)?.label;o.push(r.I18n.get("Output language")+": "+(w?r.I18n.get(w):N))}return g==="summarize"&&Le&&W?.type&&o.push(r.I18n.get("Type")+": "+r.I18n.get(Le)),(g==="write"||g==="rewrite")&&Fe&&W?.tone&&o.push(r.I18n.get("Tone")+": "+r.I18n.get(Fe)),(g==="write"||g==="rewrite"||g==="summarize")&&me&&W?.length&&o.push(r.I18n.get("Length")+": "+r.I18n.get(me)),de?.trim()&&W?.instructions&&o.push(r.I18n.get("Instructions")+": \u2713"),o.length?o.join(" \u2022 "):r.I18n.get("No overrides")},[H,g,ut,N,Le,Fe,me,de]),ge={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},Qe=f==="modal"?b.Modal.Root:b.Group,Ee=f==="modal"?b.Modal.Content:b.Group,Kt=f==="modal"?b.Modal.Body:b.Group,Ut=L==="collapse"?b.Collapse:b.Stack,gt=L==="horizontal"?b.Group:b.Stack;return(0,B.useEffect)(()=>{if(!(f!=="modal"||!ye))return document.body.style.overflow="hidden",document.body.onkeydown=o=>{o.key==="Escape"&&(o.preventDefault(),je())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[je,f]),(0,c.jsxs)(c.Fragment,{children:[G&&(0,c.jsx)(b.Button,{leftSection:ie&&(se?(0,c.jsx)("span",{dangerouslySetInnerHTML:{__html:se}}):ft()),className:ce?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:ye,onClick:()=>ue(!0),"data-ai-kit-open-button":!0,children:ce&&r.I18n.get(ne||St)}),ye&&(0,c.jsxs)(Qe,{opened:!0,className:"ai-feature-root",onClose:je,padding:"md",gap:"md",size:"md",portalProps:f==="modal"?{target:be,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Z,"data-ai-kit-variation":f,children:[f==="modal"&&(0,c.jsx)(b.Modal.Overlay,{}),(0,c.jsxs)(Ee,{w:"100%",style:{left:0},children:[f==="modal"&&(0,c.jsxs)(b.Modal.Header,{style:{zIndex:1e3},children:[ft("ai-feature-title-icon"),(0,c.jsx)(b.Modal.Title,{children:r.I18n.get(St)}),(0,c.jsx)(b.Modal.CloseButton,{})]}),(0,c.jsx)(Kt,{w:"100%",style:{zIndex:1001},children:(0,c.jsxs)(Lt,{enabled:f!=="modal",working:z.busy,variation:f,children:[(0,c.jsxs)(b.Stack,{gap:"sm",mb:"sm",p:"sm",children:[Oe&&(0,c.jsx)(b.Alert,{color:"red",children:r.I18n.get(Oe)}),Te&&g!=="proofread"&&(0,c.jsxs)(b.Paper,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":L,children:[(0,c.jsxs)(b.Group,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:L==="collapse"?()=>_e(o=>!o):void 0,children:[L==="collapse"&&(0,c.jsxs)(b.Stack,{gap:0,children:[(0,c.jsx)(b.Text,{size:"sm",fw:600,style:{lineHeight:1.1},children:r.I18n.get("Options")}),(0,c.jsx)(b.Text,{size:"xs",c:"dimmed",style:{marginTop:2},children:We})]}),L==="collapse"&&(0,c.jsx)(b.Button,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:o=>{o.stopPropagation(),_e(w=>!w)},children:wt?r.I18n.get("Hide"):r.I18n.get("Show")})]}),(0,c.jsxs)(Ut,{in:wt,children:[L==="collapse"&&(0,c.jsx)(b.Divider,{my:"sm"}),(0,c.jsxs)(gt,{gap:"xs",justify:"space-between",children:[g==="write"&&W?.text&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The topic or subject for the AI to write about."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.TextInput,{size:"xs",className:"ai-feature-option",styles:ge,disabled:z.busy,label:r.I18n.get("Topic"),description:L!=="horizontal"?r.I18n.get("The topic or subject for the AI to write about."):void 0,value:Re||"",onChange:o=>{let w=o.target.value;we(w),D?.({text:w})}})}),(g==="write"||g==="rewrite"||g==="generateImageMetadata"||g==="generatePostMetadata")&&W?.instructions&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("Additional instructions to guide the AI."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.TextInput,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Instructions"),description:L!=="horizontal"?r.I18n.get("Additional instructions to guide the AI."):void 0,value:de||"",onChange:o=>{let w=o.target.value;st(w),D?.({instructions:w})}})}),g==="translate"&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The language of the input text."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",styles:ge,className:"ai-feature-option",label:r.I18n.get("Input language"),description:L!=="horizontal"?r.I18n.get("The language of the input text."):void 0,data:[{value:"auto",label:r.I18n.get("Auto-detect")},...j.LANGUAGE_OPTIONS.map(o=>({value:o.value,label:r.I18n.get(o.label)})).sort((o,w)=>o.label.localeCompare(w.label))],value:ut||"auto",onChange:o=>{let w=o;pt(w),lt(void 0),D?.({inputLanguage:w})}})}),W?.outputLanguage&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",styles:ge,className:"ai-feature-option",label:r.I18n.get("Output language"),description:L!=="horizontal"?r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[g==="rewrite"?{value:"auto",label:r.I18n.get("Auto-detect")}:void 0].filter(Boolean),...j.LANGUAGE_OPTIONS.map(o=>({value:o.value,label:r.I18n.get(o.label)})).sort((o,w)=>o.label.localeCompare(w.label))],value:N||bn.settings.defaultOutputLanguage||(g==="rewrite"?"auto":""),onChange:o=>{let w=o;dt(w),lt(void 0),D?.({outputLanguage:w})}})}),g==="summarize"&&W?.type&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The summary style to generate."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Type"),description:L!=="horizontal"?r.I18n.get("The summary style to generate."):void 0,data:[{value:"headline",label:r.I18n.get("Headline")},{value:"key-points",label:r.I18n.get("Key Points")},{value:"teaser",label:r.I18n.get("Teaser")},{value:"tldr",label:r.I18n.get("TL;DR")}],value:Le||"key-points",onChange:o=>{let w=o;zt(w),D?.({type:w})}})}),(g==="write"||g==="rewrite")&&W?.tone&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The tone or style for the AI to use."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Tone"),description:L!=="horizontal"?r.I18n.get("The tone or style for the AI to use."):void 0,data:g==="write"?[{value:"neutral",label:r.I18n.get("Neutral")},{value:"formal",label:r.I18n.get("Formal")},{value:"casual",label:r.I18n.get("Casual")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"more-formal",label:r.I18n.get("More formal")},{value:"more-casual",label:r.I18n.get("More casual")}],value:Fe||(g==="write"?"neutral":"as-is"),onChange:o=>{let w=o;pe(w),D?.({tone:w})}})}),(g==="write"||g==="rewrite"||g==="summarize")&&W?.length&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The target output length."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Length"),description:L!=="horizontal"?r.I18n.get("The target output length."):void 0,data:g==="write"||g==="summarize"?[{value:"short",label:r.I18n.get("Short")},{value:"medium",label:r.I18n.get("Medium")},{value:"long",label:r.I18n.get("Long")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"shorter",label:r.I18n.get("Shorter")},{value:"longer",label:r.I18n.get("Longer")}],value:me||(g==="rewrite"?"as-is":"short"),onChange:o=>{let w=o;Ze(w),D?.({length:w})}})}),g==="summarize"||g==="write"||g==="rewrite"&&W?.outputFormat&&(0,c.jsx)(b.Tooltip,{label:r.I18n.get("The format for the generated output."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(b.Select,{disabled:z.busy,size:"xs",className:"ai-feature-option",styles:ge,label:r.I18n.get("Output format"),description:L!=="horizontal"?r.I18n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:r.I18n.get("Plain Text")},{value:"markdown",label:r.I18n.get("Markdown")},{value:"html",label:r.I18n.get("HTML")}],value:F||"markdown",onChange:o=>{let w=o;ht(w),D?.({outputFormat:w})}})})]})]})]}),z.busy&&ct&&(0,c.jsx)(Lt,{enabled:f==="modal",working:!0,variation:f,children:(0,c.jsxs)(b.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,c.jsx)(b.Loader,{size:"sm"}),(0,c.jsx)(b.Input.Label,{className:"ai-feature-status-text",children:ct})]})}),E&&(0,c.jsxs)(b.Stack,{mt:"md",children:[g==="proofread"&&(E.corrections.length===0?(0,c.jsx)(b.Alert,{color:"green",children:r.I18n.get("No issues found. Your text looks great!")}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("p",{style:{marginTop:0,opacity:.85},children:r.I18n.get("Hover highlights to see explanations.")}),(0,c.jsx)(gn,{original:Re,corrections:E.corrections}),E.correctedInput?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("h4",{style:{marginTop:16,marginBottom:8},children:r.I18n.get("Corrected")}),(0,c.jsx)(b.Group,{c:"pre",className:"ai-feature-generated-content",children:E.correctedInput})]}):null]})),g==="generateImageMetadata"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Alt Text"),description:r.I18n.get("The alt text for the image."),value:E.alt_text||"",onChange:o=>U({...E,alt_text:o.target.value})}),(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the image."),value:E.title||"",onChange:o=>U({...E,title:o.target.value})}),(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Caption"),description:r.I18n.get("The caption for the image."),value:E.caption||"",onChange:o=>U({...E,caption:o.target.value})}),(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Description"),description:r.I18n.get("The description for the image."),value:E.description||"",onChange:o=>U({...E,description:o.target.value})})]}),g==="generatePostMetadata"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the post."),value:E.title||"",onChange:o=>U({...E,title:o.target.value})}),(0,c.jsx)(b.TextInput,{readOnly:!l,label:r.I18n.get("Excerpt"),description:r.I18n.get("The excerpt for the post."),value:E.excerpt||"",onChange:o=>U({...E,excerpt:o.target.value})})]}),g!=="proofread"&&g!=="generateImageMetadata"&&g!=="generatePostMetadata"&&typeof E=="string"&&(0,c.jsx)(yn,{value:E,editable:!!l,onChange:o=>{U(o)}})]}),E===""&&(0,c.jsx)(yn,{value:E,editable:!1})]}),(0,c.jsxs)(b.Group,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[z.busy&&(0,c.jsx)(b.Button,{variant:"outline",size:"sm",onClick:De,"data-ai-kit-cancel-button":!0,children:r.I18n.get("Cancel")}),!z.busy&&(0,c.jsx)(b.Button,{variant:"filled",size:"sm",disabled:!he,onClick:()=>ze(),"data-ai-kit-generate-button":!0,children:Je()}),!z.busy&&z.lastSource==="on-device"&&it&&Ue&&(0,c.jsx)(b.Button,{variant:"filled",size:"sm",disabled:!he,onClick:et,"data-ai-kit-regenerate-on-backend-button":!0,children:tt()}),!z.busy&&T&&(0,c.jsx)(b.Button,{variant:"outline",size:"sm",disabled:!E||g==="proofread"&&E.corrections.length===0,onClick:async()=>{T(F==="html"?await ea(E):E),je()},"data-ai-kit-accept-button":!0,children:r.I18n.get(le)}),(0,c.jsx)(b.Button,{variant:"default",size:"sm",onClick:je,"data-ai-kit-close-button":!0,children:r.I18n.get("Close")})]}),(0,c.jsx)(Jt,{variation:f})]})})]})]})]})};function yn(e){let{value:n,editable:m,onChange:l}=e;return m?(0,c.jsxs)(b.Stack,{p:0,gap:"sm",children:[(0,c.jsx)(b.Input.Label,{children:r.I18n.get("Generated content")}),(0,c.jsx)(b.Textarea,{value:n,onChange:a=>l?.(a.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),(0,c.jsx)(b.Input.Label,{children:r.I18n.get("Preview")}),(0,c.jsx)(b.Stack,{className:"ai-feature-generated-content ai-feature-preview",children:(0,c.jsx)(ma.default,{remarkPlugins:[pa.default],children:n})})]}):(0,c.jsx)(b.Stack,{className:"ai-feature-generated-content",children:n?(0,c.jsx)(ma.default,{remarkPlugins:[pa.default],children:n}):(0,c.jsx)(b.Alert,{color:"yellow",children:r.I18n.get("No content generated.")})})}var An=At(pr);var k=require("@mantine/core"),ve=require("@tabler/icons-react"),Et=require("@smart-cloud/ai-kit-core"),Tn=require("@wordpress/data"),S=require("aws-amplify/utils"),i=require("react"),wn=Ye(require("react-markdown"),1),Sn=Ye(require("remark-gfm"),1);var hr="ai-kit-chatbot-attachments",ot="attachments";var ha=null;function fr(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function ta(){if(!fr())return null;ha||(ha=new Promise(e=>{try{let n=window.indexedDB.open(hr,1);n.onerror=()=>e(null),n.onblocked=()=>e(null),n.onupgradeneeded=()=>{let m=n.result;m.objectStoreNames.contains(ot)||m.createObjectStore(ot,{keyPath:"id"})},n.onsuccess=()=>e(n.result)}catch(n){console.warn("[AiChatbot] IndexedDB is not available",n),e(null)}}));try{return await ha}catch(e){return console.warn("[AiChatbot] Failed to open attachment store",e),null}}async function fa(e,n){let m=await ta();return m?new Promise((l,a)=>{try{let f=m.transaction(ot,e),I=f.objectStore(ot),G=n(I);f.oncomplete=()=>l(G),f.onerror=()=>a(f.error),f.onabort=()=>a(f.error)}catch(f){a(f)}}).catch(l=>(console.warn("[AiChatbot] Attachment store transaction failed",l),null)):null}async function ka(e,n,m){await Ar();let l={id:e,blob:n,name:m.name,type:m.type,size:m.size,createdAt:Date.now()};return await fa("readwrite",f=>(f.put(l),e))}async function ba(e){let n=await ta();return n?new Promise((m,l)=>{try{let a=n.transaction(ot,"readonly"),f=a.objectStore(ot).get(e);f.onsuccess=()=>{let I=f.result;m(I??null)},f.onerror=()=>l(f.error),a.onabort=()=>l(a.error)}catch(a){l(a)}}).catch(m=>(console.warn("[AiChatbot] Failed to load attachment",m),null)):null}async function kr(e){await fa("readwrite",n=>{n.delete(e)})}async function aa(){await fa("readwrite",e=>{e.clear()})}async function ya(e){let n=await ta();n&&await new Promise((m,l)=>{try{let a=n.transaction(ot,"readwrite"),f=a.objectStore(ot),I=f.getAllKeys();I.onsuccess=()=>{let G=I.result;for(let ce of G){let ie=String(ce);e.has(ie)||f.delete(ce)}},I.onerror=()=>l(I.error),a.oncomplete=()=>m(),a.onerror=()=>l(a.error),a.onabort=()=>l(a.error)}catch(a){l(a)}}).catch(m=>{console.warn("[AiChatbot] Failed to cleanup attachments",m)})}var br=50*1024*1024;async function yr(){let e=await ta();return e?new Promise((n,m)=>{try{let l=e.transaction(ot,"readonly"),a=l.objectStore(ot).getAll();a.onsuccess=()=>{let f=a.result||[];n(f)},a.onerror=()=>m(a.error),l.onerror=()=>m(l.error),l.onabort=()=>m(l.error)}catch(l){m(l)}}).catch(n=>(console.warn("[AiChatbot] Failed to get all attachments",n),[])):[]}async function Ar(){let e=await yr();if(e.length===0)return;let n=e.sort((f,I)=>f.createdAt-I.createdAt),m=n.reduce((f,I)=>f+I.size,0),l=[],a=0;for(;m>br&&a<n.length;){let f=n[a];f&&(l.push(f.id),m-=f.size),a++}for(let f of l)await kr(f);l.length>0&&console.log(`[AiChatbot] Deleted ${l.length} old attachment(s) to enforce storage quota`)}var s=require("react/jsx-runtime");S.I18n.putVocabularies(bt);var na=1440*60*1e3,Aa=!1,vr=1,Tr="localstorage",Mt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,oa={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function vt(e){return`${e}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var wr=4,Sr=5*1024*1024,Rr=e=>{let n=(e?.name||"").toString(),m=(e?.code||"").toString(),l=(e?.message||"").toString();return n==="AbortError"||m==="ABORT_ERR"||/abort|aborted|cancel/i.test(l)},Ir=(e,n)=>{if(!e)return null;let m=e.step,l=S.I18n.get((e.message??"").trim()),a=typeof e.progress=="number"?e.progress:null,f=a==null?null:Math.round(a*100);switch(m){case"decide":return l||S.I18n.get("Checking capabilities...");case"on-device:init":return l||S.I18n.get("Initializing on-device AI...");case"on-device:download":return f==null?l||S.I18n.get("Downloading model..."):l||`${S.I18n.get("Downloading model...")} ${f}%`;case"on-device:ready":return l||S.I18n.get("On-device model ready...");case"on-device:run":return l||S.I18n.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return S.I18n.get(n.assistantThinkingLabel??oa.assistantThinkingLabel);case"done":return l||S.I18n.get("Done.");case"error":return l||S.I18n.get("An error occurred.");default:return l||null}};function va(e){if(typeof window>"u")return null;try{return e==="localstorage"?window.localStorage:e==="sessionstorage"?window.sessionStorage:null}catch{return null}}var Dt=e=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(e)}catch{return null}},ra=e=>{if(e&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(e)}catch{}},Rn=e=>{!e||e.length===0||e.forEach(n=>ra(n.objectUrl))},vn=e=>{e.forEach(n=>Rn(n.attachments))},zr=e=>{let{rootElement:n,store:m,previewMode:l,title:a,openButtonTitle:f,openButtonIcon:I,showOpenButtonTitle:G=!0,showOpenButtonIcon:ce=!0,colorMode:ie,language:ne,onClose:se,context:Ue,placeholder:le,maxImages:L,maxImageBytes:g,historyStorage:P=Tr,emptyHistoryAfterDays:fe=vr,labels:Z,openButtonIconLayout:ae="top",openButtonPosition:ke="bottom-right"}=e,T=(0,i.useMemo)(()=>({...oa,...Z||{}}),[Z]),D=It(),[H,be]=(0,i.useState)(""),[W,Te]=(0,i.useState)([]),[M,J]=(0,i.useState)(null),[ye,ue]=(0,i.useState)(!1),[wt,_e]=(0,i.useState)(0),it=(0,i.useRef)(null),$e=(0,i.useRef)([]),Oe=(0,i.useRef)(null),xe=(0,i.useRef)(null),E=(0,i.useRef)(null),[U,Re]=(0,i.useState)([]),[we,Ne]=(0,i.useState)(null),[de,st]=(0,i.useState)(!1),[Ie,lt]=(0,i.useState)(!1),[ut,pt]=(0,i.useState)(!1),[F,ht]=(0,i.useState)(!1),[N,dt]=(0,i.useState)(!0),[me,Ze]=(0,i.useState)(null),[Fe,pe]=(0,i.useState)(!1),[Le,zt]=(0,i.useState)(null),[K,St]=(0,i.useState)(null),[Bt,Pe]=(0,i.useState)(!1),[he,z]=(0,i.useState)(null),ct=(0,i.useRef)(he);(0,i.useEffect)(()=>{ct.current=he},[he]);let ze=(0,i.useRef)(null),et=(0,i.useRef)(!1),[ft,Je]=(0,i.useState)(null),tt=(0,i.useRef)(null),je=(0,i.useRef)(null),De=(0,i.useRef)(null),We=(0,i.useRef)(null),ge=(0,i.useCallback)(t=>{t.forEach(d=>ra(d.objectUrl))},[]),Qe=(0,i.useCallback)(()=>{ge(re.current),Te([]),tt.current&&(tt.current.value="")},[ge]),Ee=(0,i.useCallback)(()=>{Y.current&&ra(Y.current.objectUrl),J(null),$e.current=[],_e(0)},[]),Kt=(0,i.useCallback)(async()=>{try{be(""),Ee();let t=await navigator.mediaDevices.getUserMedia({audio:!0}),d=new MediaRecorder(t,{mimeType:"audio/webm"}),v=new AudioContext,u=v.createMediaStreamSource(t),C=v.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.8,u.connect(C),Oe.current=v,xe.current=C;let R=new Uint8Array(C.fftSize),O=()=>{if(!xe.current)return;xe.current.getByteTimeDomainData(R);let ee=0;for(let Ge=0;Ge<R.length;Ge++){let Rt=(R[Ge]-128)/128;ee+=Rt*Rt}let Ce=Math.sqrt(ee/R.length),Ke=Math.min(100,Ce*200);_e(Ke),E.current=requestAnimationFrame(O)};O(),$e.current=[];let V=Date.now();d.ondataavailable=ee=>{ee.data.size>0&&$e.current.push(ee.data)},d.onstop=()=>{let ee=new Blob($e.current,{type:"audio/webm"}),Ce=(Date.now()-V)/1e3,Ke=Dt(ee);Ke&&J({id:vt("composer-audio"),blob:ee,objectUrl:Ke,duration:Ce}),t.getTracks().forEach(Ge=>Ge.stop()),E.current&&(cancelAnimationFrame(E.current),E.current=null),Oe.current&&(Oe.current.close(),Oe.current=null),xe.current=null,_e(0)},it.current=d,d.start(),ue(!0)}catch(t){console.error("Failed to start recording:",t)}},[Ee]),Ut=(0,i.useCallback)(()=>{it.current&&ye&&(it.current.stop(),ue(!1))},[ye]);(0,i.useEffect)(()=>()=>{E.current&&cancelAnimationFrame(E.current),Oe.current&&Oe.current.close(),Ee()},[Ee]);let[gt,o]=(0,i.useState)(null),w=(0,i.useRef)(H),q=(0,i.useRef)(U),_=(0,i.useRef)(gt),re=(0,i.useRef)(W),Y=(0,i.useRef)(M);(0,i.useEffect)(()=>{w.current=H},[H]),(0,i.useEffect)(()=>{re.current=W},[W]),(0,i.useEffect)(()=>{Y.current=M},[M]),(0,i.useEffect)(()=>{q.current=U},[U]),(0,i.useEffect)(()=>{_.current=gt},[gt]),(0,i.useEffect)(()=>{ne&&S.I18n.setLanguage(ne||"en")},[ne]);let te=(0,Tn.useSelect)(()=>(0,Et.getStoreSelect)(m).isShowChatbotPreview()),oe=(0,i.useMemo)(()=>Math.max(0,L??wr),[L]),qe=(0,i.useMemo)(()=>Math.max(0,g??Sr),[g]),h=U.length>0,A=(0,i.useMemo)(()=>D.busy&&he==="chat",[D.busy,he]),Q=(0,i.useMemo)(()=>A?!1:H.trim().length>0||M!==null,[H,A,M]),X=(0,i.useMemo)(()=>{let t=f||T.askMeLabel;return S.I18n.get(t)},[f,T.askMeLabel,ne]),Se=(0,i.useMemo)(()=>{let t=a||T.modalTitle;return S.I18n.get(t)},[a,T.modalTitle,ne]),Be=(0,i.useMemo)(()=>{let t=le||T.placeholder;return S.I18n.get(t)},[le,T.placeholder,ne]),at=(0,i.useMemo)(()=>{let t="ai-docs-ask",d=`ai-open-btn--${ke}`;return`${t} ${d}`},[ke]),Ae=(0,i.useCallback)(()=>{let t=We.current;if(t)try{let d=window.innerHeight||document.documentElement.clientHeight,v=360,u=1e3,C=Math.floor(d*.8),R=Math.max(v,Math.min(C,u));t.style.height=`${R}px`}catch{}},[]),mt=(0,i.useCallback)(()=>{let t=K;t&&window.setTimeout(()=>{try{t.scrollTop=t.scrollHeight}catch{}},50)},[K]),Ft=(0,i.useCallback)(()=>{ht(!1),Ie&&lt(!1),pt(!1),se?.()},[Ie,se]);(0,i.useEffect)(()=>{if(F)return Ae(),window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[F,Ae]),(0,i.useEffect)(()=>{if(!(!F||!Ie))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[F,Ie,Ft]);let Ct=(0,i.useMemo)(()=>W.map(t=>({id:t.id,url:t.objectUrl,title:t.file.name})),[W]);(0,i.useEffect)(()=>{h||dt(!0)},[h]),(0,i.useEffect)(()=>()=>{ge(re.current)},[ge]),(0,i.useEffect)(()=>{let t=K;if(!t)return;let d=()=>{let v=t.scrollHeight-(t.scrollTop+t.clientHeight);dt(v<20)};return t.addEventListener("scroll",d),()=>{t.removeEventListener("scroll",d)}},[F,K]),(0,i.useEffect)(()=>{if(!N)return;let t=K;t&&t.scrollHeight>t.clientHeight&&(t.scrollTop=t.scrollHeight)},[U,D.busy,N,K]),(0,i.useEffect)(()=>{F||Ze(null)},[F]);let Ot=(0,i.useMemo)(()=>D.busy?Ir(D.statusEvent,T)||S.I18n.get("Working\u2026"):null,[D.busy,D.statusEvent,ne,T]),Mn=(0,i.useMemo)(()=>{for(let t=U.length-1;t>=0;t--){let d=U[t];if(d.role==="user"&&d.clientStatus==="canceled")return d.id}return null},[U]),Nt=(0,i.useCallback)(t=>{Re(d=>{let v=[...d].map((R,O)=>({m:R,i:O})).reverse().find(R=>R.m.role==="user"&&R.m.clientStatus==="pending")?.i;if(v==null)return d;let u=d.slice(),C=u[v];return u[v]={...C,clientStatus:t??void 0},u})},[Re]),Wt=(0,i.useCallback)(()=>{if(!(!D.busy||ct.current!=="chat")){et.current=!0;try{D.cancel()}catch{}Nt("canceled"),z(null),Ne(null),mt()}},[D,Nt,mt]),Dn=(0,i.useCallback)(t=>{let d=re.current,v=Array.from(t.target.files||[]),u=Math.max(0,oe-d.length);if(u===0){t.currentTarget.value="";return}let C=[];for(let R of v){if(C.length>=u)break;let O=/image\/(jpeg|png|gif|webp)/i.test(R.type),V=R.size<=qe,ee=[...d,...C].some(Ke=>Ke.file.name===R.name&&Ke.file.size===R.size&&Ke.file.lastModified===R.lastModified);if(!O||!V||ee)continue;let Ce=Dt(R);Ce&&C.push({id:vt("composer-image"),file:R,objectUrl:Ce})}C.length&&Te(R=>[...R,...C]),t.currentTarget.value=""},[oe,qe]),En=(0,i.useCallback)(t=>{Te(d=>{if(t<0||t>=d.length)return d;let v=d[t];return v&&ra(v.objectUrl),d.filter((u,C)=>C!==t)})},[]),kt=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(we)return kt.current&&(window.clearTimeout(kt.current),kt.current=null),kt.current=window.setTimeout(()=>{Ne(null),kt.current=null},6e3),()=>{kt.current&&(window.clearTimeout(kt.current),kt.current=null)}},[we]);let Ta=(0,i.useCallback)(async(t,d)=>{let v=P!=="nostorage",u=[];if(t.length>0){let C=await Promise.all(t.map(async R=>{let O=vt("attachment-image"),V;if(v)try{V=await ka(O,R.file,{name:R.file.name,type:R.file.type,size:R.file.size})??void 0}catch(Ce){console.warn("[AiChatbot] Failed to persist image",Ce)}let ee=Dt(R.file);return{id:O,name:R.file.name,type:R.file.type||"application/octet-stream",size:R.file.size,blobId:V,objectUrl:ee??void 0,blob:R.file,mediaType:"image"}}));u.push(...C.filter(Boolean))}if(d){let C=vt("attachment-audio"),R;if(v)try{R=await ka(C,d.blob,{name:`audio-${Date.now()}.webm`,type:d.blob.type,size:d.blob.size})??void 0}catch(V){console.warn("[AiChatbot] Failed to persist audio",V)}let O=Dt(d.blob);u.push({id:C,name:`audio-${Date.now()}.webm`,type:d.blob.type||"audio/webm",size:d.blob.size,blobId:R,objectUrl:O??void 0,blob:d.blob,duration:d.duration,mediaType:"audio"})}return u},[P]),wa=(0,i.useCallback)(async t=>{let d=[];for(let v of t){let u;if(v.attachments&&v.attachments.length>0){u=[];for(let C of v.attachments){let R;if(C.blobId)try{R=(await ba(C.blobId))?.blob??void 0}catch(V){console.warn("[AiChatbot] Failed to hydrate attachment",V)}if(!R)continue;let O=R?Dt(R):null;u.push({...C,objectUrl:O??void 0,blob:R??void 0})}}d.push({...v,attachments:u})}return d},[]),Sa=(0,i.useCallback)(async t=>{if(!t||t.length===0){Qe();return}let d=[];for(let v of t){let u=v.blob;if(!u&&v.blobId)try{u=(await ba(v.blobId))?.blob??void 0}catch(O){console.warn("[AiChatbot] Failed to reload attachment",O)}if(!u)continue;let C=u instanceof File?u:new File([u],v.name||"attachment",{type:v.type||u.type||"application/octet-stream"}),R=Dt(C);if(R&&(d.push({id:vt("composer-image"),file:C,objectUrl:R}),d.length>=oe))break}if(d.length===0){Qe();return}Te(v=>(ge(v),d)),tt.current&&(tt.current.value="")},[Qe,ge,oe]),ia=(0,i.useCallback)((t,d)=>{t&&Ze({url:t,title:d})},[]),Bn=(0,i.useCallback)(()=>{Ze(null)},[]),Ra=(0,i.useCallback)(()=>{vn(q.current),Qe(),Ee(),Re([]),Ne(null),De.current=null,o(null),dt(!0),st(!1);let t=va(P);if(t)try{t.removeItem(Mt)}catch{}aa()},[Qe,Ee,P]),Kn=(0,i.useCallback)(()=>{st(!0)},[]),Un=(0,i.useCallback)(()=>{D.busy&&ct.current==="chat"&&Wt(),Ra()},[D.busy,Wt,Ra]),Ia=(0,i.useCallback)(()=>{st(!1)},[]),za=(0,i.useCallback)(async(t,d)=>{if(!D.busy)try{let v=De.current&&Date.now()-De.current.storedAt<fe*na?De.current.id:void 0;if(!v)return;z("feedback"),Ne(null),await D.run(async({signal:u,onStatus:C})=>(await(0,Et.sendFeedbackMessage)({sessionId:v,feedbackMessageId:t,feedbackType:d},{signal:u,onStatus:C,context:Ue}),null)),Ne(null)}catch(v){let u=v?.message?.trim()||S.I18n.get("An error occurred.");Ne(u),console.error("Failed to send feedback",v)}finally{z(v=>v==="feedback"?null:v)}},[D,ne]),Ca=(0,i.useCallback)((t,d)=>{Re(v=>v.map(u=>u.id!==t||u.role!=="assistant"?u:u.feedback===d?{...u,feedback:void 0}:{...u,feedback:d})),za(t,d)},[za]),qt=(0,i.useCallback)(async()=>{let t=w.current.trim(),d=Y.current;if(!t&&!d||D.busy)return;et.current=!1,Ne(null),z("chat");let v=[...re.current],u=await Ta(v,d),C=vt("user"),R=Date.now(),O={id:C,role:"user",content:t||(d?"[Audio message]":""),createdAt:R,clientStatus:"pending",attachments:u.length?u:void 0};be(""),Qe(),Ee(),Re(V=>[...V,O]),F||ht(!0),mt();try{let V=De.current&&Date.now()-De.current.storedAt<fe*na?De.current.id:void 0,ee=await D.run(async({signal:Ke,onStatus:Ge})=>await(0,Et.sendChatMessage)({sessionId:V,message:t||void 0,audio:d?.blob,images:v.map(_n=>_n.file)},{signal:Ke,onStatus:Ge,context:Ue}));if(et.current){Nt("canceled");return}if(!ee)throw new Error(S.I18n.get(D.error??T.emptyResponseLabel));ee.sessionId&&(De.current={id:ee.sessionId,storedAt:Date.now()});let Ce={id:ee.metadata?.messageId||vt("assistant"),role:"assistant",content:ee.result||"",citations:ee.citations,createdAt:Date.now()};Re(Ke=>[...Ke.map(Rt=>Rt.id===C?{...Rt,clientStatus:void 0}:Rt),Ce]),o(R)}catch(V){if(console.error("Error during ask()",V),et.current||Rr(V)){Nt("canceled");return}let ee=V?.message?.trim()||S.I18n.get(T.unexpectedErrorLabel);Re(Ce=>[...Ce.map(Ge=>Ge.id===C?{...Ge,clientStatus:void 0}:Ge),{id:vt("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${ee}`,createdAt:Date.now()}]),o(R)}finally{z(V=>V==="chat"?null:V),et.current=!1,je.current&&je.current.focus(),mt()}},[D,Ta,Qe,Ee,F,mt,Nt,T.emptyResponseLabel,T.unexpectedErrorLabel,ne]),On=(0,i.useCallback)(t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Q&&qt())},[qt,Q]),Nn=(0,i.useCallback)(()=>{ht(!0)},[]);(0,i.useEffect)(()=>()=>{ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null)},[]);let jn=(0,i.useCallback)(()=>{lt(t=>{let d=!t;return ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null),d?(pt(!0),requestAnimationFrame(()=>{ze.current=requestAnimationFrame(()=>{pt(!1),ze.current=null})})):pt(!1),d})},[]),Gn=(0,i.useCallback)(t=>{be(t.content),(async()=>(await Sa(t.attachments),Re(d=>d.filter(v=>v.id!==t.id)),Rn(t.attachments),queueMicrotask(()=>je.current?.focus())))()},[Sa]),xa=(0,i.useMemo)(()=>ce?I?(0,s.jsx)("img",{src:I,className:"ai-open-btn-icon",alt:S.I18n.get(T.askMeLabel||X)}):(0,s.jsx)(ve.IconMessage,{size:18}):null,[ce,I,T,X,ne]),Hn=(0,i.useMemo)(()=>{let t=xa,d=G?(0,s.jsx)(k.Text,{inherit:!0,children:X}):null;if(!ce&&!d)return null;if(!ce)return d;if(!G)return t;switch(ae){case"top":return(0,s.jsxs)(k.Stack,{gap:4,align:"center",children:[t,d]});case"bottom":return(0,s.jsxs)(k.Stack,{gap:4,align:"center",children:[d,t]});case"right":return(0,s.jsxs)(k.Group,{gap:6,align:"center",children:[d,t]});default:return(0,s.jsxs)(k.Group,{gap:6,align:"center",children:[t,d]})}},[xa,ce,G,X,ae]),Fn=(0,i.useMemo)(()=>A,[A]),Wn=(0,i.useMemo)(()=>!A,[A]),qn=(0,i.useMemo)(()=>we||(h?S.I18n.get(T.readyLabel):S.I18n.get(T.readyEmptyLabel)),[we,h,T.readyLabel,T.readyEmptyLabel,ne]),Yn=(0,i.useMemo)(()=>A?S.I18n.get(T.cancelLabel):S.I18n.get(T.sendLabel),[A,T.cancelLabel,T.sendLabel,ne]),Vn=(0,i.useMemo)(()=>A?(0,s.jsx)(ve.IconPlayerStop,{size:18}):(0,s.jsx)(ve.IconSend,{size:18}),[A]),Jn=(0,i.useCallback)(()=>{if(A){Wt();return}qt()},[A,Wt,qt]);return(0,i.useEffect)(()=>{if(!F||!Le||!K)return;let t=()=>{let V=window.getComputedStyle(K).overflowY,ee=V==="auto"||V==="scroll",Ce=Math.ceil(K.scrollHeight),Ke=Math.floor(K.clientHeight),Ge=Ce>Ke;return ee&&Ge},d=!1,v=O=>{if(!t())return;O.preventDefault();let V=K.scrollHeight-K.clientHeight;K.scrollTop=Math.max(0,Math.min(V,K.scrollTop+O.deltaY))},u=()=>{let O=t();Pe(O),O!==d&&(d=O,d?Le.addEventListener("wheel",v,{passive:!1}):Le.removeEventListener("wheel",v))};u();let C=new ResizeObserver(u);C.observe(K);let R=new MutationObserver(u);return R.observe(K,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",u),()=>{d&&Le.removeEventListener("wheel",v),C.disconnect(),R.disconnect(),window.removeEventListener("resize",u)}},[F,Le,K]),(0,i.useEffect)(()=>{let t=!1,d=va(P);if(!d){P==="nostorage"&&aa(),pe(!0);return}return(async()=>{try{let v=d.getItem(Mt);if(!v){pe(!0);return}let u=JSON.parse(v),C=typeof u?.lastUserSentAt=="number"?u.lastUserSentAt:null;if(!C||Date.now()-C>fe*na){d.removeItem(Mt),await aa(),pe(!0);return}let O=(Array.isArray(u.messages)?u.messages:[]).map(ee=>ee?.role==="user"&&ee.clientStatus==="pending"?{...ee,clientStatus:"canceled"}:ee),V=await wa(O);if(t){vn(V);return}Re(V),o(C),u.session&&u.session.id&&(De.current=u.session)}catch(v){console.warn("[AiChatbot] Failed to load history",v);try{d.removeItem(Mt)}catch{}}finally{t||pe(!0)}})(),()=>{t=!0}},[P,fe,wa]),(0,i.useEffect)(()=>{if(!Fe)return;let t=va(P);if(!t)return;let d=_.current;if(!d)return;if(Date.now()-d>fe*na){try{t.removeItem(Mt)}catch{}ya(new Set);return}let v=U.map(({attachments:R,...O})=>({...O,attachments:R?.map(({objectUrl:V,blob:ee,...Ce})=>Ce)})),u={version:1,lastUserSentAt:d,session:De.current,messages:v};try{t.setItem(Mt,JSON.stringify(u))}catch{}let C=new Set;v.forEach(R=>{R.attachments?.forEach(O=>{O.blobId&&C.add(O.blobId)})}),ya(C)},[Fe,U,gt,P,fe]),l&&!te||!l&&te?null:(0,s.jsxs)(k.Group,{className:at,children:[!F&&(0,s.jsx)(k.Button,{variant:"filled",className:G?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:Nn,"aria-label":X,title:X,"data-ai-kit-open-button":!0,children:Hn}),F&&(0,s.jsx)(k.Modal.Root,{ref:We,opened:F,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:Ft,className:at+" ai-chat-container"+(Ie?" maximized":"")+(Ie&&ut?" ai-max-enter":""),portalProps:{target:n,reuseTargetNode:!0},"data-ai-kit-theme":ie,"data-ai-kit-variation":"modal",children:(0,s.jsxs)("div",{className:"ai-chat-container-internal",ref:zt,children:[(0,s.jsxs)(k.Modal.Header,{className:"ai-chat-header-bar",children:[(0,s.jsx)(k.Modal.Title,{className:"ai-chat-title",children:Se}),(0,s.jsxs)(k.Group,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&(0,s.jsx)(k.ActionIcon,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:jn,title:Ie?S.I18n.get(T.restoreSizeLabel):S.I18n.get(T.maximizeLabel),"aria-label":Ie?S.I18n.get(T.restoreSizeLabel):S.I18n.get(T.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Ie?(0,s.jsx)(ve.IconMinimize,{size:16}):(0,s.jsx)(ve.IconMaximize,{size:16})}),(0,s.jsx)(k.Modal.CloseButton,{"aria-label":S.I18n.get(T.closeChatLabel)})]})]}),(0,s.jsxs)(k.Modal.Body,{className:"ai-chat-scroll",ref:St,"data-scrollable":Bt?"true":"false",children:[U.map(t=>{let d=t.role==="user",v=d&&t.clientStatus==="canceled"&&t.id===Mn;return(0,s.jsx)(k.Group,{justify:d?"flex-end":"flex-start",className:"ai-chat-row "+t.role,onMouseEnter:()=>Je(t.id),onMouseLeave:()=>Je(u=>u===t.id?null:u),children:(0,s.jsxs)(k.Stack,{gap:4,w:"100%",style:{alignItems:d?"flex-end":"flex-start"},children:[(0,s.jsxs)(k.Stack,{className:"ai-chat-bubble",children:[(0,s.jsxs)(k.Text,{className:"ai-chat-header",children:[(0,s.jsx)(k.Text,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:d?S.I18n.get(T.userLabel):S.I18n.get(T.assistantLabel)}),"\xA0",(0,s.jsx)(k.Text,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(t.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),t.role==="assistant"?(0,s.jsx)(wn.default,{remarkPlugins:[Sn.default],children:t.content}):(0,s.jsx)(k.Text,{size:"sm",miw:"100px",children:t.content})]}),t.attachments&&t.attachments.length>0&&(0,s.jsxs)(k.Stack,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).length>0&&(0,s.jsx)(k.Group,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).map(u=>(0,s.jsx)("button",{type:"button",className:"thumb",style:{backgroundImage:u.objectUrl?`url(${u.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>ia(u.objectUrl,u.name),disabled:!u.objectUrl,title:u.name||S.I18n.get("View image"),"aria-label":u.name||S.I18n.get("View image"),children:!u.objectUrl&&(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:S.I18n.get("Image no longer available")})},u.id))}),t.attachments.filter(u=>u.mediaType==="audio"||!u.mediaType&&u.type.startsWith("audio/")).map(u=>(0,s.jsx)(k.Box,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:u.objectUrl?(0,s.jsxs)(k.Stack,{gap:"xs",children:[(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:u.objectUrl,preload:"metadata"}),u.duration&&(0,s.jsxs)(k.Text,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(u.duration),"s"]})]}):(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:S.I18n.get("Audio no longer available")})},u.id))]}),v&&(0,s.jsxs)(k.Group,{justify:"flex-end",gap:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:S.I18n.get(T.notSentLabel)})}),ft===t.id&&(0,s.jsx)(k.ActionIcon,{size:"sm",variant:"subtle",onClick:()=>Gn(t),title:S.I18n.get(T.editLabel),"aria-label":S.I18n.get(T.editLabel),"data-ai-kit-edit-button":!0,children:(0,s.jsx)(ve.IconPencil,{size:14})})]}),t.citations&&t.citations.length>0&&(0,s.jsxs)(k.Stack,{className:"ai-citations",children:[(0,s.jsx)(k.Text,{fw:"bold",size:"sm",mb:"xs",children:S.I18n.get(T.referencesLabel)}),(0,s.jsx)(k.List,{spacing:"xs",size:"sm",children:t.citations.map((u,C)=>{let R=u.sourceUrl||u.url,O=u.title||R||`${S.I18n.get(T.referenceLabel)} #${C+1}`;return(0,s.jsxs)(k.List.Item,{children:[R?(0,s.jsx)(k.Anchor,{href:R,target:"_blank",rel:"noreferrer",children:O}):(0,s.jsx)(k.Text,{children:O}),u.snippet?(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",mt:4,children:u.snippet}):null]},C)})})]}),t.role==="assistant"&&(0,s.jsxs)(k.Group,{className:"ai-feedback",gap:"xs",children:[(0,s.jsx)(k.Button,{className:t.feedback==="accepted"?"active":void 0,onClick:()=>Ca(t.id,"accepted"),"aria-label":S.I18n.get(T.acceptResponseLabel),disabled:D.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),(0,s.jsx)(k.Button,{type:"button",className:t.feedback==="rejected"?"active":void 0,onClick:()=>Ca(t.id,"rejected"),"aria-label":S.I18n.get(T.rejectResponseLabel),disabled:D.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},t.id)}),Fn&&(0,s.jsx)(k.Group,{justify:"flex-start",className:"ai-chat-row assistant status",children:(0,s.jsxs)(k.Stack,{className:"ai-chat-bubble typing",children:[Ot?(0,s.jsx)(k.Text,{size:"sm",c:"dimmed",children:(0,s.jsx)("em",{children:Ot})}):null,(0,s.jsxs)("div",{className:"typing-indicator",children:[(0,s.jsx)("span",{}),(0,s.jsx)("span",{}),(0,s.jsx)("span",{})]})]})})]}),Wn&&(0,s.jsx)(k.Group,{className:"ai-status-line",children:(0,s.jsx)(k.Text,{className:"ai-status-text",children:(0,s.jsx)("em",{children:qn})})}),(0,s.jsxs)(k.Stack,{className:"ai-box ai-box-open",children:[(0,s.jsxs)(k.Modal,{opened:de,onClose:Ia,centered:!0,title:S.I18n.get("Reset conversation"),style:{zIndex:"var(--mb-z-index)",position:"fixed"},left:0,children:[(0,s.jsx)(k.Text,{size:"sm",children:S.I18n.get("Are you sure you want to reset the conversation?")}),(0,s.jsxs)(k.Group,{justify:"flex-end",mt:"md",children:[(0,s.jsx)(k.Button,{variant:"default",onClick:Ia,"data-ai-kit-no-button":!0,children:S.I18n.get("No")}),(0,s.jsx)(k.Button,{color:"var(--ai-kit-color-danger, red)",onClick:Un,disabled:!h&&!A,"data-ai-kit-yes-button":!0,children:S.I18n.get("Yes")})]})]}),(0,s.jsx)(k.Group,{children:(0,s.jsx)(k.Textarea,{className:"ai-message",ref:je,placeholder:Be,value:H,onChange:t=>{be(t.target.value),M&&Ee()},onKeyDown:On,rows:3,disabled:ye||!!M})}),Aa&&ye&&(0,s.jsxs)(k.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:S.I18n.get("Recording...")})}),(0,s.jsx)("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:(0,s.jsx)("div",{style:{width:`${wt}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Aa&&M&&!ye&&(0,s.jsxs)(k.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(k.Text,{size:"xs",c:"dimmed",children:(0,s.jsxs)("em",{children:[S.I18n.get("Audio recorded")," (",Math.round(M.duration),"s)"]})}),(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:M.objectUrl})]}),(0,s.jsxs)(k.Group,{className:"ai-actions",justify:"space-between",w:"100%",children:[(0,s.jsx)(k.Group,{justify:"flex-start",children:(0,s.jsx)(k.Button,{variant:"light",leftSection:(0,s.jsx)(ve.IconTrash,{size:18}),onClick:Kn,disabled:!h&&!A,"data-ai-kit-reset-button":!0,children:S.I18n.get(T.resetLabel)})}),(0,s.jsxs)(k.Group,{justify:"flex-end",children:[Aa&&(0,s.jsx)(s.Fragment,{children:M?(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(ve.IconX,{size:18}),onClick:Ee,disabled:A,title:S.I18n.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:S.I18n.get("Clear")}):(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(ve.IconMicrophone,{size:18}),onClick:ye?Ut:Kt,disabled:A,title:ye?S.I18n.get("Stop recording"):S.I18n.get("Record audio"),color:ye?"red":void 0,"data-ai-kit-microphone-button":!0,children:ye?S.I18n.get("Stop"):S.I18n.get("Record")})}),oe>0&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(k.Button,{variant:"outline",leftSection:(0,s.jsx)(ve.IconPaperclip,{size:18}),onClick:()=>tt.current?.click(),disabled:W.length>=oe||A||ye||!!M,title:S.I18n.get(T.addImageLabel),"data-ai-kit-add-image-button":!0,children:S.I18n.get(T.addLabel)}),(0,s.jsx)(k.Input,{ref:tt,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:Dn})]}),(0,s.jsx)(k.Button,{leftSection:Vn,variant:"filled",onClick:Jn,disabled:!A&&!Q,"data-ai-kit-send-button":!0,children:Yn})]})]}),Ct.length>0&&(0,s.jsx)(k.Group,{className:"ai-thumbs",mt:"xs",gap:"xs",children:Ct.map(({url:t,title:d},v)=>(0,s.jsx)("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:t?`url(${t})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":d||S.I18n.get("View image"),onClick:()=>ia(t,d),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),ia(t,d))},children:(0,s.jsx)(k.Button,{variant:"white",onClick:u=>{u.stopPropagation(),En(v)},"aria-label":S.I18n.get(T.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:S.I18n.get(T.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},W[v]?.id??v))})]})]})}),(0,s.jsx)(k.Modal,{opened:!!me,onClose:Bn,centered:!0,size:"auto",title:me?.title||S.I18n.get("Image preview"),children:me&&(0,s.jsx)("img",{src:me.url,alt:me.title||S.I18n.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},In=At(zr,{showOpenButton:!0,variation:"modal"});var y=require("@mantine/core"),Tt=require("@smart-cloud/ai-kit-core"),$=require("aws-amplify/utils"),x=require("react"),Cn=Ye(require("react-markdown"),1),xn=Ye(require("rehype-raw"),1),Ln=Ye(require("remark-gfm"),1),Ve=require("@tabler/icons-react");var p=require("react/jsx-runtime");$.I18n.putVocabularies(bt);var zn=!1;function Cr(e){let n=e?.citations?.docs??[],m=e?.citations?.chunks??[],l=new Map;for(let a of n)l.set(a.docId,{doc:a,chunks:[]});for(let a of m){let f=l.get(a.docId);f?f.chunks.push(a):l.set(a.docId,{doc:{docId:a.docId},chunks:[a]})}return Array.from(l.values())}var xr=e=>{let{autoRun:n=!0,context:m,title:l,showOpenButton:a=!1,openButtonTitle:f,showOpenButtonTitle:I=!0,openButtonIcon:G,showOpenButtonIcon:ce=!0,searchButtonIcon:ie,showSearchButtonTitle:ne=!0,showSearchButtonIcon:se=!0,showSources:Ue=!0,topK:le=10,getSearchText:L,enableUserFilters:g=!1,availableCategories:P,availableTags:fe,variation:Z,rootElement:ae,colorMode:ke,language:T,onClose:D,onClickDoc:H}=e,[be,W]=(0,x.useState)(!a),[Te,M]=(0,x.useState)(""),[J,ye]=(0,x.useState)(!1),[ue,wt]=(0,x.useState)(null),[_e,it]=(0,x.useState)(0),$e=(0,x.useRef)(null),Oe=(0,x.useRef)([]),xe=(0,x.useRef)(null),E=(0,x.useRef)(null),[U,Re]=(0,x.useState)(!1),[we,Ne]=(0,x.useState)([]),[de,st]=(0,x.useState)([]),[Ie,lt]=(0,x.useState)([]),[ut,pt]=(0,x.useState)(""),[F,ht]=(0,x.useState)(null),[N,dt]=(0,x.useState)(!1),me=(0,x.useRef)(null),Ze=(0,x.useRef)(null),Fe=1440*60*1e3,{busy:pe,error:Le,statusEvent:zt,result:K,run:St,cancel:Bt,reset:Pe}=It(),he=(0,x.useRef)(!1),z=(0,x.useRef)([]),ct=K?.sessionId,ze=K?.citations?.docs??[],et=K?.citations?.chunks??[],ft=K?.citations?.anchors??[],Je=K?.result??"",tt=(0,x.useMemo)(()=>{if(se)return ie?.trim()?(0,p.jsx)("img",{src:ie,alt:"",style:{width:18,height:18,objectFit:"contain"}}):(0,p.jsx)(Ve.IconSearch,{size:18})},[ie,se]),je=(0,x.useMemo)(()=>(T&&$.I18n.setLanguage(T||"en"),$.I18n.get(l||"Search with AI-Kit")),[T]),De=(0,x.useMemo)(()=>zt?$.I18n.get("Searching\u2026"):null,[T,zt]),We=(0,x.useMemo)(()=>Te||L,[Te,L]),ge=(0,x.useMemo)(()=>{if(pe||!be)return!1;let h=typeof We=="function"?We():We;return!!(h&&h.trim().length>0||ue)},[We,pe,ue,be]),Qe=(0,x.useMemo)(()=>{if(!F)return!1;let h=Object.keys(F.allowedCategories).length>0,A=F.allowedTags.length>0;return h||A},[F]),Ee=(0,x.useMemo)(()=>we.length===0||!F?[]:we.flatMap(h=>F.allowedCategories[h]||[]).filter((h,A,Q)=>Q.indexOf(h)===A),[we,F]),Kt=(0,x.useCallback)(async()=>{try{M("");let h=await navigator.mediaDevices.getUserMedia({audio:!0}),A=new MediaRecorder(h,{mimeType:"audio/webm"}),Q=new AudioContext,X=Q.createMediaStreamSource(h),Se=Q.createAnalyser();Se.fftSize=2048,Se.smoothingTimeConstant=.8,X.connect(Se),xe.current=Q,E.current=Se;let Be=new Uint8Array(Se.fftSize),at=()=>{if(!E.current)return;E.current.getByteTimeDomainData(Be);let Ae=0;for(let Ct=0;Ct<Be.length;Ct++){let Ot=(Be[Ct]-128)/128;Ae+=Ot*Ot}let mt=Math.sqrt(Ae/Be.length),Ft=Math.min(100,mt*200);it(Ft),me.current=requestAnimationFrame(at)};at(),Oe.current=[],A.ondataavailable=Ae=>{Ae.data.size>0&&Oe.current.push(Ae.data)},A.onstop=()=>{let Ae=new Blob(Oe.current,{type:"audio/webm"});wt(Ae),h.getTracks().forEach(mt=>mt.stop()),me.current&&(cancelAnimationFrame(me.current),me.current=null),xe.current&&(xe.current.close(),xe.current=null),E.current=null,it(0)},$e.current=A,A.start(),ye(!0)}catch(h){console.error("Failed to start recording:",h)}},[]),Ut=(0,x.useCallback)(()=>{$e.current&&J&&($e.current.stop(),ye(!1))},[J]),gt=(0,x.useCallback)(()=>{wt(null),Oe.current=[],it(0),Ze.current=null},[]);(0,x.useEffect)(()=>()=>{me.current&&cancelAnimationFrame(me.current),xe.current&&xe.current.close()},[]),(0,x.useEffect)(()=>{if(!g)return;if(P||fe){ht({allowedCategories:P||{},allowedTags:fe||[]});return}(async()=>{dt(!0);try{let A=await(0,Tt.resolveBackend)();if(!A.available){console.error("Backend not available for metadata options");return}let Q={feature:"prompt",source:"backend",mode:"backend-only",onDeviceAvailable:!1,backendAvailable:A.available,backendTransport:A.transport,backendApiName:A.apiName,backendBaseUrl:A.baseUrl,reason:A.reason??""},X=await(0,Tt.dispatchBackend)(Q,m??"frontend","/kb/metadata-options","GET",null,{});ht({allowedCategories:X.allowedCategories||{},allowedTags:X.allowedTags||[]})}catch(A){console.error("Failed to load metadata options:",A)}finally{dt(!1)}})()},[g,P,fe,m]);let o=(0,x.useCallback)(async()=>{let h;if(!ue){if(h=typeof We=="function"?We():We,!h)return;M(h)}console.log("Starting search with query:",h,"and audio:",ue);let A=Date.now(),Q=ue&&Ze.current?.blob===ue&&A-Ze.current.uploadTimestamp<Fe;ue&&!Q?(Ze.current={blob:ue,uploadTimestamp:A},console.log("Audio cache updated for new recording")):Q&&console.log("Reusing cached audio (no re-upload needed within",Math.round((Fe-(A-Ze.current.uploadTimestamp))/1e3),"seconds)"),Pe(),await St(async({signal:X,onStatus:Se})=>await(0,Tt.sendSearchMessage)({sessionId:ct,...h&&{query:h},...ue&&{audio:ue},topK:le,...g&&{userSelectedCategories:we},...g&&de.length>0&&{userSelectedSubcategories:de},...g&&Ie.length>0&&{userSelectedTags:Ie}},{signal:X,onStatus:Se,context:m}))},[m,We,ue,St,Pe,le,ct,g,we,de,Ie]),w=(0,x.useCallback)(async()=>{W(!1),Pe(),a||D()},[D,Pe,he,a]);(0,x.useEffect)(()=>{!n||!ge||pe||he.current||(he.current=!0,queueMicrotask(()=>{o()}))},[pe,he,ge,n,o]),(0,x.useEffect)(()=>{ge||(he.current=!0)},[ge]),(0,x.useEffect)(()=>{let h=z.current,A=we;(h.length!==A.length||!A.every(X=>h.includes(X)))&&h.length>0&&Pe(),z.current=[...A]},[we,Pe]);let q=(0,x.useMemo)(()=>Cr(K),[K]),_=(0,x.useMemo)(()=>{let h=new Map;return ze.forEach((A,Q)=>{A?.docId&&h.set(A.docId,Q+1)}),h},[ze]),re=(0,x.useMemo)(()=>{let h=new Map;return et.forEach(A=>{A?.chunkId&&A?.docId&&h.set(A.chunkId,A.docId)}),h},[et]),Y=(0,x.useMemo)(()=>{if(!Je)return"";if(!ft.length||_.size===0)return Je;let h=[...ft].filter(X=>Array.isArray(X?.chunkIds)&&X?.span?.end!==void 0).sort((X,Se)=>{let Be=X.span?.end??0,at=Se.span?.end??0;return Be-at}),A=0,Q=[];for(let X of h){let Se=X.span?.end;if(typeof Se!="number"||Se<A)continue;let Be=Array.from(new Set((X.chunkIds??[]).map(Ae=>Ae?re.get(Ae):void 0).map(Ae=>Ae?_.get(Ae):void 0).filter(Ae=>typeof Ae=="number")));if(!Be.length)continue;let at=Math.min(Se,Je.length);Q.push(Je.slice(A,at)),Q.push(`<sup>${Be.join(",")}</sup>`),A=at}return Q.push(Je.slice(A)),Q.join("")},[ft,Je]),te=Z==="modal"?y.Modal.Root:y.Group,oe=Z==="modal"?y.Modal.Content:y.Group,qe=Z==="modal"?y.Modal.Body:y.Group;return(0,x.useEffect)(()=>{if(!(Z!=="modal"||!be))return document.body.style.overflow="hidden",document.body.onkeydown=h=>{h.key==="Escape"&&(h.preventDefault(),w())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[w,Z,be]),(0,p.jsxs)(p.Fragment,{children:[a&&(0,p.jsx)(y.Button,{leftSection:ce&&(G?(0,p.jsx)("span",{dangerouslySetInnerHTML:{__html:G}}):(0,p.jsx)(Ve.IconSearch,{size:18})),className:I?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:be,onClick:()=>W(!0),"data-ai-kit-open-button":!0,children:I&&$.I18n.get(f||je)}),be&&(0,p.jsxs)(te,{opened:!0,className:"doc-search-root",onClose:w,padding:"md",gap:"md",size:"xl",portalProps:Z==="modal"?{target:ae,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":ke,"data-ai-kit-variation":Z,children:[Z==="modal"&&(0,p.jsx)(y.Modal.Overlay,{}),(0,p.jsxs)(oe,{w:"100%",style:{left:0,...Z==="modal"&&!K?.result&&{overflow:"visible"}},children:[Z==="modal"&&(0,p.jsxs)(y.Modal.Header,{style:{zIndex:1e3},children:[(0,p.jsx)(Tt.AiKitDocSearchIcon,{className:"doc-search-title-icon"}),(0,p.jsx)(y.Modal.Title,{children:$.I18n.get(je)}),(0,p.jsx)(y.Modal.CloseButton,{})]}),(0,p.jsx)(qe,{w:"100%",style:{zIndex:1001,...Z==="modal"&&!K?.result&&{overflow:"visible"}},children:(0,p.jsx)(Lt,{enabled:Z!=="modal",working:pe,variation:Z,children:(0,p.jsx)(y.Paper,{shadow:"sm",radius:"md",p:"md",children:(0,p.jsxs)(y.Stack,{gap:"sm",children:[Z!=="modal"&&(0,p.jsxs)(y.Group,{justify:"space-between",children:[(0,p.jsx)(y.Title,{order:4,style:{margin:0},children:$.I18n.get(je)}),a&&(0,p.jsx)(y.Button,{variant:"subtle",color:"gray",size:"xs",onClick:w,style:{minWidth:32,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":$.I18n.get("Close"),children:(0,p.jsx)(Ve.IconX,{size:18,style:{color:ke==="dark"?"var(--mantine-color-dark-1)":"var(--mantine-color-gray-7)"}})})]}),(0,p.jsxs)(y.Group,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[(0,p.jsx)(y.TextInput,{style:{flex:1},value:Te,onChange:h=>{M(h.currentTarget.value),ue&&gt()},placeholder:ue?$.I18n.get("Audio recorded"):$.I18n.get("Search the documentation\u2026"),disabled:pe||J||!!ue,onKeyDown:h=>{h.key==="Enter"&&ge&&(h.preventDefault(),o())}}),zn&&(0,p.jsx)(p.Fragment,{children:ue?(0,p.jsx)(y.Button,{variant:"outline",size:"sm",color:"red",onClick:gt,disabled:pe,title:$.I18n.get("Clear audio"),children:(0,p.jsx)(Ve.IconMicrophoneOff,{size:18})}):(0,p.jsx)(y.Button,{variant:J?"filled":"outline",size:"sm",color:J?"red":"gray",onClick:J?Ut:Kt,disabled:pe,title:J?$.I18n.get("Stop recording"):$.I18n.get("Record audio"),style:J?{transform:`scale(${1+_e/300})`,transition:"transform 0.1s ease-out"}:void 0,children:(0,p.jsx)(Ve.IconMicrophone,{size:18})})}),(0,p.jsx)(y.Button,{variant:"filled",size:"sm",leftSection:tt,onClick:()=>{o()},disabled:!ge,className:ne?"doc-search-button":"doc-search-button-no-title",children:ne?$.I18n.get("Search"):null}),pe?(0,p.jsx)(y.Button,{variant:"outline",size:"sm",onClick:Bt,children:$.I18n.get("Stop")}):null]}),!pe&&!Le&&!K?.result?(0,p.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:$.I18n.get("Enter a search query to start.")}):null,g&&F&&Qe&&(0,p.jsxs)(y.Stack,{gap:"xs",children:[(0,p.jsx)(y.Button,{variant:"subtle",size:"xs",onClick:()=>Re(!U),leftSection:U?(0,p.jsx)(Ve.IconChevronDown,{size:14}):(0,p.jsx)(Ve.IconChevronRight,{size:14}),style:{alignSelf:"flex-start"},children:$.I18n.get("Filters")}),(0,p.jsx)(y.Collapse,{in:U,children:(0,p.jsxs)(y.Stack,{gap:"md",children:[Object.keys(F.allowedCategories).length>0&&(0,p.jsxs)("div",{children:[(0,p.jsx)(y.Text,{size:"sm",fw:500,mb:"xs",children:$.I18n.get("Categories")}),(0,p.jsx)(y.Group,{gap:"md",children:Object.keys(F.allowedCategories).map(h=>(0,p.jsx)(y.Checkbox,{label:$.I18n.get(h),checked:we.includes(h),onChange:A=>{if(A.currentTarget.checked)Ne([...we,h]);else{Ne(we.filter(X=>X!==h));let Q=F.allowedCategories[h]||[];st(de.filter(X=>!Q.includes(X)))}},disabled:pe||N},h))})]}),Ee.length>0&&(0,p.jsxs)("div",{children:[(0,p.jsx)(y.Text,{size:"sm",fw:500,mb:"xs",children:$.I18n.get("Subcategories")}),(0,p.jsx)(y.Group,{gap:"md",children:Ee.map(h=>(0,p.jsx)(y.Checkbox,{label:$.I18n.get(h),checked:de.includes(h),onChange:A=>{A.currentTarget.checked?st([...de,h]):st(de.filter(Q=>Q!==h))},disabled:pe||N},h))})]}),F.allowedTags.length>0&&(0,p.jsx)(y.MultiSelect,{label:$.I18n.get("Tags"),placeholder:$.I18n.get("Select or type tags..."),data:F.allowedTags.map(h=>({value:h,label:$.I18n.get(h)})),value:Ie,onChange:lt,searchValue:ut,onSearchChange:pt,disabled:pe||N,searchable:!0,clearable:!0,maxDropdownHeight:200,limit:20})]})})]}),zn&&(0,p.jsxs)(p.Fragment,{children:[J&&(0,p.jsxs)(y.Stack,{gap:"xs",children:[(0,p.jsxs)(y.Text,{size:"xs",c:"dimmed",children:[$.I18n.get("Recording...")," \u{1F3A4}"]}),(0,p.jsx)(y.Progress,{value:_e,size:"sm",color:"red",animated:!0,striped:!0})]}),ue&&!J&&(0,p.jsxs)(y.Stack,{gap:"xs",children:[(0,p.jsx)(y.Text,{size:"xs",c:"dimmed",children:$.I18n.get("Recorded audio:")}),(0,p.jsx)("audio",{controls:!0,src:URL.createObjectURL(ue),className:"ai-kit-audio-player"})]})]}),Le?(0,p.jsx)(y.Alert,{color:"red",title:$.I18n.get("Error"),children:Le}):null,pe&&De&&(0,p.jsx)(Lt,{enabled:Z==="modal",working:!0,variation:Z,children:(0,p.jsxs)(y.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,p.jsx)(y.Loader,{size:"sm"}),(0,p.jsx)(y.Text,{size:"sm",c:"dimmed",children:De})]})}),K?.result?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(y.Divider,{}),(0,p.jsxs)(y.Stack,{gap:"xs","data-doc-search-result":!0,children:[(0,p.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:$.I18n.get("AI Summary")}),(0,p.jsx)(Cn.default,{remarkPlugins:[Ln.default],rehypePlugins:[xn.default],"data-doc-search-result-content":!0,children:Y||Je})]})]}):null,Ue&&(K?.citations?.docs?.length||K?.citations?.chunks?.length)?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(y.Divider,{}),(0,p.jsxs)(y.Stack,{gap:"sm","data-doc-search-sources":!0,children:[(0,p.jsx)(y.Text,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:$.I18n.get("Sources")}),q.map(({doc:h})=>{let A=h.sourceUrl?.trim()||void 0,Q=h.docId?_.get(h.docId):void 0,X=h.title?.trim()||h.docId,Se=(0,p.jsxs)(y.Text,{fw:600,style:{display:"inline"},children:[Q?`${Q}. `:"",X]});return(0,p.jsx)(y.Paper,{withBorder:!0,radius:"md",p:"sm",children:(0,p.jsx)(y.Stack,{gap:"xs",children:(0,p.jsx)(y.Group,{justify:"space-between",align:"flex-start",children:(0,p.jsxs)(y.Stack,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[A?(0,p.jsx)(y.Anchor,{href:A,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Be=>{H&&(Be.preventDefault(),H?.(h))},"data-doc-search-source-title":!0,children:Se}):Se,(0,p.jsx)(y.Anchor,{href:A,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Be=>{H&&(Be.preventDefault(),H?.(h))},"data-doc-search-source-url":!0,children:h.sourceUrl}),h.author?(0,p.jsx)(y.Text,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:h.author}):null,h.description?(0,p.jsx)(y.Text,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:h.description}):null]})})})},h.docId)})]})]}):null,(0,p.jsx)(Jt,{variation:Z})]})})})})]})]})]})},Pn=At(xr);0&&(module.exports={AiChatbot,AiFeature,DEFAULT_CHATBOT_LABELS,DocSearch,isBackendConfigured,markdownToHtml,readDefaultOutputLanguage,stripCodeFence,translations,useAiRun,withAiKitShell});
package/dist/index.js CHANGED
@@ -28,4 +28,4 @@ Guidelines:
28
28
  - caption: optional context users might see below the image; keep short.
29
29
  - description: 1\u20132 short sentences; can include context/usage if known.
30
30
  `+(oe?`
31
- Follow these additional instructions: ${oe}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),H=await w.run(async({signal:$,onStatus:ee})=>(await Ln({messages:O,images:[Ge],outputLanguage:"en",responseConstraint:uo},{signal:$,onStatus:ee,context:I,modeOverride:o,onDeviceTimeoutOverride:a})).result);if(!H){P("");return}let X=(D&&D!=="auto"?D:null)||Dt(),N=ta(H).trim();try{G("Translating result...");let $=await w.run(async({signal:ee})=>await go(N,X,{signal:ee,context:I,modeOverride:o,onDeviceTimeoutOverride:a,silent:!0}));P($)}catch($){P(N),console.warn("AI Kit: failed to parse SEO JSON",$)}break}}}catch(k){Le(k instanceof Error?k.message:n.get("An unknown error occurred."))}G(void 0)}},[B,w,oe,ue,D,Re,We,I,u,Pe,dt,ce,ve]),nt=Rt(async()=>{await ze("backend-only")},[ze]),At=Rt(o=>{switch(u){case"proofread":return b(no,{className:o});case"translate":return b(ro,{className:o});case"summarize":return b(so,{className:o});case"rewrite":case"write":return b(oo,{className:o});case"generateImageMetadata":case"generatePostMetadata":return b(io,{className:o});default:return b(_r,{mode:u,className:o})}},[u]),Ve=Rt(()=>{switch(u){case"proofread":return w.lastSource?n.get("Proofread again"):n.get("Proofread");case"translate":return w.lastSource?n.get("Translate again"):n.get("Translate");case"rewrite":return w.lastSource?n.get("Rewrite again"):n.get("Rewrite");case"summarize":return w.lastSource?n.get("Summarize again"):n.get("Summarize");default:return w.lastSource?n.get("Regenerate"):n.get("Generate")}},[B,w.lastSource,u]),rt=Rt(()=>{switch(u){case"proofread":return n.get("Proofread on Backend");case"translate":return n.get("Translate on Backend");case"rewrite":return n.get("Rewrite on Backend");case"summarize":return n.get("Summarize on Backend");default:return n.get("Regenerate on Backend")}},[B,u]),He=Rt(async()=>{re(!1),P(null),Le(null),L.current=!1,w.reset(),E||me()},[me,L,w,E]),Be=Rt(async()=>{w.busy&&w.cancel()},[w.busy]);ha(()=>{!he||!g||!ce||w.busy||x||L.current||(L.current=!0,queueMicrotask(()=>{ze(ge)}))},[w.busy,L,he,ce,g,x,ze,ge]),ha(()=>{ve&&u!=="proofread"&&(ce||(_e(!0),L.current=!0))},[ve,ce,u]),ha(()=>{let o=!0;return(async()=>{try{await eo();let k=await yn();o&&$e(k)}catch(k){console.error(k),o&&$e(!1)}})(),()=>{o=!1}},[]);let qe=na(()=>{let o=[];if(u==="translate"){let k=pa.find(O=>O.value===dt)?.label;o.push(n.get("Input language")+": "+(k?n.get(k):"auto"))}if(D&&U?.outputLanguage){let k=pa.find(O=>O.value===D)?.label;o.push(n.get("Output language")+": "+(k?n.get(k):D))}return u==="summarize"&&Pe&&U?.type&&o.push(n.get("Type")+": "+n.get(Pe)),(u==="write"||u==="rewrite")&&We&&U?.tone&&o.push(n.get("Tone")+": "+n.get(We)),(u==="write"||u==="rewrite"||u==="summarize")&&ue&&U?.length&&o.push(n.get("Length")+": "+n.get(ue)),oe?.trim()&&U?.instructions&&o.push(n.get("Instructions")+": \u2713"),o.length?o.join(" \u2022 "):n.get("No overrides")},[B,u,dt,D,Pe,We,ue,oe]),se={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},Qe=c==="modal"?Ut.Root:Tt,Ke=c==="modal"?Ut.Content:Tt,Zt=c==="modal"?Ut.Body:Tt,Qt=R==="collapse"?Wr:It,mt=R==="horizontal"?Tt:It;return ha(()=>{if(!(c!=="modal"||!he))return document.body.style.overflow="hidden",document.body.onkeydown=o=>{o.key==="Escape"&&(o.preventDefault(),He())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[He,c]),ye(ra,{children:[E&&b(Kt,{leftSection:te&&(ae?b("span",{dangerouslySetInnerHTML:{__html:ae}}):At()),className:ie?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:he,onClick:()=>re(!0),"data-ai-kit-open-button":!0,children:ie&&n.get(Q||Lt)}),he&&ye(Qe,{opened:!0,className:"ai-feature-root",onClose:He,padding:"md",gap:"md",size:"md",portalProps:c==="modal"?{target:pe,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":W,"data-ai-kit-variation":c,children:[c==="modal"&&b(Ut.Overlay,{}),ye(Ke,{w:"100%",style:{left:0},children:[c==="modal"&&ye(Ut.Header,{style:{zIndex:1e3},children:[At("ai-feature-title-icon"),b(Ut.Title,{children:n.get(Lt)}),b(Ut.CloseButton,{})]}),b(Zt,{w:"100%",style:{zIndex:1001},children:ye(qt,{enabled:c!=="modal",working:w.busy,variation:c,children:[ye(It,{gap:"sm",mb:"sm",p:"sm",children:[je&&b(xa,{color:"red",children:n.get(je)}),ve&&u!=="proofread"&&ye(Vr,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":R,children:[ye(Tt,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:R==="collapse"?()=>_e(o=>!o):void 0,children:[R==="collapse"&&ye(It,{gap:0,children:[b(xn,{size:"sm",fw:600,style:{lineHeight:1.1},children:n.get("Options")}),b(xn,{size:"xs",c:"dimmed",style:{marginTop:2},children:qe})]}),R==="collapse"&&b(Kt,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:o=>{o.stopPropagation(),_e(k=>!k)},children:xt?n.get("Hide"):n.get("Show")})]}),ye(Qt,{in:xt,children:[R==="collapse"&&b(qr,{my:"sm"}),ye(mt,{gap:"xs",justify:"space-between",children:[u==="write"&&U?.text&&b(St,{label:n.get("The topic or subject for the AI to write about."),disabled:R!=="horizontal",position:"top",children:b(wt,{size:"xs",className:"ai-feature-option",styles:se,disabled:w.busy,label:n.get("Topic"),description:R!=="horizontal"?n.get("The topic or subject for the AI to write about."):void 0,value:Re||"",onChange:o=>{let k=o.target.value;Te(k),C?.({text:k})}})}),(u==="write"||u==="rewrite"||u==="generateImageMetadata"||u==="generatePostMetadata")&&U?.instructions&&b(St,{label:n.get("Additional instructions to guide the AI."),disabled:R!=="horizontal",position:"top",children:b(wt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Instructions"),description:R!=="horizontal"?n.get("Additional instructions to guide the AI."):void 0,value:oe||"",onChange:o=>{let k=o.target.value;lt(k),C?.({instructions:k})}})}),u==="translate"&&b(St,{label:n.get("The language of the input text."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",styles:se,className:"ai-feature-option",label:n.get("Input language"),description:R!=="horizontal"?n.get("The language of the input text."):void 0,data:[{value:"auto",label:n.get("Auto-detect")},...pa.map(o=>({value:o.value,label:n.get(o.label)})).sort((o,k)=>o.label.localeCompare(k.label))],value:dt||"auto",onChange:o=>{let k=o;bt(k),ut(void 0),C?.({inputLanguage:k})}})}),U?.outputLanguage&&b(St,{label:n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",styles:se,className:"ai-feature-option",label:n.get("Output language"),description:R!=="horizontal"?n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[u==="rewrite"?{value:"auto",label:n.get("Auto-detect")}:void 0].filter(Boolean),...pa.map(o=>({value:o.value,label:n.get(o.label)})).sort((o,k)=>o.label.localeCompare(k.label))],value:D||Dn.settings.defaultOutputLanguage||(u==="rewrite"?"auto":""),onChange:o=>{let k=o;ct(k),ut(void 0),C?.({outputLanguage:k})}})}),u==="summarize"&&U?.type&&b(St,{label:n.get("The summary style to generate."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Type"),description:R!=="horizontal"?n.get("The summary style to generate."):void 0,data:[{value:"headline",label:n.get("Headline")},{value:"key-points",label:n.get("Key Points")},{value:"teaser",label:n.get("Teaser")},{value:"tldr",label:n.get("TL;DR")}],value:Pe||"key-points",onChange:o=>{let k=o;Gt(k),C?.({type:k})}})}),(u==="write"||u==="rewrite")&&U?.tone&&b(St,{label:n.get("The tone or style for the AI to use."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Tone"),description:R!=="horizontal"?n.get("The tone or style for the AI to use."):void 0,data:u==="write"?[{value:"neutral",label:n.get("Neutral")},{value:"formal",label:n.get("Formal")},{value:"casual",label:n.get("Casual")}]:[{value:"as-is",label:n.get("As-Is")},{value:"more-formal",label:n.get("More formal")},{value:"more-casual",label:n.get("More casual")}],value:We||(u==="write"?"neutral":"as-is"),onChange:o=>{let k=o;de(k),C?.({tone:k})}})}),(u==="write"||u==="rewrite"||u==="summarize")&&U?.length&&b(St,{label:n.get("The target output length."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Length"),description:R!=="horizontal"?n.get("The target output length."):void 0,data:u==="write"||u==="summarize"?[{value:"short",label:n.get("Short")},{value:"medium",label:n.get("Medium")},{value:"long",label:n.get("Long")}]:[{value:"as-is",label:n.get("As-Is")},{value:"shorter",label:n.get("Shorter")},{value:"longer",label:n.get("Longer")}],value:ue||(u==="rewrite"?"as-is":"short"),onChange:o=>{let k=o;Ze(k),C?.({length:k})}})}),u==="summarize"||u==="write"||u==="rewrite"&&U?.outputFormat&&b(St,{label:n.get("The format for the generated output."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Output format"),description:R!=="horizontal"?n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:n.get("Plain Text")},{value:"markdown",label:n.get("Markdown")},{value:"html",label:n.get("HTML")}],value:K||"markdown",onChange:o=>{let k=o;yt(k),C?.({outputFormat:k})}})})]})]})]}),w.busy&&gt&&b(qt,{enabled:c==="modal",working:!0,variation:c,children:ye(Tt,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[b(Yr,{size:"sm"}),b(La.Label,{className:"ai-feature-status-text",children:gt})]})}),x&&ye(It,{mt:"md",children:[u==="proofread"&&(x.corrections.length===0?b(xa,{color:"green",children:n.get("No issues found. Your text looks great!")}):ye(ra,{children:[b("p",{style:{marginTop:0,opacity:.85},children:n.get("Hover highlights to see explanations.")}),b(Cn,{original:Re,corrections:x.corrections}),x.correctedInput?ye(ra,{children:[b("h4",{style:{marginTop:16,marginBottom:8},children:n.get("Corrected")}),b(Tt,{c:"pre",className:"ai-feature-generated-content",children:x.correctedInput})]}):null]})),u==="generateImageMetadata"&&ye(ra,{children:[b(wt,{readOnly:!s,label:n.get("Alt Text"),description:n.get("The alt text for the image."),value:x.alt_text||"",onChange:o=>P({...x,alt_text:o.target.value})}),b(wt,{readOnly:!s,label:n.get("Title"),description:n.get("The title for the image."),value:x.title||"",onChange:o=>P({...x,title:o.target.value})}),b(wt,{readOnly:!s,label:n.get("Caption"),description:n.get("The caption for the image."),value:x.caption||"",onChange:o=>P({...x,caption:o.target.value})}),b(wt,{readOnly:!s,label:n.get("Description"),description:n.get("The description for the image."),value:x.description||"",onChange:o=>P({...x,description:o.target.value})})]}),u==="generatePostMetadata"&&ye(ra,{children:[b(wt,{readOnly:!s,label:n.get("Title"),description:n.get("The title for the post."),value:x.title||"",onChange:o=>P({...x,title:o.target.value})}),b(wt,{readOnly:!s,label:n.get("Excerpt"),description:n.get("The excerpt for the post."),value:x.excerpt||"",onChange:o=>P({...x,excerpt:o.target.value})})]}),u!=="proofread"&&u!=="generateImageMetadata"&&u!=="generatePostMetadata"&&typeof x=="string"&&b(En,{value:x,editable:!!s,onChange:o=>{P(o)}})]}),x===""&&b(En,{value:x,editable:!1})]}),ye(Tt,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[w.busy&&b(Kt,{variant:"outline",size:"sm",onClick:Be,"data-ai-kit-cancel-button":!0,children:n.get("Cancel")}),!w.busy&&b(Kt,{variant:"filled",size:"sm",disabled:!ce,onClick:()=>ze(),"data-ai-kit-generate-button":!0,children:Ve()}),!w.busy&&w.lastSource==="on-device"&&st&&Ne&&b(Kt,{variant:"filled",size:"sm",disabled:!ce,onClick:nt,"data-ai-kit-regenerate-on-backend-button":!0,children:rt()}),!w.busy&&f&&b(Kt,{variant:"outline",size:"sm",disabled:!x||u==="proofread"&&x.corrections.length===0,onClick:async()=>{f(K==="html"?await za(x):x),He()},"data-ai-kit-accept-button":!0,children:n.get(ne)}),b(Kt,{variant:"default",size:"sm",onClick:He,"data-ai-kit-close-button":!0,children:n.get("Close")})]}),b(da,{variation:c})]})})]})]})]})};function En(t){let{value:r,editable:g,onChange:s}=t;return g?ye(It,{p:0,gap:"sm",children:[b(La.Label,{children:n.get("Generated content")}),b(Jr,{value:r,onChange:a=>s?.(a.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),b(La.Label,{children:n.get("Preview")}),b(It,{className:"ai-feature-generated-content ai-feature-preview",children:b(Pn,{remarkPlugins:[Mn],children:r})})]}):b(It,{className:"ai-feature-generated-content",children:r?b(Pn,{remarkPlugins:[Mn],children:r}):b(xa,{color:"yellow",children:n.get("No content generated.")})})}var ho=Bt(po);import{ActionIcon as Kn,Anchor as To,Box as wo,Button as Xe,Group as Ee,Input as So,List as Un,Modal as Ot,Stack as et,Text as xe,Textarea as Ro}from"@mantine/core";import{IconMaximize as Io,IconMessage as zo,IconMicrophone as Co,IconMinimize as xo,IconPaperclip as Lo,IconPencil as Po,IconPlayerStop as Mo,IconSend as Do,IconTrash as Eo,IconX as Bo}from"@tabler/icons-react";import{getStoreSelect as Ko,sendChatMessage as Uo,sendFeedbackMessage as Oo}from"@smart-cloud/ai-kit-core";import{useSelect as No}from"@wordpress/data";import{I18n as y}from"aws-amplify/utils";import{useCallback as J,useEffect as ke,useMemo as Ae,useRef as Se,useState as be}from"react";import jo from"react-markdown";import Go from"remark-gfm";var fo="ai-kit-chatbot-attachments",it="attachments";var Pa=null;function ko(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function fa(){if(!ko())return null;Pa||(Pa=new Promise(t=>{try{let r=window.indexedDB.open(fo,1);r.onerror=()=>t(null),r.onblocked=()=>t(null),r.onupgradeneeded=()=>{let g=r.result;g.objectStoreNames.contains(it)||g.createObjectStore(it,{keyPath:"id"})},r.onsuccess=()=>t(r.result)}catch(r){console.warn("[AiChatbot] IndexedDB is not available",r),t(null)}}));try{return await Pa}catch(t){return console.warn("[AiChatbot] Failed to open attachment store",t),null}}async function Ma(t,r){let g=await fa();return g?new Promise((s,a)=>{try{let c=g.transaction(it,t),T=c.objectStore(it),E=r(T);c.oncomplete=()=>s(E),c.onerror=()=>a(c.error),c.onabort=()=>a(c.error)}catch(c){a(c)}}).catch(s=>(console.warn("[AiChatbot] Attachment store transaction failed",s),null)):null}async function Da(t,r,g){await vo();let s={id:t,blob:r,name:g.name,type:g.type,size:g.size,createdAt:Date.now()};return await Ma("readwrite",c=>(c.put(s),t))}async function Ea(t){let r=await fa();return r?new Promise((g,s)=>{try{let a=r.transaction(it,"readonly"),c=a.objectStore(it).get(t);c.onsuccess=()=>{let T=c.result;g(T??null)},c.onerror=()=>s(c.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(g=>(console.warn("[AiChatbot] Failed to load attachment",g),null)):null}async function bo(t){await Ma("readwrite",r=>{r.delete(t)})}async function ka(){await Ma("readwrite",t=>{t.clear()})}async function Ba(t){let r=await fa();r&&await new Promise((g,s)=>{try{let a=r.transaction(it,"readwrite"),c=a.objectStore(it),T=c.getAllKeys();T.onsuccess=()=>{let E=T.result;for(let ie of E){let te=String(ie);t.has(te)||c.delete(ie)}},T.onerror=()=>s(T.error),a.oncomplete=()=>g(),a.onerror=()=>s(a.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(g=>{console.warn("[AiChatbot] Failed to cleanup attachments",g)})}var yo=50*1024*1024;async function Ao(){let t=await fa();return t?new Promise((r,g)=>{try{let s=t.transaction(it,"readonly"),a=s.objectStore(it).getAll();a.onsuccess=()=>{let c=a.result||[];r(c)},a.onerror=()=>g(a.error),s.onerror=()=>g(s.error),s.onabort=()=>g(s.error)}catch(s){g(s)}}).catch(r=>(console.warn("[AiChatbot] Failed to get all attachments",r),[])):[]}async function vo(){let t=await Ao();if(t.length===0)return;let r=t.sort((c,T)=>c.createdAt-T.createdAt),g=r.reduce((c,T)=>c+T.size,0),s=[],a=0;for(;g>yo&&a<r.length;){let c=r[a];c&&(s.push(c.id),g-=c.size),a++}for(let c of s)await bo(c);s.length>0&&console.log(`[AiChatbot] Deleted ${s.length} old attachment(s) to enforce storage quota`)}import{Fragment as Nn,jsx as m,jsxs as F}from"react/jsx-runtime";y.putVocabularies(Mt);var ba=1440*60*1e3,Ka=!1,Ho=1,Fo="localstorage",Vt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,Oa={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function zt(t){return`${t}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var Wo=4,qo=5*1024*1024,Yo=t=>{let r=(t?.name||"").toString(),g=(t?.code||"").toString(),s=(t?.message||"").toString();return r==="AbortError"||g==="ABORT_ERR"||/abort|aborted|cancel/i.test(s)},Vo=(t,r)=>{if(!t)return null;let g=t.step,s=y.get((t.message??"").trim()),a=typeof t.progress=="number"?t.progress:null,c=a==null?null:Math.round(a*100);switch(g){case"decide":return s||y.get("Checking capabilities...");case"on-device:init":return s||y.get("Initializing on-device AI...");case"on-device:download":return c==null?s||y.get("Downloading model..."):s||`${y.get("Downloading model...")} ${c}%`;case"on-device:ready":return s||y.get("On-device model ready...");case"on-device:run":return s||y.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return y.get(r.assistantThinkingLabel??Oa.assistantThinkingLabel);case"done":return s||y.get("Done.");case"error":return s||y.get("An error occurred.");default:return s||null}};function Ua(t){if(typeof window>"u")return null;try{return t==="localstorage"?window.localStorage:t==="sessionstorage"?window.sessionStorage:null}catch{return null}}var Jt=t=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(t)}catch{return null}},ya=t=>{if(t&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(t)}catch{}},jn=t=>{!t||t.length===0||t.forEach(r=>ya(r.objectUrl))},On=t=>{t.forEach(r=>jn(r.attachments))},Jo=t=>{let{rootElement:r,store:g,previewMode:s,title:a,openButtonTitle:c,openButtonIcon:T,showOpenButtonTitle:E=!0,showOpenButtonIcon:ie=!0,colorMode:te,language:Q,onClose:ae,context:Ne,placeholder:ne,maxImages:R,maxImageBytes:u,historyStorage:I=Fo,emptyHistoryAfterDays:ge=Ho,labels:W,openButtonIconLayout:Z="top",openButtonPosition:me="bottom-right"}=t,f=Ae(()=>({...Oa,...W||{}}),[W]),C=Wt(),[B,pe]=be(""),[U,ve]=be([]),[z,G]=be(null),[he,re]=be(!1),[xt,_e]=be(0),st=Se(null),$e=Se([]),je=Se(null),Le=Se(null),x=Se(null),[P,Re]=be([]),[Te,Ge]=be(null),[oe,lt]=be(!1),[Ie,ut]=be(!1),[dt,bt]=be(!1),[K,yt]=be(!1),[D,ct]=be(!0),[ue,Ze]=be(null),[We,de]=be(!1),[Pe,Gt]=be(null),[L,Lt]=be(null),[$t,Me]=be(!1),[ce,w]=be(null),gt=Se(ce);ke(()=>{gt.current=ce},[ce]);let ze=Se(null),nt=Se(!1),[At,Ve]=be(null),rt=Se(null),He=Se(null),Be=Se(null),qe=Se(null),se=J(e=>{e.forEach(l=>ya(l.objectUrl))},[]),Qe=J(()=>{se(X.current),ve([]),rt.current&&(rt.current.value="")},[se]),Ke=J(()=>{N.current&&ya(N.current.objectUrl),G(null),$e.current=[],_e(0)},[]),Zt=J(async()=>{try{pe(""),Ke();let e=await navigator.mediaDevices.getUserMedia({audio:!0}),l=new MediaRecorder(e,{mimeType:"audio/webm"}),h=new AudioContext,i=h.createMediaStreamSource(e),S=h.createAnalyser();S.fftSize=2048,S.smoothingTimeConstant=.8,i.connect(S),je.current=h,Le.current=S;let A=new Uint8Array(S.fftSize),M=()=>{if(!Le.current)return;Le.current.getByteTimeDomainData(A);let V=0;for(let Fe=0;Fe<A.length;Fe++){let Pt=(A[Fe]-128)/128;V+=Pt*Pt}let Ce=Math.sqrt(V/A.length),Oe=Math.min(100,Ce*200);_e(Oe),x.current=requestAnimationFrame(M)};M(),$e.current=[];let j=Date.now();l.ondataavailable=V=>{V.data.size>0&&$e.current.push(V.data)},l.onstop=()=>{let V=new Blob($e.current,{type:"audio/webm"}),Ce=(Date.now()-j)/1e3,Oe=Jt(V);Oe&&G({id:zt("composer-audio"),blob:V,objectUrl:Oe,duration:Ce}),e.getTracks().forEach(Fe=>Fe.stop()),x.current&&(cancelAnimationFrame(x.current),x.current=null),je.current&&(je.current.close(),je.current=null),Le.current=null,_e(0)},st.current=l,l.start(),re(!0)}catch(e){console.error("Failed to start recording:",e)}},[Ke]),Qt=J(()=>{st.current&&he&&(st.current.stop(),re(!1))},[he]);ke(()=>()=>{x.current&&cancelAnimationFrame(x.current),je.current&&je.current.close(),Ke()},[Ke]);let[mt,o]=be(null),k=Se(B),O=Se(P),H=Se(mt),X=Se(U),N=Se(z);ke(()=>{k.current=B},[B]),ke(()=>{X.current=U},[U]),ke(()=>{N.current=z},[z]),ke(()=>{O.current=P},[P]),ke(()=>{H.current=mt},[mt]),ke(()=>{Q&&y.setLanguage(Q||"en")},[Q]);let $=No(()=>Ko(g).isShowChatbotPreview()),ee=Ae(()=>Math.max(0,R??Wo),[R]),Ye=Ae(()=>Math.max(0,u??qo),[u]),d=P.length>0,p=Ae(()=>C.busy&&ce==="chat",[C.busy,ce]),q=Ae(()=>p?!1:B.trim().length>0||z!==null,[B,p,z]),Y=Ae(()=>{let e=c||f.askMeLabel;return y.get(e)},[c,f.askMeLabel,Q]),we=Ae(()=>{let e=a||f.modalTitle;return y.get(e)},[a,f.modalTitle,Q]),Ue=Ae(()=>{let e=ne||f.placeholder;return y.get(e)},[ne,f.placeholder,Q]),ot=Ae(()=>{let e="ai-docs-ask",l=`ai-open-btn--${me}`;return`${e} ${l}`},[me]),fe=J(()=>{let e=qe.current;if(e)try{let l=window.innerHeight||document.documentElement.clientHeight,h=360,i=1e3,S=Math.floor(l*.8),A=Math.max(h,Math.min(S,i));e.style.height=`${A}px`}catch{}},[]),pt=J(()=>{let e=L;e&&window.setTimeout(()=>{try{e.scrollTop=e.scrollHeight}catch{}},50)},[L]),sa=J(()=>{yt(!1),Ie&&ut(!1),bt(!1),ae?.()},[Ie,ae]);ke(()=>{if(K)return fe(),window.addEventListener("resize",fe),()=>window.removeEventListener("resize",fe)},[K,fe]),ke(()=>{if(!(!K||!Ie))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[K,Ie,sa]);let Ht=Ae(()=>U.map(e=>({id:e.id,url:e.objectUrl,title:e.file.name})),[U]);ke(()=>{d||ct(!0)},[d]),ke(()=>()=>{se(X.current)},[se]),ke(()=>{let e=L;if(!e)return;let l=()=>{let h=e.scrollHeight-(e.scrollTop+e.clientHeight);ct(h<20)};return e.addEventListener("scroll",l),()=>{e.removeEventListener("scroll",l)}},[K,L]),ke(()=>{if(!D)return;let e=L;e&&e.scrollHeight>e.clientHeight&&(e.scrollTop=e.scrollHeight)},[P,C.busy,D,L]),ke(()=>{K||Ze(null)},[K]);let Xt=Ae(()=>C.busy?Vo(C.statusEvent,f)||y.get("Working\u2026"):null,[C.busy,C.statusEvent,Q,f]),Vn=Ae(()=>{for(let e=P.length-1;e>=0;e--){let l=P[e];if(l.role==="user"&&l.clientStatus==="canceled")return l.id}return null},[P]),ea=J(e=>{Re(l=>{let h=[...l].map((A,M)=>({m:A,i:M})).reverse().find(A=>A.m.role==="user"&&A.m.clientStatus==="pending")?.i;if(h==null)return l;let i=l.slice(),S=i[h];return i[h]={...S,clientStatus:e??void 0},i})},[Re]),la=J(()=>{if(!(!C.busy||gt.current!=="chat")){nt.current=!0;try{C.cancel()}catch{}ea("canceled"),w(null),Ge(null),pt()}},[C,ea,pt]),Jn=J(e=>{let l=X.current,h=Array.from(e.target.files||[]),i=Math.max(0,ee-l.length);if(i===0){e.currentTarget.value="";return}let S=[];for(let A of h){if(S.length>=i)break;let M=/image\/(jpeg|png|gif|webp)/i.test(A.type),j=A.size<=Ye,V=[...l,...S].some(Oe=>Oe.file.name===A.name&&Oe.file.size===A.size&&Oe.file.lastModified===A.lastModified);if(!M||!j||V)continue;let Ce=Jt(A);Ce&&S.push({id:zt("composer-image"),file:A,objectUrl:Ce})}S.length&&ve(A=>[...A,...S]),e.currentTarget.value=""},[ee,Ye]),_n=J(e=>{ve(l=>{if(e<0||e>=l.length)return l;let h=l[e];return h&&ya(h.objectUrl),l.filter((i,S)=>S!==e)})},[]),vt=Se(null);ke(()=>{if(Te)return vt.current&&(window.clearTimeout(vt.current),vt.current=null),vt.current=window.setTimeout(()=>{Ge(null),vt.current=null},6e3),()=>{vt.current&&(window.clearTimeout(vt.current),vt.current=null)}},[Te]);let Na=J(async(e,l)=>{let h=I!=="nostorage",i=[];if(e.length>0){let S=await Promise.all(e.map(async A=>{let M=zt("attachment-image"),j;if(h)try{j=await Da(M,A.file,{name:A.file.name,type:A.file.type,size:A.file.size})??void 0}catch(Ce){console.warn("[AiChatbot] Failed to persist image",Ce)}let V=Jt(A.file);return{id:M,name:A.file.name,type:A.file.type||"application/octet-stream",size:A.file.size,blobId:j,objectUrl:V??void 0,blob:A.file,mediaType:"image"}}));i.push(...S.filter(Boolean))}if(l){let S=zt("attachment-audio"),A;if(h)try{A=await Da(S,l.blob,{name:`audio-${Date.now()}.webm`,type:l.blob.type,size:l.blob.size})??void 0}catch(j){console.warn("[AiChatbot] Failed to persist audio",j)}let M=Jt(l.blob);i.push({id:S,name:`audio-${Date.now()}.webm`,type:l.blob.type||"audio/webm",size:l.blob.size,blobId:A,objectUrl:M??void 0,blob:l.blob,duration:l.duration,mediaType:"audio"})}return i},[I]),ja=J(async e=>{let l=[];for(let h of e){let i;if(h.attachments&&h.attachments.length>0){i=[];for(let S of h.attachments){let A;if(S.blobId)try{A=(await Ea(S.blobId))?.blob??void 0}catch(j){console.warn("[AiChatbot] Failed to hydrate attachment",j)}if(!A)continue;let M=A?Jt(A):null;i.push({...S,objectUrl:M??void 0,blob:A??void 0})}}l.push({...h,attachments:i})}return l},[]),Ga=J(async e=>{if(!e||e.length===0){Qe();return}let l=[];for(let h of e){let i=h.blob;if(!i&&h.blobId)try{i=(await Ea(h.blobId))?.blob??void 0}catch(M){console.warn("[AiChatbot] Failed to reload attachment",M)}if(!i)continue;let S=i instanceof File?i:new File([i],h.name||"attachment",{type:h.type||i.type||"application/octet-stream"}),A=Jt(S);if(A&&(l.push({id:zt("composer-image"),file:S,objectUrl:A}),l.length>=ee))break}if(l.length===0){Qe();return}ve(h=>(se(h),l)),rt.current&&(rt.current.value="")},[Qe,se,ee]),Aa=J((e,l)=>{e&&Ze({url:e,title:l})},[]),$n=J(()=>{Ze(null)},[]),Ha=J(()=>{On(O.current),Qe(),Ke(),Re([]),Ge(null),Be.current=null,o(null),ct(!0),lt(!1);let e=Ua(I);if(e)try{e.removeItem(Vt)}catch{}ka()},[Qe,Ke,I]),Zn=J(()=>{lt(!0)},[]),Qn=J(()=>{C.busy&&gt.current==="chat"&&la(),Ha()},[C.busy,la,Ha]),Fa=J(()=>{lt(!1)},[]),Wa=J(async(e,l)=>{if(!C.busy)try{let h=Be.current&&Date.now()-Be.current.storedAt<ge*ba?Be.current.id:void 0;if(!h)return;w("feedback"),Ge(null),await C.run(async({signal:i,onStatus:S})=>(await Oo({sessionId:h,feedbackMessageId:e,feedbackType:l},{signal:i,onStatus:S,context:Ne}),null)),Ge(null)}catch(h){let i=h?.message?.trim()||y.get("An error occurred.");Ge(i),console.error("Failed to send feedback",h)}finally{w(h=>h==="feedback"?null:h)}},[C,Q]),qa=J((e,l)=>{Re(h=>h.map(i=>i.id!==e||i.role!=="assistant"?i:i.feedback===l?{...i,feedback:void 0}:{...i,feedback:l})),Wa(e,l)},[Wa]),ua=J(async()=>{let e=k.current.trim(),l=N.current;if(!e&&!l||C.busy)return;nt.current=!1,Ge(null),w("chat");let h=[...X.current],i=await Na(h,l),S=zt("user"),A=Date.now(),M={id:S,role:"user",content:e||(l?"[Audio message]":""),createdAt:A,clientStatus:"pending",attachments:i.length?i:void 0};pe(""),Qe(),Ke(),Re(j=>[...j,M]),K||yt(!0),pt();try{let j=Be.current&&Date.now()-Be.current.storedAt<ge*ba?Be.current.id:void 0,V=await C.run(async({signal:Oe,onStatus:Fe})=>await Uo({sessionId:j,message:e||void 0,audio:l?.blob,images:h.map(dr=>dr.file)},{signal:Oe,onStatus:Fe,context:Ne}));if(nt.current){ea("canceled");return}if(!V)throw new Error(y.get(C.error??f.emptyResponseLabel));V.sessionId&&(Be.current={id:V.sessionId,storedAt:Date.now()});let Ce={id:V.metadata?.messageId||zt("assistant"),role:"assistant",content:V.result||"",citations:V.citations,createdAt:Date.now()};Re(Oe=>[...Oe.map(Pt=>Pt.id===S?{...Pt,clientStatus:void 0}:Pt),Ce]),o(A)}catch(j){if(console.error("Error during ask()",j),nt.current||Yo(j)){ea("canceled");return}let V=j?.message?.trim()||y.get(f.unexpectedErrorLabel);Re(Ce=>[...Ce.map(Fe=>Fe.id===S?{...Fe,clientStatus:void 0}:Fe),{id:zt("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${V}`,createdAt:Date.now()}]),o(A)}finally{w(j=>j==="chat"?null:j),nt.current=!1,He.current&&He.current.focus(),pt()}},[C,Na,Qe,Ke,K,pt,ea,f.emptyResponseLabel,f.unexpectedErrorLabel,Q]),Xn=J(e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),q&&ua())},[ua,q]),er=J(()=>{yt(!0)},[]);ke(()=>()=>{ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null)},[]);let tr=J(()=>{ut(e=>{let l=!e;return ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null),l?(bt(!0),requestAnimationFrame(()=>{ze.current=requestAnimationFrame(()=>{bt(!1),ze.current=null})})):bt(!1),l})},[]),ar=J(e=>{pe(e.content),(async()=>(await Ga(e.attachments),Re(l=>l.filter(h=>h.id!==e.id)),jn(e.attachments),queueMicrotask(()=>He.current?.focus())))()},[Ga]),Ya=Ae(()=>ie?T?m("img",{src:T,className:"ai-open-btn-icon",alt:y.get(f.askMeLabel||Y)}):m(zo,{size:18}):null,[ie,T,f,Y,Q]),nr=Ae(()=>{let e=Ya,l=E?m(xe,{inherit:!0,children:Y}):null;if(!ie&&!l)return null;if(!ie)return l;if(!E)return e;switch(Z){case"top":return F(et,{gap:4,align:"center",children:[e,l]});case"bottom":return F(et,{gap:4,align:"center",children:[l,e]});case"right":return F(Ee,{gap:6,align:"center",children:[l,e]});default:return F(Ee,{gap:6,align:"center",children:[e,l]})}},[Ya,ie,E,Y,Z]),rr=Ae(()=>p,[p]),or=Ae(()=>!p,[p]),ir=Ae(()=>Te||(d?y.get(f.readyLabel):y.get(f.readyEmptyLabel)),[Te,d,f.readyLabel,f.readyEmptyLabel,Q]),sr=Ae(()=>p?y.get(f.cancelLabel):y.get(f.sendLabel),[p,f.cancelLabel,f.sendLabel,Q]),lr=Ae(()=>p?m(Mo,{size:18}):m(Do,{size:18}),[p]),ur=J(()=>{if(p){la();return}ua()},[p,la,ua]);return ke(()=>{if(!K||!Pe||!L)return;let e=()=>{let j=window.getComputedStyle(L).overflowY,V=j==="auto"||j==="scroll",Ce=Math.ceil(L.scrollHeight),Oe=Math.floor(L.clientHeight),Fe=Ce>Oe;return V&&Fe},l=!1,h=M=>{if(!e())return;M.preventDefault();let j=L.scrollHeight-L.clientHeight;L.scrollTop=Math.max(0,Math.min(j,L.scrollTop+M.deltaY))},i=()=>{let M=e();Me(M),M!==l&&(l=M,l?Pe.addEventListener("wheel",h,{passive:!1}):Pe.removeEventListener("wheel",h))};i();let S=new ResizeObserver(i);S.observe(L);let A=new MutationObserver(i);return A.observe(L,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",i),()=>{l&&Pe.removeEventListener("wheel",h),S.disconnect(),A.disconnect(),window.removeEventListener("resize",i)}},[K,Pe,L]),ke(()=>{let e=!1,l=Ua(I);if(!l){I==="nostorage"&&ka(),de(!0);return}return(async()=>{try{let h=l.getItem(Vt);if(!h){de(!0);return}let i=JSON.parse(h),S=typeof i?.lastUserSentAt=="number"?i.lastUserSentAt:null;if(!S||Date.now()-S>ge*ba){l.removeItem(Vt),await ka(),de(!0);return}let M=(Array.isArray(i.messages)?i.messages:[]).map(V=>V?.role==="user"&&V.clientStatus==="pending"?{...V,clientStatus:"canceled"}:V),j=await ja(M);if(e){On(j);return}Re(j),o(S),i.session&&i.session.id&&(Be.current=i.session)}catch(h){console.warn("[AiChatbot] Failed to load history",h);try{l.removeItem(Vt)}catch{}}finally{e||de(!0)}})(),()=>{e=!0}},[I,ge,ja]),ke(()=>{if(!We)return;let e=Ua(I);if(!e)return;let l=H.current;if(!l)return;if(Date.now()-l>ge*ba){try{e.removeItem(Vt)}catch{}Ba(new Set);return}let h=P.map(({attachments:A,...M})=>({...M,attachments:A?.map(({objectUrl:j,blob:V,...Ce})=>Ce)})),i={version:1,lastUserSentAt:l,session:Be.current,messages:h};try{e.setItem(Vt,JSON.stringify(i))}catch{}let S=new Set;h.forEach(A=>{A.attachments?.forEach(M=>{M.blobId&&S.add(M.blobId)})}),Ba(S)},[We,P,mt,I,ge]),s&&!$||!s&&$?null:F(Ee,{className:ot,children:[!K&&m(Xe,{variant:"filled",className:E?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:er,"aria-label":Y,title:Y,"data-ai-kit-open-button":!0,children:nr}),K&&m(Ot.Root,{ref:qe,opened:K,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:sa,className:ot+" ai-chat-container"+(Ie?" maximized":"")+(Ie&&dt?" ai-max-enter":""),portalProps:{target:r,reuseTargetNode:!0},"data-ai-kit-theme":te,"data-ai-kit-variation":"modal",children:F("div",{className:"ai-chat-container-internal",ref:Gt,children:[F(Ot.Header,{className:"ai-chat-header-bar",children:[m(Ot.Title,{className:"ai-chat-title",children:we}),F(Ee,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&m(Kn,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:tr,title:Ie?y.get(f.restoreSizeLabel):y.get(f.maximizeLabel),"aria-label":Ie?y.get(f.restoreSizeLabel):y.get(f.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Ie?m(xo,{size:16}):m(Io,{size:16})}),m(Ot.CloseButton,{"aria-label":y.get(f.closeChatLabel)})]})]}),F(Ot.Body,{className:"ai-chat-scroll",ref:Lt,"data-scrollable":$t?"true":"false",children:[P.map(e=>{let l=e.role==="user",h=l&&e.clientStatus==="canceled"&&e.id===Vn;return m(Ee,{justify:l?"flex-end":"flex-start",className:"ai-chat-row "+e.role,onMouseEnter:()=>Ve(e.id),onMouseLeave:()=>Ve(i=>i===e.id?null:i),children:F(et,{gap:4,w:"100%",style:{alignItems:l?"flex-end":"flex-start"},children:[F(et,{className:"ai-chat-bubble",children:[F(xe,{className:"ai-chat-header",children:[m(xe,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:l?y.get(f.userLabel):y.get(f.assistantLabel)}),"\xA0",m(xe,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(e.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.role==="assistant"?m(jo,{remarkPlugins:[Go],children:e.content}):m(xe,{size:"sm",miw:"100px",children:e.content})]}),e.attachments&&e.attachments.length>0&&F(et,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).length>0&&m(Ee,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).map(i=>m("button",{type:"button",className:"thumb",style:{backgroundImage:i.objectUrl?`url(${i.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>Aa(i.objectUrl,i.name),disabled:!i.objectUrl,title:i.name||y.get("View image"),"aria-label":i.name||y.get("View image"),children:!i.objectUrl&&m(xe,{size:"xs",c:"dimmed",children:y.get("Image no longer available")})},i.id))}),e.attachments.filter(i=>i.mediaType==="audio"||!i.mediaType&&i.type.startsWith("audio/")).map(i=>m(wo,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:i.objectUrl?F(et,{gap:"xs",children:[m("audio",{className:"ai-kit-audio-player",controls:!0,src:i.objectUrl,preload:"metadata"}),i.duration&&F(xe,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(i.duration),"s"]})]}):m(xe,{size:"xs",c:"dimmed",children:y.get("Audio no longer available")})},i.id))]}),h&&F(Ee,{justify:"flex-end",gap:"xs",children:[m(xe,{size:"xs",c:"dimmed",children:m("em",{children:y.get(f.notSentLabel)})}),At===e.id&&m(Kn,{size:"sm",variant:"subtle",onClick:()=>ar(e),title:y.get(f.editLabel),"aria-label":y.get(f.editLabel),"data-ai-kit-edit-button":!0,children:m(Po,{size:14})})]}),e.citations&&e.citations.length>0&&F(et,{className:"ai-citations",children:[m(xe,{fw:"bold",size:"sm",mb:"xs",children:y.get(f.referencesLabel)}),m(Un,{spacing:"xs",size:"sm",children:e.citations.map((i,S)=>{let A=i.sourceUrl||i.url,M=i.title||A||`${y.get(f.referenceLabel)} #${S+1}`;return F(Un.Item,{children:[A?m(To,{href:A,target:"_blank",rel:"noreferrer",children:M}):m(xe,{children:M}),i.snippet?m(xe,{size:"xs",c:"dimmed",mt:4,children:i.snippet}):null]},S)})})]}),e.role==="assistant"&&F(Ee,{className:"ai-feedback",gap:"xs",children:[m(Xe,{className:e.feedback==="accepted"?"active":void 0,onClick:()=>qa(e.id,"accepted"),"aria-label":y.get(f.acceptResponseLabel),disabled:C.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),m(Xe,{type:"button",className:e.feedback==="rejected"?"active":void 0,onClick:()=>qa(e.id,"rejected"),"aria-label":y.get(f.rejectResponseLabel),disabled:C.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},e.id)}),rr&&m(Ee,{justify:"flex-start",className:"ai-chat-row assistant status",children:F(et,{className:"ai-chat-bubble typing",children:[Xt?m(xe,{size:"sm",c:"dimmed",children:m("em",{children:Xt})}):null,F("div",{className:"typing-indicator",children:[m("span",{}),m("span",{}),m("span",{})]})]})})]}),or&&m(Ee,{className:"ai-status-line",children:m(xe,{className:"ai-status-text",children:m("em",{children:ir})})}),F(et,{className:"ai-box ai-box-open",children:[F(Ot,{opened:oe,onClose:Fa,centered:!0,title:y.get("Reset conversation"),style:{position:"fixed"},left:0,children:[m(xe,{size:"sm",children:y.get("Are you sure you want to reset the conversation?")}),F(Ee,{justify:"flex-end",mt:"md",children:[m(Xe,{variant:"default",onClick:Fa,"data-ai-kit-no-button":!0,children:y.get("No")}),m(Xe,{color:"var(--ai-kit-color-danger, red)",onClick:Qn,disabled:!d&&!p,"data-ai-kit-yes-button":!0,children:y.get("Yes")})]})]}),m(Ee,{children:m(Ro,{className:"ai-message",ref:He,placeholder:Ue,value:B,onChange:e=>{pe(e.target.value),z&&Ke()},onKeyDown:Xn,rows:3,disabled:he||!!z})}),Ka&&he&&F(et,{gap:"xs",mt:"xs",children:[m(xe,{size:"xs",c:"dimmed",children:m("em",{children:y.get("Recording...")})}),m("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:m("div",{style:{width:`${xt}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Ka&&z&&!he&&F(et,{gap:"xs",mt:"xs",children:[m(xe,{size:"xs",c:"dimmed",children:F("em",{children:[y.get("Audio recorded")," (",Math.round(z.duration),"s)"]})}),m("audio",{className:"ai-kit-audio-player",controls:!0,src:z.objectUrl})]}),F(Ee,{className:"ai-actions",justify:"space-between",w:"100%",children:[m(Ee,{justify:"flex-start",children:m(Xe,{variant:"light",leftSection:m(Eo,{size:18}),onClick:Zn,disabled:!d&&!p,"data-ai-kit-reset-button":!0,children:y.get(f.resetLabel)})}),F(Ee,{justify:"flex-end",children:[Ka&&m(Nn,{children:z?m(Xe,{variant:"outline",leftSection:m(Bo,{size:18}),onClick:Ke,disabled:p,title:y.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:y.get("Clear")}):m(Xe,{variant:"outline",leftSection:m(Co,{size:18}),onClick:he?Qt:Zt,disabled:p,title:he?y.get("Stop recording"):y.get("Record audio"),color:he?"red":void 0,"data-ai-kit-microphone-button":!0,children:he?y.get("Stop"):y.get("Record")})}),ee>0&&F(Nn,{children:[m(Xe,{variant:"outline",leftSection:m(Lo,{size:18}),onClick:()=>rt.current?.click(),disabled:U.length>=ee||p||he||!!z,title:y.get(f.addImageLabel),"data-ai-kit-add-image-button":!0,children:y.get(f.addLabel)}),m(So,{ref:rt,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:Jn})]}),m(Xe,{leftSection:lr,variant:"filled",onClick:ur,disabled:!p&&!q,"data-ai-kit-send-button":!0,children:sr})]})]}),Ht.length>0&&m(Ee,{className:"ai-thumbs",mt:"xs",gap:"xs",children:Ht.map(({url:e,title:l},h)=>m("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:e?`url(${e})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":l||y.get("View image"),onClick:()=>Aa(e,l),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),Aa(e,l))},children:m(Xe,{variant:"white",onClick:i=>{i.stopPropagation(),_n(h)},"aria-label":y.get(f.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:y.get(f.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},U[h]?.id??h))})]})]})}),m(Ot,{opened:!!ue,onClose:$n,centered:!0,size:"auto",title:ue?.title||y.get("Image preview"),children:ue&&m("img",{src:ue.url,alt:ue.title||y.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},_o=Bt(Jo,{showOpenButton:!0,variation:"modal"});import{Alert as $o,Anchor as Gn,Button as Nt,Checkbox as Hn,Collapse as Zo,Divider as Fn,Group as ft,Loader as Qo,Modal as jt,MultiSelect as Xo,Paper as Wn,Progress as ei,Stack as kt,Text as tt,TextInput as ti,Title as ai}from"@mantine/core";import{AiKitDocSearchIcon as ni,dispatchBackend as ri,resolveBackend as oi,sendSearchMessage as ii}from"@smart-cloud/ai-kit-core";import{I18n as _}from"aws-amplify/utils";import{useCallback as oa,useEffect as _t,useMemo as at,useRef as Ct,useState as Je}from"react";import si from"react-markdown";import li from"rehype-raw";import ui from"remark-gfm";import{IconChevronDown as di,IconChevronRight as ci,IconMicrophone as gi,IconMicrophoneOff as mi,IconSearch as qn,IconX as pi}from"@tabler/icons-react";import{Fragment as ia,jsx as v,jsxs as le}from"react/jsx-runtime";_.putVocabularies(Mt);var Yn=!1;function hi(t){let r=t?.citations?.docs??[],g=t?.citations?.chunks??[],s=new Map;for(let a of r)s.set(a.docId,{doc:a,chunks:[]});for(let a of g){let c=s.get(a.docId);c?c.chunks.push(a):s.set(a.docId,{doc:{docId:a.docId},chunks:[a]})}return Array.from(s.values())}var fi=t=>{let{autoRun:r=!0,context:g,title:s,showOpenButton:a=!1,openButtonTitle:c,showOpenButtonTitle:T=!0,openButtonIcon:E,showOpenButtonIcon:ie=!0,searchButtonIcon:te,showSearchButtonTitle:Q=!0,showSearchButtonIcon:ae=!0,showSources:Ne=!0,topK:ne=10,getSearchText:R,enableUserFilters:u=!1,availableCategories:I,availableTags:ge,variation:W,rootElement:Z,colorMode:me,language:f,onClose:C,onClickDoc:B}=t,[pe,U]=Je(!a),[ve,z]=Je(""),[G,he]=Je(!1),[re,xt]=Je(null),[_e,st]=Je(0),$e=Ct(null),je=Ct([]),Le=Ct(null),x=Ct(null),[P,Re]=Je(!1),[Te,Ge]=Je([]),[oe,lt]=Je([]),[Ie,ut]=Je([]),[dt,bt]=Je(""),[K,yt]=Je(null),[D,ct]=Je(!1),ue=Ct(null),Ze=Ct(null),We=1440*60*1e3,{busy:de,error:Pe,statusEvent:Gt,result:L,run:Lt,cancel:$t,reset:Me}=Wt(),ce=Ct(!1),w=Ct([]),gt=L?.sessionId,ze=L?.citations?.docs??[],nt=L?.citations?.chunks??[],At=L?.citations?.anchors??[],Ve=L?.result??"",rt=at(()=>{if(ae)return te?.trim()?v("img",{src:te,alt:"",style:{width:18,height:18,objectFit:"contain"}}):v(qn,{size:18})},[te,ae]),He=at(()=>(f&&_.setLanguage(f||"en"),_.get(s||"Search with AI-Kit")),[f]),Be=at(()=>Gt?_.get("Searching\u2026"):null,[f,Gt]),qe=at(()=>ve||R,[ve,R]),se=at(()=>{if(de||!pe)return!1;let d=typeof qe=="function"?qe():qe;return!!(d&&d.trim().length>0||re)},[qe,de,re,pe]),Qe=at(()=>{if(!K)return!1;let d=Object.keys(K.allowedCategories).length>0,p=K.allowedTags.length>0;return d||p},[K]),Ke=at(()=>Te.length===0||!K?[]:Te.flatMap(d=>K.allowedCategories[d]||[]).filter((d,p,q)=>q.indexOf(d)===p),[Te,K]),Zt=oa(async()=>{try{z("");let d=await navigator.mediaDevices.getUserMedia({audio:!0}),p=new MediaRecorder(d,{mimeType:"audio/webm"}),q=new AudioContext,Y=q.createMediaStreamSource(d),we=q.createAnalyser();we.fftSize=2048,we.smoothingTimeConstant=.8,Y.connect(we),Le.current=q,x.current=we;let Ue=new Uint8Array(we.fftSize),ot=()=>{if(!x.current)return;x.current.getByteTimeDomainData(Ue);let fe=0;for(let Ht=0;Ht<Ue.length;Ht++){let Xt=(Ue[Ht]-128)/128;fe+=Xt*Xt}let pt=Math.sqrt(fe/Ue.length),sa=Math.min(100,pt*200);st(sa),ue.current=requestAnimationFrame(ot)};ot(),je.current=[],p.ondataavailable=fe=>{fe.data.size>0&&je.current.push(fe.data)},p.onstop=()=>{let fe=new Blob(je.current,{type:"audio/webm"});xt(fe),d.getTracks().forEach(pt=>pt.stop()),ue.current&&(cancelAnimationFrame(ue.current),ue.current=null),Le.current&&(Le.current.close(),Le.current=null),x.current=null,st(0)},$e.current=p,p.start(),he(!0)}catch(d){console.error("Failed to start recording:",d)}},[]),Qt=oa(()=>{$e.current&&G&&($e.current.stop(),he(!1))},[G]),mt=oa(()=>{xt(null),je.current=[],st(0),Ze.current=null},[]);_t(()=>()=>{ue.current&&cancelAnimationFrame(ue.current),Le.current&&Le.current.close()},[]),_t(()=>{if(!u)return;if(I||ge){yt({allowedCategories:I||{},allowedTags:ge||[]});return}(async()=>{ct(!0);try{let p=await oi();if(!p.available){console.error("Backend not available for metadata options");return}let q={feature:"prompt",source:"backend",mode:"backend-only",onDeviceAvailable:!1,backendAvailable:p.available,backendTransport:p.transport,backendApiName:p.apiName,backendBaseUrl:p.baseUrl,reason:p.reason??""},Y=await ri(q,g??"frontend","/kb/metadata-options","GET",null,{});yt({allowedCategories:Y.allowedCategories||{},allowedTags:Y.allowedTags||[]})}catch(p){console.error("Failed to load metadata options:",p)}finally{ct(!1)}})()},[u,I,ge,g]);let o=oa(async()=>{let d;if(!re){if(d=typeof qe=="function"?qe():qe,!d)return;z(d)}console.log("Starting search with query:",d,"and audio:",re);let p=Date.now(),q=re&&Ze.current?.blob===re&&p-Ze.current.uploadTimestamp<We;re&&!q?(Ze.current={blob:re,uploadTimestamp:p},console.log("Audio cache updated for new recording")):q&&console.log("Reusing cached audio (no re-upload needed within",Math.round((We-(p-Ze.current.uploadTimestamp))/1e3),"seconds)"),Me(),await Lt(async({signal:Y,onStatus:we})=>await ii({sessionId:gt,...d&&{query:d},...re&&{audio:re},topK:ne,...u&&{userSelectedCategories:Te},...u&&oe.length>0&&{userSelectedSubcategories:oe},...u&&Ie.length>0&&{userSelectedTags:Ie}},{signal:Y,onStatus:we,context:g}))},[g,qe,re,Lt,Me,ne,gt,u,Te,oe,Ie]),k=oa(async()=>{U(!1),Me(),a||C()},[C,Me,ce,a]);_t(()=>{!r||!se||de||ce.current||(ce.current=!0,queueMicrotask(()=>{o()}))},[de,ce,se,r,o]),_t(()=>{se||(ce.current=!0)},[se]),_t(()=>{let d=w.current,p=Te;(d.length!==p.length||!p.every(Y=>d.includes(Y)))&&d.length>0&&Me(),w.current=[...p]},[Te,Me]);let O=at(()=>hi(L),[L]),H=at(()=>{let d=new Map;return ze.forEach((p,q)=>{p?.docId&&d.set(p.docId,q+1)}),d},[ze]),X=at(()=>{let d=new Map;return nt.forEach(p=>{p?.chunkId&&p?.docId&&d.set(p.chunkId,p.docId)}),d},[nt]),N=at(()=>{if(!Ve)return"";if(!At.length||H.size===0)return Ve;let d=[...At].filter(Y=>Array.isArray(Y?.chunkIds)&&Y?.span?.end!==void 0).sort((Y,we)=>{let Ue=Y.span?.end??0,ot=we.span?.end??0;return Ue-ot}),p=0,q=[];for(let Y of d){let we=Y.span?.end;if(typeof we!="number"||we<p)continue;let Ue=Array.from(new Set((Y.chunkIds??[]).map(fe=>fe?X.get(fe):void 0).map(fe=>fe?H.get(fe):void 0).filter(fe=>typeof fe=="number")));if(!Ue.length)continue;let ot=Math.min(we,Ve.length);q.push(Ve.slice(p,ot)),q.push(`<sup>${Ue.join(",")}</sup>`),p=ot}return q.push(Ve.slice(p)),q.join("")},[At,Ve]),$=W==="modal"?jt.Root:ft,ee=W==="modal"?jt.Content:ft,Ye=W==="modal"?jt.Body:ft;return _t(()=>{if(!(W!=="modal"||!pe))return document.body.style.overflow="hidden",document.body.onkeydown=d=>{d.key==="Escape"&&(d.preventDefault(),k())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[k,W,pe]),le(ia,{children:[a&&v(Nt,{leftSection:ie&&(E?v("span",{dangerouslySetInnerHTML:{__html:E}}):v(qn,{size:18})),className:T?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:pe,onClick:()=>U(!0),"data-ai-kit-open-button":!0,children:T&&_.get(c||He)}),pe&&le($,{opened:!0,className:"doc-search-root",onClose:k,padding:"md",gap:"md",size:"xl",portalProps:W==="modal"?{target:Z,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":me,"data-ai-kit-variation":W,children:[W==="modal"&&v(jt.Overlay,{}),le(ee,{w:"100%",style:{left:0,...W==="modal"&&!L?.result&&{overflow:"visible"}},children:[W==="modal"&&le(jt.Header,{style:{zIndex:1e3},children:[v(ni,{className:"doc-search-title-icon"}),v(jt.Title,{children:_.get(He)}),v(jt.CloseButton,{})]}),v(Ye,{w:"100%",style:{zIndex:1001,...W==="modal"&&!L?.result&&{overflow:"visible"}},children:v(qt,{enabled:W!=="modal",working:de,variation:W,children:v(Wn,{shadow:"sm",radius:"md",p:"md",children:le(kt,{gap:"sm",children:[W!=="modal"&&le(ft,{justify:"space-between",children:[v(ai,{order:4,style:{margin:0},children:_.get(He)}),a&&v(Nt,{variant:"subtle",color:"gray",size:"xs",onClick:k,style:{minWidth:32,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":_.get("Close"),children:v(pi,{size:18,style:{color:me==="dark"?"var(--mantine-color-dark-1)":"var(--mantine-color-gray-7)"}})})]}),le(ft,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[v(ti,{style:{flex:1},value:ve,onChange:d=>{z(d.currentTarget.value),re&&mt()},placeholder:re?_.get("Audio recorded"):_.get("Search the documentation\u2026"),disabled:de||G||!!re,onKeyDown:d=>{d.key==="Enter"&&se&&(d.preventDefault(),o())}}),Yn&&v(ia,{children:re?v(Nt,{variant:"outline",size:"sm",color:"red",onClick:mt,disabled:de,title:_.get("Clear audio"),children:v(mi,{size:18})}):v(Nt,{variant:G?"filled":"outline",size:"sm",color:G?"red":"gray",onClick:G?Qt:Zt,disabled:de,title:G?_.get("Stop recording"):_.get("Record audio"),style:G?{transform:`scale(${1+_e/300})`,transition:"transform 0.1s ease-out"}:void 0,children:v(gi,{size:18})})}),v(Nt,{variant:"filled",size:"sm",leftSection:rt,onClick:()=>{o()},disabled:!se,className:Q?"doc-search-button":"doc-search-button-no-title",children:Q?_.get("Search"):null}),de?v(Nt,{variant:"outline",size:"sm",onClick:$t,children:_.get("Stop")}):null]}),!de&&!Pe&&!L?.result?v(tt,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:_.get("Enter a search query to start.")}):null,u&&K&&Qe&&le(kt,{gap:"xs",children:[v(Nt,{variant:"subtle",size:"xs",onClick:()=>Re(!P),leftSection:P?v(di,{size:14}):v(ci,{size:14}),style:{alignSelf:"flex-start"},children:_.get("Filters")}),v(Zo,{in:P,children:le(kt,{gap:"md",children:[Object.keys(K.allowedCategories).length>0&&le("div",{children:[v(tt,{size:"sm",fw:500,mb:"xs",children:_.get("Categories")}),v(ft,{gap:"md",children:Object.keys(K.allowedCategories).map(d=>v(Hn,{label:_.get(d),checked:Te.includes(d),onChange:p=>{if(p.currentTarget.checked)Ge([...Te,d]);else{Ge(Te.filter(Y=>Y!==d));let q=K.allowedCategories[d]||[];lt(oe.filter(Y=>!q.includes(Y)))}},disabled:de||D},d))})]}),Ke.length>0&&le("div",{children:[v(tt,{size:"sm",fw:500,mb:"xs",children:_.get("Subcategories")}),v(ft,{gap:"md",children:Ke.map(d=>v(Hn,{label:_.get(d),checked:oe.includes(d),onChange:p=>{p.currentTarget.checked?lt([...oe,d]):lt(oe.filter(q=>q!==d))},disabled:de||D},d))})]}),K.allowedTags.length>0&&v(Xo,{label:_.get("Tags"),placeholder:_.get("Select or type tags..."),data:K.allowedTags.map(d=>({value:d,label:_.get(d)})),value:Ie,onChange:ut,searchValue:dt,onSearchChange:bt,disabled:de||D,searchable:!0,clearable:!0,maxDropdownHeight:200,limit:20})]})})]}),Yn&&le(ia,{children:[G&&le(kt,{gap:"xs",children:[le(tt,{size:"xs",c:"dimmed",children:[_.get("Recording...")," \u{1F3A4}"]}),v(ei,{value:_e,size:"sm",color:"red",animated:!0,striped:!0})]}),re&&!G&&le(kt,{gap:"xs",children:[v(tt,{size:"xs",c:"dimmed",children:_.get("Recorded audio:")}),v("audio",{controls:!0,src:URL.createObjectURL(re),className:"ai-kit-audio-player"})]})]}),Pe?v($o,{color:"red",title:_.get("Error"),children:Pe}):null,de&&Be&&v(qt,{enabled:W==="modal",working:!0,variation:W,children:le(ft,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[v(Qo,{size:"sm"}),v(tt,{size:"sm",c:"dimmed",children:Be})]})}),L?.result?le(ia,{children:[v(Fn,{}),le(kt,{gap:"xs","data-doc-search-result":!0,children:[v(tt,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:_.get("AI Summary")}),v(si,{remarkPlugins:[ui],rehypePlugins:[li],"data-doc-search-result-content":!0,children:N||Ve})]})]}):null,Ne&&(L?.citations?.docs?.length||L?.citations?.chunks?.length)?le(ia,{children:[v(Fn,{}),le(kt,{gap:"sm","data-doc-search-sources":!0,children:[v(tt,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:_.get("Sources")}),O.map(({doc:d})=>{let p=d.sourceUrl?.trim()||void 0,q=d.docId?H.get(d.docId):void 0,Y=d.title?.trim()||d.docId,we=le(tt,{fw:600,style:{display:"inline"},children:[q?`${q}. `:"",Y]});return v(Wn,{withBorder:!0,radius:"md",p:"sm",children:v(kt,{gap:"xs",children:v(ft,{justify:"space-between",align:"flex-start",children:le(kt,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[p?v(Gn,{href:p,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ue=>{B&&(Ue.preventDefault(),B?.(d))},"data-doc-search-source-title":!0,children:we}):we,v(Gn,{href:p,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ue=>{B&&(Ue.preventDefault(),B?.(d))},"data-doc-search-source-url":!0,children:d.sourceUrl}),d.author?v(tt,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:d.author}):null,d.description?v(tt,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:d.description}):null]})})})},d.docId)})]})]}):null,v(da,{variation:W})]})})})})]})]})]})},ki=Bt(fi);export{_o as AiChatbot,ho as AiFeature,Oa as DEFAULT_CHATBOT_LABELS,ki as DocSearch,yn as isBackendConfigured,za as markdownToHtml,Dt as readDefaultOutputLanguage,ta as stripCodeFence,Mt as translations,Wt as useAiRun,Bt as withAiKitShell};
31
+ Follow these additional instructions: ${oe}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),H=await w.run(async({signal:$,onStatus:ee})=>(await Ln({messages:O,images:[Ge],outputLanguage:"en",responseConstraint:uo},{signal:$,onStatus:ee,context:I,modeOverride:o,onDeviceTimeoutOverride:a})).result);if(!H){P("");return}let X=(D&&D!=="auto"?D:null)||Dt(),N=ta(H).trim();try{G("Translating result...");let $=await w.run(async({signal:ee})=>await go(N,X,{signal:ee,context:I,modeOverride:o,onDeviceTimeoutOverride:a,silent:!0}));P($)}catch($){P(N),console.warn("AI Kit: failed to parse SEO JSON",$)}break}}}catch(k){Le(k instanceof Error?k.message:n.get("An unknown error occurred."))}G(void 0)}},[B,w,oe,ue,D,Re,We,I,u,Pe,dt,ce,ve]),nt=Rt(async()=>{await ze("backend-only")},[ze]),At=Rt(o=>{switch(u){case"proofread":return b(no,{className:o});case"translate":return b(ro,{className:o});case"summarize":return b(so,{className:o});case"rewrite":case"write":return b(oo,{className:o});case"generateImageMetadata":case"generatePostMetadata":return b(io,{className:o});default:return b(_r,{mode:u,className:o})}},[u]),Ve=Rt(()=>{switch(u){case"proofread":return w.lastSource?n.get("Proofread again"):n.get("Proofread");case"translate":return w.lastSource?n.get("Translate again"):n.get("Translate");case"rewrite":return w.lastSource?n.get("Rewrite again"):n.get("Rewrite");case"summarize":return w.lastSource?n.get("Summarize again"):n.get("Summarize");default:return w.lastSource?n.get("Regenerate"):n.get("Generate")}},[B,w.lastSource,u]),rt=Rt(()=>{switch(u){case"proofread":return n.get("Proofread on Backend");case"translate":return n.get("Translate on Backend");case"rewrite":return n.get("Rewrite on Backend");case"summarize":return n.get("Summarize on Backend");default:return n.get("Regenerate on Backend")}},[B,u]),He=Rt(async()=>{re(!1),P(null),Le(null),L.current=!1,w.reset(),E||me()},[me,L,w,E]),Be=Rt(async()=>{w.busy&&w.cancel()},[w.busy]);ha(()=>{!he||!g||!ce||w.busy||x||L.current||(L.current=!0,queueMicrotask(()=>{ze(ge)}))},[w.busy,L,he,ce,g,x,ze,ge]),ha(()=>{ve&&u!=="proofread"&&(ce||(_e(!0),L.current=!0))},[ve,ce,u]),ha(()=>{let o=!0;return(async()=>{try{await eo();let k=await yn();o&&$e(k)}catch(k){console.error(k),o&&$e(!1)}})(),()=>{o=!1}},[]);let qe=na(()=>{let o=[];if(u==="translate"){let k=pa.find(O=>O.value===dt)?.label;o.push(n.get("Input language")+": "+(k?n.get(k):"auto"))}if(D&&U?.outputLanguage){let k=pa.find(O=>O.value===D)?.label;o.push(n.get("Output language")+": "+(k?n.get(k):D))}return u==="summarize"&&Pe&&U?.type&&o.push(n.get("Type")+": "+n.get(Pe)),(u==="write"||u==="rewrite")&&We&&U?.tone&&o.push(n.get("Tone")+": "+n.get(We)),(u==="write"||u==="rewrite"||u==="summarize")&&ue&&U?.length&&o.push(n.get("Length")+": "+n.get(ue)),oe?.trim()&&U?.instructions&&o.push(n.get("Instructions")+": \u2713"),o.length?o.join(" \u2022 "):n.get("No overrides")},[B,u,dt,D,Pe,We,ue,oe]),se={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},Qe=c==="modal"?Ut.Root:Tt,Ke=c==="modal"?Ut.Content:Tt,Zt=c==="modal"?Ut.Body:Tt,Qt=R==="collapse"?Wr:It,mt=R==="horizontal"?Tt:It;return ha(()=>{if(!(c!=="modal"||!he))return document.body.style.overflow="hidden",document.body.onkeydown=o=>{o.key==="Escape"&&(o.preventDefault(),He())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[He,c]),ye(ra,{children:[E&&b(Kt,{leftSection:te&&(ae?b("span",{dangerouslySetInnerHTML:{__html:ae}}):At()),className:ie?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:he,onClick:()=>re(!0),"data-ai-kit-open-button":!0,children:ie&&n.get(Q||Lt)}),he&&ye(Qe,{opened:!0,className:"ai-feature-root",onClose:He,padding:"md",gap:"md",size:"md",portalProps:c==="modal"?{target:pe,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":W,"data-ai-kit-variation":c,children:[c==="modal"&&b(Ut.Overlay,{}),ye(Ke,{w:"100%",style:{left:0},children:[c==="modal"&&ye(Ut.Header,{style:{zIndex:1e3},children:[At("ai-feature-title-icon"),b(Ut.Title,{children:n.get(Lt)}),b(Ut.CloseButton,{})]}),b(Zt,{w:"100%",style:{zIndex:1001},children:ye(qt,{enabled:c!=="modal",working:w.busy,variation:c,children:[ye(It,{gap:"sm",mb:"sm",p:"sm",children:[je&&b(xa,{color:"red",children:n.get(je)}),ve&&u!=="proofread"&&ye(Vr,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":R,children:[ye(Tt,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:R==="collapse"?()=>_e(o=>!o):void 0,children:[R==="collapse"&&ye(It,{gap:0,children:[b(xn,{size:"sm",fw:600,style:{lineHeight:1.1},children:n.get("Options")}),b(xn,{size:"xs",c:"dimmed",style:{marginTop:2},children:qe})]}),R==="collapse"&&b(Kt,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:o=>{o.stopPropagation(),_e(k=>!k)},children:xt?n.get("Hide"):n.get("Show")})]}),ye(Qt,{in:xt,children:[R==="collapse"&&b(qr,{my:"sm"}),ye(mt,{gap:"xs",justify:"space-between",children:[u==="write"&&U?.text&&b(St,{label:n.get("The topic or subject for the AI to write about."),disabled:R!=="horizontal",position:"top",children:b(wt,{size:"xs",className:"ai-feature-option",styles:se,disabled:w.busy,label:n.get("Topic"),description:R!=="horizontal"?n.get("The topic or subject for the AI to write about."):void 0,value:Re||"",onChange:o=>{let k=o.target.value;Te(k),C?.({text:k})}})}),(u==="write"||u==="rewrite"||u==="generateImageMetadata"||u==="generatePostMetadata")&&U?.instructions&&b(St,{label:n.get("Additional instructions to guide the AI."),disabled:R!=="horizontal",position:"top",children:b(wt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Instructions"),description:R!=="horizontal"?n.get("Additional instructions to guide the AI."):void 0,value:oe||"",onChange:o=>{let k=o.target.value;lt(k),C?.({instructions:k})}})}),u==="translate"&&b(St,{label:n.get("The language of the input text."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",styles:se,className:"ai-feature-option",label:n.get("Input language"),description:R!=="horizontal"?n.get("The language of the input text."):void 0,data:[{value:"auto",label:n.get("Auto-detect")},...pa.map(o=>({value:o.value,label:n.get(o.label)})).sort((o,k)=>o.label.localeCompare(k.label))],value:dt||"auto",onChange:o=>{let k=o;bt(k),ut(void 0),C?.({inputLanguage:k})}})}),U?.outputLanguage&&b(St,{label:n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",styles:se,className:"ai-feature-option",label:n.get("Output language"),description:R!=="horizontal"?n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[u==="rewrite"?{value:"auto",label:n.get("Auto-detect")}:void 0].filter(Boolean),...pa.map(o=>({value:o.value,label:n.get(o.label)})).sort((o,k)=>o.label.localeCompare(k.label))],value:D||Dn.settings.defaultOutputLanguage||(u==="rewrite"?"auto":""),onChange:o=>{let k=o;ct(k),ut(void 0),C?.({outputLanguage:k})}})}),u==="summarize"&&U?.type&&b(St,{label:n.get("The summary style to generate."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Type"),description:R!=="horizontal"?n.get("The summary style to generate."):void 0,data:[{value:"headline",label:n.get("Headline")},{value:"key-points",label:n.get("Key Points")},{value:"teaser",label:n.get("Teaser")},{value:"tldr",label:n.get("TL;DR")}],value:Pe||"key-points",onChange:o=>{let k=o;Gt(k),C?.({type:k})}})}),(u==="write"||u==="rewrite")&&U?.tone&&b(St,{label:n.get("The tone or style for the AI to use."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Tone"),description:R!=="horizontal"?n.get("The tone or style for the AI to use."):void 0,data:u==="write"?[{value:"neutral",label:n.get("Neutral")},{value:"formal",label:n.get("Formal")},{value:"casual",label:n.get("Casual")}]:[{value:"as-is",label:n.get("As-Is")},{value:"more-formal",label:n.get("More formal")},{value:"more-casual",label:n.get("More casual")}],value:We||(u==="write"?"neutral":"as-is"),onChange:o=>{let k=o;de(k),C?.({tone:k})}})}),(u==="write"||u==="rewrite"||u==="summarize")&&U?.length&&b(St,{label:n.get("The target output length."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Length"),description:R!=="horizontal"?n.get("The target output length."):void 0,data:u==="write"||u==="summarize"?[{value:"short",label:n.get("Short")},{value:"medium",label:n.get("Medium")},{value:"long",label:n.get("Long")}]:[{value:"as-is",label:n.get("As-Is")},{value:"shorter",label:n.get("Shorter")},{value:"longer",label:n.get("Longer")}],value:ue||(u==="rewrite"?"as-is":"short"),onChange:o=>{let k=o;Ze(k),C?.({length:k})}})}),u==="summarize"||u==="write"||u==="rewrite"&&U?.outputFormat&&b(St,{label:n.get("The format for the generated output."),disabled:R!=="horizontal",position:"top",children:b(Yt,{disabled:w.busy,size:"xs",className:"ai-feature-option",styles:se,label:n.get("Output format"),description:R!=="horizontal"?n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:n.get("Plain Text")},{value:"markdown",label:n.get("Markdown")},{value:"html",label:n.get("HTML")}],value:K||"markdown",onChange:o=>{let k=o;yt(k),C?.({outputFormat:k})}})})]})]})]}),w.busy&&gt&&b(qt,{enabled:c==="modal",working:!0,variation:c,children:ye(Tt,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[b(Yr,{size:"sm"}),b(La.Label,{className:"ai-feature-status-text",children:gt})]})}),x&&ye(It,{mt:"md",children:[u==="proofread"&&(x.corrections.length===0?b(xa,{color:"green",children:n.get("No issues found. Your text looks great!")}):ye(ra,{children:[b("p",{style:{marginTop:0,opacity:.85},children:n.get("Hover highlights to see explanations.")}),b(Cn,{original:Re,corrections:x.corrections}),x.correctedInput?ye(ra,{children:[b("h4",{style:{marginTop:16,marginBottom:8},children:n.get("Corrected")}),b(Tt,{c:"pre",className:"ai-feature-generated-content",children:x.correctedInput})]}):null]})),u==="generateImageMetadata"&&ye(ra,{children:[b(wt,{readOnly:!s,label:n.get("Alt Text"),description:n.get("The alt text for the image."),value:x.alt_text||"",onChange:o=>P({...x,alt_text:o.target.value})}),b(wt,{readOnly:!s,label:n.get("Title"),description:n.get("The title for the image."),value:x.title||"",onChange:o=>P({...x,title:o.target.value})}),b(wt,{readOnly:!s,label:n.get("Caption"),description:n.get("The caption for the image."),value:x.caption||"",onChange:o=>P({...x,caption:o.target.value})}),b(wt,{readOnly:!s,label:n.get("Description"),description:n.get("The description for the image."),value:x.description||"",onChange:o=>P({...x,description:o.target.value})})]}),u==="generatePostMetadata"&&ye(ra,{children:[b(wt,{readOnly:!s,label:n.get("Title"),description:n.get("The title for the post."),value:x.title||"",onChange:o=>P({...x,title:o.target.value})}),b(wt,{readOnly:!s,label:n.get("Excerpt"),description:n.get("The excerpt for the post."),value:x.excerpt||"",onChange:o=>P({...x,excerpt:o.target.value})})]}),u!=="proofread"&&u!=="generateImageMetadata"&&u!=="generatePostMetadata"&&typeof x=="string"&&b(En,{value:x,editable:!!s,onChange:o=>{P(o)}})]}),x===""&&b(En,{value:x,editable:!1})]}),ye(Tt,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[w.busy&&b(Kt,{variant:"outline",size:"sm",onClick:Be,"data-ai-kit-cancel-button":!0,children:n.get("Cancel")}),!w.busy&&b(Kt,{variant:"filled",size:"sm",disabled:!ce,onClick:()=>ze(),"data-ai-kit-generate-button":!0,children:Ve()}),!w.busy&&w.lastSource==="on-device"&&st&&Ne&&b(Kt,{variant:"filled",size:"sm",disabled:!ce,onClick:nt,"data-ai-kit-regenerate-on-backend-button":!0,children:rt()}),!w.busy&&f&&b(Kt,{variant:"outline",size:"sm",disabled:!x||u==="proofread"&&x.corrections.length===0,onClick:async()=>{f(K==="html"?await za(x):x),He()},"data-ai-kit-accept-button":!0,children:n.get(ne)}),b(Kt,{variant:"default",size:"sm",onClick:He,"data-ai-kit-close-button":!0,children:n.get("Close")})]}),b(da,{variation:c})]})})]})]})]})};function En(t){let{value:r,editable:g,onChange:s}=t;return g?ye(It,{p:0,gap:"sm",children:[b(La.Label,{children:n.get("Generated content")}),b(Jr,{value:r,onChange:a=>s?.(a.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),b(La.Label,{children:n.get("Preview")}),b(It,{className:"ai-feature-generated-content ai-feature-preview",children:b(Pn,{remarkPlugins:[Mn],children:r})})]}):b(It,{className:"ai-feature-generated-content",children:r?b(Pn,{remarkPlugins:[Mn],children:r}):b(xa,{color:"yellow",children:n.get("No content generated.")})})}var ho=Bt(po);import{ActionIcon as Kn,Anchor as To,Box as wo,Button as Xe,Group as Ee,Input as So,List as Un,Modal as Ot,Stack as et,Text as xe,Textarea as Ro}from"@mantine/core";import{IconMaximize as Io,IconMessage as zo,IconMicrophone as Co,IconMinimize as xo,IconPaperclip as Lo,IconPencil as Po,IconPlayerStop as Mo,IconSend as Do,IconTrash as Eo,IconX as Bo}from"@tabler/icons-react";import{getStoreSelect as Ko,sendChatMessage as Uo,sendFeedbackMessage as Oo}from"@smart-cloud/ai-kit-core";import{useSelect as No}from"@wordpress/data";import{I18n as y}from"aws-amplify/utils";import{useCallback as J,useEffect as ke,useMemo as Ae,useRef as Se,useState as be}from"react";import jo from"react-markdown";import Go from"remark-gfm";var fo="ai-kit-chatbot-attachments",it="attachments";var Pa=null;function ko(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function fa(){if(!ko())return null;Pa||(Pa=new Promise(t=>{try{let r=window.indexedDB.open(fo,1);r.onerror=()=>t(null),r.onblocked=()=>t(null),r.onupgradeneeded=()=>{let g=r.result;g.objectStoreNames.contains(it)||g.createObjectStore(it,{keyPath:"id"})},r.onsuccess=()=>t(r.result)}catch(r){console.warn("[AiChatbot] IndexedDB is not available",r),t(null)}}));try{return await Pa}catch(t){return console.warn("[AiChatbot] Failed to open attachment store",t),null}}async function Ma(t,r){let g=await fa();return g?new Promise((s,a)=>{try{let c=g.transaction(it,t),T=c.objectStore(it),E=r(T);c.oncomplete=()=>s(E),c.onerror=()=>a(c.error),c.onabort=()=>a(c.error)}catch(c){a(c)}}).catch(s=>(console.warn("[AiChatbot] Attachment store transaction failed",s),null)):null}async function Da(t,r,g){await vo();let s={id:t,blob:r,name:g.name,type:g.type,size:g.size,createdAt:Date.now()};return await Ma("readwrite",c=>(c.put(s),t))}async function Ea(t){let r=await fa();return r?new Promise((g,s)=>{try{let a=r.transaction(it,"readonly"),c=a.objectStore(it).get(t);c.onsuccess=()=>{let T=c.result;g(T??null)},c.onerror=()=>s(c.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(g=>(console.warn("[AiChatbot] Failed to load attachment",g),null)):null}async function bo(t){await Ma("readwrite",r=>{r.delete(t)})}async function ka(){await Ma("readwrite",t=>{t.clear()})}async function Ba(t){let r=await fa();r&&await new Promise((g,s)=>{try{let a=r.transaction(it,"readwrite"),c=a.objectStore(it),T=c.getAllKeys();T.onsuccess=()=>{let E=T.result;for(let ie of E){let te=String(ie);t.has(te)||c.delete(ie)}},T.onerror=()=>s(T.error),a.oncomplete=()=>g(),a.onerror=()=>s(a.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(g=>{console.warn("[AiChatbot] Failed to cleanup attachments",g)})}var yo=50*1024*1024;async function Ao(){let t=await fa();return t?new Promise((r,g)=>{try{let s=t.transaction(it,"readonly"),a=s.objectStore(it).getAll();a.onsuccess=()=>{let c=a.result||[];r(c)},a.onerror=()=>g(a.error),s.onerror=()=>g(s.error),s.onabort=()=>g(s.error)}catch(s){g(s)}}).catch(r=>(console.warn("[AiChatbot] Failed to get all attachments",r),[])):[]}async function vo(){let t=await Ao();if(t.length===0)return;let r=t.sort((c,T)=>c.createdAt-T.createdAt),g=r.reduce((c,T)=>c+T.size,0),s=[],a=0;for(;g>yo&&a<r.length;){let c=r[a];c&&(s.push(c.id),g-=c.size),a++}for(let c of s)await bo(c);s.length>0&&console.log(`[AiChatbot] Deleted ${s.length} old attachment(s) to enforce storage quota`)}import{Fragment as Nn,jsx as m,jsxs as F}from"react/jsx-runtime";y.putVocabularies(Mt);var ba=1440*60*1e3,Ka=!1,Ho=1,Fo="localstorage",Vt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,Oa={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function zt(t){return`${t}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var Wo=4,qo=5*1024*1024,Yo=t=>{let r=(t?.name||"").toString(),g=(t?.code||"").toString(),s=(t?.message||"").toString();return r==="AbortError"||g==="ABORT_ERR"||/abort|aborted|cancel/i.test(s)},Vo=(t,r)=>{if(!t)return null;let g=t.step,s=y.get((t.message??"").trim()),a=typeof t.progress=="number"?t.progress:null,c=a==null?null:Math.round(a*100);switch(g){case"decide":return s||y.get("Checking capabilities...");case"on-device:init":return s||y.get("Initializing on-device AI...");case"on-device:download":return c==null?s||y.get("Downloading model..."):s||`${y.get("Downloading model...")} ${c}%`;case"on-device:ready":return s||y.get("On-device model ready...");case"on-device:run":return s||y.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return y.get(r.assistantThinkingLabel??Oa.assistantThinkingLabel);case"done":return s||y.get("Done.");case"error":return s||y.get("An error occurred.");default:return s||null}};function Ua(t){if(typeof window>"u")return null;try{return t==="localstorage"?window.localStorage:t==="sessionstorage"?window.sessionStorage:null}catch{return null}}var Jt=t=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(t)}catch{return null}},ya=t=>{if(t&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(t)}catch{}},jn=t=>{!t||t.length===0||t.forEach(r=>ya(r.objectUrl))},On=t=>{t.forEach(r=>jn(r.attachments))},Jo=t=>{let{rootElement:r,store:g,previewMode:s,title:a,openButtonTitle:c,openButtonIcon:T,showOpenButtonTitle:E=!0,showOpenButtonIcon:ie=!0,colorMode:te,language:Q,onClose:ae,context:Ne,placeholder:ne,maxImages:R,maxImageBytes:u,historyStorage:I=Fo,emptyHistoryAfterDays:ge=Ho,labels:W,openButtonIconLayout:Z="top",openButtonPosition:me="bottom-right"}=t,f=Ae(()=>({...Oa,...W||{}}),[W]),C=Wt(),[B,pe]=be(""),[U,ve]=be([]),[z,G]=be(null),[he,re]=be(!1),[xt,_e]=be(0),st=Se(null),$e=Se([]),je=Se(null),Le=Se(null),x=Se(null),[P,Re]=be([]),[Te,Ge]=be(null),[oe,lt]=be(!1),[Ie,ut]=be(!1),[dt,bt]=be(!1),[K,yt]=be(!1),[D,ct]=be(!0),[ue,Ze]=be(null),[We,de]=be(!1),[Pe,Gt]=be(null),[L,Lt]=be(null),[$t,Me]=be(!1),[ce,w]=be(null),gt=Se(ce);ke(()=>{gt.current=ce},[ce]);let ze=Se(null),nt=Se(!1),[At,Ve]=be(null),rt=Se(null),He=Se(null),Be=Se(null),qe=Se(null),se=J(e=>{e.forEach(l=>ya(l.objectUrl))},[]),Qe=J(()=>{se(X.current),ve([]),rt.current&&(rt.current.value="")},[se]),Ke=J(()=>{N.current&&ya(N.current.objectUrl),G(null),$e.current=[],_e(0)},[]),Zt=J(async()=>{try{pe(""),Ke();let e=await navigator.mediaDevices.getUserMedia({audio:!0}),l=new MediaRecorder(e,{mimeType:"audio/webm"}),h=new AudioContext,i=h.createMediaStreamSource(e),S=h.createAnalyser();S.fftSize=2048,S.smoothingTimeConstant=.8,i.connect(S),je.current=h,Le.current=S;let A=new Uint8Array(S.fftSize),M=()=>{if(!Le.current)return;Le.current.getByteTimeDomainData(A);let V=0;for(let Fe=0;Fe<A.length;Fe++){let Pt=(A[Fe]-128)/128;V+=Pt*Pt}let Ce=Math.sqrt(V/A.length),Oe=Math.min(100,Ce*200);_e(Oe),x.current=requestAnimationFrame(M)};M(),$e.current=[];let j=Date.now();l.ondataavailable=V=>{V.data.size>0&&$e.current.push(V.data)},l.onstop=()=>{let V=new Blob($e.current,{type:"audio/webm"}),Ce=(Date.now()-j)/1e3,Oe=Jt(V);Oe&&G({id:zt("composer-audio"),blob:V,objectUrl:Oe,duration:Ce}),e.getTracks().forEach(Fe=>Fe.stop()),x.current&&(cancelAnimationFrame(x.current),x.current=null),je.current&&(je.current.close(),je.current=null),Le.current=null,_e(0)},st.current=l,l.start(),re(!0)}catch(e){console.error("Failed to start recording:",e)}},[Ke]),Qt=J(()=>{st.current&&he&&(st.current.stop(),re(!1))},[he]);ke(()=>()=>{x.current&&cancelAnimationFrame(x.current),je.current&&je.current.close(),Ke()},[Ke]);let[mt,o]=be(null),k=Se(B),O=Se(P),H=Se(mt),X=Se(U),N=Se(z);ke(()=>{k.current=B},[B]),ke(()=>{X.current=U},[U]),ke(()=>{N.current=z},[z]),ke(()=>{O.current=P},[P]),ke(()=>{H.current=mt},[mt]),ke(()=>{Q&&y.setLanguage(Q||"en")},[Q]);let $=No(()=>Ko(g).isShowChatbotPreview()),ee=Ae(()=>Math.max(0,R??Wo),[R]),Ye=Ae(()=>Math.max(0,u??qo),[u]),d=P.length>0,p=Ae(()=>C.busy&&ce==="chat",[C.busy,ce]),q=Ae(()=>p?!1:B.trim().length>0||z!==null,[B,p,z]),Y=Ae(()=>{let e=c||f.askMeLabel;return y.get(e)},[c,f.askMeLabel,Q]),we=Ae(()=>{let e=a||f.modalTitle;return y.get(e)},[a,f.modalTitle,Q]),Ue=Ae(()=>{let e=ne||f.placeholder;return y.get(e)},[ne,f.placeholder,Q]),ot=Ae(()=>{let e="ai-docs-ask",l=`ai-open-btn--${me}`;return`${e} ${l}`},[me]),fe=J(()=>{let e=qe.current;if(e)try{let l=window.innerHeight||document.documentElement.clientHeight,h=360,i=1e3,S=Math.floor(l*.8),A=Math.max(h,Math.min(S,i));e.style.height=`${A}px`}catch{}},[]),pt=J(()=>{let e=L;e&&window.setTimeout(()=>{try{e.scrollTop=e.scrollHeight}catch{}},50)},[L]),sa=J(()=>{yt(!1),Ie&&ut(!1),bt(!1),ae?.()},[Ie,ae]);ke(()=>{if(K)return fe(),window.addEventListener("resize",fe),()=>window.removeEventListener("resize",fe)},[K,fe]),ke(()=>{if(!(!K||!Ie))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[K,Ie,sa]);let Ht=Ae(()=>U.map(e=>({id:e.id,url:e.objectUrl,title:e.file.name})),[U]);ke(()=>{d||ct(!0)},[d]),ke(()=>()=>{se(X.current)},[se]),ke(()=>{let e=L;if(!e)return;let l=()=>{let h=e.scrollHeight-(e.scrollTop+e.clientHeight);ct(h<20)};return e.addEventListener("scroll",l),()=>{e.removeEventListener("scroll",l)}},[K,L]),ke(()=>{if(!D)return;let e=L;e&&e.scrollHeight>e.clientHeight&&(e.scrollTop=e.scrollHeight)},[P,C.busy,D,L]),ke(()=>{K||Ze(null)},[K]);let Xt=Ae(()=>C.busy?Vo(C.statusEvent,f)||y.get("Working\u2026"):null,[C.busy,C.statusEvent,Q,f]),Vn=Ae(()=>{for(let e=P.length-1;e>=0;e--){let l=P[e];if(l.role==="user"&&l.clientStatus==="canceled")return l.id}return null},[P]),ea=J(e=>{Re(l=>{let h=[...l].map((A,M)=>({m:A,i:M})).reverse().find(A=>A.m.role==="user"&&A.m.clientStatus==="pending")?.i;if(h==null)return l;let i=l.slice(),S=i[h];return i[h]={...S,clientStatus:e??void 0},i})},[Re]),la=J(()=>{if(!(!C.busy||gt.current!=="chat")){nt.current=!0;try{C.cancel()}catch{}ea("canceled"),w(null),Ge(null),pt()}},[C,ea,pt]),Jn=J(e=>{let l=X.current,h=Array.from(e.target.files||[]),i=Math.max(0,ee-l.length);if(i===0){e.currentTarget.value="";return}let S=[];for(let A of h){if(S.length>=i)break;let M=/image\/(jpeg|png|gif|webp)/i.test(A.type),j=A.size<=Ye,V=[...l,...S].some(Oe=>Oe.file.name===A.name&&Oe.file.size===A.size&&Oe.file.lastModified===A.lastModified);if(!M||!j||V)continue;let Ce=Jt(A);Ce&&S.push({id:zt("composer-image"),file:A,objectUrl:Ce})}S.length&&ve(A=>[...A,...S]),e.currentTarget.value=""},[ee,Ye]),_n=J(e=>{ve(l=>{if(e<0||e>=l.length)return l;let h=l[e];return h&&ya(h.objectUrl),l.filter((i,S)=>S!==e)})},[]),vt=Se(null);ke(()=>{if(Te)return vt.current&&(window.clearTimeout(vt.current),vt.current=null),vt.current=window.setTimeout(()=>{Ge(null),vt.current=null},6e3),()=>{vt.current&&(window.clearTimeout(vt.current),vt.current=null)}},[Te]);let Na=J(async(e,l)=>{let h=I!=="nostorage",i=[];if(e.length>0){let S=await Promise.all(e.map(async A=>{let M=zt("attachment-image"),j;if(h)try{j=await Da(M,A.file,{name:A.file.name,type:A.file.type,size:A.file.size})??void 0}catch(Ce){console.warn("[AiChatbot] Failed to persist image",Ce)}let V=Jt(A.file);return{id:M,name:A.file.name,type:A.file.type||"application/octet-stream",size:A.file.size,blobId:j,objectUrl:V??void 0,blob:A.file,mediaType:"image"}}));i.push(...S.filter(Boolean))}if(l){let S=zt("attachment-audio"),A;if(h)try{A=await Da(S,l.blob,{name:`audio-${Date.now()}.webm`,type:l.blob.type,size:l.blob.size})??void 0}catch(j){console.warn("[AiChatbot] Failed to persist audio",j)}let M=Jt(l.blob);i.push({id:S,name:`audio-${Date.now()}.webm`,type:l.blob.type||"audio/webm",size:l.blob.size,blobId:A,objectUrl:M??void 0,blob:l.blob,duration:l.duration,mediaType:"audio"})}return i},[I]),ja=J(async e=>{let l=[];for(let h of e){let i;if(h.attachments&&h.attachments.length>0){i=[];for(let S of h.attachments){let A;if(S.blobId)try{A=(await Ea(S.blobId))?.blob??void 0}catch(j){console.warn("[AiChatbot] Failed to hydrate attachment",j)}if(!A)continue;let M=A?Jt(A):null;i.push({...S,objectUrl:M??void 0,blob:A??void 0})}}l.push({...h,attachments:i})}return l},[]),Ga=J(async e=>{if(!e||e.length===0){Qe();return}let l=[];for(let h of e){let i=h.blob;if(!i&&h.blobId)try{i=(await Ea(h.blobId))?.blob??void 0}catch(M){console.warn("[AiChatbot] Failed to reload attachment",M)}if(!i)continue;let S=i instanceof File?i:new File([i],h.name||"attachment",{type:h.type||i.type||"application/octet-stream"}),A=Jt(S);if(A&&(l.push({id:zt("composer-image"),file:S,objectUrl:A}),l.length>=ee))break}if(l.length===0){Qe();return}ve(h=>(se(h),l)),rt.current&&(rt.current.value="")},[Qe,se,ee]),Aa=J((e,l)=>{e&&Ze({url:e,title:l})},[]),$n=J(()=>{Ze(null)},[]),Ha=J(()=>{On(O.current),Qe(),Ke(),Re([]),Ge(null),Be.current=null,o(null),ct(!0),lt(!1);let e=Ua(I);if(e)try{e.removeItem(Vt)}catch{}ka()},[Qe,Ke,I]),Zn=J(()=>{lt(!0)},[]),Qn=J(()=>{C.busy&&gt.current==="chat"&&la(),Ha()},[C.busy,la,Ha]),Fa=J(()=>{lt(!1)},[]),Wa=J(async(e,l)=>{if(!C.busy)try{let h=Be.current&&Date.now()-Be.current.storedAt<ge*ba?Be.current.id:void 0;if(!h)return;w("feedback"),Ge(null),await C.run(async({signal:i,onStatus:S})=>(await Oo({sessionId:h,feedbackMessageId:e,feedbackType:l},{signal:i,onStatus:S,context:Ne}),null)),Ge(null)}catch(h){let i=h?.message?.trim()||y.get("An error occurred.");Ge(i),console.error("Failed to send feedback",h)}finally{w(h=>h==="feedback"?null:h)}},[C,Q]),qa=J((e,l)=>{Re(h=>h.map(i=>i.id!==e||i.role!=="assistant"?i:i.feedback===l?{...i,feedback:void 0}:{...i,feedback:l})),Wa(e,l)},[Wa]),ua=J(async()=>{let e=k.current.trim(),l=N.current;if(!e&&!l||C.busy)return;nt.current=!1,Ge(null),w("chat");let h=[...X.current],i=await Na(h,l),S=zt("user"),A=Date.now(),M={id:S,role:"user",content:e||(l?"[Audio message]":""),createdAt:A,clientStatus:"pending",attachments:i.length?i:void 0};pe(""),Qe(),Ke(),Re(j=>[...j,M]),K||yt(!0),pt();try{let j=Be.current&&Date.now()-Be.current.storedAt<ge*ba?Be.current.id:void 0,V=await C.run(async({signal:Oe,onStatus:Fe})=>await Uo({sessionId:j,message:e||void 0,audio:l?.blob,images:h.map(dr=>dr.file)},{signal:Oe,onStatus:Fe,context:Ne}));if(nt.current){ea("canceled");return}if(!V)throw new Error(y.get(C.error??f.emptyResponseLabel));V.sessionId&&(Be.current={id:V.sessionId,storedAt:Date.now()});let Ce={id:V.metadata?.messageId||zt("assistant"),role:"assistant",content:V.result||"",citations:V.citations,createdAt:Date.now()};Re(Oe=>[...Oe.map(Pt=>Pt.id===S?{...Pt,clientStatus:void 0}:Pt),Ce]),o(A)}catch(j){if(console.error("Error during ask()",j),nt.current||Yo(j)){ea("canceled");return}let V=j?.message?.trim()||y.get(f.unexpectedErrorLabel);Re(Ce=>[...Ce.map(Fe=>Fe.id===S?{...Fe,clientStatus:void 0}:Fe),{id:zt("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${V}`,createdAt:Date.now()}]),o(A)}finally{w(j=>j==="chat"?null:j),nt.current=!1,He.current&&He.current.focus(),pt()}},[C,Na,Qe,Ke,K,pt,ea,f.emptyResponseLabel,f.unexpectedErrorLabel,Q]),Xn=J(e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),q&&ua())},[ua,q]),er=J(()=>{yt(!0)},[]);ke(()=>()=>{ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null)},[]);let tr=J(()=>{ut(e=>{let l=!e;return ze.current!=null&&(cancelAnimationFrame(ze.current),ze.current=null),l?(bt(!0),requestAnimationFrame(()=>{ze.current=requestAnimationFrame(()=>{bt(!1),ze.current=null})})):bt(!1),l})},[]),ar=J(e=>{pe(e.content),(async()=>(await Ga(e.attachments),Re(l=>l.filter(h=>h.id!==e.id)),jn(e.attachments),queueMicrotask(()=>He.current?.focus())))()},[Ga]),Ya=Ae(()=>ie?T?m("img",{src:T,className:"ai-open-btn-icon",alt:y.get(f.askMeLabel||Y)}):m(zo,{size:18}):null,[ie,T,f,Y,Q]),nr=Ae(()=>{let e=Ya,l=E?m(xe,{inherit:!0,children:Y}):null;if(!ie&&!l)return null;if(!ie)return l;if(!E)return e;switch(Z){case"top":return F(et,{gap:4,align:"center",children:[e,l]});case"bottom":return F(et,{gap:4,align:"center",children:[l,e]});case"right":return F(Ee,{gap:6,align:"center",children:[l,e]});default:return F(Ee,{gap:6,align:"center",children:[e,l]})}},[Ya,ie,E,Y,Z]),rr=Ae(()=>p,[p]),or=Ae(()=>!p,[p]),ir=Ae(()=>Te||(d?y.get(f.readyLabel):y.get(f.readyEmptyLabel)),[Te,d,f.readyLabel,f.readyEmptyLabel,Q]),sr=Ae(()=>p?y.get(f.cancelLabel):y.get(f.sendLabel),[p,f.cancelLabel,f.sendLabel,Q]),lr=Ae(()=>p?m(Mo,{size:18}):m(Do,{size:18}),[p]),ur=J(()=>{if(p){la();return}ua()},[p,la,ua]);return ke(()=>{if(!K||!Pe||!L)return;let e=()=>{let j=window.getComputedStyle(L).overflowY,V=j==="auto"||j==="scroll",Ce=Math.ceil(L.scrollHeight),Oe=Math.floor(L.clientHeight),Fe=Ce>Oe;return V&&Fe},l=!1,h=M=>{if(!e())return;M.preventDefault();let j=L.scrollHeight-L.clientHeight;L.scrollTop=Math.max(0,Math.min(j,L.scrollTop+M.deltaY))},i=()=>{let M=e();Me(M),M!==l&&(l=M,l?Pe.addEventListener("wheel",h,{passive:!1}):Pe.removeEventListener("wheel",h))};i();let S=new ResizeObserver(i);S.observe(L);let A=new MutationObserver(i);return A.observe(L,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",i),()=>{l&&Pe.removeEventListener("wheel",h),S.disconnect(),A.disconnect(),window.removeEventListener("resize",i)}},[K,Pe,L]),ke(()=>{let e=!1,l=Ua(I);if(!l){I==="nostorage"&&ka(),de(!0);return}return(async()=>{try{let h=l.getItem(Vt);if(!h){de(!0);return}let i=JSON.parse(h),S=typeof i?.lastUserSentAt=="number"?i.lastUserSentAt:null;if(!S||Date.now()-S>ge*ba){l.removeItem(Vt),await ka(),de(!0);return}let M=(Array.isArray(i.messages)?i.messages:[]).map(V=>V?.role==="user"&&V.clientStatus==="pending"?{...V,clientStatus:"canceled"}:V),j=await ja(M);if(e){On(j);return}Re(j),o(S),i.session&&i.session.id&&(Be.current=i.session)}catch(h){console.warn("[AiChatbot] Failed to load history",h);try{l.removeItem(Vt)}catch{}}finally{e||de(!0)}})(),()=>{e=!0}},[I,ge,ja]),ke(()=>{if(!We)return;let e=Ua(I);if(!e)return;let l=H.current;if(!l)return;if(Date.now()-l>ge*ba){try{e.removeItem(Vt)}catch{}Ba(new Set);return}let h=P.map(({attachments:A,...M})=>({...M,attachments:A?.map(({objectUrl:j,blob:V,...Ce})=>Ce)})),i={version:1,lastUserSentAt:l,session:Be.current,messages:h};try{e.setItem(Vt,JSON.stringify(i))}catch{}let S=new Set;h.forEach(A=>{A.attachments?.forEach(M=>{M.blobId&&S.add(M.blobId)})}),Ba(S)},[We,P,mt,I,ge]),s&&!$||!s&&$?null:F(Ee,{className:ot,children:[!K&&m(Xe,{variant:"filled",className:E?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:er,"aria-label":Y,title:Y,"data-ai-kit-open-button":!0,children:nr}),K&&m(Ot.Root,{ref:qe,opened:K,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:sa,className:ot+" ai-chat-container"+(Ie?" maximized":"")+(Ie&&dt?" ai-max-enter":""),portalProps:{target:r,reuseTargetNode:!0},"data-ai-kit-theme":te,"data-ai-kit-variation":"modal",children:F("div",{className:"ai-chat-container-internal",ref:Gt,children:[F(Ot.Header,{className:"ai-chat-header-bar",children:[m(Ot.Title,{className:"ai-chat-title",children:we}),F(Ee,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&m(Kn,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:tr,title:Ie?y.get(f.restoreSizeLabel):y.get(f.maximizeLabel),"aria-label":Ie?y.get(f.restoreSizeLabel):y.get(f.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Ie?m(xo,{size:16}):m(Io,{size:16})}),m(Ot.CloseButton,{"aria-label":y.get(f.closeChatLabel)})]})]}),F(Ot.Body,{className:"ai-chat-scroll",ref:Lt,"data-scrollable":$t?"true":"false",children:[P.map(e=>{let l=e.role==="user",h=l&&e.clientStatus==="canceled"&&e.id===Vn;return m(Ee,{justify:l?"flex-end":"flex-start",className:"ai-chat-row "+e.role,onMouseEnter:()=>Ve(e.id),onMouseLeave:()=>Ve(i=>i===e.id?null:i),children:F(et,{gap:4,w:"100%",style:{alignItems:l?"flex-end":"flex-start"},children:[F(et,{className:"ai-chat-bubble",children:[F(xe,{className:"ai-chat-header",children:[m(xe,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:l?y.get(f.userLabel):y.get(f.assistantLabel)}),"\xA0",m(xe,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(e.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.role==="assistant"?m(jo,{remarkPlugins:[Go],children:e.content}):m(xe,{size:"sm",miw:"100px",children:e.content})]}),e.attachments&&e.attachments.length>0&&F(et,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).length>0&&m(Ee,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).map(i=>m("button",{type:"button",className:"thumb",style:{backgroundImage:i.objectUrl?`url(${i.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>Aa(i.objectUrl,i.name),disabled:!i.objectUrl,title:i.name||y.get("View image"),"aria-label":i.name||y.get("View image"),children:!i.objectUrl&&m(xe,{size:"xs",c:"dimmed",children:y.get("Image no longer available")})},i.id))}),e.attachments.filter(i=>i.mediaType==="audio"||!i.mediaType&&i.type.startsWith("audio/")).map(i=>m(wo,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:i.objectUrl?F(et,{gap:"xs",children:[m("audio",{className:"ai-kit-audio-player",controls:!0,src:i.objectUrl,preload:"metadata"}),i.duration&&F(xe,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(i.duration),"s"]})]}):m(xe,{size:"xs",c:"dimmed",children:y.get("Audio no longer available")})},i.id))]}),h&&F(Ee,{justify:"flex-end",gap:"xs",children:[m(xe,{size:"xs",c:"dimmed",children:m("em",{children:y.get(f.notSentLabel)})}),At===e.id&&m(Kn,{size:"sm",variant:"subtle",onClick:()=>ar(e),title:y.get(f.editLabel),"aria-label":y.get(f.editLabel),"data-ai-kit-edit-button":!0,children:m(Po,{size:14})})]}),e.citations&&e.citations.length>0&&F(et,{className:"ai-citations",children:[m(xe,{fw:"bold",size:"sm",mb:"xs",children:y.get(f.referencesLabel)}),m(Un,{spacing:"xs",size:"sm",children:e.citations.map((i,S)=>{let A=i.sourceUrl||i.url,M=i.title||A||`${y.get(f.referenceLabel)} #${S+1}`;return F(Un.Item,{children:[A?m(To,{href:A,target:"_blank",rel:"noreferrer",children:M}):m(xe,{children:M}),i.snippet?m(xe,{size:"xs",c:"dimmed",mt:4,children:i.snippet}):null]},S)})})]}),e.role==="assistant"&&F(Ee,{className:"ai-feedback",gap:"xs",children:[m(Xe,{className:e.feedback==="accepted"?"active":void 0,onClick:()=>qa(e.id,"accepted"),"aria-label":y.get(f.acceptResponseLabel),disabled:C.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),m(Xe,{type:"button",className:e.feedback==="rejected"?"active":void 0,onClick:()=>qa(e.id,"rejected"),"aria-label":y.get(f.rejectResponseLabel),disabled:C.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},e.id)}),rr&&m(Ee,{justify:"flex-start",className:"ai-chat-row assistant status",children:F(et,{className:"ai-chat-bubble typing",children:[Xt?m(xe,{size:"sm",c:"dimmed",children:m("em",{children:Xt})}):null,F("div",{className:"typing-indicator",children:[m("span",{}),m("span",{}),m("span",{})]})]})})]}),or&&m(Ee,{className:"ai-status-line",children:m(xe,{className:"ai-status-text",children:m("em",{children:ir})})}),F(et,{className:"ai-box ai-box-open",children:[F(Ot,{opened:oe,onClose:Fa,centered:!0,title:y.get("Reset conversation"),style:{zIndex:"var(--mb-z-index)",position:"fixed"},left:0,children:[m(xe,{size:"sm",children:y.get("Are you sure you want to reset the conversation?")}),F(Ee,{justify:"flex-end",mt:"md",children:[m(Xe,{variant:"default",onClick:Fa,"data-ai-kit-no-button":!0,children:y.get("No")}),m(Xe,{color:"var(--ai-kit-color-danger, red)",onClick:Qn,disabled:!d&&!p,"data-ai-kit-yes-button":!0,children:y.get("Yes")})]})]}),m(Ee,{children:m(Ro,{className:"ai-message",ref:He,placeholder:Ue,value:B,onChange:e=>{pe(e.target.value),z&&Ke()},onKeyDown:Xn,rows:3,disabled:he||!!z})}),Ka&&he&&F(et,{gap:"xs",mt:"xs",children:[m(xe,{size:"xs",c:"dimmed",children:m("em",{children:y.get("Recording...")})}),m("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:m("div",{style:{width:`${xt}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Ka&&z&&!he&&F(et,{gap:"xs",mt:"xs",children:[m(xe,{size:"xs",c:"dimmed",children:F("em",{children:[y.get("Audio recorded")," (",Math.round(z.duration),"s)"]})}),m("audio",{className:"ai-kit-audio-player",controls:!0,src:z.objectUrl})]}),F(Ee,{className:"ai-actions",justify:"space-between",w:"100%",children:[m(Ee,{justify:"flex-start",children:m(Xe,{variant:"light",leftSection:m(Eo,{size:18}),onClick:Zn,disabled:!d&&!p,"data-ai-kit-reset-button":!0,children:y.get(f.resetLabel)})}),F(Ee,{justify:"flex-end",children:[Ka&&m(Nn,{children:z?m(Xe,{variant:"outline",leftSection:m(Bo,{size:18}),onClick:Ke,disabled:p,title:y.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:y.get("Clear")}):m(Xe,{variant:"outline",leftSection:m(Co,{size:18}),onClick:he?Qt:Zt,disabled:p,title:he?y.get("Stop recording"):y.get("Record audio"),color:he?"red":void 0,"data-ai-kit-microphone-button":!0,children:he?y.get("Stop"):y.get("Record")})}),ee>0&&F(Nn,{children:[m(Xe,{variant:"outline",leftSection:m(Lo,{size:18}),onClick:()=>rt.current?.click(),disabled:U.length>=ee||p||he||!!z,title:y.get(f.addImageLabel),"data-ai-kit-add-image-button":!0,children:y.get(f.addLabel)}),m(So,{ref:rt,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:Jn})]}),m(Xe,{leftSection:lr,variant:"filled",onClick:ur,disabled:!p&&!q,"data-ai-kit-send-button":!0,children:sr})]})]}),Ht.length>0&&m(Ee,{className:"ai-thumbs",mt:"xs",gap:"xs",children:Ht.map(({url:e,title:l},h)=>m("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:e?`url(${e})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":l||y.get("View image"),onClick:()=>Aa(e,l),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),Aa(e,l))},children:m(Xe,{variant:"white",onClick:i=>{i.stopPropagation(),_n(h)},"aria-label":y.get(f.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:y.get(f.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},U[h]?.id??h))})]})]})}),m(Ot,{opened:!!ue,onClose:$n,centered:!0,size:"auto",title:ue?.title||y.get("Image preview"),children:ue&&m("img",{src:ue.url,alt:ue.title||y.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},_o=Bt(Jo,{showOpenButton:!0,variation:"modal"});import{Alert as $o,Anchor as Gn,Button as Nt,Checkbox as Hn,Collapse as Zo,Divider as Fn,Group as ft,Loader as Qo,Modal as jt,MultiSelect as Xo,Paper as Wn,Progress as ei,Stack as kt,Text as tt,TextInput as ti,Title as ai}from"@mantine/core";import{AiKitDocSearchIcon as ni,dispatchBackend as ri,resolveBackend as oi,sendSearchMessage as ii}from"@smart-cloud/ai-kit-core";import{I18n as _}from"aws-amplify/utils";import{useCallback as oa,useEffect as _t,useMemo as at,useRef as Ct,useState as Je}from"react";import si from"react-markdown";import li from"rehype-raw";import ui from"remark-gfm";import{IconChevronDown as di,IconChevronRight as ci,IconMicrophone as gi,IconMicrophoneOff as mi,IconSearch as qn,IconX as pi}from"@tabler/icons-react";import{Fragment as ia,jsx as v,jsxs as le}from"react/jsx-runtime";_.putVocabularies(Mt);var Yn=!1;function hi(t){let r=t?.citations?.docs??[],g=t?.citations?.chunks??[],s=new Map;for(let a of r)s.set(a.docId,{doc:a,chunks:[]});for(let a of g){let c=s.get(a.docId);c?c.chunks.push(a):s.set(a.docId,{doc:{docId:a.docId},chunks:[a]})}return Array.from(s.values())}var fi=t=>{let{autoRun:r=!0,context:g,title:s,showOpenButton:a=!1,openButtonTitle:c,showOpenButtonTitle:T=!0,openButtonIcon:E,showOpenButtonIcon:ie=!0,searchButtonIcon:te,showSearchButtonTitle:Q=!0,showSearchButtonIcon:ae=!0,showSources:Ne=!0,topK:ne=10,getSearchText:R,enableUserFilters:u=!1,availableCategories:I,availableTags:ge,variation:W,rootElement:Z,colorMode:me,language:f,onClose:C,onClickDoc:B}=t,[pe,U]=Je(!a),[ve,z]=Je(""),[G,he]=Je(!1),[re,xt]=Je(null),[_e,st]=Je(0),$e=Ct(null),je=Ct([]),Le=Ct(null),x=Ct(null),[P,Re]=Je(!1),[Te,Ge]=Je([]),[oe,lt]=Je([]),[Ie,ut]=Je([]),[dt,bt]=Je(""),[K,yt]=Je(null),[D,ct]=Je(!1),ue=Ct(null),Ze=Ct(null),We=1440*60*1e3,{busy:de,error:Pe,statusEvent:Gt,result:L,run:Lt,cancel:$t,reset:Me}=Wt(),ce=Ct(!1),w=Ct([]),gt=L?.sessionId,ze=L?.citations?.docs??[],nt=L?.citations?.chunks??[],At=L?.citations?.anchors??[],Ve=L?.result??"",rt=at(()=>{if(ae)return te?.trim()?v("img",{src:te,alt:"",style:{width:18,height:18,objectFit:"contain"}}):v(qn,{size:18})},[te,ae]),He=at(()=>(f&&_.setLanguage(f||"en"),_.get(s||"Search with AI-Kit")),[f]),Be=at(()=>Gt?_.get("Searching\u2026"):null,[f,Gt]),qe=at(()=>ve||R,[ve,R]),se=at(()=>{if(de||!pe)return!1;let d=typeof qe=="function"?qe():qe;return!!(d&&d.trim().length>0||re)},[qe,de,re,pe]),Qe=at(()=>{if(!K)return!1;let d=Object.keys(K.allowedCategories).length>0,p=K.allowedTags.length>0;return d||p},[K]),Ke=at(()=>Te.length===0||!K?[]:Te.flatMap(d=>K.allowedCategories[d]||[]).filter((d,p,q)=>q.indexOf(d)===p),[Te,K]),Zt=oa(async()=>{try{z("");let d=await navigator.mediaDevices.getUserMedia({audio:!0}),p=new MediaRecorder(d,{mimeType:"audio/webm"}),q=new AudioContext,Y=q.createMediaStreamSource(d),we=q.createAnalyser();we.fftSize=2048,we.smoothingTimeConstant=.8,Y.connect(we),Le.current=q,x.current=we;let Ue=new Uint8Array(we.fftSize),ot=()=>{if(!x.current)return;x.current.getByteTimeDomainData(Ue);let fe=0;for(let Ht=0;Ht<Ue.length;Ht++){let Xt=(Ue[Ht]-128)/128;fe+=Xt*Xt}let pt=Math.sqrt(fe/Ue.length),sa=Math.min(100,pt*200);st(sa),ue.current=requestAnimationFrame(ot)};ot(),je.current=[],p.ondataavailable=fe=>{fe.data.size>0&&je.current.push(fe.data)},p.onstop=()=>{let fe=new Blob(je.current,{type:"audio/webm"});xt(fe),d.getTracks().forEach(pt=>pt.stop()),ue.current&&(cancelAnimationFrame(ue.current),ue.current=null),Le.current&&(Le.current.close(),Le.current=null),x.current=null,st(0)},$e.current=p,p.start(),he(!0)}catch(d){console.error("Failed to start recording:",d)}},[]),Qt=oa(()=>{$e.current&&G&&($e.current.stop(),he(!1))},[G]),mt=oa(()=>{xt(null),je.current=[],st(0),Ze.current=null},[]);_t(()=>()=>{ue.current&&cancelAnimationFrame(ue.current),Le.current&&Le.current.close()},[]),_t(()=>{if(!u)return;if(I||ge){yt({allowedCategories:I||{},allowedTags:ge||[]});return}(async()=>{ct(!0);try{let p=await oi();if(!p.available){console.error("Backend not available for metadata options");return}let q={feature:"prompt",source:"backend",mode:"backend-only",onDeviceAvailable:!1,backendAvailable:p.available,backendTransport:p.transport,backendApiName:p.apiName,backendBaseUrl:p.baseUrl,reason:p.reason??""},Y=await ri(q,g??"frontend","/kb/metadata-options","GET",null,{});yt({allowedCategories:Y.allowedCategories||{},allowedTags:Y.allowedTags||[]})}catch(p){console.error("Failed to load metadata options:",p)}finally{ct(!1)}})()},[u,I,ge,g]);let o=oa(async()=>{let d;if(!re){if(d=typeof qe=="function"?qe():qe,!d)return;z(d)}console.log("Starting search with query:",d,"and audio:",re);let p=Date.now(),q=re&&Ze.current?.blob===re&&p-Ze.current.uploadTimestamp<We;re&&!q?(Ze.current={blob:re,uploadTimestamp:p},console.log("Audio cache updated for new recording")):q&&console.log("Reusing cached audio (no re-upload needed within",Math.round((We-(p-Ze.current.uploadTimestamp))/1e3),"seconds)"),Me(),await Lt(async({signal:Y,onStatus:we})=>await ii({sessionId:gt,...d&&{query:d},...re&&{audio:re},topK:ne,...u&&{userSelectedCategories:Te},...u&&oe.length>0&&{userSelectedSubcategories:oe},...u&&Ie.length>0&&{userSelectedTags:Ie}},{signal:Y,onStatus:we,context:g}))},[g,qe,re,Lt,Me,ne,gt,u,Te,oe,Ie]),k=oa(async()=>{U(!1),Me(),a||C()},[C,Me,ce,a]);_t(()=>{!r||!se||de||ce.current||(ce.current=!0,queueMicrotask(()=>{o()}))},[de,ce,se,r,o]),_t(()=>{se||(ce.current=!0)},[se]),_t(()=>{let d=w.current,p=Te;(d.length!==p.length||!p.every(Y=>d.includes(Y)))&&d.length>0&&Me(),w.current=[...p]},[Te,Me]);let O=at(()=>hi(L),[L]),H=at(()=>{let d=new Map;return ze.forEach((p,q)=>{p?.docId&&d.set(p.docId,q+1)}),d},[ze]),X=at(()=>{let d=new Map;return nt.forEach(p=>{p?.chunkId&&p?.docId&&d.set(p.chunkId,p.docId)}),d},[nt]),N=at(()=>{if(!Ve)return"";if(!At.length||H.size===0)return Ve;let d=[...At].filter(Y=>Array.isArray(Y?.chunkIds)&&Y?.span?.end!==void 0).sort((Y,we)=>{let Ue=Y.span?.end??0,ot=we.span?.end??0;return Ue-ot}),p=0,q=[];for(let Y of d){let we=Y.span?.end;if(typeof we!="number"||we<p)continue;let Ue=Array.from(new Set((Y.chunkIds??[]).map(fe=>fe?X.get(fe):void 0).map(fe=>fe?H.get(fe):void 0).filter(fe=>typeof fe=="number")));if(!Ue.length)continue;let ot=Math.min(we,Ve.length);q.push(Ve.slice(p,ot)),q.push(`<sup>${Ue.join(",")}</sup>`),p=ot}return q.push(Ve.slice(p)),q.join("")},[At,Ve]),$=W==="modal"?jt.Root:ft,ee=W==="modal"?jt.Content:ft,Ye=W==="modal"?jt.Body:ft;return _t(()=>{if(!(W!=="modal"||!pe))return document.body.style.overflow="hidden",document.body.onkeydown=d=>{d.key==="Escape"&&(d.preventDefault(),k())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[k,W,pe]),le(ia,{children:[a&&v(Nt,{leftSection:ie&&(E?v("span",{dangerouslySetInnerHTML:{__html:E}}):v(qn,{size:18})),className:T?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:pe,onClick:()=>U(!0),"data-ai-kit-open-button":!0,children:T&&_.get(c||He)}),pe&&le($,{opened:!0,className:"doc-search-root",onClose:k,padding:"md",gap:"md",size:"xl",portalProps:W==="modal"?{target:Z,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":me,"data-ai-kit-variation":W,children:[W==="modal"&&v(jt.Overlay,{}),le(ee,{w:"100%",style:{left:0,...W==="modal"&&!L?.result&&{overflow:"visible"}},children:[W==="modal"&&le(jt.Header,{style:{zIndex:1e3},children:[v(ni,{className:"doc-search-title-icon"}),v(jt.Title,{children:_.get(He)}),v(jt.CloseButton,{})]}),v(Ye,{w:"100%",style:{zIndex:1001,...W==="modal"&&!L?.result&&{overflow:"visible"}},children:v(qt,{enabled:W!=="modal",working:de,variation:W,children:v(Wn,{shadow:"sm",radius:"md",p:"md",children:le(kt,{gap:"sm",children:[W!=="modal"&&le(ft,{justify:"space-between",children:[v(ai,{order:4,style:{margin:0},children:_.get(He)}),a&&v(Nt,{variant:"subtle",color:"gray",size:"xs",onClick:k,style:{minWidth:32,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":_.get("Close"),children:v(pi,{size:18,style:{color:me==="dark"?"var(--mantine-color-dark-1)":"var(--mantine-color-gray-7)"}})})]}),le(ft,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[v(ti,{style:{flex:1},value:ve,onChange:d=>{z(d.currentTarget.value),re&&mt()},placeholder:re?_.get("Audio recorded"):_.get("Search the documentation\u2026"),disabled:de||G||!!re,onKeyDown:d=>{d.key==="Enter"&&se&&(d.preventDefault(),o())}}),Yn&&v(ia,{children:re?v(Nt,{variant:"outline",size:"sm",color:"red",onClick:mt,disabled:de,title:_.get("Clear audio"),children:v(mi,{size:18})}):v(Nt,{variant:G?"filled":"outline",size:"sm",color:G?"red":"gray",onClick:G?Qt:Zt,disabled:de,title:G?_.get("Stop recording"):_.get("Record audio"),style:G?{transform:`scale(${1+_e/300})`,transition:"transform 0.1s ease-out"}:void 0,children:v(gi,{size:18})})}),v(Nt,{variant:"filled",size:"sm",leftSection:rt,onClick:()=>{o()},disabled:!se,className:Q?"doc-search-button":"doc-search-button-no-title",children:Q?_.get("Search"):null}),de?v(Nt,{variant:"outline",size:"sm",onClick:$t,children:_.get("Stop")}):null]}),!de&&!Pe&&!L?.result?v(tt,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:_.get("Enter a search query to start.")}):null,u&&K&&Qe&&le(kt,{gap:"xs",children:[v(Nt,{variant:"subtle",size:"xs",onClick:()=>Re(!P),leftSection:P?v(di,{size:14}):v(ci,{size:14}),style:{alignSelf:"flex-start"},children:_.get("Filters")}),v(Zo,{in:P,children:le(kt,{gap:"md",children:[Object.keys(K.allowedCategories).length>0&&le("div",{children:[v(tt,{size:"sm",fw:500,mb:"xs",children:_.get("Categories")}),v(ft,{gap:"md",children:Object.keys(K.allowedCategories).map(d=>v(Hn,{label:_.get(d),checked:Te.includes(d),onChange:p=>{if(p.currentTarget.checked)Ge([...Te,d]);else{Ge(Te.filter(Y=>Y!==d));let q=K.allowedCategories[d]||[];lt(oe.filter(Y=>!q.includes(Y)))}},disabled:de||D},d))})]}),Ke.length>0&&le("div",{children:[v(tt,{size:"sm",fw:500,mb:"xs",children:_.get("Subcategories")}),v(ft,{gap:"md",children:Ke.map(d=>v(Hn,{label:_.get(d),checked:oe.includes(d),onChange:p=>{p.currentTarget.checked?lt([...oe,d]):lt(oe.filter(q=>q!==d))},disabled:de||D},d))})]}),K.allowedTags.length>0&&v(Xo,{label:_.get("Tags"),placeholder:_.get("Select or type tags..."),data:K.allowedTags.map(d=>({value:d,label:_.get(d)})),value:Ie,onChange:ut,searchValue:dt,onSearchChange:bt,disabled:de||D,searchable:!0,clearable:!0,maxDropdownHeight:200,limit:20})]})})]}),Yn&&le(ia,{children:[G&&le(kt,{gap:"xs",children:[le(tt,{size:"xs",c:"dimmed",children:[_.get("Recording...")," \u{1F3A4}"]}),v(ei,{value:_e,size:"sm",color:"red",animated:!0,striped:!0})]}),re&&!G&&le(kt,{gap:"xs",children:[v(tt,{size:"xs",c:"dimmed",children:_.get("Recorded audio:")}),v("audio",{controls:!0,src:URL.createObjectURL(re),className:"ai-kit-audio-player"})]})]}),Pe?v($o,{color:"red",title:_.get("Error"),children:Pe}):null,de&&Be&&v(qt,{enabled:W==="modal",working:!0,variation:W,children:le(ft,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[v(Qo,{size:"sm"}),v(tt,{size:"sm",c:"dimmed",children:Be})]})}),L?.result?le(ia,{children:[v(Fn,{}),le(kt,{gap:"xs","data-doc-search-result":!0,children:[v(tt,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:_.get("AI Summary")}),v(si,{remarkPlugins:[ui],rehypePlugins:[li],"data-doc-search-result-content":!0,children:N||Ve})]})]}):null,Ne&&(L?.citations?.docs?.length||L?.citations?.chunks?.length)?le(ia,{children:[v(Fn,{}),le(kt,{gap:"sm","data-doc-search-sources":!0,children:[v(tt,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:_.get("Sources")}),O.map(({doc:d})=>{let p=d.sourceUrl?.trim()||void 0,q=d.docId?H.get(d.docId):void 0,Y=d.title?.trim()||d.docId,we=le(tt,{fw:600,style:{display:"inline"},children:[q?`${q}. `:"",Y]});return v(Wn,{withBorder:!0,radius:"md",p:"sm",children:v(kt,{gap:"xs",children:v(ft,{justify:"space-between",align:"flex-start",children:le(kt,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[p?v(Gn,{href:p,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ue=>{B&&(Ue.preventDefault(),B?.(d))},"data-doc-search-source-title":!0,children:we}):we,v(Gn,{href:p,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:Ue=>{B&&(Ue.preventDefault(),B?.(d))},"data-doc-search-source-url":!0,children:d.sourceUrl}),d.author?v(tt,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:d.author}):null,d.description?v(tt,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:d.description}):null]})})})},d.docId)})]})]}):null,v(da,{variation:W})]})})})})]})]})]})},ki=Bt(fi);export{_o as AiChatbot,ho as AiFeature,Oa as DEFAULT_CHATBOT_LABELS,ki as DocSearch,yn as isBackendConfigured,za as markdownToHtml,Dt as readDefaultOutputLanguage,ta as stripCodeFence,Mt as translations,Wt as useAiRun,Bt as withAiKitShell};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/ai-kit-ui",
3
- "version": "1.3.11",
3
+ "version": "1.3.12",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -65,9 +65,8 @@ const USE_AUDIO = false; // Set to true to enable audio recording feature (requi
65
65
  // New: history storage support
66
66
  const DEFAULT_PRESERVATION_TIME_DAYS = 1;
67
67
  const DEFAULT_HISTORY_STORAGE: HistoryStorageMode = "localstorage";
68
- const HISTORY_STORAGE_KEY = `ai-kit-chatbot-history-v1:${
69
- typeof window !== "undefined" ? window.location.hostname : "unknown"
70
- }`;
68
+ const HISTORY_STORAGE_KEY = `ai-kit-chatbot-history-v1:${typeof window !== "undefined" ? window.location.hostname : "unknown"
69
+ }`;
71
70
 
72
71
  export const DEFAULT_CHATBOT_LABELS: Required<AiChatbotLabels> = {
73
72
  modalTitle: "AI Assistant",
@@ -223,7 +222,7 @@ const formatStatusEvent = (
223
222
  case "backend:response":
224
223
  return I18n.get(
225
224
  labels.assistantThinkingLabel ??
226
- DEFAULT_CHATBOT_LABELS.assistantThinkingLabel,
225
+ DEFAULT_CHATBOT_LABELS.assistantThinkingLabel,
227
226
  );
228
227
  case "done":
229
228
  return msg || I18n.get("Done.");
@@ -964,9 +963,9 @@ const AiChatbotBase: FC<AiChatbotProps & AiKitShellInjectedProps> = (props) => {
964
963
  blob instanceof File
965
964
  ? blob
966
965
  : new File([blob], attachment.name || "attachment", {
967
- type:
968
- attachment.type || blob.type || "application/octet-stream",
969
- });
966
+ type:
967
+ attachment.type || blob.type || "application/octet-stream",
968
+ });
970
969
 
971
970
  const objectUrl = createObjectUrl(file);
972
971
  if (!objectUrl) continue;
@@ -1055,7 +1054,7 @@ const AiChatbotBase: FC<AiChatbotProps & AiKitShellInjectedProps> = (props) => {
1055
1054
  try {
1056
1055
  const activeSessionId =
1057
1056
  sessionRef.current &&
1058
- Date.now() - sessionRef.current.storedAt <
1057
+ Date.now() - sessionRef.current.storedAt <
1059
1058
  emptyHistoryAfterDays * TWENTY_FOUR_HOURS_MS
1060
1059
  ? sessionRef.current.id
1061
1060
  : undefined;
@@ -1149,7 +1148,7 @@ const AiChatbotBase: FC<AiChatbotProps & AiKitShellInjectedProps> = (props) => {
1149
1148
  try {
1150
1149
  const activeSessionId =
1151
1150
  sessionRef.current &&
1152
- Date.now() - sessionRef.current.storedAt <
1151
+ Date.now() - sessionRef.current.storedAt <
1153
1152
  emptyHistoryAfterDays * TWENTY_FOUR_HOURS_MS
1154
1153
  ? sessionRef.current.id
1155
1154
  : undefined;
@@ -1777,53 +1776,53 @@ const AiChatbotBase: FC<AiChatbotProps & AiKitShellInjectedProps> = (props) => {
1777
1776
  att.mediaType === "image" ||
1778
1777
  (!att.mediaType && att.type.startsWith("image/")),
1779
1778
  ).length > 0 && (
1780
- <Group
1781
- className="ai-thumbs ai-message-thumbs"
1782
- gap="xs"
1783
- >
1784
- {msg.attachments
1785
- .filter(
1786
- (att) =>
1787
- att.mediaType === "image" ||
1788
- (!att.mediaType &&
1789
- att.type.startsWith("image/")),
1790
- )
1791
- .map((attachment) => (
1792
- <button
1793
- key={attachment.id}
1794
- type="button"
1795
- className="thumb"
1796
- style={{
1797
- backgroundImage: attachment.objectUrl
1798
- ? `url(${attachment.objectUrl})`
1799
- : undefined,
1800
- backgroundSize: "cover",
1801
- backgroundPosition: "center",
1802
- backgroundRepeat: "no-repeat",
1803
- }}
1804
- onClick={() =>
1805
- openAttachmentPreview(
1806
- attachment.objectUrl,
1807
- attachment.name,
1808
- )
1809
- }
1810
- disabled={!attachment.objectUrl}
1811
- title={
1812
- attachment.name || I18n.get("View image")
1813
- }
1814
- aria-label={
1815
- attachment.name || I18n.get("View image")
1816
- }
1817
- >
1818
- {!attachment.objectUrl && (
1819
- <Text size="xs" c="dimmed">
1820
- {I18n.get("Image no longer available")}
1821
- </Text>
1822
- )}
1823
- </button>
1824
- ))}
1825
- </Group>
1826
- )}
1779
+ <Group
1780
+ className="ai-thumbs ai-message-thumbs"
1781
+ gap="xs"
1782
+ >
1783
+ {msg.attachments
1784
+ .filter(
1785
+ (att) =>
1786
+ att.mediaType === "image" ||
1787
+ (!att.mediaType &&
1788
+ att.type.startsWith("image/")),
1789
+ )
1790
+ .map((attachment) => (
1791
+ <button
1792
+ key={attachment.id}
1793
+ type="button"
1794
+ className="thumb"
1795
+ style={{
1796
+ backgroundImage: attachment.objectUrl
1797
+ ? `url(${attachment.objectUrl})`
1798
+ : undefined,
1799
+ backgroundSize: "cover",
1800
+ backgroundPosition: "center",
1801
+ backgroundRepeat: "no-repeat",
1802
+ }}
1803
+ onClick={() =>
1804
+ openAttachmentPreview(
1805
+ attachment.objectUrl,
1806
+ attachment.name,
1807
+ )
1808
+ }
1809
+ disabled={!attachment.objectUrl}
1810
+ title={
1811
+ attachment.name || I18n.get("View image")
1812
+ }
1813
+ aria-label={
1814
+ attachment.name || I18n.get("View image")
1815
+ }
1816
+ >
1817
+ {!attachment.objectUrl && (
1818
+ <Text size="xs" c="dimmed">
1819
+ {I18n.get("Image no longer available")}
1820
+ </Text>
1821
+ )}
1822
+ </button>
1823
+ ))}
1824
+ </Group>
1825
+ )}
1827
1826
 
1828
1827
  {/* Audio attachments */}
1829
1828
  {msg.attachments
@@ -2000,7 +1999,7 @@ const AiChatbotBase: FC<AiChatbotProps & AiKitShellInjectedProps> = (props) => {
2000
1999
  onClose={cancelReset}
2001
2000
  centered
2002
2001
  title={I18n.get("Reset conversation")}
2003
- style={{ position: "fixed" }}
2002
+ style={{ zIndex: "var(--mb-z-index)", position: "fixed" }}
2004
2003
  left={0}
2005
2004
  >
2006
2005
  <Text size="sm">
@@ -566,7 +566,6 @@
566
566
  border-top: 1px solid var(--ai-kit-color-border-light);
567
567
  background: var(--ai-kit-chat-surface-subtle);
568
568
  margin-top: auto;
569
- z-index: 1;
570
569
  }
571
570
 
572
571
  /* Responsive tweaks */