(()=>{(function(){"use strict";let h=null,o=typeof window.aipkit_getMarkdownRenderer=="function"?window.aipkit_getMarkdownRenderer:null;function i(){return window.aipkit_escapeHtml||function(c){return typeof c!="string"?"":c.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}}function n(){return{aipkitIsFallback:!0,render:function(c){return i()(String(c||"")).replace(/\n/g,"<br>")}}}function a(c={}){if(typeof window.markdownit=="function"){let m=window.markdownit(Object.assign({html:!1,xhtmlOut:!1,breaks:!0,langPrefix:"language-",linkify:!0,typographer:!0,quotes:"\u201C\u201D\u2018\u2019"},c)),l=m.renderer.rules.link_open||function(k,d,f,g,I){return I.renderToken(k,d,f)};return m.renderer.rules.link_open=function(k,d,f,g,I){let b=k[d],y=b.attrIndex("target");y<0?b.attrPush(["target","_blank"]):b.attrs[y][1]="_blank";let v=b.attrIndex("rel");if(v<0)b.attrPush(["rel","noopener noreferrer"]);else{let x=(b.attrs[v][1]||"").split(/\s+/).filter(Boolean);x.includes("noopener")||x.push("noopener"),x.includes("noreferrer")||x.push("noreferrer"),b.attrs[v][1]=x.join(" ")}return l(k,d,f,g,I)},window.hljs&&typeof window.markdownitHighlight=="function"&&m.use(window.markdownitHighlight,{hljs:window.hljs}),m.aipkitIsFallback=!1,m}return n()}function t(){return window.aipkitPublicAssetUrls&&typeof window.aipkitPublicAssetUrls=="object"?window.aipkitPublicAssetUrls:{}}function e(c){return new Promise(function(m,l){if(typeof window.markdownit=="function"){m(window.markdownit);return}if(!c){l(new Error("AIPKit markdown asset URL was not provided."));return}let k=c;try{k=new URL(c,window.location.href).href}catch{k=c}let d=function(){if(typeof window.markdownit=="function"){m(window.markdownit);return}l(new Error("AIPKit markdown asset loaded, but window.markdownit is unavailable."))},f=function(){l(new Error("AIPKit markdown asset failed to load."))},g=Array.from(document.querySelectorAll("script[src]")).find(function(b){try{return new URL(b.src,window.location.href).href===k}catch{return b.src===c}});if(g){if(typeof window.markdownit=="function"){m(window.markdownit);return}g.addEventListener("load",d,{once:!0}),g.addEventListener("error",f,{once:!0});return}let I=document.createElement("script");I.src=c,I.async=!0,I.dataset.aipkitMarkdownLoader="1",I.addEventListener("load",d,{once:!0}),I.addEventListener("error",f,{once:!0}),document.head.appendChild(I)})}function r(){return window.aipkit_md=a(),window.aipkit_md}function s(){return(!window.aipkit_md||typeof window.aipkit_md.render!="function")&&(window.aipkit_md=n()),window.aipkit_md}function w(){if(typeof window.markdownit=="function")return Promise.resolve(window.markdownit);if(h)return h;let c=t(),m=c.markdownIt||c.markdownit||"";return h=e(m).catch(function(l){throw h=null,console.warn("AIPKit Chat Markdown: markdown-it lazy load failed.",l),l}),h}function u(c={}){return typeof window.markdownit=="function"?Promise.resolve(a(c)):w().then(function(){return a(c)}).catch(function(){return n()})}function _(){let c=s();return c.aipkitIsFallback?u().then(function(m){return window.aipkit_md=m,m}):Promise.resolve(c)}function p(){return!s().aipkitIsFallback}window.aipkit_createFallbackMarkdownRenderer=n,window.aipkit_createMarkdownRenderer=a,window.aipkit_initializeMarkdownParser=r,o||(window.aipkit_getMarkdownRenderer=s),window.aipkit_public_getMarkdownRenderer=s,window.aipkit_ensureMarkdownLibrary=w,window.aipkit_ensureMarkdownRenderer=u,window.aipkit_ensureMarkdownParser=_,window.aipkit_isMarkdownParserReady=p,s()})();(function(){"use strict";let h=Object.create(null),o={sidebar:{urlKeys:["chatSidebar","sidebar"],isReady:()=>typeof window.aipkit_initConversationSidebar=="function"},stt:{urlKeys:["chatStt","stt"],isReady:()=>typeof window.aipkit_chatUI_handleVoiceInputAction=="function"},uploads:{urlKeys:["chatUploads","uploads"],isReady:()=>!!(window.chatImageUpload&&typeof window.chatImageUpload.init=="function"&&window.aipkitChatFileUpload&&typeof window.aipkitChatFileUpload.processFile=="function")},tts:{urlKeys:["chatTts","tts"],isReady:()=>typeof window.aipkit_handlePlayAction=="function"&&!!window.aipkitTtsState},starters:{urlKeys:["chatStarters","starters"],isReady:()=>typeof window.aipkit_initConversationStarters=="function"},imageCommand:{urlKeys:["chatImageCommand","imageCommand"],isReady:()=>typeof window.aipkit_chatUI_handleImageGeneration=="function"},realtime:{urlKeys:["chatRealtime","realtime"],isReady:()=>typeof window.aipkit_initRealtimeVoiceAgent=="function"},pdf:{urlKeys:["chatPdf","pdf"],isReady:()=>typeof window.aipkit_chatUI_downloadTranscriptActionPdf=="function"}};function i(){return window.aipkitPublicAssetUrls&&typeof window.aipkitPublicAssetUrls=="object"?window.aipkitPublicAssetUrls:{}}function n(l){let k=o[l];if(!k)return"";let d=i();for(let f of k.urlKeys)if(typeof d[f]=="string"&&d[f])return d[f];return""}function a(...l){let k=i();for(let d of l)if(typeof k[d]=="string"&&k[d])return k[d];return""}function t(l,k){return new Promise((d,f)=>{if(!l){f(new Error(`AIPKit Chat feature "${k}" is missing a public asset URL.`));return}let g=l;try{g=new URL(l,window.location.href).href}catch{g=l}let I=()=>d(),b=()=>f(new Error(`AIPKit Chat feature "${k}" failed to load from ${l}.`)),y=Array.from(document.querySelectorAll("script[src]")).find(A=>{try{return new URL(A.src,window.location.href).href===g}catch{return A.src===l}});if(y){if(y.dataset.aipkitLoaded==="true"){d();return}if(y.dataset.aipkitErrored==="true")y.remove();else{y.addEventListener("load",I,{once:!0}),y.addEventListener("error",b,{once:!0});return}}let v=document.createElement("script");v.src=l,v.async=!0,v.dataset.aipkitChatFeature=k,v.addEventListener("load",()=>{v.dataset.aipkitLoaded="true",I()},{once:!0}),v.addEventListener("error",()=>{v.dataset.aipkitErrored="true",b()},{once:!0}),document.head.appendChild(v)})}function e(l){let k=o[l];if(!k)return Promise.reject(new Error(`Unknown AIPKit chat feature bundle: ${l}`));if(k.isReady())return Promise.resolve(!0);if(h[l])return h[l];let d=n(l);return h[l]=t(d,l).then(()=>{if(!k.isReady())throw new Error(`AIPKit chat feature "${l}" loaded, but expected globals were not registered.`);return!0}).catch(f=>{throw delete h[l],console.warn(`AIPKit Chat Feature Loader: Failed to prepare "${l}".`,f),f}),h[l]}async function r(l,k){return!k||!k.imageUploadEnabledUI&&!k.fileUploadEnabledUI?!1:(await e("uploads"),k.imageUploadEnabledUI&&window.chatImageUpload&&typeof window.chatImageUpload.init=="function"&&l&&l.imageUploadInput&&l.imagePreviewContainer&&window.chatImageUpload.init(l.imageUploadInput,l.imagePreviewContainer),l&&l.container&&k.imageUploadEnabledUI&&l.container.classList.add("aipkit-image-upload-enabled"),!0)}async function s(l,k,d,f){return!d||!d.enableSidebar||!l||!k||!k.sidebarEl||!k.sidebarToggleBtn?!1:l.dataset.aipkitSidebarInitialized==="true"&&typeof window.aipkit_initConversationSidebar=="function"?!0:(await e("sidebar"),typeof window.aipkit_initConversationSidebar!="function"?!1:(l.dataset.aipkitSidebarInitialized!=="true"&&(window.aipkit_initConversationSidebar(l,k,d,f),l.dataset.aipkitSidebarInitialized="true"),!0))}async function w(){return await e("stt"),typeof window.aipkit_chatUI_handleVoiceInputAction=="function"}async function u(){return await e("tts"),typeof window.aipkit_handlePlayAction=="function"}async function _(l,k,d,f,g,I){return!k||!k.enableStarters||!l||(await e("starters"),typeof window.aipkit_initConversationStarters!="function")?!1:l.dataset.aipkitStartersInitialized!=="true"?(window.aipkit_initConversationStarters(l,k,d,f,g,I),l.dataset.aipkitStartersInitialized="true",!0):(d&&d.startersContainer&&typeof window.aipkit_chatUI_refreshStartersAnimation=="function"&&!d.startersContainer.classList.contains("aipkit_hidden")&&window.aipkit_chatUI_refreshStartersAnimation(d.startersContainer),!0)}async function p(){return await e("imageCommand"),typeof window.aipkit_chatUI_handleImageGeneration=="function"}async function c(l){return!l||l.pdfDownloadActive!==!0?!1:((typeof window.jspdf>"u"||typeof window.jspdf.jsPDF>"u")&&await t(a("jspdf"),"jspdf"),await e("pdf"),typeof window.jspdf<"u"&&typeof window.jspdf.jsPDF<"u"&&typeof window.aipkit_chatUI_downloadTranscriptActionPdf=="function")}async function m(l,k,d,f,g){return!k||!k.enableRealtimeVoiceUI||!l||!l.container?!1:l.container.dataset.aipkitRealtimeInitialized==="true"&&typeof window.aipkit_initRealtimeVoiceAgent=="function"?!0:(await e("realtime"),typeof window.aipkit_initRealtimeVoiceAgent!="function"?!1:(l.container.dataset.aipkitRealtimeInitialized!=="true"&&(window.aipkit_initRealtimeVoiceAgent(l,k,d,f,g),l.container.dataset.aipkitRealtimeInitialized="true"),!0))}window.aipkit_chatUI_ensureFeatureBundle=e,window.aipkit_chatUI_prepareUploadsFeature=r,window.aipkit_chatUI_prepareSidebarFeature=s,window.aipkit_chatUI_prepareSttFeature=w,window.aipkit_chatUI_prepareTtsFeature=u,window.aipkit_chatUI_prepareStartersFeature=_,window.aipkit_chatUI_prepareImageCommandFeature=p,window.aipkit_chatUI_preparePdfFeature=c,window.aipkit_chatUI_prepareRealtimeFeature=m})();(function(){"use strict";function h(i){return i===null||typeof i>"u"?"":String(i).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function o(i){return h(i)}window.aipkit_escapeHtml=h,window.aipkit_escapeAttribute=o})();(function(){"use strict";function h(o){let i=Number(o);if(!i||isNaN(i))return"";try{let n=new Date(i*1e3);if(isNaN(n.getTime()))return"";let a=String(n.getHours()).padStart(2,"0"),t=String(n.getMinutes()).padStart(2,"0"),e=String(n.getSeconds()).padStart(2,"0");return`${a}:${t}:${e}`}catch(n){return console.error("Error formatting timestamp:",o,n),""}}window.aipkit_formatTimestamp=h})();(function(){"use strict";function h(){return("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,i=>(i^crypto.getRandomValues(new Uint8Array(1))[0]&15>>i/4).toString(16))}function o(){let i=localStorage.getItem("aipkit_guest_uuid");return i||(i=h(),localStorage.setItem("aipkit_guest_uuid",i)),window.aipkit_guest_uuid=i,i}window.aipkit_generateGuestUuid=h,window.aipkit_ensureGuestUuid=o,o()})();(function(){"use strict";function h(o,i={},n={}){return new Promise((a,t)=>{if(!n.ajaxUrl)return t(new Error("AIPKit Frontend AJAX: ajaxUrl missing in config."));let e=new FormData;e.append("action",o),n.nonce?e.append("_ajax_nonce",n.nonce):console.warn(`AIPKit Frontend AJAX: Nonce not found in config for action "${o}".`),n.botId&&e.append("bot_id",n.botId),window.aipkit_guest_uuid&&e.append("session_id",window.aipkit_guest_uuid),window.aipkit_current_conversation_uuid&&e.append("conversation_uuid",window.aipkit_current_conversation_uuid),window.aipkit_current_post_id&&e.append("post_id",window.aipkit_current_post_id),n.provider==="OpenAI"&&n.enableOpenAIConversationState&&window.aipkit_current_openai_response_id&&e.append("previous_openai_response_id",window.aipkit_current_openai_response_id),i.frontend_web_search_active===!0&&e.append("frontend_web_search_active","true"),i.frontend_google_search_grounding_active===!0&&e.append("frontend_google_search_grounding_active","true"),n.activeFileContext?(n.activeFileContext.provider==="OpenAI"&&n.activeFileContext.vector_store_id&&e.append("active_openai_vs_id",n.activeFileContext.vector_store_id),n.activeFileContext.provider==="Pinecone"&&n.activeFileContext.index_name&&n.activeFileContext.namespace&&(e.append("active_pinecone_index_name",n.activeFileContext.index_name),e.append("active_pinecone_namespace",n.activeFileContext.namespace)),n.activeFileContext.provider==="Qdrant"&&n.activeFileContext.collection_name&&n.activeFileContext.file_upload_context_id&&(e.append("active_qdrant_collection_name",n.activeFileContext.collection_name),e.append("active_qdrant_file_upload_context_id",n.activeFileContext.file_upload_context_id)),n.activeFileContext.provider==="Claude"&&n.activeFileContext.file_id&&e.append("active_claude_file_id",n.activeFileContext.file_id)):i.active_openai_vs_id?console.log(`AIPKit frontendApiRequest: Sending active_openai_vs_id from data object: ${i.active_openai_vs_id}`):i.active_pinecone_index_name&&i.active_pinecone_namespace?console.log(`AIPKit frontendApiRequest: Sending Pinecone context from data object: Index: ${i.active_pinecone_index_name}, Namespace: ${i.active_pinecone_namespace}`):i.active_qdrant_collection_name&&i.active_qdrant_file_upload_context_id?console.log(`AIPKit frontendApiRequest: Sending Qdrant context from data object: Collection: ${i.active_qdrant_collection_name}, File Context ID: ${i.active_qdrant_file_upload_context_id}`):i.active_claude_file_id&&console.log(`AIPKit frontendApiRequest: Sending Claude file context from data object: File ID: ${i.active_claude_file_id}`);for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&r!=="frontend_web_search_active"&&r!=="frontend_google_search_grounding_active"&&r!=="active_openai_vs_id"&&r!=="active_pinecone_index_name"&&r!=="active_pinecone_namespace"&&r!=="active_qdrant_collection_name"&&r!=="active_qdrant_file_upload_context_id"&&r!=="active_claude_file_id"&&(r==="audio_file"&&i[r]instanceof Blob?e.append(r,i[r],"speech."+(i.audio_format||"webm")):e.append(r,i[r]));fetch(n.ajaxUrl,{method:"POST",body:e,credentials:"same-origin"}).then(r=>r.json()).then(r=>{if(r.success)a(r.data);else{let s=r.data&&typeof r.data=="object"&&r.data.message?r.data.message:"Unknown frontend API error (data or data.message missing/invalid)";t(new Error(s))}}).catch(r=>{console.error(`AIPKit Frontend AJAX Error (Action: ${o}):`,r),t(r)})})}window.aipkit_frontendApiRequest=h})();(function(){"use strict";function h(o){return`aipkit-client-msg-${String(o||"default").replace(/[^a-zA-Z0-9_-]/g,"")}-${Date.now()}-${Math.random().toString(36).substring(2,7)}`}window.aipkit_generateClientMessageId=h})();(function(){"use strict";function h(o){if(!o||typeof o.style>"u")return;o.style.height="auto";let i=o.scrollHeight,n=window.getComputedStyle(o),a=parseInt(n.minHeight,10)||0,t=parseInt(n.maxHeight,10)||1/0,e=Math.max(a,i);e=Math.min(e,t),o.style.height=`${e}px`,e>=t?(o.style.overflowY="auto",o.classList.add("aipkit-textarea-scrollable")):(o.style.overflowY="hidden",o.classList.remove("aipkit-textarea-scrollable"))}window.aipkit_autoResizeTextarea=h})();(function(){"use strict";function h(i,n,a,t){let{webSearchToggleButton:e}=i,r=n.allowWebSearchTool&&(n.provider==="OpenAI"||n.provider==="Claude"||n.provider==="OpenRouter");a.webSearchToolActive=r&&!!t,!(!e||!r)&&(e.classList.toggle("aipkit_active",a.webSearchToolActive),e.title=a.webSearchToolActive?n.text?.webSearchActive||"Web Search Active":n.text?.webSearchInactive||"Web Search Inactive",e.setAttribute("aria-pressed",a.webSearchToolActive.toString()))}function o(i,n,a){h(i,n,a,!a.webSearchToolActive)}window.aipkit_syncWebSearchToggleState=h,window.aipkit_toggleWebSearchAction=o})();(function(){"use strict";function h(i,n,a,t){let{googleSearchGroundingToggleButton:e}=i,r=n.allowGoogleSearchGrounding&&n.provider==="Google";a.googleSearchGroundingActive=r&&!!t,!(!e||!r)&&(e.classList.toggle("aipkit_active",a.googleSearchGroundingActive),e.title=a.googleSearchGroundingActive?n.text?.googleSearchGroundingActive||"Google Search Grounding Active":n.text?.googleSearchGroundingInactive||"Google Search Grounding Inactive",e.setAttribute("aria-pressed",a.googleSearchGroundingActive.toString()))}function o(i,n,a){h(i,n,a,!a.googleSearchGroundingActive)}window.aipkit_syncGoogleSearchGroundingToggleState=h,window.aipkit_toggleGoogleSearchGroundingAction=o})();(function(){"use strict";let h="aipkit_chat_ui_notice",o="aipkit_chat_ui_notice--visible",i=new Set(["info","success","error","processing","warning"]),n=new WeakMap,a=new WeakMap;function t(u){if(!u)return null;if(u.inputArea&&u.inputArea.nodeType===1)return u.inputArea;if(u.elements&&u.elements.inputArea)return u.elements.inputArea;if(u.container&&u.container.nodeType===1)return u.container.querySelector(".aipkit_chat_input");let _=u.messagesEl?u.messagesEl:u.elements&&u.elements.messagesEl?u.elements.messagesEl:null;if(_&&_.nodeType===1){let p=_.closest(".aipkit_chat_container");if(p)return p.querySelector(".aipkit_chat_input")}return null}function e(u){let _=u.querySelector(`.${h}`);if(_)return _;_=document.createElement("div"),_.className=h,_.setAttribute("role","status"),_.setAttribute("aria-live","polite");let p=u.querySelector(".aipkit_chat_input_wrapper");return p?u.insertBefore(_,p):u.appendChild(_),_}function r(u){let _=n.get(u);_&&(clearTimeout(_),n.delete(u));let p=a.get(u);p&&(clearTimeout(p),a.delete(u))}function s(u,_=!0){if(!u)return;r(u);let p=()=>{u.textContent="",u.style.display="none",u.className=h,a.delete(u)};if(!_){p();return}u.classList.remove(o);let c=window.setTimeout(p,220);a.set(u,c)}function w(u,_="info",p={},c,m){let l=String(u||"").trim();if(!l)return;let k=i.has(_)?_:"info",d=t(p);if(!d){console.warn("AIPKit Inline Notice: Could not resolve input area for message:",l);return}let f=e(d);if(r(f),f.textContent=l,f.className=`${h} aipkit_status-${k}`,f.style.display="block",requestAnimationFrame(()=>{f.style.display!=="none"&&f.classList.add(o)}),!(typeof c=="boolean"?c:k!=="processing"))return;let I=Number.isFinite(m)?Math.max(1e3,m):k==="error"||k==="warning"?7e3:4500,b=window.setTimeout(()=>{s(f,!0)},I);n.set(f,b)}window.aipkit_chatUI_showInlineNotice=w})();(function(){"use strict";let h=new Set(["muted","info","error","loading"]);function o(n={}){let a=h.has(n.type)?n.type:"muted",t=String(n.message||"").trim(),e=n.scope==="messages"?"messages":"sidebar",r=!!n.showSpinner,s=document.createElement("div");if(s.className=`aipkit_ui_state aipkit_ui_state--${a} aipkit_ui_state--${e}`,r&&!t&&s.classList.add("aipkit_ui_state--spinner-only"),t){let w=document.createElement("p");w.className="aipkit_ui_state_text",w.textContent=t,s.appendChild(w)}if(r){let w=document.createElement("span");w.className="aipkit_ui_state_spinner";let u=document.createElement("span");u.className="aipkit_spinner",u.setAttribute("aria-hidden","true"),w.appendChild(u),s.appendChild(w)}return s}function i(n,a={}){n&&(n.innerHTML="",n.appendChild(o(a)))}window.aipkit_chatUI_createStateElement=o,window.aipkit_chatUI_renderUIState=i})();(function(){"use strict";function h(o,i){let n=i.botId||"unknown",a=o.querySelector(".aipkit_chat_header"),t=o.querySelector(".aipkit_chat_main"),e=t?t.querySelector(".aipkit_chat_messages"):null,r=t?t.querySelector(".aipkit_chat_footer"):null,s=t?t.querySelector(".aipkit_chat_input"):null,w=s?s.querySelector(".aipkit_chat_input_field"):null,u=s?s.querySelector(".aipkit_chat_input_wrapper"):null,_=u?u.querySelector(".aipkit_chat_input_actions_bar"):null,p=o.querySelector(".aipkit_chat_image_preview_container"),c=o.querySelector(".aipkit_chat_image_upload_input");if(i.imageUploadEnabledUI&&s&&u){if(p||(p=document.createElement("div"),p.className="aipkit_chat_image_preview_container"),!u.contains(p)){let L=u.querySelector(".aipkit_chat_input_field");L?u.insertBefore(p,L):u.appendChild(p)}c||(c=document.createElement("input"),c.type="file",c.className="aipkit_chat_image_upload_input",c.hidden=!0,c.setAttribute("aria-hidden","true"),s.appendChild(c))}let m=s?s.querySelector(".aipkit_chat_file_upload_input"):null;i.fileUploadEnabledUI&&s&&(m||(m=document.createElement("input"),m.type="file",m.className="aipkit_chat_file_upload_input",m.hidden=!0,m.setAttribute("aria-hidden","true"),s.appendChild(m)));let l=_?_.querySelector(".aipkit_input_action_btn.aipkit_input_action_toggle"):null,k=s?s.querySelector(".aipkit_input_action_menu"):null,d=_?_.querySelector(".aipkit_voice_input_btn"):null,f=_?_.querySelector(".aipkit_web_search_toggle"):null,g=_?_.querySelector(".aipkit_google_search_grounding_toggle"):null,I=_?_.querySelector(".aipkit_chat_action_btn.aipkit_send_btn"):null,b=I?I.querySelector(".aipkit_send_icon"):null,y=I?I.querySelector(".aipkit_clear_icon"):null,v=I?I.querySelector(".aipkit_spinner"):null,A=t?t.querySelector(".aipkit_conversation_starters"):null,x=a?a.querySelector(".aipkit_sidebar_toggle_btn"):null,S=a?a.querySelector(".aipkit_fullscreen_btn"):null,U=a?a.querySelector(".aipkit_download_btn"):null,M=o.querySelector(".aipkit_chat_sidebar"),F=M?M.querySelector(".aipkit_sidebar_new_chat_btn"):null;return!t||!e||!w||!I||!b||!y||!v?(console.error(`AIPKit Chat FindElements (${n}): Essential chat UI elements not found within container.`),null):(i.enableStarters&&!A&&console.warn(`AIPKit Chat FindElements (${n}): Starters enabled but container not found.`),i.enableSidebar&&(!M||!x)&&console.warn(`AIPKit Chat FindElements (${n}): Sidebar enabled but container or toggle button not found.`),i.inputActionButtonEnabled&&!l&&console.warn(`AIPKit Chat FindElements (${n}): Input Action Button features enabled but button element missing.`),i.allowWebSearchTool&&(i.provider==="OpenAI"||i.provider==="Claude"||i.provider==="OpenRouter")&&!f&&console.warn(`AIPKit Chat FindElements (${n}): Provider Web Search allowed but toggle button missing.`),i.allowGoogleSearchGrounding&&i.provider==="Google"&&!g&&console.warn(`AIPKit Chat FindElements (${n}): Google Search Grounding allowed but toggle button missing.`),{container:o,headerEl:a,mainContentEl:t,messagesEl:e,footerEl:r,inputArea:s,inputField:w,inputWrapper:u,actionsBar:_,imageUploadInput:c,imagePreviewContainer:p,fileUploadInput:m,inputActionButton:l,inputActionMenu:k,voiceInputButton:d,webSearchToggleButton:f,googleSearchGroundingToggleButton:g,actionButton:I,sendIcon:b,clearIcon:y,spinner:v,startersContainer:A,sidebarToggleBtn:x,fullscreenButton:S,downloadButton:U,sidebarEl:M,newChatBtn:F})}window.aipkit_chatUI_findElements=h})();(function(){"use strict";function h(o,i=!1){o&&requestAnimationFrame(()=>{let n=o.scrollHeight-o.scrollTop-o.clientHeight<100;(i||n)&&(o.scrollTop=o.scrollHeight,setTimeout(()=>{o&&(o.scrollTop=o.scrollHeight)},50)),typeof window.aipkit_chatUI_updateScrollToBottomButton=="function"&&window.aipkit_chatUI_updateScrollToBottomButton(o)})}window.aipkit_chatUI_scrollToBottom=h})();(function(){"use strict";function h(i){if(!i)return;let n=i.style.animation;i.style.animation="none",i.offsetHeight,n?i.style.animation=n:i.style.removeProperty("animation")}function o(i){i&&(h(i),i.classList.contains("aipkit_initial_greeting")&&i.querySelectorAll(".aipkit_chat_bubble p").forEach(h))}window.aipkit_chatUI_triggerMessageAnimation=o})();(function(){"use strict";let h="aipkit_scroll_to_bottom_btn",o="aipkit-scroll-visible",a=window.requestAnimationFrame||function(p){return window.setTimeout(p,16)};function t(p,c=48){return p?p.scrollHeight-p.scrollTop-p.clientHeight<=c:!0}function e(p){return p?p.scrollHeight>p.clientHeight+4:!1}function r(p){if(!p||!p._aipkitScrollToBottomButton)return;let c=p._aipkitScrollToBottomButton,m=e(p)&&!t(p);c.classList.toggle(o,m),c.setAttribute("aria-hidden",m?"false":"true")}function s(p,c,m){if(!p)return;let l=c?Math.round(c.getBoundingClientRect().height):0,k=m?Math.round(m.getBoundingClientRect().height):0,f=Math.max(96,l+k+12);p.style.setProperty("--aipkit-chat-scroll-button-bottom-offset",`${f}px`)}function w(p){let c=p.querySelector(`.${h}`);return c||(c=document.createElement("button"),c.type="button",c.className=h,c.setAttribute("aria-label","Scroll to bottom"),c.setAttribute("aria-hidden","true"),c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M6 13l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',p.appendChild(c),c)}function u(p){if(!p||!p.mainContentEl||!p.messagesEl||p.mainContentEl.dataset.aipkitScrollButtonInit==="1")return;p.mainContentEl.dataset.aipkitScrollButtonInit="1";let{mainContentEl:c,messagesEl:m,inputArea:l,footerEl:k}=p,d=w(c);m._aipkitScrollToBottomButton=d,m._aipkitScrollToBottomUpdate=()=>r(m);let f=()=>{a(()=>r(m))};if(m.addEventListener("scroll",f,{passive:!0}),typeof MutationObserver<"u"&&new MutationObserver(f).observe(m,{childList:!0,subtree:!0}),typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>{s(c,l,k),f()});g.observe(m),l&&g.observe(l),k&&g.observe(k)}else window.addEventListener("resize",()=>{s(c,l,k),f()});d.addEventListener("click",()=>{typeof window.aipkit_chatUI_scrollToBottom=="function"?window.aipkit_chatUI_scrollToBottom(m,!0):m&&m.scrollTo({top:m.scrollHeight,behavior:"smooth"}),f()}),s(c,l,k),f()}function _(p){!p||!p._aipkitScrollToBottomUpdate||p._aipkitScrollToBottomUpdate()}window.aipkit_chatUI_initScrollToBottomButton=u,window.aipkit_chatUI_updateScrollToBottomButton=_})();(function(){"use strict";function h(o,i=null){if(!o)return;if(i&&i.parentNode===o){try{o.removeChild(i)}catch(r){r.name!=="NotFoundError"&&console.warn("AIPKit removeTypingIndicator: Error removing provided indicator:",r)}return}let a=`aipkit-typing-indicator-${o.closest(".aipkit_chat_container")?.dataset.botId||o.closest(".aipkit_popup_wrapper")?.dataset.botId||"default"}`,t=o.querySelector(`#${CSS.escape(a)}`);if(t)try{o.removeChild(t)}catch(r){r.name!=="NotFoundError"&&console.warn("AIPKit removeTypingIndicator: Error removing indicator by ID:",r)}let e=o.querySelector(".aipkit_typing-indicator");if(e)try{o.removeChild(e)}catch(r){r.name!=="NotFoundError"&&console.warn("AIPKit removeTypingIndicator: Error removing indicator by class:",r)}}window.aipkit_chatUI_removeTypingIndicator=h})();(function(){"use strict";function h(o,i=null){if(!o)return;if(i&&i.parentNode===o){try{o.removeChild(i)}catch(r){r.name!=="NotFoundError"&&console.warn("AIPKit removeImageLoadingIndicator: Error removing provided indicator:",r)}return}let a=`aipkit-image-loading-indicator-${o.closest(".aipkit_chat_container")?.dataset.botId||o.closest(".aipkit_popup_wrapper")?.dataset.botId||"default"}`,t=o.querySelector(`#${CSS.escape(a)}`);if(t)try{o.removeChild(t)}catch(r){r.name!=="NotFoundError"&&console.warn("AIPKit removeImageLoadingIndicator: Error removing indicator by ID:",r)}let e=o.querySelector(".aipkit_image_loading_indicator");if(e)try{o.removeChild(e)}catch(r){r.name!=="NotFoundError"&&console.warn("AIPKit removeImageLoadingIndicator: Error removing indicator by class:",r)}}window.aipkit_chatUI_removeImageLoadingIndicator=h})();(function(){"use strict";function h(o,i){if(!o||!i||!i.text)return null;typeof window.aipkit_chatUI_removeTypingIndicator=="function"&&window.aipkit_chatUI_removeTypingIndicator(o),typeof window.aipkit_chatUI_removeImageLoadingIndicator=="function"&&window.aipkit_chatUI_removeImageLoadingIndicator(o);let a=`aipkit-typing-indicator-${i.botId||"default"}`,t=document.createElement("div");t.className="aipkit_chat_message aipkit_chat_message-bot aipkit_typing-indicator",t.id=a;let e=(i.customTypingText||"").trim(),r=document.createElement("div");if(r.className="aipkit_chat_bubble",e!==""){let s=(window.aipkit_escapeHtml||(w=>String(w)))(e);r.innerHTML=`
<span class="aipkit_typing-text">${s}</span>
<span class="aipkit_typing-ellipsis-text" aria-hidden="true"><span>.</span><span>.</span><span>.</span></span>
`}else r.innerHTML=`
<span class="aipkit_typing-dot"></span>
<span class="aipkit_typing-dot"></span>
<span class="aipkit_typing-dot"></span>
`;return t.appendChild(r),o.appendChild(t),typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(o,!0),t}window.aipkit_chatUI_showTypingIndicator=h})();(function(){"use strict";function h(o,i){if(!o||!i)return null;typeof window.aipkit_chatUI_removeTypingIndicator=="function"&&window.aipkit_chatUI_removeTypingIndicator(o),typeof window.aipkit_chatUI_removeImageLoadingIndicator=="function"&&window.aipkit_chatUI_removeImageLoadingIndicator(o);let a=`aipkit-image-loading-indicator-${i.botId||"default"}`,t=document.createElement("div");t.className="aipkit_chat_message aipkit_chat_message-bot aipkit_image_loading_indicator",t.id=a;let e=document.createElement("div");return e.className="aipkit_chat_bubble aipkit_image_loader_bubble_thumbnail",e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M15 8h.01" /><path d="M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z" /><path d="M4 15l4 -4a3 5 0 0 1 3 0l5 5" /><path d="M14 14l1 -1a3 5 0 0 1 3 0l2 2" /></svg>',t.appendChild(e),o.appendChild(t),typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(o,!0),t}window.aipkit_chatUI_showImageLoadingIndicator=h})();(function(){"use strict";let h='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-copy"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z" /><path d="M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1" /></svg>';function o(e){if(!e)return"";let r=e.querySelector("code");return r?r.textContent:e.textContent}function i(e,r){if(e){if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(e).then(r).catch(()=>{n(e,r)});return}n(e,r)}}function n(e,r){try{let s=document.createElement("textarea");s.value=e,s.setAttribute("readonly",""),s.style.position="absolute",s.style.left="-9999px",document.body.appendChild(s),s.select();let w=document.execCommand ("copy");document.body.removeChild(s),w&&r()}catch(s){console.error("AIPKit Code Copy: Fallback copy failed.",s)}}function a(e,r){if(!e||r&&r.enableCopyButton===!1)return;let s=e.querySelectorAll("pre");if(!s.length)return;let w=r&&r.text&&r.text.copyCodeLabel||"Copy code";s.forEach(u=>{if(u.classList.contains("aipkit_code_block"))return;let _=document.createElement("button");_.type="button",_.className="aipkit_code_copy_btn",_.setAttribute("aria-label",w),_.setAttribute("title",w),_.innerHTML=h,u.classList.add("aipkit_code_block"),u.insertBefore(_,u.firstChild)})}function t(e){let r=e.target.closest(".aipkit_code_copy_btn");if(!r)return;e.preventDefault();let s=r.closest("pre"),w=o(s);w&&i(w,()=>{typeof window.aipkit_chatUI_showSuccessIcon=="function"&&window.aipkit_chatUI_showSuccessIcon(r)})}document.addEventListener("click",t),window.aipkit_chatUI_attachCodeCopyButtons=a})();(function(){"use strict";let h="aipkit_chat_status",o="aipkit_grounding_widget",i="aipkit_citations_widget";function n(l){let k=typeof l=="string"?l.trim():"";if(k==="")return"";let d=document.createElement("div");return d.innerHTML=k,(d.textContent||d.innerText||"").replace(/\s+/g," ").trim()}function a(l,k,d){let g=(l&&l.text?l.text:{})[k];return typeof g=="string"&&g.trim()!==""?g.trim():d}function t(l){return l?l.querySelector(".aipkit_message_actions"):null}function e(l,k){if(!l||!k)return;let d=t(l);if(d&&d.parentNode===l){l.insertBefore(k,d);return}l.appendChild(k)}function r(l,k){if(!l)return;let d=l.querySelector(`.${h}`),f=typeof k=="string"?k.trim():"";if(f===""){d&&d.parentNode&&d.parentNode.removeChild(d);return}d||(d=document.createElement("div"),d.className=h,d.setAttribute("role","status"),d.setAttribute("aria-live","polite")),d.textContent=f,e(l,d)}function s(l,k,d){if(!l)return;let f=l.querySelector(`.${o}`),g=!(typeof d<"u"&&d&&Object.prototype.hasOwnProperty.call(d,"showSources")&&d.showSources===!1),I=k&&k.searchEntryPoint&&typeof k.searchEntryPoint.renderedContent=="string"?k.searchEntryPoint.renderedContent:"";if(!g||I===""){f&&f.parentNode&&f.parentNode.removeChild(f);return}f||(f=document.createElement("div"),f.className=o),f.innerHTML=I,e(l,f)}function w(l){return!l||typeof l!="object"?"":[l.type||"",l.url||"",l.document_title||l.title||"",l.document_index??"",l.start_char_index??"",l.end_char_index??"",l.start_page_number??"",l.end_page_number??"",l.start_block_index??"",l.end_block_index??"",l.cited_text||""].join("|")}function u(l){if(!Array.isArray(l))return[];let k=new Set,d=[];return l.forEach(f=>{if(!f||typeof f!="object")return;let g=w(f);g&&k.has(g)||(g&&k.add(g),d.push(f))}),d}function _(l,k,d){let f=`${a(d,"source","Source")} ${k+1}`,g=[l.document_title,l.title,l.website_title,l.source_title].find(I=>typeof I=="string"&&I.trim()!=="");if(g)return n(g)||g.trim();if(typeof l.url=="string"&&l.url.trim()!=="")try{return new URL(l.url).hostname}catch{return l.url.trim()}return f}function p(l){if(!l||typeof l!="object")return"";switch(l.type){case"char_location":if(l.start_char_index!==void 0&&l.end_char_index!==void 0)return`Chars ${l.start_char_index}-${l.end_char_index}`;break;case"page_location":if(l.start_page_number!==void 0&&l.end_page_number!==void 0)return`Pages ${l.start_page_number}-${l.end_page_number}`;break;case"content_block_location":if(l.start_block_index!==void 0&&l.end_block_index!==void 0)return`Blocks ${l.start_block_index}-${l.end_block_index}`;break;default:break}return""}function c(l,k,d){if(!l)return;let f=l.querySelector(`.${i}`),g=!(d&&Object.prototype.hasOwnProperty.call(d,"showSources")&&d.showSources===!1),I=u(k);if(!g||I.length===0){f&&f.parentNode&&f.parentNode.removeChild(f);return}f||(f=document.createElement("details"),f.className=i),f.textContent="";let b=I.length,y=document.createElement("summary");y.className="aipkit_citations_toggle";let v=document.createElement("span");v.className="aipkit_citations_toggle_icon",v.setAttribute("aria-hidden","true"),v.textContent="\u203A",y.appendChild(v);let A=document.createElement("span");A.className="aipkit_citations_toggle_label",A.textContent=`${a(d,b===1?"source":"sources",b===1?"Source":"Sources")} (${b})`,y.appendChild(A),f.appendChild(y);let x=document.createElement("div");x.className="aipkit_citations_panel";let S=document.createElement("ol");S.className="aipkit_citations_list",I.forEach((U,M)=>{let F=document.createElement("li");F.className="aipkit_citations_item";let L=document.createElement("div");L.className="aipkit_citations_item_header";let O=_(U,M,d);if(typeof U.url=="string"&&U.url.trim()!==""){let T=document.createElement("a");T.className="aipkit_citations_item_link",T.href=U.url.trim(),T.target="_blank",T.rel="noopener noreferrer",T.textContent=O,L.appendChild(T)}else{let T=document.createElement("span");T.className="aipkit_citations_item_title",T.textContent=O,L.appendChild(T)}let j=p(U);if(j!==""){let T=document.createElement("span");T.className="aipkit_citations_item_location",T.textContent=j,L.appendChild(T)}if(F.appendChild(L),typeof U.cited_text=="string"&&U.cited_text.trim()!==""){let T=n(U.cited_text);if(T!==""){let C=document.createElement("div");C.className="aipkit_citations_item_excerpt",C.textContent=T,F.appendChild(C)}}S.appendChild(F)}),x.appendChild(S),f.appendChild(x),e(l,f)}function m(l,k,d){!l||!k||typeof k!="object"||(Object.prototype.hasOwnProperty.call(k,"statusText")&&r(l,k.statusText),Object.prototype.hasOwnProperty.call(k,"groundingMetadata")&&s(l,k.groundingMetadata,d),Object.prototype.hasOwnProperty.call(k,"citations")&&c(l,k.citations,d))}window.aipkit_chatUI_upsertMessageMeta=m,window.aipkit_chatUI_normalizeCitations=u})();(function(){"use strict";function h(_){let p=typeof _=="string"?_.trim():"";if(p==="")return"";try{let c=new URL(p);return c.hash="",c.toString().replace(/\/$/,"").toLowerCase()}catch{return p.replace(/\/$/,"").toLowerCase()}}function o(_){let p=typeof _=="string"?_.trim():"";return p===""?"":p.replace(/^https?:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").replace(/[)\],.;:!?]+$/,"").trim().toLowerCase()}function i(_){if(!_||typeof _!="object")return"";let p=_.url||_.uri||"";return typeof p=="string"?p.trim():""}function n(_){return(typeof window.aipkit_chatUI_normalizeCitations=="function"?window.aipkit_chatUI_normalizeCitations:function(c){return Array.isArray(c)?c:[]})(_).map((c,m)=>{let l=i(c),k=h(l),d=o(l);return{citation:c,index:m+1,url:l,normalizedUrl:k,normalizedDomain:d}}).filter(c=>c.normalizedUrl!==""||c.normalizedDomain!=="")}function a(_,p){let c=h(_),m=o(_);return p.find(l=>l.normalizedUrl!==""&&l.normalizedUrl===c)||p.find(l=>l.normalizedDomain!==""&&l.normalizedDomain===m)||null}function t(_){let p=document.createElement("sup");p.className="aipkit_inline_citation";let c=document.createElement("a");c.className="aipkit_inline_citation_ref",c.href=_.url||"#",c.textContent=`[${_.index}]`,_.url?(c.target="_blank",c.rel="noopener noreferrer"):c.removeAttribute("href");let m=_.citation&&(_.citation.document_title||_.citation.title||_.citation.website_title||_.citation.source_title)||_.normalizedDomain||"";return m?(c.title=m,c.setAttribute("aria-label",`Source ${_.index}: ${m}`)):c.setAttribute("aria-label",`Source ${_.index}`),p.appendChild(c),p}function e(_){if(!_||!_.parentNode)return;let p=_.previousSibling;if(p&&p.nodeType===Node.TEXT_NODE){let m=p.textContent.replace(/\s*\(\s*$/,"");m!==p.textContent&&(p.textContent=m),p.textContent===""&&p.parentNode.removeChild(p)}let c=_.nextSibling;if(c&&c.nodeType===Node.TEXT_NODE){let m=c.textContent.replace(/^\s*\)\s*/,"");m!==c.textContent&&(c.textContent=m),c.textContent.trim()===""&&c.parentNode.removeChild(c)}}function r(_){return!_||!_.parentElement?!0:!!_.parentElement.closest("a, pre, code, .aipkit_citations_widget, .aipkit_grounding_widget")}function s(_,p){if(!_||r(_))return;let c=_.textContent;if(typeof c!="string"||c.indexOf("(")===-1)return;let m=/\(\s*((?:https?:\/\/)?(?:www\.)?[a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s)]*)?)\s*\)/gi,l,k=0,d=!1,f=document.createDocumentFragment();for(;(l=m.exec(c))!==null;){let I=a(l[1],p);if(!I)continue;d=!0;let b=c.slice(k,l.index);b&&f.appendChild(document.createTextNode(b)),f.appendChild(t(I)),k=m.lastIndex}if(!d)return;let g=c.slice(k);g&&f.appendChild(document.createTextNode(g)),_.parentNode.replaceChild(f,_)}function w(_,p){if(!_)return;Array.from(_.querySelectorAll("a")).filter(m=>!m.closest("pre, code, .aipkit_citations_widget, .aipkit_grounding_widget")).forEach(m=>{let l=(m.textContent||"").trim(),k=(m.getAttribute("href")||"").trim(),d=a(k||l,p);if(!d)return;let f=o(l);if(f===""||f!==d.normalizedDomain&&f!==o(k))return;let g=t(d);m.parentNode.replaceChild(g,m),e(g)})}function u(_,p){if(!_||!Array.isArray(p)||p.length===0)return;let c=n(p);if(c.length===0)return;w(_,c);let m=document.createTreeWalker(_,NodeFilter.SHOW_TEXT,null),l=[],k=m.nextNode();for(;k;)l.push(k),k=m.nextNode();l.forEach(d=>{s(d,c)})}window.aipkit_chatUI_applyInlineCitationMarkers=u})();(function(){"use strict";function h(t,e){let r=String(e||"").split(`
`);r.forEach((s,w)=>{t.appendChild(document.createTextNode(s)),w<r.length-1&&t.appendChild(document.createElement("br"))})}function o(t,e,r){let s=String(r?.text?.initialGreeting||"").trim(),w=String(r?.text?.initialSubgreeting||"").trim(),u=s,_=w;if(!u&&!_&&typeof e=="string"){let p=e.split(/\n\s*\n/).map(c=>c.trim()).filter(Boolean);u=p.shift()||"",_=p.join(`
`)}if(u){let p=document.createElement("p");p.textContent=u,t.appendChild(p)}if(_){let p=document.createElement("p");p.textContent=_,t.appendChild(p)}return!t.childNodes.length&&typeof e=="string"&&h(t,e),[u,_].filter(Boolean).join(`
`)||(typeof e=="string"?e:"")}function i(t,e,r){e.showSources!==!1&&Array.isArray(r)&&r.length>0&&typeof window.aipkit_chatUI_applyInlineCitationMarkers=="function"&&window.aipkit_chatUI_applyInlineCitationMarkers(t,r),typeof window.aipkit_chatUI_attachCodeCopyButtons=="function"&&window.aipkit_chatUI_attachCodeCopyButtons(t,e)}function n(t,e,r,s){let w=typeof window.aipkit_getMarkdownRenderer=="function"?window.aipkit_getMarkdownRenderer():window.aipkit_md;t.setAttribute("data-raw-text",e),w&&typeof w.render=="function"?(t.innerHTML=w.render(e),i(t,r,s)):h(t,e),w&&w.aipkitIsFallback&&typeof window.aipkit_ensureMarkdownParser=="function"&&t.dataset.aipkitMarkdownUpgradePending!=="1"&&(t.dataset.aipkitMarkdownUpgradePending="1",window.aipkit_ensureMarkdownParser().then(function(u){if(delete t.dataset.aipkitMarkdownUpgradePending,!t.isConnected||!u||u.aipkitIsFallback)return;let _=t.getAttribute("data-raw-text")||e;t.innerHTML=u.render(_),i(t,r,s)}))}function a(t,e,r,s,w=!1,u=!1,_=null,p=!1,c=null,m=null){if(!t||!s)return;u||t.querySelectorAll(".aipkit_initial_greeting").forEach(I=>I.remove());let l=document.createElement("div"),k=r==="user"?"user":"bot";l.className=`aipkit_chat_message aipkit_chat_message-${k}`,w&&l.classList.add("aipkit_chat_message-error"),u&&l.classList.add("aipkit_initial_greeting"),_&&(l.id=_,l.setAttribute("data-message-id",_));let d=document.createElement("div");d.className="aipkit_chat_bubble";let f="";if(k==="user"&&typeof e=="object"&&e!==null&&e.user_image){if(e.user_image.base64_data&&e.user_image.mime_type){let g=document.createElement("img");g.src=`data:${e.user_image.mime_type};base64,${e.user_image.base64_data}`,g.alt=e.text||"User uploaded image",g.className="aipkit_user_sent_image_thumbnail",d.appendChild(g)}if(e.text&&e.text.trim()!==""){let g=document.createElement("div");g.className="aipkit_user_message_text_content",g.textContent=e.text,d.appendChild(g),f=e.text}else!e.text&&e.user_image&&(f="Image sent by user.")}else if(typeof e=="object"&&e?.type==="image"&&e.images?.length>0){let g=e.images[0],I=String(e.prompt||"Generated image"),b=typeof g.revised_prompt=="string"?g.revised_prompt:"",y=({src:v,href:A,alt:x})=>{let S=document.createElement("img");if(S.src=v,S.alt=x,S.className="aipkit_bot_generated_image",A){let U=document.createElement("a");U.href=A,U.target="_blank",U.rel="noopener noreferrer",U.appendChild(S),d.appendChild(U);return}d.appendChild(S)};if(g.media_library_url)y({src:String(g.media_library_url),href:String(g.media_library_url),alt:I});else if(g.url)y({src:String(g.url),href:String(g.url),alt:I});else if(g.b64_json)y({src:`data:image/png;base64,${g.b64_json}`,alt:I});else{let v=e.content||s.text?.noImageData||"Image data unavailable.",A=document.createElement("p");A.className="aipkit_image_unavailable_text",A.textContent=v,d.appendChild(A)}if(d.classList.add("aipkit_chat_bubble--image"),d.title=`Prompt: ${I}`,f=`Image generated for prompt: ${I}`,b){let v=document.createElement("p");v.className="aipkit_image_revised_prompt",v.textContent=`Revised: ${b}`,d.appendChild(v),f+=`. Revised prompt: ${b}`}}else typeof e=="string"?(f=e,u?f=o(d,e,s):k==="bot"&&!w?n(d,e,s,m):h(d,e)):(console.error("AIPKit appendMessage: Invalid content type provided.",e),d.textContent=escaper("[Invalid Content]"),f="Invalid Content");if(d.setAttribute("data-raw-text",f),l.appendChild(d),k==="bot"&&!u&&!w)if(l.classList.add("aipkit_message_complete"),typeof window.aipkit_chatUI_createActionsContainerHTML=="function"){let g=window.aipkit_chatUI_createActionsContainerHTML(s);g&&(l.insertAdjacentHTML("beforeend",g),l.classList.add("aipkit_has_message_actions"))}else console.error("AIPKit DOM: aipkit_chatUI_createActionsContainerHTML function not found globally.");k==="bot"&&!w&&typeof window.aipkit_chatUI_upsertMessageMeta=="function"&&window.aipkit_chatUI_upsertMessageMeta(l,{groundingMetadata:c,citations:m},s),t.appendChild(l),typeof window.aipkit_chatUI_triggerMessageAnimation=="function"&&window.aipkit_chatUI_triggerMessageAnimation(l),typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(t,p)}window.aipkit_chatUI_appendMessage=a})();(function(){"use strict";function h(a,t){if(!a)return!0;if(a.nodeType===Node.ELEMENT_NODE){let e=a;return e.classList.contains(t)?!0:!!e.closest(".aipkit_code_copy_btn, .aipkit_citations_widget, .aipkit_grounding_widget")}if(a.nodeType===Node.TEXT_NODE){let e=a.parentElement;return e?!!e.closest(".aipkit_code_copy_btn, .aipkit_citations_widget, .aipkit_grounding_widget"):!0}return!0}function o(a,t){let e=document.createTreeWalker(a,NodeFilter.SHOW_TEXT),r=null,s=e.nextNode();for(;s;)!h(s,t)&&typeof s.textContent=="string"&&s.textContent.trim()!==""&&(r=s),s=e.nextNode();return r}function i(a,t){let e=document.createTreeWalker(a,NodeFilter.SHOW_ELEMENT),r=null,s=e.nextNode();for(;s;)h(s,t)||(r=s),s=e.nextNode();return r}function n(a,t){if(!a)return;let e=a.querySelector(`.${t}`);e?e.parentNode&&e.parentNode.removeChild(e):(e=document.createElement("span"),e.className=t);let r=o(a,t);if(r){let w=document.createRange();w.setStart(r,r.textContent.length),w.collapse(!0),w.insertNode(e);return}let s=i(a,t);if(s&&s.parentNode){s.nextSibling?s.parentNode.insertBefore(e,s.nextSibling):s.parentNode.appendChild(e);return}a.appendChild(e)}window.positionStreamingIndicator=n})();(function(){"use strict";function h(n,a,t){a.showSources!==!1&&Array.isArray(t)&&t.length>0&&typeof window.aipkit_chatUI_applyInlineCitationMarkers=="function"&&window.aipkit_chatUI_applyInlineCitationMarkers(n,t),typeof window.aipkit_chatUI_attachCodeCopyButtons=="function"&&window.aipkit_chatUI_attachCodeCopyButtons(n,a)}function o(n,a,t,e){let r=typeof window.aipkit_getMarkdownRenderer=="function"?window.aipkit_getMarkdownRenderer():window.aipkit_md;r&&typeof r.render=="function"?(n.innerHTML=r.render(a),h(n,t,e)):n.innerHTML=String(a||"").replace(/\n/g,"<br>"),r&&r.aipkitIsFallback&&typeof window.aipkit_ensureMarkdownParser=="function"&&n.dataset.aipkitMarkdownUpgradePending!=="1"&&(n.dataset.aipkitMarkdownUpgradePending="1",window.aipkit_ensureMarkdownParser().then(function(s){if(delete n.dataset.aipkitMarkdownUpgradePending,!n.isConnected||!s||s.aipkitIsFallback)return;let w=n.dataset.aipkitFullContent||n.getAttribute("data-raw-text")||a;n.innerHTML=s.render(w),h(n,t,e)}))}function i(n,a,t,e,r,s=!1,w=!1,u=null,_=null){if(!n||!r||!a){console.error("AIPKit appendOrUpdateMessage: Missing messagesEl, config, or messageId.",{messagesEl:n,messageId:a,config:r});return}let p=n.querySelector(`#${CSS.escape(a)}`),c,m="",l="aipkit_stream_indicator",k=e==="user"?"user":"bot";if(!p)n.querySelectorAll(".aipkit_initial_greeting").forEach(f=>f.remove()),p=document.createElement("div"),p.id=a,p.setAttribute("data-message-id",a),p.className=`aipkit_chat_message aipkit_chat_message-${k}`,w&&p.classList.add("aipkit_chat_message-error"),c=document.createElement("div"),c.className="aipkit_chat_bubble",c.dataset.aipkitFullContent="",c.setAttribute("data-raw-text",""),p.appendChild(c),n.appendChild(p),typeof window.aipkit_chatUI_triggerMessageAnimation=="function"&&window.aipkit_chatUI_triggerMessageAnimation(p);else{if(c=p.querySelector(".aipkit_chat_bubble"),!c)return;w&&!p.classList.contains("aipkit_chat_message-error")&&p.classList.add("aipkit_chat_message-error")}if(c.dataset.aipkitFullContent===void 0&&(c.dataset.aipkitFullContent=""),c.getAttribute("data-raw-text")===null&&c.setAttribute("data-raw-text",""),c.dataset.aipkitFullContent+=t,c.setAttribute("data-raw-text",c.getAttribute("data-raw-text")+t),m=c.dataset.aipkitFullContent,w?c.textContent=m:o(c,m,r,_),p.classList.remove("aipkit_message_streaming"),!s&&!w){if(typeof window.positionStreamingIndicator=="function")window.positionStreamingIndicator(c,l);else{console.error("AIPKit appendOrUpdateMessage: positionStreamingIndicator function not found.");let d=c.querySelector(`.${l}`);d||(d=document.createElement("span"),d.className=l,c.appendChild(d))}p.classList.add("aipkit_message_streaming")}else{let d=c.querySelector(`.${l}`);if(d&&d.parentNode&&d.parentNode.removeChild(d),typeof window.aipkit_chatUI_upsertMessageMeta=="function"&&window.aipkit_chatUI_upsertMessageMeta(p,{statusText:null,groundingMetadata:s&&!w?u:null,citations:s&&!w?_:null},r),s&&!w&&k==="bot"&&!p.querySelector(".aipkit_message_actions")){if(p.classList.remove("aipkit_message_streaming"),p.classList.add("aipkit_message_complete"),typeof window.aipkit_chatUI_createActionsContainerHTML=="function"){let f=window.aipkit_chatUI_createActionsContainerHTML(r);f&&(p.insertAdjacentHTML("beforeend",f),p.classList.add("aipkit_has_message_actions"))}else console.error("AIPKit DOM: aipkit_chatUI_createActionsContainerHTML function not found globally.");typeof window.aipkit_chatUI_upsertMessageMeta=="function"&&window.aipkit_chatUI_upsertMessageMeta(p,{groundingMetadata:u,citations:_},r)}}typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(n,s||w)}window.aipkit_chatUI_appendOrUpdateMessage=i})();(function(){"use strict";function h(o,i,n,a=null){if(!o||!i||!i.form_id||!Array.isArray(i.elements)){console.error("AIPKit RenderChatForm: Invalid arguments. Missing messagesEl, formDefinition, form_id, or elements array.");return}let t=window.aipkit_escapeHtml||function(c){return c},e=n.botId||"default",r=document.createElement("div");if(r.className="aipkit_chat_message aipkit_chat_message-bot aipkit_chat_form_message",a)r.id=a,r.setAttribute("data-message-id",a);else{let c=window.aipkit_generateClientMessageId?window.aipkit_generateClientMessageId(e):`form-msg-${Date.now()}`;r.id=c,r.setAttribute("data-message-id",c)}let s=document.createElement("div");s.className="aipkit_chat_bubble";let w=document.createElement("div");if(w.className="aipkit_chat_form_wrapper",w.dataset.formId=i.form_id,i.title){let c=document.createElement("h5");c.className="aipkit_chat_form_title",c.textContent=t(i.title),w.appendChild(c)}let u=document.createElement("form");u.className="aipkit_chat_form",u.dataset.formId=i.form_id;let _={};i.elements.forEach(c=>{let m=document.createElement("div");m.className="aipkit_chat_form_element";let l,k=typeof c.id=="string"?c.id:"";if(k){let d={};Array.isArray(c.options)&&c.options.forEach(f=>{if(!f||f.value===void 0)return;let g=String(f.value);d[g]=String(f.text??f.value)}),_[k]={label:String(c.label||k),type:String(c.type||""),optionsMap:d}}switch(c.type){case"text_input":case"textarea":if(c.label){let f=document.createElement("label");f.setAttribute("for",`form-${t(i.form_id)}-${t(c.id)}`),f.textContent=t(c.label),f.className="aipkit_chat_form_label_text",m.appendChild(f)}l=c.type==="textarea"?document.createElement("textarea"):document.createElement("input"),c.type==="text_input"&&(l.type="text"),c.type==="textarea"&&(l.rows=c.rows||3),l.id=`form-${t(i.form_id)}-${t(c.id)}`,l.name=t(c.id),l.className="aipkit_form-input",c.placeholder&&(l.placeholder=t(c.placeholder)),c.required&&(l.required=!0),c.default_value!==void 0&&(l.value=t(String(c.default_value))),m.appendChild(l);break;case"dropdown":if(c.label){let f=document.createElement("label");f.setAttribute("for",`form-${t(i.form_id)}-${t(c.id)}`),f.textContent=t(c.label),f.className="aipkit_chat_form_label_text",m.appendChild(f)}l=document.createElement("select"),l.id=`form-${t(i.form_id)}-${t(c.id)}`,l.name=t(c.id),l.className="aipkit_form-input",c.required&&(l.required=!0),Array.isArray(c.options)&&c.options.forEach(f=>{let g=document.createElement("option");g.value=t(f.value),g.textContent=t(f.text),c.default_value===f.value&&(g.selected=!0),l.appendChild(g)}),m.appendChild(l);break;case"checkbox_group":case"radio_group":let d=document.createElement("fieldset");if(c.label){let f=document.createElement("legend");f.textContent=t(c.label),f.className="aipkit_chat_form_label_text",d.appendChild(f)}Array.isArray(c.options)&&c.options.forEach(f=>{let g=document.createElement("div");g.className=c.type==="checkbox_group"?"aipkit_form_checkbox_group_item":"aipkit_form_radio_group_item";let I=document.createElement("input");I.type=c.type==="checkbox_group"?"checkbox":"radio",I.id=`form-${t(i.form_id)}-${t(c.id)}-${t(f.value)}`,I.name=t(c.id)+(c.type==="checkbox_group"?"[]":""),I.value=t(f.value),(c.type==="checkbox_group"&&Array.isArray(c.default_value)&&c.default_value.includes(f.value)||c.type==="radio_group"&&c.default_value===f.value)&&(I.checked=!0);let b=document.createElement("label");b.setAttribute("for",I.id),b.textContent=t(f.text),g.appendChild(I),g.appendChild(b),d.appendChild(g)}),m.appendChild(d);break;case"heading":l=document.createElement(c.level||"h5"),l.className="aipkit_chat_form_element_heading",l.textContent=t(c.label||""),m.appendChild(l);break;case"label":l=document.createElement("p"),l.className="aipkit_chat_form_element_label_only",l.textContent=t(c.label||""),m.appendChild(l);break}if(c.help_text){let d=document.createElement("p");d.className="aipkit_form_help_text",d.textContent=t(c.help_text),m.appendChild(d)}u.appendChild(m)}),u.aipkitFieldMeta=_;let p=document.createElement("button");p.type="submit",p.className="aipkit_btn aipkit_chat_form_submit_btn",p.textContent=t(i.submit_button_text||"Submit"),u.appendChild(p),u.addEventListener("submit",c=>{if(typeof window.aipkit_chatUI_handleChatFormSubmission=="function"){let m=o.closest(".aipkit_chat_container")||o.closest(".aipkit_popup_wrapper"),l=null,k=null;m&&window.aipkitChatInstances&&window.aipkitChatInstances[m.id]?(l=window.aipkitChatInstances[m.id].elements,k=window.aipkitChatInstances[m.id].actions):window.aipkit_chat_ui_elements&&window.aipkit_chat_ui_actions&&(l=window.aipkit_chat_ui_elements,k=window.aipkit_chat_ui_actions),l&&k?window.aipkit_chatUI_handleChatFormSubmission(c,n,l,k):(console.error("AIPKit RenderChatForm: Could not find chat instance elements/actions for form submission. Form ID:",i.form_id),typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice("Error submitting form: Chat context not found.","error",{messagesEl:o,config:n},!0,7e3))}else console.error("AIPKit RenderChatForm: aipkit_chatUI_handleChatFormSubmission function not found."),typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice("Error submitting form: Submission handler missing.","error",{messagesEl:o,config:n},!0,7e3)}),w.appendChild(u),s.appendChild(w),r.appendChild(s),o.appendChild(r),typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(o,!0)}window.aipkit_chatUI_renderChatForm=h})();(function(){"use strict";function h(o,i,n,a,t=!1){let{inputField:e,actionButton:r,sendIcon:s,clearIcon:w,spinner:u,voiceInputButton:_,inputActionButton:p,webSearchToggleButton:c,googleSearchGroundingToggleButton:m}=i,l=n.text||{},k=(f,g)=>{!f||typeof f.setAttribute!="function"||typeof f.removeAttribute!="function"||(g?f.setAttribute("hidden","hidden"):f.removeAttribute("hidden"))};if(!r||!s||!w||!u||!e)return console.error("AIPKit SetButtonState: Missing required elements."),null;k(u,!0),k(s,!0),k(w,!0),r.disabled=!1,r.classList.remove("aipkit_btn-clear-state");let d=o;switch(o){case"sending":case"streaming":e.disabled=!0,r.disabled=!0,_&&(_.disabled=!0),p&&(p.disabled=!0),c&&(c.disabled=!0),m&&(m.disabled=!0),k(u,!1);let f=o==="streaming"?l.streaming||"Streaming...":l.sending||"Sending...";r.setAttribute("aria-label",f),r.setAttribute("title",f);break;case"clear":e.disabled=n.requireConsentCompliance&&!a.consentGiven,k(w,!1),r.classList.add("aipkit_btn-clear-state"),r.setAttribute("aria-label",l.clearChat||"Clear Chat"),r.setAttribute("title",l.clearChat||"Clear Chat"),r.disabled=!1,_&&(_.disabled=n.requireConsentCompliance&&!a.consentGiven),p&&(p.disabled=n.requireConsentCompliance&&!a.consentGiven),c&&(c.disabled=n.requireConsentCompliance&&!a.consentGiven),m&&(m.disabled=n.requireConsentCompliance&&!a.consentGiven);break;case"send":default:d="send",e.disabled=n.requireConsentCompliance&&!a.consentGiven,k(s,!1),r.setAttribute("aria-label",l.sendMessage||"Send Message"),r.setAttribute("title",l.sendMessage||"Send Message"),r.disabled=!t&&e.value.trim()==="",n.requireConsentCompliance&&!a.consentGiven&&(r.disabled=!0),_&&(_.disabled=n.requireConsentCompliance&&!a.consentGiven),p&&(p.disabled=n.requireConsentCompliance&&!a.consentGiven),c&&(c.disabled=n.requireConsentCompliance&&!a.consentGiven),m&&(m.disabled=n.requireConsentCompliance&&!a.consentGiven);break}return d}window.aipkit_chatUI_setButtonStateAction=h})();(function(){"use strict";function h(o,i,n){if(!o)return;let a=o.closest("#aipkit_admin_chat_preview_container"),t=window.innerWidth<=760;i.requireConsentCompliance&&!n.consentGiven||i.popupEnabled&&!n.isPopupOpen||((a||!t||n.userInitiatedAction)&&setTimeout(()=>{o&&typeof o.focus=="function"&&o.focus()},50),n.userInitiatedAction&&(n.userInitiatedAction=!1))}window.aipkit_chatUI_focusInputAction=h})();(function(){"use strict";function h(o,i,n,a,t,e){let{inputField:r,messagesEl:s,container:w,voiceInputButton:u,inputActionButton:_,webSearchToggleButton:p,googleSearchGroundingToggleButton:c}=n;t.isSending=!1,t.currentStreamId=null,t.currentStreamMessageId=null,r.disabled=a.requireConsentCompliance&&!t.consentGiven,u&&(u.disabled=a.requireConsentCompliance&&!t.consentGiven),_&&(_.disabled=a.requireConsentCompliance&&!t.consentGiven),p&&a.allowWebSearchTool&&(a.provider==="OpenAI"||a.provider==="Claude"||a.provider==="OpenRouter")&&(p.disabled=a.requireConsentCompliance&&!t.consentGiven),c&&a.allowGoogleSearchGrounding&&a.provider==="Google"&&(c.disabled=a.requireConsentCompliance&&!t.consentGiven);let m=r.value.trim()==="",l=s.querySelectorAll(".aipkit_chat_message:not(.aipkit_initial_greeting)").length>0;t.buttonState=e.setButtonStateAction(m&&l?"clear":"send",!1,t),e.focusInputAction(),w.dispatchEvent(new CustomEvent("aipkit:messageReceived",{detail:{messageId:o,conversationUUID:window.aipkit_current_conversation_uuid,newConversation:i}})),a.ttsEnabled&&a.ttsAutoPlay&&o&&setTimeout(async()=>{if(typeof window.aipkit_chatUI_prepareTtsFeature=="function")try{await window.aipkit_chatUI_prepareTtsFeature()}catch(f){console.error(`AIPKit AutoPlay (${a.botId}): Failed to lazy-load TTS feature.`,f)}let d=s.querySelector(`#${CSS.escape(o)}`)?.querySelector(".aipkit_play_btn");d&&typeof window.aipkit_handlePlayAction=="function"?window.aipkit_handlePlayAction(d):a.ttsEnabled&&a.ttsAutoPlay&&console.warn(`AIPKit AutoPlay (${a.botId}): Could not find play button for message ${o} or play action is missing.`)},100)}window.aipkit_chatUI_handleCompletion=h})();(function(){"use strict";function h(o,i,n=!0,a,t,e,r){let{messagesEl:s,inputField:w,container:u,voiceInputButton:_,inputActionButton:p,webSearchToggleButton:c,googleSearchGroundingToggleButton:m}=a,l=t.botId;e.isSending=!1,e.currentStreamId=null,e.currentStreamMessageId=null;let k=window.aipkit_generateClientMessageId(l);window.aipkit_chatUI_appendMessage(s,o,"bot",t,!0,!1,k,n),window.aipkit_chatUI_removeTypingIndicator(s),w.disabled=t.requireConsentCompliance&&!e.consentGiven,_&&(_.disabled=t.requireConsentCompliance&&!e.consentGiven),p&&(p.disabled=t.requireConsentCompliance&&!e.consentGiven),c&&t.allowWebSearchTool&&(t.provider==="OpenAI"||t.provider==="Claude"||t.provider==="OpenRouter")&&(c.disabled=t.requireConsentCompliance&&!e.consentGiven),m&&t.allowGoogleSearchGrounding&&t.provider==="Google"&&(m.disabled=t.requireConsentCompliance&&!e.consentGiven),e.buttonState=r.setButtonStateAction("send",!1,e),r.focusInputAction(),u.dispatchEvent(new CustomEvent("aipkit:messageError",{detail:{messageId:k,error:o}}))}window.aipkit_chatUI_handleError=h})();(function(){"use strict";function h(o){if(!o)return;o.querySelectorAll(".aipkit_chat_message:not(.aipkit_initial_greeting)").forEach(n=>{try{o.removeChild(n)}catch(a){a.name!=="NotFoundError"&&console.warn("AIPKit clearMessages: Error removing node:",a)}}),typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(o,!0)}window.aipkit_chatUI_clearMessages=h})();(function(){"use strict";function h(o,i,n,a){let{messagesEl:t,inputField:e,imagePreviewContainer:r,imageUploadInput:s,fileUploadInput:w,inputArea:u}=o;typeof window.aipkit_chatUI_removeTypingIndicator!="function"?console.error("AIPKit Clear Action: Dependency window.aipkit_chatUI_removeTypingIndicator not found."):window.aipkit_chatUI_removeTypingIndicator(t),typeof window.aipkit_chatUI_clearMessages!="function"?console.error("AIPKit Clear Action: Dependency window.aipkit_chatUI_clearMessages not found."):window.aipkit_chatUI_clearMessages(t);let _=t.querySelector(".aipkit_initial_greeting");if(!_&&typeof window.aipkit_chatUI_appendMessage=="function"){let m=(i?.text?.initialGreeting||"Hello there!").trim(),l=(i?.text?.initialSubgreeting||"").trim(),k=m;l&&(k=m?`${m}
${l}`:l),typeof window.aipkit_generateClientMessageId=="function"?window.aipkit_chatUI_appendMessage(t,k,"bot",i,!1,!0,window.aipkit_generateClientMessageId(i.botId)):console.error("AIPKit Clear Action: window.aipkit_generateClientMessageId is missing, cannot append initial greeting reliably.")}else _||console.error("AIPKit Clear Action: Initial greeting missing after clear, and appendMessage function unavailable.");e&&(e.value="",e.disabled=i.requireConsentCompliance&&!n.consentGiven,typeof window.aipkit_autoResizeTextarea=="function"&&window.aipkit_autoResizeTextarea(e)),i.imageUploadEnabledUI&&window.chatImageUpload&&typeof window.chatImageUpload.reset=="function"?o.imagePreviewContainer&&o.imageUploadInput?window.chatImageUpload.reset(o.imagePreviewContainer,o.imageUploadInput):console.warn("AIPKit Clear Action: Image upload UI reset skipped, preview or input element missing from 'elements' object passed to clearChatAction."):i.imageUploadEnabledUI&&typeof window.chatImageUpload>"u"&&console.warn("AIPKit Clear Action: Image upload UI reset skipped, chatImageUpload script not loaded."),i.fileUploadEnabledUI&&window.aipkitChatFileUpload&&typeof window.aipkitChatFileUpload.resetUI=="function"?o.fileUploadInput&&o.inputArea?window.aipkitChatFileUpload.resetUI(o.fileUploadInput,o.inputArea):console.warn("AIPKit Clear Action: File upload UI reset skipped, file input or input area missing from 'elements' object."):i.fileUploadEnabledUI&&typeof window.aipkitChatFileUpload>"u"&&console.warn("AIPKit Clear Action: File upload UI reset skipped, aipkitChatFileUpload script not loaded."),typeof a.setButtonStateAction=="function"?n.buttonState=a.setButtonStateAction("send",!1):console.error("AIPKit Clear Action: actions.setButtonStateAction function not provided.");let p=i.webToggleDefaultOn===!0;typeof window.aipkit_syncWebSearchToggleState=="function"&&window.aipkit_syncWebSearchToggleState(o,i,n,p),typeof window.aipkit_syncGoogleSearchGroundingToggleState=="function"&&window.aipkit_syncGoogleSearchGroundingToggleState(o,i,n,p),n.isSending=!1,n.currentStreamId=null,n.currentStreamMessageId=null,window.aipkit_current_conversation_uuid=null,window.aipkit_is_fresh_session=!0,sessionStorage.removeItem("aipkit_current_conversation_uuid"),window.aipkit_current_openai_response_id=null,sessionStorage.removeItem("aipkit_current_openai_response_id"),window.aipkit_active_file_context_provider=null,window.aipkit_active_file_context_data=null,sessionStorage.removeItem("aipkit_active_file_context_provider"),sessionStorage.removeItem("aipkit_active_file_context_data"),document.dispatchEvent(new CustomEvent("aipkit:fileContextCleared")),typeof window.aipkit_regenerateConversationUUID=="function"&&window.aipkit_regenerateConversationUUID(),typeof a.focusInputAction=="function"&&(!i.requireConsentCompliance||n.consentGiven)?a.focusInputAction():typeof a.focusInputAction!="function"&&console.error("AIPKit Clear Action: actions.focusInputAction function not provided.");let c=t.closest(".aipkit_chat_container")||t.closest(".aipkit_popup_wrapper");c&&c.dispatchEvent(new CustomEvent("aipkit:chatCleared"))}window.aipkit_chatUI_clearChatAction=h})();(function(){"use strict";async function h(o,i,n,a,t=null){let{inputField:e,messagesEl:r,container:s,inputArea:w}=o,u=i.botId,_=null;if(window.aipkit_active_file_context_data&&typeof window.aipkit_active_file_context_data=="object"&&window.aipkit_active_file_context_data!==null&&Object.keys(window.aipkit_active_file_context_data).length>0&&window.aipkit_active_file_context_data.provider){let b=!1,y=window.aipkit_active_file_context_data;(y.provider==="OpenAI"&&y.vector_store_id||y.provider==="Pinecone"&&y.index_name&&y.namespace||y.provider==="Qdrant"&&y.collection_name&&y.file_upload_context_id||y.provider==="Claude"&&y.file_id)&&(b=!0),b?_={...y}:(console.warn(`SendMessageAction (${u}): File context data found on window object, but missing required fields for provider: ${y.provider||"unknown"}. Context ignored. Data:`,y),_=null)}let p=null;if(i.imageUploadEnabledUI&&window.chatImageUpload&&typeof window.chatImageUpload.getImageData=="function"&&(p=window.chatImageUpload.getImageData(),p&&o.imagePreviewContainer&&o.imageUploadInput&&typeof window.chatImageUpload.reset=="function"&&window.chatImageUpload.reset(o.imagePreviewContainer,o.imageUploadInput)),window.aipkitChatFileUpload&&typeof window.aipkitChatFileUpload.resetUI=="function"&&o.fileUploadInput&&w){let b=window.aipkitFileUploadState;(_||b&&b.currentFile)&&window.aipkitChatFileUpload.resetUI(o.fileUploadInput,w)}let c=n.consentUIInstance;if(c&&typeof c.showConsentBoxIfNeeded=="function"&&c.showConsentBoxIfNeeded()){console.warn(`AIPKit SendMessage (${u}): Cannot send message, consent required and box shown.`);return}if(i.requireConsentCompliance&&!n.consentGiven){console.warn(`AIPKit SendMessage (${u}): Consent required but not given.`);return}let m=t!==null?t.trim():e.value.trim();if(n.isSending||!m&&!p&&!_||t===null&&(n.buttonState!=="send"||o.actionButton.disabled))return;let l=!1;(window.aipkit_is_fresh_session||!window.aipkit_current_conversation_uuid)&&(typeof window.aipkit_regenerateConversationUUID=="function"&&(window.aipkit_current_conversation_uuid||(window.aipkit_regenerateConversationUUID(),window.aipkit_active_file_context_data&&typeof window.aipkit_active_file_context_data=="object"&&window.aipkit_active_file_context_data!==null&&Object.keys(window.aipkit_active_file_context_data).length>0&&window.aipkit_active_file_context_data.provider&&(_={...window.aipkit_active_file_context_data}))),l=!0);let k=window.aipkit_generateClientMessageId(u),d=m;p&&(d={text:m,user_image:p}),window.aipkit_chatUI_appendMessage(r,d,"user",i,!1,!1,k,!0),t===null&&(e.value="",typeof window.aipkit_autoResizeTextarea=="function"&&window.aipkit_autoResizeTextarea(e)),l&&(window.aipkit_is_fresh_session=!1),typeof window.aipkit_ensureMarkdownParser=="function"&&window.aipkit_ensureMarkdownParser();let f=(i.imageTriggers||"/image").toLowerCase().split(",").map(b=>b.trim()).filter(b=>b.length>0&&b.startsWith("/")),g=m.toLowerCase(),I=null;for(let b of f)if(g.startsWith(b+" ")||g===b){I=b;break}if(I){let b=m.substring(I.length).trim();if(!b&&g!==I){let y=(i.text.imageCommandEmptyPrompt||"Please provide description after /image.").replace("[trigger]",I);a.handleError(y,!1,!0),t===null&&(n.buttonState=a.setButtonStateAction("send",!1));return}if(typeof window.aipkit_chatUI_prepareImageCommandFeature=="function")try{await window.aipkit_chatUI_prepareImageCommandFeature()}catch(y){console.error("AIPKit SendMessage: Failed to lazy-load image command feature.",y)}typeof window.aipkit_chatUI_handleImageGeneration=="function"?window.aipkit_chatUI_handleImageGeneration(b,m,k,l,{state:n,elements:o,config:i,...a}):(console.error("AIPKit SendMessage: aipkit_chatUI_handleImageGeneration function not found."),a.handleError("Image generation feature unavailable.",!1,!0));return}if(n.isSending=!0,e.disabled=!0,o.voiceInputButton&&(o.voiceInputButton.disabled=!0),o.inputActionButton&&(o.inputActionButton.disabled=!0),o.webSearchToggleButton&&(o.webSearchToggleButton.disabled=!0),o.googleSearchGroundingToggleButton&&(o.googleSearchGroundingToggleButton.disabled=!0),n.buttonState=a.setButtonStateAction("streaming",!0),s.dispatchEvent(new CustomEvent("aipkit:messageSent",{detail:{messageId:k}})),typeof window.aipkit_chatUI_streamMessage=="function")window.aipkit_chatUI_showTypingIndicator(r,i),window.aipkit_chatUI_streamMessage(m,u,i,r,a.handleError,()=>a.handleCompletion(n.currentStreamMessageId,l),n.webSearchToolActive,n.googleSearchGroundingActive,p,_,k);else{let b=i.text.streamError||"Streaming function not loaded.";console.error(`AIPKit SendMessage (${u}): Required send function not available.`),a.handleError(b,!1)}}window.aipkit_chatUI_sendMessageAction=h})();(function(){"use strict";let h=new Set(["primary_color","secondary_color","auto_text_contrast","accent_color","app_bg_color","surface_color","text_color","border_color"]),o=new Set(["font_family","bubble_border_radius","container_border_radius"]),i=new Set(["container_max_width","popup_width","container_height","container_min_height","container_max_height","popup_height","popup_min_height","popup_max_height"]),n=new Set([...h,...o,...i]);function a(d,f,g){return Number.isNaN(d)?f:Math.min(Math.max(d,f),g)}function t(d){if(!d||typeof d!="string")return null;let f=d.trim().toLowerCase();if(f==="transparent")return{r:0,g:0,b:0,a:0};if(f[0]==="#"){let S=f.slice(1);if(S.length===3&&(S=S.split("").map(M=>M+M).join("")),S.length!==6)return null;let U=parseInt(S,16);return Number.isNaN(U)?null:{r:U>>16&255,g:U>>8&255,b:U&255,a:1}}let g=f.match(/^rgba?\((.+)\)$/);if(!g)return null;let I=g[1].split(",").map(S=>S.trim());if(I.length<3)return null;let b=S=>{if(S.endsWith("%")){let M=parseFloat(S);return Number.isNaN(M)?null:a(Math.round(255*M/100),0,255)}let U=parseFloat(S);return Number.isNaN(U)?null:a(Math.round(U),0,255)},y=b(I[0]),v=b(I[1]),A=b(I[2]);if(y===null||v===null||A===null)return null;let x=1;if(I[3]!==void 0){let S=parseFloat(I[3]);Number.isNaN(S)||(x=a(S,0,1))}return{r:y,g:v,b:A,a:x}}function e(d){if(!d)return"";if(typeof d=="string")return d;let f=a(Math.round(d.r),0,255),g=a(Math.round(d.g),0,255),I=a(Math.round(d.b),0,255),b=d.a===void 0?1:a(d.a,0,1);if(b>=1)return`rgb(${f}, ${g}, ${I})`;let y=Math.round(b*1e3)/1e3;return`rgba(${f}, ${g}, ${I}, ${y})`}function r(d,f,g){let I=a(g,0,1);return{r:d.r*(1-I)+f.r*I,g:d.g*(1-I)+f.g*I,b:d.b*(1-I)+f.b*I,a:1}}function s(d,f){return{r:d.r,g:d.g,b:d.b,a:a(f,0,1)}}function w(d,f){if(!d||!f)return!1;let g=d.a===void 0?1:d.a,I=f.a===void 0?1:f.a;return Math.round(d.r)===Math.round(f.r)&&Math.round(d.g)===Math.round(f.g)&&Math.round(d.b)===Math.round(f.b)&&Math.abs(g-I)<.01}function u(d){let f=d/255;return f<=.03928?f/12.92:Math.pow((f+.055)/1.055,2.4)}function _(d){return .2126*u(d.r)+.7152*u(d.g)+.0722*u(d.b)}function p(d,f){let g=_(d),I=_(f),b=Math.max(g,I),y=Math.min(g,I);return(b+.05)/(y+.05)}function c(d,f,g){let I=p(d,f),b=p(d,g);return I>=b?f:g}function m(d){let f={primary:"#0F766E",secondary:"#ECFEFF",legacyAccent:"#111111",legacyAppBg:"#FFFFFF",legacySurface:"#FFFFFF",legacyText:"#111111",legacyBorder:"#E5E5E5",botBubble:"#F3F3F3"},g={primary:t(f.primary),secondary:t(f.secondary),legacyAccent:t(f.legacyAccent),legacyAppBg:t(f.legacyAppBg),legacySurface:t(f.legacySurface),legacyText:t(f.legacyText),legacyBorder:t(f.legacyBorder),botBubble:t(f.botBubble)},I=t(d.primary_color),b=t(d.secondary_color),y=t(d.accent_color),v=t(d.app_bg_color),A=t(d.surface_color),x=y&&!w(y,g.legacyAccent),S=A&&!w(A,g.legacySurface)||v&&!w(v,g.legacyAppBg),U=null;I&&(!w(I,g.primary)||!x)?U=I:x?U=y:I?U=I:U=g.primary;let M=null;b&&(!w(b,g.secondary)||!S)?M=b:A&&!w(A,g.legacySurface)?M=A:v&&!w(v,g.legacyAppBg)?M=v:b?M=b:M=g.secondary;let F=d.auto_text_contrast!=="0",L={r:255,g:255,b:255,a:1},O={r:17,g:17,b:17,a:1},j=t(d.text_color),T=j&&!w(j,g.legacyText),C=!F&&T?j:c(M,L,O),$=_(M)<.5,P=M,q=r(P,C,$?.12:.06),W=t(d.border_color),B=W&&!w(W,g.legacyBorder)?W:r(P,C,$?.22:.12),K=r(C,P,$?.35:.18),J=r(C,P,$?.5:.35),Q=t(d.bot_bubble_bg_color)||r(q,C,$?.18:.08),E=t(d.user_bubble_bg_color)||U,N=F?c(U,L,O):C,V=F&&p(U,q)>=3?U:C,D=F?c(Q,L,O):C,G=F?c(E,L,O):C,z=r(P,C,$?.18:.08),Y=r(P,U,$?.22:.12),R=r(P,C,$?.12:.04),H=r(C,P,$?.3:.12),X=F?c(Y,L,O):C,Z=P,tt=z,at=F?c(Z,L,O):C,ct=F?c(tt,L,O):C,lt=_(U)<.5,et=r(U,lt?L:O,.12),dt=U,rt=s(U,.2),st=r(P,U,$?.2:.12),pt=s(N,.3);return{container_bg_color:e(q),container_text_color:e(C),container_border_color:e(B),border_color:e(B),bg_color_secondary:e(P),bg_color_hover:e(z),text_color_link:e(H),primary_color_dark:e(C),header_bg_color:e(P),header_text_color:e(K),header_border_color:e(B),messages_bg_color:e(q),messages_scrollbar_thumb_color:e(B),messages_scrollbar_track_color:"transparent",greeting_text_color:e(V),bot_bubble_bg_color:e(Q),bot_bubble_text_color:e(D),user_bubble_bg_color:e(E),user_bubble_text_color:e(G),subgreeting_text_color:e(K),input_area_bg_color:e(q),input_area_border_color:e(B),input_wrapper_bg_color:e(P),input_wrapper_border_color:e(B),input_text_color:e(C),input_placeholder_color:e(J),input_focus_border_color:e(U),input_focus_shadow_color:e(rt),send_button_bg_color:e(U),send_button_text_color:e(N),send_button_border_color:e(U),send_button_hover_bg_color:e(et),send_button_hover_border_color:e(et),send_button_disabled_bg_color:e(st),send_button_disabled_border_color:e(st),send_button_spinner_base_color:e(pt),send_button_spinner_accent_color:e(N),popup_trigger_bg_color:e(U),popup_trigger_hover_bg_color:e(et),popup_trigger_icon_color:e(N),action_button_bg_color:e(P),action_button_color:e(K),action_button_border_color:e(B),action_button_hover_bg_color:e(z),action_button_hover_color:e(C),action_button_hover_border_color:e(dt),mic_hover_bg_color:e(z),footer_bg_color:e(P),footer_text_color:e(K),footer_border_color:e(B),sidebar_bg_color:e(R),sidebar_text_color:e(H),sidebar_border_color:e(B),sidebar_active_bg_color:e(Y),sidebar_active_text_color:e(X),sidebar_hover_bg_color:e(z),sidebar_hover_text_color:e(C),action_menu_bg_color:e(P),action_menu_border_color:e(B),action_menu_item_text_color:e(C),action_menu_item_hover_bg_color:e(z),action_menu_item_hover_text_color:e(C),starter_bg_color:e(Z),starter_text_color:e(at),starter_border_color:e(B),starter_hover_bg_color:e(tt),starter_hover_text_color:e(ct),pdf_icon_color:e(U),image_icon_color:e(K),consent_overlay_bg_color:e(s(q,.95)),consent_overlay_border_color:e(B),consent_title_color:e(C),consent_message_color:e(K),consent_button_bg_color:e(U),consent_button_text_color:e(N),form_title_color:e(C),form_label_color:e(C),form_help_text_color:e(K),form_input_bg:e(P),form_input_text:e(C),form_input_border:e(B),form_input_focus_border:e(U),form_input_focus_shadow:e(rt),form_submit_button_bg:e(U),form_submit_button_text:e(N),form_submit_button_hover_bg:e(et)}}function l(d,f={}){let g=m(d),I=Object.assign({},g),b=!!f.skipDimensionSync;return o.forEach(y=>{let v=d[y];v!==""&&v!==null&&v!==void 0&&(I[y]=v)}),b||i.forEach(y=>{let v=d[y];v!==""&&v!==null&&v!==void 0&&(I[y]=v)}),b||(I.container_height!==""&&I.container_height!==null&&I.container_height!==void 0&&(I.popup_height=I.container_height),I.container_min_height!==""&&I.container_min_height!==null&&I.container_min_height!==void 0&&(I.popup_min_height=I.container_min_height),I.container_max_height!==""&&I.container_max_height!==null&&I.container_max_height!==void 0&&(I.popup_max_height=I.container_max_height)),I}function k(d,f,g={}){if(!d||typeof f!="object"||Object.keys(f).length===0)return;let I=l(f,g),b=v=>{if(v)for(let A in I){if(!Object.prototype.hasOwnProperty.call(I,A)||I[A]===""||I[A]===null)continue;let x=`--aipkit-chat-${A.replace(/_/g,"-")}`,S=I[A];A==="container_max_height"||A==="popup_max_height"?S=I[A]+"vh":A==="container_max_width"||A==="popup_width"||A==="container_height"||A==="container_min_height"||A==="popup_height"||A==="popup_min_height"?S=I[A]+"px":(A==="bubble_border_radius"||A==="container_border_radius")&&typeof S=="number"?S=S===0?"0":`${S}px`:(A==="bubble_border_radius"||A==="container_border_radius")&&typeof S=="string"&&/^\d+$/.test(S)&&(S=S==="0"?"0":`${S}px`),v.style.setProperty(x,S)}};b(d);let y=d.closest(".aipkit_popup_wrapper");y&&b(y)}window.aipkit_chatUI_applyCustomThemeStyles=k})();(function(){"use strict";function h(o){let n=`aipkit_chatbot_consent_given_${o.botId||"default"}`,a=localStorage.getItem(n)==="true",t=o.webToggleDefaultOn===!0,e=o.allowWebSearchTool&&(o.provider==="OpenAI"||o.provider==="Claude"||o.provider==="OpenRouter"),r=o.allowGoogleSearchGrounding&&o.provider==="Google";return{buttonState:"send",isPopupOpen:!1,isSending:!1,currentStreamId:null,isFullscreen:!1,isSidebarOpen:!1,currentStreamMessageId:null,isActionMenuOpen:!1,activeInputActionMenu:null,activeInputActionTrigger:null,closeActionMenuHandler:null,consentGiven:a,isRecording:!1,webSearchToolActive:t&&e,googleSearchGroundingActive:t&&r}}window.aipkit_chatUI_initState=h})();(function(){"use strict";function h(o,i){if(!o||!i||!i.text){console.error("AIPKit InitialMessage: Missing messagesEl or config.");return}let n=i.botId||"default";if(o.querySelectorAll(".aipkit_chat_message:not(.aipkit_initial_greeting)").forEach(t=>{try{o.removeChild(t)}catch{}}),!o.querySelector(".aipkit_initial_greeting")){let t=(i.text.initialGreeting||"Hello there!").trim(),e=(i.text.initialSubgreeting||"").trim(),r=t;if(e&&(r=t?`${t}
${e}`:e),typeof window.aipkit_chatUI_appendMessage=="function"&&typeof window.aipkit_generateClientMessageId=="function")window.aipkit_chatUI_appendMessage(o,r,"bot",i,!1,!0,window.aipkit_generateClientMessageId(n));else{console.error("AIPKit InitialMessage: appendMessage or generateClientMessageId function not found.");let s=document.createElement("div");s.className="aipkit_chat_message aipkit_chat_message-bot aipkit_initial_greeting";let w=document.createElement("div");if(w.className="aipkit_chat_bubble",t){let u=document.createElement("p");u.textContent=t,w.appendChild(u)}if(e){let u=document.createElement("p");u.textContent=e,w.appendChild(u)}w.childNodes.length||(w.textContent=r),s.appendChild(w),o.appendChild(s),typeof window.aipkit_chatUI_triggerMessageAnimation=="function"&&window.aipkit_chatUI_triggerMessageAnimation(s)}}}window.aipkit_chatUI_displayInitialMessage=h})();(function(){"use strict";function h(o,i,n,a){let{inputField:t,messagesEl:e,container:r}=o,s=i.botId,w=i.webToggleDefaultOn===!0;n.buttonState=a.setButtonStateAction("send",!1,n),typeof window.aipkit_autoResizeTextarea=="function"&&window.aipkit_autoResizeTextarea(t),i.popupEnabled||typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(e,!0),t.disabled=i.requireConsentCompliance&&!n.consentGiven,o.voiceInputButton&&(o.voiceInputButton.disabled=i.requireConsentCompliance&&!n.consentGiven),o.inputActionButton&&(o.inputActionButton.disabled=i.requireConsentCompliance&&!n.consentGiven),o.webSearchToggleButton&&i.allowWebSearchTool&&(i.provider==="OpenAI"||i.provider==="Claude"||i.provider==="OpenRouter")&&(o.webSearchToggleButton.disabled=i.requireConsentCompliance&&!n.consentGiven),o.googleSearchGroundingToggleButton&&i.allowGoogleSearchGrounding&&i.provider==="Google"&&(o.googleSearchGroundingToggleButton.disabled=i.requireConsentCompliance&&!n.consentGiven),typeof window.aipkit_syncWebSearchToggleState=="function"&&window.aipkit_syncWebSearchToggleState(o,i,n,w),typeof window.aipkit_syncGoogleSearchGroundingToggleState=="function"&&window.aipkit_syncGoogleSearchGroundingToggleState(o,i,n,w),r.dispatchEvent(new CustomEvent("aipkit:chatLoaded",{detail:{botId:s}}))}window.aipkit_chatUI_finalizeSetup=h})();(function(){"use strict";function h(i,n,a){if(!i||!n)return;let t=!!a;i.classList.toggle("aipkit-popup-open",t),i.setAttribute("aria-hidden",t?"false":"true"),n.isPopupOpen=t;let e=i.closest(".aipkit_popup_wrapper");if(!e)return;e.classList.toggle("aipkit-popup-open",t);let r=e.querySelector(".aipkit_popup_trigger");if(!r)return;r.setAttribute("aria-expanded",t?"true":"false");let s=r.getAttribute("data-label-open")||"Open Chat",w=r.getAttribute("data-label-close")||"Close Chat",u=t?w:s;r.setAttribute("aria-label",u),r.setAttribute("title",u);let _=r.querySelector(".aipkit_popup_icon--open"),p=r.querySelector(".aipkit_popup_icon--close");_&&_.setAttribute("aria-hidden",t?"true":"false"),p&&p.setAttribute("aria-hidden",t?"false":"true")}function o(i,n,a,t){if(!i||!a||!t||t.isPopupOpen)return;try{i._aipkitHint&&(typeof i._aipkitHint.handlePopupOpen=="function"?i._aipkitHint.handlePopupOpen():typeof i._aipkitHint.hideHint=="function"&&i._aipkitHint.hideHint())}catch{}h(i,t,!0),i.dispatchEvent(new CustomEvent("aipkit:popupOpened")),typeof window.aipkit_chatUI_scrollToBottom=="function"?window.aipkit_chatUI_scrollToBottom(n):console.error("AIPKit Popup Open: scrollToBottom function not found.");let e=i.closest("#aipkit_admin_chat_preview_container");(!(window.innerWidth<=768)||e)&&setTimeout(()=>{a&&typeof a.focus=="function"&&a.focus()},50)}window.aipkit_chatUI_setPopupLauncherState=h,window.aipkit_chatUI_openPopup=o})();(function(){"use strict";function h(o,i){if(!o||!i||!i.isPopupOpen)return;if(typeof window.aipkit_chatUI_setPopupLauncherState=="function"){window.aipkit_chatUI_setPopupLauncherState(o,i,!1);return}o.classList.remove("aipkit-popup-open"),o.setAttribute("aria-hidden","true"),i.isPopupOpen=!1;let n=o.closest(".aipkit_popup_wrapper");n&&n.classList.remove("aipkit-popup-open")}window.aipkit_chatUI_closePopup=h})();(function(){"use strict";function h(o,i,n,a,t,e){if(!o||!i||!t||!e){console.warn("AIPKit Chat Popup Handlers: Missing elements for setup (container, trigger, stateRef, or config).");return}let r=!!o.closest("#aipkit_admin_chat_preview_container");try{let u=o.closest(".aipkit_popup_wrapper"),_=u?u.querySelector(".aipkit_popup_hint"):null,p=768,c=()=>window.innerWidth<=p,m=e.popupLabelVersion&&String(e.popupLabelVersion).trim()||"v1",l=`aipkit_popup_hint_seen_${e.botId}_${m}`,k=`aipkit_popup_hint_dismissed_${e.botId}_${m}`,f=["always","once_per_session","once_per_visitor"].includes(e.popupLabelFrequency)?e.popupLabelFrequency:"once_per_visitor",g=r?"always":f,b=["always","on_delay","until_open","until_dismissed"].includes(e.popupLabelMode)?e.popupLabelMode:"on_delay",y=(e.popupLabelDelaySeconds>0?e.popupLabelDelaySeconds:0)*1e3,v=(e.popupLabelAutoHideSeconds>0?e.popupLabelAutoHideSeconds:0)*1e3,A=!!e.popupLabelDismissible,x=g==="always"?null:g==="once_per_session"?window.sessionStorage:window.localStorage,S=E=>{if(!x)return null;try{return x.getItem(E)}catch{return null}},U=(E,N)=>{if(x)try{x.setItem(E,N)}catch{}},M=!1,F=!1,L=()=>M||S(l)==="1",O=()=>F||S(k)==="1",j=()=>b==="until_dismissed"?!O():b==="until_open"?!L():g==="always"?!0:!L(),T=()=>{M=!0,U(l,"1")},C=()=>{F=!0,U(k,"1")},$=null,P=null,q=()=>{$&&(clearTimeout($),$=null)},W=()=>{P&&(clearTimeout(P),P=null)},it=()=>{_&&(_.removeAttribute("hidden"),_.classList.add("aipkit-visible"),_.setAttribute("aria-hidden","false"),(b==="on_delay"||b==="always")&&T(),v>0&&(W(),P=setTimeout(B,v)))},B=()=>{_&&(_.classList.remove("aipkit-visible"),_.setAttribute("aria-hidden","true"),_.setAttribute("hidden",""),W())},K=()=>{let E=c();return!(E&&!e.popupLabelShowOnMobile||!E&&!e.popupLabelShowOnDesktop)},J=()=>{if(!_||!e.popupLabelEnabled||!e.popupLabelText||t.isPopupOpen||!K()||!j())return;q();let E=b==="always"?0:y;if(E<=0){it();return}$=setTimeout(it,E)},ot=()=>{q(),B(),b==="until_open"&&T()},Q=()=>{J()},nt=()=>{q(),B(),b==="until_dismissed"?C():g!=="always"&&T()};if(_&&A){let E=_.querySelector(".aipkit_popup_hint_close");E&&E.addEventListener("click",N=>{N.stopPropagation(),nt()})}if(_)try{let E=window.getComputedStyle(o),N=o.querySelector(".aipkit_chat_header"),V=N?window.getComputedStyle(N):null,D="",G="";if(V){let H=V.getPropertyValue("background-color").trim(),X=V.getPropertyValue("color").trim();H&&(D=H),X&&(G=X)}D||(D=E.getPropertyValue("--aipkit-chat-header-bg-color").trim()),D||(D=E.getPropertyValue("--aipkit_brand-primary").trim()),D||(D="#4a6fa5"),G||(G=E.getPropertyValue("--aipkit-chat-header-text-color").trim()),G||(G="#ffffff");let z=u||o;D&&z.style.setProperty("--aipkit-chat-popup-hint-bg",D);let Y=E.getPropertyValue("--aipkit-chat-bot-bubble-text-color").trim(),R="";if(Y)R=Y;else if(G)R=G;else if(D){let H=D.match(/rgba?\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})/i);if(H){let X=parseInt(H[1],10),Z=parseInt(H[2],10),tt=parseInt(H[3],10);R=(X*299+Z*587+tt*114)/1e3>200?"#2d3748":"#ffffff"}else R="#2d3748"}else R="#2d3748";R&&z.style.setProperty("--aipkit-chat-popup-hint-text-color",R)}catch{}B(),J(),o._aipkitHint={scheduleShow:J,hideHint:B,markSeen:T,markDismissed:C,handlePopupOpen:ot,handlePopupClose:Q,dismissHintFromUser:nt,isDismissible:A,isVisible:()=>!!(_&&_.classList.contains("aipkit-visible"))}}catch(u){console.warn("AIPKit Popup Hint: setup error",u)}if(typeof window.aipkit_chatUI_openPopup!="function"||typeof window.aipkit_chatUI_closePopup!="function"){console.error("AIPKit Chat Popup Handlers: Missing openPopup or closePopup helper functions.");return}typeof window.aipkit_chatUI_setPopupLauncherState=="function"&&window.aipkit_chatUI_setPopupLauncherState(o,t,!!t.isPopupOpen);let s=(u=!1)=>{window.aipkit_chatUI_closePopup(o,t),u&&typeof i.focus=="function"?i.focus():typeof i.blur=="function"&&i.blur(),o._aipkitHint&&typeof o._aipkitHint.handlePopupClose=="function"&&o._aipkitHint.handlePopupClose()};document.addEventListener("keydown",u=>{if(u.key==="Escape"){if(t.isPopupOpen){s(!0);return}!o._aipkitHint||!o._aipkitHint.isDismissible||o._aipkitHint.isVisible?.()&&(o._aipkitHint.dismissHintFromUser?.(),typeof i.focus=="function"&&i.focus())}});let w=o.querySelector(".aipkit_popup_close_btn");w&&w.addEventListener("click",u=>{u.stopPropagation(),t.isPopupOpen&&s()}),!e.directVoiceMode&&(i.addEventListener("click",u=>{u.stopPropagation(),t.isPopupOpen?s(!1):window.aipkit_chatUI_openPopup(o,n,a,t)}),document.addEventListener("click",u=>{t.isPopupOpen&&(r||o.contains(u.target)||i.contains(u.target)||s(!1))},!0))}window.aipkit_chatUI_setupPopupHandlers=h})();(function(){"use strict";function h(o,i){let n=new Date,a=`${n.getFullYear()}${String(n.getMonth()+1).padStart(2,"0")}${String(n.getDate()).padStart(2,"0")}-${String(n.getHours()).padStart(2,"0")}${String(n.getMinutes()).padStart(2,"0")}`;return`chat-${o.botId||"transcript"}-${a}.${i}`}window.aipkit_chatUI_generateDownloadFilename=h})();(function(){"use strict";function h(o,i){let n=document.createElement("a");if(typeof n.download=="string")n.href=URL.createObjectURL(o),n.download=i,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(n.href);else{console.warn("AIPKit Chat Download: Download attribute not supported, opening in new window.");let a=URL.createObjectURL(o);window.open(a,"_blank")}}window.aipkit_chatUI_triggerBlobDownload=h})();(function(){"use strict";function h(p,c){return String(c||"").split(`
`).map(m=>m?`${p}${m}`:p.trimEnd()).join(`
`)}function o(p){return String(p||"").replace(/\s+/g," ")}function i(p){return p.endsWith(`
`)?p:p.endsWith(`
`)?p+`
`:p+`
`}function n(p,c){let m="";return p.childNodes.forEach(l=>{m+=e(l,c)}),m}function a(p,c,m){let l=Array.from(p.children).filter(d=>d.tagName==="LI");return l.length?`${l.map((d,f)=>{let g=m?`${f+1}. `:"- ",I=n(d,c).trim().replace(/\n{3,}/g,`
`);return h(" ".repeat(g.length),`${g}${I}`).trimEnd()}).join(`
`)}
`:""}function t(p,c){let m=Array.from(p.querySelectorAll("tr"));if(!m.length)return"";let l=m.map(k=>Array.from(k.querySelectorAll("th, td")).map(f=>o(n(f,c).trim())).filter(Boolean).join(" | ")).filter(Boolean);return l.length?`${l.join(`
`)}
`:""}function e(p,c){if(!p)return"";if(p.nodeType===Node.TEXT_NODE)return c.preserveWhitespace?String(p.textContent||""):o(p.textContent||"");if(p.nodeType!==Node.ELEMENT_NODE)return"";let m=p.tagName.toUpperCase();if(m==="BR")return`
`;if(m==="IMG"){let k=o(p.getAttribute("alt")||"").trim();return k?`[Image: ${k}]`:"[Image]"}if(m==="A"){let k=o(n(p,c)).trim(),d=String(p.getAttribute("href")||"").trim();return d?!k||k===d?d:`${k} (${d})`:k}if(m==="HR")return`
---
`;if(m==="PRE"){let k=String(p.textContent||"").replace(/\s+$/,"");return k?`\`\`\`
${k}
\`\`\`
`:""}if(m==="CODE"){if(p.closest("pre"))return String(p.textContent||"");let k=o(p.textContent||"").trim();return k?`\`${k}\``:""}if(m==="BLOCKQUOTE"){let k=n(p,c).trim().replace(/\n{3,}/g,`
`);return k?`${h("> ",k)}
`:""}if(m==="UL")return a(p,c,!1);if(m==="OL")return a(p,c,!0);if(m==="TABLE")return t(p,c);if(/^H[1-6]$/.test(m)){let k=parseInt(m.slice(1),10),d=o(n(p,c)).trim();return d?`${"#".repeat(k)} ${d}
`:""}let l=n(p,c);return m==="P"||m==="DIV"?(l=l.trim(),l?`${l}
`:""):l}function r(p){return String(p||"").replace(/[ \t]+\n/g,`
`).replace(/\n{3,}/g,`
`).trim()}function s(p,c){let m=c&&c.text?c.text:{},l=c?.headerName||"Bot";return p.classList.contains("aipkit_chat_message-error")?{role:"error",label:m.errorPrefix||"Error"}:p.classList.contains("aipkit_chat_message-user")?{role:"user",label:m.userPrefix||"User"}:{role:"bot",label:l}}function w(){try{return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date)}catch{return new Date().toLocaleString()}}function u(p,c){if(!p)return[];let m=[];return p.querySelectorAll(".aipkit_chat_message").forEach(k=>{if(k.classList.contains("aipkit_typing-indicator"))return;let d=k.querySelector(".aipkit_chat_bubble");if(!d)return;let f=r(n(d,{preserveWhitespace:!1}));if(!f)return;let g=s(k,c);m.push({role:g.role,label:g.label,text:f})}),m}function _(p,c){let m=u(p,c);return{title:"Chat Transcript",botName:c?.headerName||"Bot",exportedAt:w(),entries:m}}window.aipkit_chatUI_collectTranscriptEntries=u,window.aipkit_chatUI_buildTranscriptDocument=_})();(function(){"use strict";function h(n,a){return String(n||"").split(`
`).map(t=>t?`${a}${t}`:"").join(`
`)}function o(n){let a="=".repeat(72),t="-".repeat(72),e=[n.title||"Chat Transcript",`Bot: ${n.botName||"Bot"}`,`Exported: ${n.exportedAt||""}`,a,""];return n.entries.forEach((r,s)=>{e.push(`[${s+1}] ${r.label}`),e.push(t),e.push(h(r.text,"  ")),e.push("")}),e.join(`
`).replace(/\n{3,}/g,`
`).trim()}function i(n,a){let{messagesEl:t}=n,e=(_,p="info",c=!0,m=4500)=>{typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice(_,p,{elements:n,config:a,messagesEl:t},c,m)};if(!t||!a||!a.text){console.error("AIPKit Download TXT: Missing messages element or config.");return}if(typeof window.aipkit_chatUI_buildTranscriptDocument!="function"){console.error("AIPKit Download TXT: Transcript export helper not found."),e(a.text?.downloadPrepareError||"Error: Could not prepare download.","error",!0,7e3);return}let r=window.aipkit_chatUI_buildTranscriptDocument(t,a);if(!r.entries.length){console.warn("AIPKit Chat Download TXT: No transcript content found."),e(a.text.downloadEmpty||"Nothing to download.","info",!0);return}let s=o(r);if(!s){console.warn("AIPKit Chat Download TXT: Transcript formatting produced empty output."),e(a.text.downloadEmpty||"Nothing to download.","info",!0);return}let w=new Blob([s],{type:"text/plain;charset=utf-8"});if(typeof window.aipkit_chatUI_generateDownloadFilename!="function"||typeof window.aipkit_chatUI_triggerBlobDownload!="function"){console.error("AIPKit Download TXT: generateDownloadFilename or triggerBlobDownload function not found."),e(a.text?.downloadPrepareError||"Error: Could not prepare download.","error",!0,7e3);return}let u=window.aipkit_chatUI_generateDownloadFilename(a,"txt");window.aipkit_chatUI_triggerBlobDownload(w,u)}window.aipkit_chatUI_downloadTranscriptActionTxt=i})();(function(){"use strict";function h(o){if(!o)return"";let i="",n=o.childNodes;function a(t){if(t.nodeType===Node.TEXT_NODE)return t.textContent;if(t.nodeName==="BR")return`
`;if(t.nodeType===Node.ELEMENT_NODE){let e="";return["P","UL","OL","H1","H2","H3","H4","H5","H6","PRE","BLOCKQUOTE","HR","DIV"].includes(t.tagName)&&(e+=`
`),t.tagName==="LI"&&(e+="- "),t.childNodes.forEach(r=>{e+=a(r)}),["P","UL","OL","H1","H2","H3","H4","H5","H6","PRE","BLOCKQUOTE","HR","DIV","LI"].includes(t.tagName)&&(e+=`
`),e}return""}return n.forEach(t=>{i+=a(t)}),i.replace(/\n\s*\n/g,`
`).replace(/^\s+|\s+$/g,"")}window.aipkit_chatUI_extractTextFromBubble=h})();(function(){"use strict";function h(o,i=1500){let n=o;if(!n){console.warn("AIPKit showSuccessIcon: Button element not found:",o);return}n.dataset.originalIconHtml||(n.dataset.originalIconHtml=n.innerHTML);let a='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-check"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 12l5 5l10 -10" /></svg>';if(o.dataset.successTimeoutId||o.disabled)return;n.innerHTML=a;let t=n.querySelector("svg");t&&(t.style.color="var(--aipkit_status-success, #38A169)"),o.dataset.successTimeoutId&&clearTimeout(parseInt(o.dataset.successTimeoutId,10));let e=setTimeout(()=>{let r=n.dataset.originalIconHtml;r&&(n.innerHTML=r),delete n.dataset.originalIconHtml,delete o.dataset.successTimeoutId},i);o.dataset.successTimeoutId=e.toString()}window.aipkit_chatUI_showSuccessIcon=h})();(function(){"use strict";function h(o,i){let n=o.target.closest(".aipkit_copy_btn");if(!n||n.disabled||n.dataset.successTimeoutId)return;let a=n.closest(".aipkit_chat_message"),t=a?a.querySelector(".aipkit_chat_bubble"):null;if(!a||!t){console.error("AIPKit Message Actions: Could not find parent message container or bubble for copy button.");return}if(typeof window.aipkit_chatUI_extractTextFromBubble!="function"||typeof window.aipkit_chatUI_showSuccessIcon!="function"){console.error("AIPKit Copy Action: Missing required helper functions (extractTextFromBubble or showSuccessIcon).");return}let e=window.aipkit_chatUI_extractTextFromBubble(t);if(!e){console.warn("AIPKit Copy Action: No text extracted from bubble to copy.");return}if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function")navigator.clipboard.writeText(e).then(()=>{window.aipkit_chatUI_showSuccessIcon(n)}).catch(r=>{console.error("AIPKit Message Actions: Clipboard API failed:",r)});else{console.warn("AIPKit Message Actions: Using fallback copy method.");try{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.top="-9999px",r.style.left="-9999px",r.style.opacity="0",document.body.appendChild(r),r.focus(),r.select();let s=document.execCommand ("copy");if(document.body.removeChild(r),s)window.aipkit_chatUI_showSuccessIcon(n);else throw new Error("execCommand failed")}catch(r){console.error("AIPKit Message Actions: Fallback copy method failed:",r)}}}window.aipkit_chatUI_handleCopyAction=h})();(function(){"use strict";function h(o,i){let n=o.target.closest(".aipkit_feedback_btn");if(!n||n.disabled||n.classList.contains("aipkit_feedback_selected"))return;let a=n.getAttribute("data-feedback"),t=n.closest(".aipkit_chat_message"),e=t?t.getAttribute("data-message-id"):null,r=n.closest(".aipkit_message_actions");if(!e||!a||!r){console.error("AIPKit Feedback: Missing message ID, feedback type, or actions container.");return}let s=r.querySelectorAll(".aipkit_feedback_btn");if(s.forEach(u=>{u.disabled=!0,u===n?u.classList.add("aipkit_feedback_selected"):(u.classList.remove("aipkit_feedback_selected"),u.style.opacity="0.4")}),typeof window.aipkit_frontendApiRequest!="function"){console.error("AIPKit Feedback Error: aipkit_frontendApiRequest function not found."),s.forEach(u=>{u.disabled=!1,u.classList.remove("aipkit_feedback_selected"),u.style.opacity="1"});return}let w={message_id:e,feedback_type:a};window.aipkit_frontendApiRequest("aipkit_store_feedback",w,i).then(u=>{console.log(`AIPKit Feedback (${i.botId}): Feedback stored successfully for ${e}.`,u)}).catch(u=>{console.error(`AIPKit Feedback (${i.botId}): Error storing feedback for ${e}:`,u),s.forEach(_=>{_.disabled=!1,_.classList.remove("aipkit_feedback_selected"),_.style.opacity="1"})})}window.aipkit_chatUI_handleFeedbackAction=h})();(function(){"use strict";function h(o){let i='<svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-player-play"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 4v16l13 -8z" /></svg>',n='<svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-copy"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z" /><path d="M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1" /></svg>',a='<svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-thumb-up"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 11v8a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1v-7a1 1 0 0 1 1 -1h3a4 4 0 0 0 4 -4v-1a2 2 0 0 1 4 0v5h3a2 2 0 0 1 2 2l-1 5a2 3 0 0 1 -2 2h-7a3 3 0 0 1 -3 -3" /></svg>',t='<svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-thumb-down"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 13v-8a1 1 0 0 0 -1 -1h-2a1 1 0 0 0 -1 1v7a1 1 0 0 0 1 1h3a4 4 0 0 1 4 4v1a2 2 0 0 0 4 0v-5h3a2 2 0 0 0 2 -2l-1 -5a2 3 0 0 0 -2 -2h-7a3 3 0 0 0 -3 3" /></svg>',e="",r=o.text||{};if(o.ttsEnabled){let s=r.playActionLabel||"Play audio";e+=`<button type="button" class="aipkit_action_btn aipkit_play_btn" title="${s}" aria-label="${s}">${i}</button>`}if(o.enableCopyButton){let s=r.copyActionLabel||"Copy response";e+=`<button type="button" class="aipkit_action_btn aipkit_copy_btn" title="${s}" aria-label="${s}">${n}</button>`}if(o.enableFeedback){let s=r.feedbackLikeLabel||"Like response",w=r.feedbackDislikeLabel||"Dislike response";e+=`<button type="button" class="aipkit_action_btn aipkit_feedback_btn aipkit_thumb_up_btn" title="${s}" aria-label="${s}" data-feedback="up">${a}</button>`,e+=`<button type="button" class="aipkit_action_btn aipkit_feedback_btn aipkit_thumb_down_btn" title="${w}" aria-label="${w}" data-feedback="down">${t}</button>`}return e?`<div class="aipkit_message_actions">${e}</div>`:""}window.aipkit_chatUI_createActionsContainerHTML=h})();(function(){"use strict";function h(o,i){if(!o){console.error("AIPKit Init Message Actions: Messages container element not provided.");return}o.dataset.aipkitMessageActionsListenerAttached!=="true"&&(o.dataset.aipkitMessageActionsListenerAttached="true",o.addEventListener("click",function(n){if(n.target.closest(".aipkit_copy_btn")){typeof window.aipkit_chatUI_handleCopyAction=="function"?window.aipkit_chatUI_handleCopyAction(n,i):console.error("AIPKit Init Message Actions: handleCopyAction function not found.");return}if(n.target.closest(".aipkit_feedback_btn")){typeof window.aipkit_chatUI_handleFeedbackAction=="function"?window.aipkit_chatUI_handleFeedbackAction(n,i):console.error("AIPKit Init Message Actions: handleFeedbackAction function not found.");return}}))}window.aipkit_chatUI_initMessageActions=h})();(function(){"use strict";function h(o,i,n,a,t){return new Promise((e,r)=>{if(!i.ajaxUrl)return r(new Error("Missing ajaxUrl in config for SSE cache."));if(!i.nonce)return r(new Error("Missing nonce in config for SSE cache."));let s=new FormData;s.append("action","aipkit_cache_sse_message"),s.append("message",o),s.append("_ajax_nonce",i.nonce),i.botId&&s.append("bot_id",i.botId),n&&s.append("image_inputs",JSON.stringify([n])),t&&s.append("user_client_message_id",t);let w=a;if(!w&&window.aipkit_current_conversation_uuid)try{let p=localStorage.getItem(`aipkit_file_context_${window.aipkit_current_conversation_uuid}`);p&&(w=JSON.parse(p))}catch(p){console.error("CacheSSE: Error reading file context from localStorage:",p)}w&&(w.provider==="OpenAI"&&w.vector_store_id&&s.append("active_openai_vs_id",w.vector_store_id),w.provider==="Pinecone"&&w.index_name&&w.namespace&&(s.append("active_pinecone_index_name",w.index_name),s.append("active_pinecone_namespace",w.namespace)),w.provider==="Qdrant"&&w.collection_name&&w.file_upload_context_id&&(s.append("active_qdrant_collection_name",w.collection_name),s.append("active_qdrant_file_upload_context_id",w.file_upload_context_id)),w.provider==="Claude"&&w.file_id&&s.append("active_claude_file_id",w.file_id));let u=()=>fetch(i.ajaxUrl,{method:"POST",body:s}).then(p=>p.ok?p.json():p.text().then(c=>{try{let m=JSON.parse(c);if(m?.data?.code==="embed_not_available")throw new Error("The embed feature is not available with your current plan. Please upgrade to use embedded chatbots.");if(m?.data?.code==="cors_denied")throw new Error("This domain is not permitted to access the chatbot. Please check your embed settings.");if(m?.data?.code==="nonce_failure_cache_sse")return _(i).then(()=>(s.set&&s.set("_ajax_nonce",i.nonce),fetch(i.ajaxUrl,{method:"POST",body:s}))).then(l=>l.ok?l.json():l.text().then(k=>{throw new Error(k||`HTTP error ${l.status} caching message.`)}));throw new Error(m?.data?.message||`HTTP error ${p.status} caching message.`)}catch{if(p.status===403)return _(i).then(()=>(s.set&&s.set("_ajax_nonce",i.nonce),fetch(i.ajaxUrl,{method:"POST",body:s}))).then(l=>l.ok?l.json():l.text().then(k=>{throw new Error(k||`HTTP error ${l.status} caching message.`)}));throw new Error(`Failed to prepare message for streaming. Please check your internet connection and try again. (HTTP ${p.status})`)}})).then(p=>{p.success&&p.data?.cache_key?e(p.data.cache_key):r(new Error(p.data?.message||"Failed to cache message for streaming."))}).catch(p=>{console.error("AIPKit SSE Cache Request Error:",p),r(p)});function _(p){return new Promise((c,m)=>{try{if(!p||!p.ajaxUrl)return m(new Error("No ajaxUrl for nonce refresh"));let l=new FormData;l.append("action",typeof window.aipkit_getChatNonceAction=="string"&&window.aipkit_getChatNonceAction?window.aipkit_getChatNonceAction:"aipkit_get_frontend_chat_nonce"),p.botId&&l.append("bot_id",p.botId),fetch(p.ajaxUrl,{method:"POST",body:l,credentials:"same-origin"}).then(k=>k.json()).then(k=>{k&&k.success&&k.data&&k.data.nonce?(p.nonce=k.data.nonce,c(k.data.nonce)):m(new Error("Nonce refresh failed"))}).catch(()=>m(new Error("Nonce refresh network error")))}catch(l){m(l)}})}u()})}window.aipkit_chatUI_cacheSseMessage=h})();(function(){"use strict";function h(o,i,n,a,t,e,r,s,w,u){if(!n.ajaxUrl||!n.nonce)return new Error("Missing ajaxUrl or nonce in config for EventSource.");let _=new URL(n.ajaxUrl);_.searchParams.append("action","aipkit_frontend_chat_stream"),_.searchParams.append("cache_key",o),_.searchParams.append("bot_id",i),_.searchParams.append("session_id",a||""),_.searchParams.append("conversation_uuid",t),e>0&&_.searchParams.append("post_id",e);try{_.searchParams.append("_ts",Date.now().toString())}catch{}n.provider==="OpenAI"&&n.enableOpenAIConversationState&&r&&_.searchParams.append("previous_openai_response_id",r),s&&n.allowWebSearchTool&&(n.provider==="OpenAI"||n.provider==="Claude"||n.provider==="OpenRouter")&&_.searchParams.append("frontend_web_search_active","true"),w&&n.provider==="Google"&&n.allowGoogleSearchGrounding&&_.searchParams.append("frontend_google_search_grounding_active","true"),u&&(u.provider==="OpenAI"&&u.vector_store_id&&_.searchParams.append("active_openai_vs_id",u.vector_store_id),u.provider==="Pinecone"&&u.index_name&&u.namespace&&(_.searchParams.append("active_pinecone_index_name",u.index_name),_.searchParams.append("active_pinecone_namespace",u.namespace)),u.provider==="Qdrant"&&u.collection_name&&u.file_upload_context_id&&(_.searchParams.append("active_qdrant_collection_name",u.collection_name),_.searchParams.append("active_qdrant_file_upload_context_id",u.file_upload_context_id)),u.provider==="Claude"&&u.file_id&&_.searchParams.append("active_claude_file_id",u.file_id)),_.searchParams.append("_ajax_nonce",n.nonce);try{return new EventSource(_.toString())}catch(p){return console.error(`[AIPKit Stream CreateEventSource (${i})] Failed to create EventSource instance:`,p),p}}window.aipkit_chatUI_createEventSource=h})();(function(){"use strict";function h(o,i,n,a){try{let t=JSON.parse(o.data),e=t.message_id;if(e){if(n.currentStreamMessageId&&n.currentStreamMessageId!==e&&a){let r=a.querySelector(`#${CSS.escape(n.currentStreamMessageId)}`);if(r){let s=r.querySelector(".aipkit_chat_bubble");if(s){let w=s.querySelector(".aipkit_stream_indicator");w&&w.parentNode&&w.parentNode.removeChild(w)}r.classList.remove("aipkit_message_streaming"),r.classList.add("aipkit_message_complete")}}n.currentStreamMessageId=e}i.provider==="OpenAI"&&i.enableOpenAIConversationState&&t.openai_response_id&&(window.aipkit_current_openai_response_id=t.openai_response_id,sessionStorage.setItem("aipkit_current_openai_response_id",t.openai_response_id))}catch(t){console.error("[AIPKit Stream HandleMessageStart] Error parsing message_start data:",o.data,t)}}window.aipkit_chatUI_handleMessageStartEvent=h})();(function(){"use strict";function h(o,i){try{let n=JSON.parse(o.data);i.provider==="OpenAI"&&i.enableOpenAIConversationState&&n.id&&(window.aipkit_current_openai_response_id=n.id,sessionStorage.setItem("aipkit_current_openai_response_id",n.id))}catch(n){console.error("[AIPKit Stream HandleOpenAIResponseId] Error parsing data:",o.data,n)}}window.aipkit_chatUI_handleOpenAIResponseIdEvent=h})();(function(){"use strict";function h(o,i){try{let n=JSON.parse(o.data);i.accumulatedGroundingMetadata=n}catch(n){console.error("[AIPKit Stream HandleGroundingMetadata] Error parsing data:",o.data,n)}}window.aipkit_chatUI_handleGroundingMetadataEvent=h})();(function(){"use strict";function h(a,t){let e=typeof a=="string"?a.trim().toLowerCase():"";return e===""?!1:[t.statusProcessing,t.streaming,"processing","processing...","streaming","streaming..."].filter(s=>typeof s=="string"&&s.trim()!=="").map(s=>s.trim().toLowerCase()).includes(e)}function o(a,t){let e=t&&t.text?t.text:{};if(typeof a?.text=="string"&&a.text.trim()!=="")return h(a.text,e)?"":a.text.trim();if(typeof a?.label=="string"&&a.label.trim()!=="")return h(a.label,e)?"":a.label.trim();let r=String(a?.type||"").toLowerCase(),s=String(a?.content_block_type||"").toLowerCase(),w=String(a?.name||"").toLowerCase();return r.includes("web_search")||s.includes("web_search")||w.includes("web_search")?e.statusSearchingWeb||"Searching web...":r.includes("file_search")||s.includes("file_search")||w.includes("file_search")?e.statusRetrievingContext||"":r.includes("tool")||r.includes("function_call")||r.includes("image_generation_call")||s==="tool_use"||s==="server_tool_use"||a?.tool_use_id?e.statusCallingTool||"Calling tool...":""}function i(a,t,e){if(!a)return null;if(t.currentStreamMessageId){let s=a.querySelector(`#${CSS.escape(t.currentStreamMessageId)}`);if(s)return s}let r=`aipkit-typing-indicator-${e}`;return a.querySelector(`#${CSS.escape(r)}`)}function n(a,t,e,r,s){if(!(s&&s.dataReceived))try{let w=JSON.parse(a.data),u=o(w,e);if(u==="")return;s.currentStatusText=u;let _=i(r,s,t);_&&typeof window.aipkit_chatUI_upsertMessageMeta=="function"&&window.aipkit_chatUI_upsertMessageMeta(_,{statusText:u},e)}catch(w){console.error(`[AIPKit Stream HandleStatus (${t})] Error parsing status data:`,a.data,w)}}window.aipkit_chatUI_handleStatusEvent=n})();(function(){"use strict";function h(o,i,n,a,t){try{let e=JSON.parse(o.data),r=Array.isArray(e)?e:[e],s=typeof window.aipkit_chatUI_normalizeCitations=="function"?window.aipkit_chatUI_normalizeCitations:w=>w;t.accumulatedCitations=s((t.accumulatedCitations||[]).concat(r))}catch(e){console.error(`[AIPKit Stream HandleCitations (${i})] Error parsing citations data:`,o.data,e)}}window.aipkit_chatUI_handleCitationsEvent=h})();(function(){"use strict";function h(i,n,a){let t=typeof window.aipkit_getMarkdownRenderer=="function"?window.aipkit_getMarkdownRenderer():window.aipkit_md;i.setAttribute("data-raw-text",n),t&&typeof t.render=="function"?(i.innerHTML=t.render(n),typeof window.aipkit_chatUI_attachCodeCopyButtons=="function"&&window.aipkit_chatUI_attachCodeCopyButtons(i,a)):i.innerHTML=String(n||"").replace(/\n/g,"<br>"),t&&t.aipkitIsFallback&&typeof window.aipkit_ensureMarkdownParser=="function"&&i.dataset.aipkitMarkdownUpgradePending!=="1"&&(i.dataset.aipkitMarkdownUpgradePending="1",window.aipkit_ensureMarkdownParser().then(function(e){if(delete i.dataset.aipkitMarkdownUpgradePending,!i.isConnected||!e||e.aipkitIsFallback)return;let r=i.dataset.aipkitFullContent||i.getAttribute("data-raw-text")||n;i.innerHTML=e.render(r),typeof window.aipkit_chatUI_attachCodeCopyButtons=="function"&&window.aipkit_chatUI_attachCodeCopyButtons(i,a)}))}function o(i,n,a,t,e){try{let r=JSON.parse(i.data),s=r.delta;if(s!==void 0&&e.currentStreamMessageId)if(e.dataReceived)window.aipkit_chatUI_appendOrUpdateMessage(t,e.currentStreamMessageId,s,"bot",a,!1,!1,null),window.aipkit_chatUI_scrollToBottom(t,!0);else{e.dataReceived=!0,e.currentStatusText=null;let w=`aipkit-typing-indicator-${n}`,u=t.querySelector(`#${CSS.escape(w)}`);if(u){let _=u.querySelector(".aipkit_chat_bubble");if(_){u.id=e.currentStreamMessageId,u.setAttribute("data-message-id",e.currentStreamMessageId),u.classList.remove("aipkit_typing-indicator"),typeof window.aipkit_chatUI_upsertMessageMeta=="function"&&window.aipkit_chatUI_upsertMessageMeta(u,{statusText:null},a),_.dataset.aipkitFullContent=s,h(_,s,a),typeof window.positionStreamingIndicator=="function"&&window.positionStreamingIndicator(_,"aipkit_stream_indicator");let p=typeof window.aipkit_chatUI_createActionsContainerHTML=="function"?window.aipkit_chatUI_createActionsContainerHTML(a):"";p&&!u.querySelector(".aipkit_message_actions")&&(u.insertAdjacentHTML("beforeend",p),u.classList.add("aipkit_has_message_actions")),window.aipkit_chatUI_scrollToBottom(t,!0)}else window.aipkit_chatUI_removeTypingIndicator(t,u),window.aipkit_chatUI_appendOrUpdateMessage(t,e.currentStreamMessageId,s,"bot",a,!1,!1,null),window.aipkit_chatUI_scrollToBottom(t,!0)}else window.aipkit_chatUI_appendOrUpdateMessage(t,e.currentStreamMessageId,s,"bot",a,!1,!1,null),window.aipkit_chatUI_scrollToBottom(t,!0)}else console.warn(`[AIPKit Stream OnMessage (${n})] Received message without delta or missing message ID:`,r)}catch(r){console.error(`[AIPKit Stream OnMessage (${n})] Error parsing message data:`,i.data,r)}}window.aipkit_chatUI_handleOnMessageEvent=o})();(function(){"use strict";function h(o,i,n,a,t,e,r){try{let s=JSON.parse(o.data);if(!r.accumulatedGroundingMetadata&&s&&s.grounding_metadata&&(r.accumulatedGroundingMetadata=s.grounding_metadata),s&&Array.isArray(s.citations)&&s.citations.length){let w=typeof window.aipkit_chatUI_normalizeCitations=="function"?window.aipkit_chatUI_normalizeCitations:u=>u;r.accumulatedCitations=w((r.accumulatedCitations||[]).concat(s.citations))}}catch{}typeof window.aipkit_chatUI_appendOrUpdateMessage=="function"&&r.currentStreamMessageId&&window.aipkit_chatUI_appendOrUpdateMessage(a,r.currentStreamMessageId,"","bot",n,!0,!1,r.accumulatedGroundingMetadata,r.accumulatedCitations||null),typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(a,!0),typeof t=="function"&&t(),e.current&&(e.current.close(),e.current=null)}window.aipkit_chatUI_handleDoneEvent=h})();(function(){"use strict";function h(o,i,n,a,t){console.warn(`[AIPKit Stream HandleWarning (${i})] Received 'warning' event:`,o.data),t.dataReceived||(t.dataReceived=!0);try{let e=JSON.parse(o.data);e.error&&t.currentStreamMessageId&&typeof window.aipkit_chatUI_appendOrUpdateMessage=="function"&&(window.aipkit_chatUI_appendOrUpdateMessage(a,t.currentStreamMessageId,`
*${e.error}*`,"bot",n,!1,!0,null),window.aipkit_chatUI_scrollToBottom(a,!0))}catch(e){console.error(`[AIPKit Stream HandleWarning (${i})] Error parsing warning data:`,o.data,e)}}window.aipkit_chatUI_handleWarningEvent=h})();(function(){"use strict";function h(o,i,n,a,t,e,r){window.aipkit_chatUI_removeTypingIndicator(a);let s=n.text||{};console.error(`[AIPKit Stream HandleError (${i})] EventSource error.`,o);let w=null;if(o.data)try{let _=JSON.parse(o.data);_.error&&(w=_.error)}catch{typeof o.data=="string"&&o.data.length>0&&o.data.length<200&&(w=o.data)}else o.target&&o.target.readyState===EventSource.CLOSED?w="Connection was closed.":o.message&&(w=o.message);let u="";w?u=`${s.errorPrefix||"Error:"} ${w}`:u=r.dataReceived?s.streamError||"Stream error. Please try again.":s.connError||"Connection error. Please check setup or try again.",typeof t=="function"&&t(u,!1,!0),r.currentStreamMessageId=null,e.current&&(e.current.close(),e.current=null)}window.aipkit_chatUI_handleErrorEvent=h})();(function(){"use strict";function h(o,i,n,a,t){typeof window.aipkit_chatUI_removeTypingIndicator=="function"&&window.aipkit_chatUI_removeTypingIndicator(a);try{let r=JSON.parse(o.data).form_definition;if(typeof r!="object"||r===null){console.error(`[AIPKit Stream HandleDisplayForm (${i})] Invalid or missing form_definition in event data.`);return}if(typeof window.aipkit_chatUI_renderChatForm!="function"){console.error(`[AIPKit Stream HandleDisplayForm (${i})] renderChatForm function not found.`);return}if(typeof window.aipkit_generateClientMessageId!="function"){console.error(`[AIPKit Stream HandleDisplayForm (${i})] generateClientMessageId function not found.`);return}let s=window.aipkit_generateClientMessageId(i);window.aipkit_chatUI_renderChatForm(a,r,n,s);let w=a.closest(".aipkit_chat_container");w&&w.dispatchEvent(new CustomEvent("aipkit:formDisplayed",{detail:{formId:r.form_id,messageId:s}}))}catch(e){console.error(`[AIPKit Stream HandleDisplayForm (${i})] Error parsing event data or rendering form:`,e,"Raw event data:",o.data)}}window.aipkit_chatUI_handleDisplayFormEvent=h})();(function(){"use strict";async function h(o,i,n,a,t,e,r,s,w,u,_){let p=n.text||{},c={dataReceived:!1,currentStreamMessageId:null,accumulatedGroundingMetadata:null,accumulatedCitations:[],currentStatusText:null},m={current:null},l=["aipkit_chatUI_cacheSseMessage","aipkit_chatUI_createEventSource","aipkit_chatUI_handleMessageStartEvent","aipkit_chatUI_handleOpenAIResponseIdEvent","aipkit_chatUI_handleGroundingMetadataEvent","aipkit_chatUI_handleStatusEvent","aipkit_chatUI_handleCitationsEvent","aipkit_chatUI_handleOnMessageEvent","aipkit_chatUI_handleDoneEvent","aipkit_chatUI_handleWarningEvent","aipkit_chatUI_handleErrorEvent","aipkit_chatUI_removeTypingIndicator","aipkit_chatUI_handleDisplayFormEvent"];for(let y of l)if(typeof window[y]!="function"){console.error(`[AIPKit Stream Orchestrator (${i})] Missing required helper function: ${y}`),typeof t=="function"&&t(`${p.errorPrefix||"Error:"} Critical script component missing.`,!1,!0),typeof window.aipkit_chatUI_removeTypingIndicator=="function"&&window.aipkit_chatUI_removeTypingIndicator(a);return}let k=window.aipkit_current_conversation_uuid,d=window.aipkit_guest_uuid,f=window.aipkit_current_post_id,g=window.aipkit_current_openai_response_id;if(!k){console.error(`[AIPKit Stream Orchestrator (${i})] Missing currentConversationUUID.`),typeof t=="function"&&t(p.errorPrefix+" "+(p.connError||"Configuration error (Conv ID)."),!1);return}let I=null;try{I=await window.aipkit_chatUI_cacheSseMessage(o,n,w,u,_)}catch(y){if(console.error(`[AIPKit Stream Orchestrator (${i})] Failed to cache message (see details below):`,y.message||"Unknown error during cache attempt."),console.error(`[AIPKit Stream Orchestrator (${i})] Full error object from cache failure:`,y),typeof t=="function"){let v=`${p.errorPrefix||"Error:"} Failed to prepare message for streaming.`;y&&typeof y=="object"&&y.code?v+=` (Code: ${y.code})`:y&&y.message?v+=` (${y.message})`:v+=" (Unknown error)",t(v)}typeof window.aipkit_chatUI_removeTypingIndicator=="function"&&window.aipkit_chatUI_removeTypingIndicator(a);return}let b=window.aipkit_chatUI_createEventSource(I,i,n,d,k,f,g,r,s,u);if(b instanceof Error){console.error(`[AIPKit Stream Orchestrator (${i})] Error creating EventSource:`,b),typeof t=="function"&&t(p.connError||"Connection error. Please try again.",!1,!0),window.aipkit_chatUI_removeTypingIndicator(a);return}if(m.current=b,n.provider==="Google"&&s&&n.allowGoogleSearchGrounding){let y=`aipkit-typing-indicator-${i}`,v=a.querySelector(`#${CSS.escape(y)}`),A=n.text&&n.text.statusSearchingWeb||"Searching web...";v&&typeof window.aipkit_chatUI_upsertMessageMeta=="function"&&(c.currentStatusText=A,window.aipkit_chatUI_upsertMessageMeta(v,{statusText:A},n))}m.current.addEventListener("message_start",y=>window.aipkit_chatUI_handleMessageStartEvent(y,n,c,a)),m.current.addEventListener("openai_response_id",y=>window.aipkit_chatUI_handleOpenAIResponseIdEvent(y,n)),m.current.addEventListener("grounding_metadata",y=>window.aipkit_chatUI_handleGroundingMetadataEvent(y,c)),m.current.addEventListener("status",y=>window.aipkit_chatUI_handleStatusEvent(y,i,n,a,c)),m.current.addEventListener("citations",y=>window.aipkit_chatUI_handleCitationsEvent(y,i,n,a,c)),m.current.addEventListener("display_form_event",y=>window.aipkit_chatUI_handleDisplayFormEvent(y,i,n,a,c)),m.current.onmessage=y=>window.aipkit_chatUI_handleOnMessageEvent(y,i,n,a,c),m.current.addEventListener("done",y=>window.aipkit_chatUI_handleDoneEvent(y,i,n,a,e,m,c)),m.current.addEventListener("warning",y=>window.aipkit_chatUI_handleWarningEvent(y,i,n,a,c)),m.current.onerror=y=>window.aipkit_chatUI_handleErrorEvent(y,i,n,a,t,m,c)}window.aipkit_chatUI_streamMessage=h})();(function(){"use strict";async function h(o,i,n,a){o.preventDefault();let t=o.target;if(!t)return;let e=t.dataset.formId;if(!e){console.error("AIPKit Chat Form: Form ID missing from submitted form.");return}let r=new FormData(t),s={},w={},u={},_=t.aipkitFieldMeta&&typeof t.aipkitFieldMeta=="object"?t.aipkitFieldMeta:{},p=(d,f)=>{let g=_[d]&&typeof _[d]=="object"?_[d]:null,I=g&&g.optionsMap&&typeof g.optionsMap=="object"?g.optionsMap:{},b=String(f??"");return Object.prototype.hasOwnProperty.call(I,b)?String(I[b]??b):b},c=d=>{if(u[d])return;let f=_[d]&&typeof _[d]=="object"?_[d]:null;u[d]=String(f?.label||d)};for(let[d,f]of r.entries())if(d.endsWith("[]")){let g=d.slice(0,-2);c(g);let I=p(g,f);s[g]||(s[g]=[]),s[g].push(f),w[g]||(w[g]=[]),w[g].push(I)}else c(d),s[d]=f,w[d]=p(d,f);let m=t.querySelector('button[type="submit"]');m&&(m.disabled=!0);let l=t.closest(".aipkit_chat_form_wrapper"),k={form_id:e,submitted_data:JSON.stringify(s),submitted_data_display:JSON.stringify(w),submitted_data_labels:JSON.stringify(u)};try{if(typeof window.aipkit_ensureMarkdownParser=="function"&&window.aipkit_ensureMarkdownParser(),typeof window.aipkit_frontendApiRequest!="function")throw new Error("Frontend API request function not found.");let d=await window.aipkit_frontendApiRequest("aipkit_handle_form_submission",k,i);if(m&&(m.disabled=!1),d.message_to_user?typeof window.aipkit_chatUI_appendMessage=="function"&&typeof window.aipkit_generateClientMessageId=="function"?window.aipkit_chatUI_appendMessage(n.messagesEl,d.message_to_user,"bot",i,!1,!1,d.message_id||window.aipkit_generateClientMessageId(i.botId),!0):console.error("AIPKit Chat Form: appendMessage or generateClientMessageId function not found."):d.message&&typeof window.aipkit_chatUI_appendMessage=="function"&&typeof window.aipkit_generateClientMessageId=="function"&&window.aipkit_chatUI_appendMessage(n.messagesEl,d.message,"bot",i,!1,!1,window.aipkit_generateClientMessageId(i.botId),!0),l){let f=l.closest(".aipkit_chat_message");f&&(f.remove(),typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(n.messagesEl,!0))}}catch(d){console.error(`AIPKit Chat Form (${i.botId}): Error submitting form "${e}":`,d),m&&(m.disabled=!1),typeof a.handleError=="function"?a.handleError(d.message||"Failed to submit form.",!1,!0):typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice(d.message||"Failed to submit form.","error",{elements:n,config:i},!0,7e3)}}window.aipkit_chatUI_handleChatFormSubmission=h})();(function(){"use strict";let h=!1,o=null,i=null,n=null,a=null;function t(){o&&(o.classList.remove("aipkit_active"),o.setAttribute("aria-hidden","true"),o=null,h=!1),i&&(i.setAttribute("aria-expanded","false"),i=null),n&&(document.removeEventListener("click",n,!0),document.removeEventListener("click",n,!1),n=null),a&&(document.removeEventListener("keydown",a,!0),document.removeEventListener("keydown",a,!1),a=null)}window.aipkit_chatUI_closeActiveDownloadMenu=t,window.aipkit_chatUI_setActiveDownloadMenu=function(e,r,s,w,u){o=e,h=r,n=s,i=w||null,a=u||null},window.aipkit_chatUI_getDownloadMenuState=function(){return{isOpen:h,activeMenu:o,activeTrigger:i,handler:n,keyHandler:a}}})();(function(){"use strict";function h(o,i){if(!o||!i)return;let{inputActionButton:n,inputActionMenu:a}=o;i.activeInputActionMenu&&i.activeInputActionTrigger&&(a&&(a.classList.remove("aipkit-action-menu-open"),a.setAttribute("aria-hidden","true"),setTimeout(()=>{a&&!a.classList.contains("aipkit-action-menu-open")&&a.setAttribute("hidden","hidden")},200)),n&&(n.classList.remove("aipkit_active"),n.setAttribute("aria-expanded","false")),i.activeInputActionMenu=null,i.activeInputActionTrigger=null,i.isActionMenuOpen=!1,i.closeActionMenuHandler&&(document.removeEventListener("click",i.closeActionMenuHandler,!0),document.removeEventListener("keydown",i.closeActionMenuHandler,!0),i.closeActionMenuHandler=null))}window.aipkit_chatUI_closeActiveInputActionMenu=h})();(function(){"use strict";function h(o,i,n){let{inputActionButton:a,inputActionMenu:t,imageUploadInput:e,fileUploadInput:r}=o,{fileUploadEnabledUI:s,imageUploadEnabledUI:w}=i,u=()=>{t&&(t.classList.remove("aipkit-action-menu-open"),t.setAttribute("aria-hidden","true"),t.setAttribute("hidden","hidden"))};if(!a){u();return}let _='<svg xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-paperclip"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M15 7l-6.5 6.5a1.5 1.5 0 0 0 3 3l6.5 -6.5a3 3 0 0 0 -6 -6l-6.5 6.5a4.5 4.5 0 0 0 9 9l6.5 -6.5" /></svg>',p='<svg xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-photo-up"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M15 8h.01" /><path d="M12.5 21h-6.5a3 3 0 0 1 -3 -3v-12a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v6.5" /><path d="M3 16l5 -5c.928 -.893 2.072 -.893 3 0l3.5 3.5" /><path d="M14 14l1 -1c.679 -.653 1.473 -.829 2.214 -.526" /><path d="M19 22v-6" /><path d="M22 19l-3 -3l-3 3" /></svg>',c='<svg xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-file-upload"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M14 3v4a1 1 0 0 0 1 1h4" /><path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z" /><path d="M12 11v6" /><path d="M9.5 13.5l2.5 -2.5l2.5 2.5" /></svg>';a.onclick=null;let m=window.aipkit_chatUI_closeActiveDownloadMenu,l=window.aipkit_chatUI_closeActiveInputActionMenu;if(typeof m!="function"||typeof l!="function"){console.error("AIPKit SetupInputActionButton: Missing global menu utility functions (closeDownloadMenu or closeInputActionMenu).");return}let k=_,d=i.text?.attachTools||"Attach or use tools",f="true";if(s&&!w)k=c,d=i.text?.uploadFile||"Upload File (TXT, PDF)",f="false";else if(!s&&w)k=p,d=i.text?.uploadImage||"Upload Image",f="false";else if(!s&&!w){a.hidden=!0,u();return}a.hidden=!1,a.innerHTML=k,a.setAttribute("aria-label",d),f==="true"?(a.setAttribute("aria-haspopup","true"),a.setAttribute("aria-expanded","false")):(a.removeAttribute("aria-haspopup"),a.removeAttribute("aria-expanded")),s&&w?(u(),a.onclick=g=>{g.stopPropagation(),m(),!n.isActionMenuOpen?(t&&(t.removeAttribute("hidden"),requestAnimationFrame(()=>{t&&t.classList.add("aipkit-action-menu-open")}),t.setAttribute("aria-hidden","false"),requestAnimationFrame(()=>{let b=t.querySelector(".aipkit_input_action_menu_item:not(:disabled)");b&&typeof b.focus=="function"&&b.focus()})),a.classList.add("aipkit_active"),a.setAttribute("aria-expanded","true"),n.isActionMenuOpen=!0,n.activeInputActionMenu=t,n.activeInputActionTrigger=a,setTimeout(()=>{n.closeActionMenuHandler=b=>{b.type==="click"&&(!n.activeInputActionMenu||!n.activeInputActionTrigger||n.activeInputActionMenu.contains(b.target)||n.activeInputActionTrigger.contains(b.target))||b.type==="keydown"&&b.key!=="Escape"||(l(o,n),b.type==="keydown"&&b.key==="Escape"&&a&&typeof a.focus=="function"&&a.focus())},document.addEventListener("click",n.closeActionMenuHandler,{capture:!0,once:!1}),document.addEventListener("keydown",n.closeActionMenuHandler,{capture:!0,once:!1})},0)):l(o,n)}):s?(u(),a.onclick=async g=>{if(g.stopPropagation(),m(),typeof window.aipkit_chatUI_prepareUploadsFeature=="function")try{await window.aipkit_chatUI_prepareUploadsFeature(o,i)}catch(I){console.error("AIPKit InputActionButton: Failed to lazy-load file upload feature.",I)}r?r.click():(console.warn("AIPKit InputActionButton: File upload input not found in elements."),typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice(i.text?.uploadInitError||"File upload feature not properly initialized.","error",{elements:o,config:i},!0,7e3))}):w?(u(),a.onclick=async g=>{if(g.stopPropagation(),m(),typeof window.aipkit_chatUI_prepareUploadsFeature=="function")try{await window.aipkit_chatUI_prepareUploadsFeature(o,i)}catch(I){console.error("AIPKit InputActionButton: Failed to lazy-load image upload feature.",I)}e?e.click():(console.warn("AIPKit InputActionButton: Image upload input not found in elements."),typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice(i.text?.imageUploadInitError||"Image upload feature not properly initialized.","error",{elements:o,config:i},!0,7e3))}):(a.hidden=!0,u())}window.aipkit_chatUI_setupInputActionButton=h})();(function(){"use strict";function h(o,i,n,a){let{actionButton:t}=o;t&&t.dataset.listenerAttached!=="true"&&(t.addEventListener("click",()=>{n.buttonState==="send"&&!t.disabled?a.sendMessageAction():n.buttonState==="clear"&&a.clearChatAction()}),t.dataset.listenerAttached="true")}window.aipkit_chatUI_attachActionButtonListener=h})();(function(){"use strict";function h(o,i,n,a){let{inputField:t,messagesEl:e,actionButton:r}=o;t&&t.dataset.listenerAttached!=="true"&&(t.addEventListener("keydown",s=>{s.key==="Enter"&&!n.isActionMenuOpen&&(s.shiftKey?setTimeout(()=>{typeof window.aipkit_autoResizeTextarea=="function"&&window.aipkit_autoResizeTextarea(t)},0):(s.preventDefault(),n.buttonState==="send"&&!r.disabled&&a.sendMessageAction()))}),t.addEventListener("input",()=>{let s=t.value.trim()==="",w=e.querySelectorAll(".aipkit_chat_message:not(.aipkit_initial_greeting)").length>0;s?w&&n.buttonState!=="sending"&&n.buttonState!=="streaming"?n.buttonState=a.setButtonStateAction("clear",!1,n):n.buttonState!=="sending"&&n.buttonState!=="streaming"&&(n.buttonState=a.setButtonStateAction("send",!1,n)):n.buttonState=a.setButtonStateAction("send",!1,n),typeof window.aipkit_autoResizeTextarea=="function"&&window.aipkit_autoResizeTextarea(t)}),t.dataset.listenerAttached="true")}window.aipkit_chatUI_attachInputFieldListeners=h})();(function(){"use strict";function h(o,i,n,a){let{fullscreenButton:t}=o;t&&typeof a.toggleFullscreenAction=="function"?t.dataset.listenerAttached!=="true"&&(t.addEventListener("click",a.toggleFullscreenAction),t.dataset.listenerAttached="true"):t&&console.warn("AIPKit Chat Events: Fullscreen button exists, but toggleFullscreenAction action is missing.")}window.aipkit_chatUI_attachFullscreenButtonListener=h})();(function(){"use strict";function h(o,i,n,a){let{webSearchToggleButton:t}=o,e=i.allowWebSearchTool&&(i.provider==="OpenAI"||i.provider==="Claude"||i.provider==="OpenRouter");t&&e?t.dataset.listenerAttached!=="true"&&(t.addEventListener("click",r=>{r.stopPropagation(),typeof window.aipkit_chatUI_closeActiveDownloadMenu=="function"&&window.aipkit_chatUI_closeActiveDownloadMenu(),typeof window.aipkit_chatUI_closeActiveInputActionMenu=="function"&&window.aipkit_chatUI_closeActiveInputActionMenu(o,n),typeof window.aipkit_toggleWebSearchAction=="function"?window.aipkit_toggleWebSearchAction(o,i,n):console.error("AIPKit Chat Events: aipkit_toggleWebSearchAction function not provided.")}),t.dataset.listenerAttached="true"):t&&(t.hidden=!0,t.setAttribute("aria-hidden","true"))}window.aipkit_chatUI_attachWebSearchToggleListener=h})();(function(){"use strict";function h(o,i,n,a){let{googleSearchGroundingToggleButton:t}=o,e=i.allowGoogleSearchGrounding&&i.provider==="Google";t&&e?t.dataset.listenerAttached!=="true"&&(t.addEventListener("click",r=>{r.stopPropagation(),typeof window.aipkit_chatUI_closeActiveDownloadMenu=="function"&&window.aipkit_chatUI_closeActiveDownloadMenu(),typeof window.aipkit_chatUI_closeActiveInputActionMenu=="function"&&window.aipkit_chatUI_closeActiveInputActionMenu(o,n),typeof window.aipkit_toggleGoogleSearchGroundingAction=="function"?window.aipkit_toggleGoogleSearchGroundingAction(o,i,n):console.error("AIPKit Chat Events: aipkit_toggleGoogleSearchGroundingAction function not provided.")}),t.dataset.listenerAttached="true"):t&&(t.hidden=!0,t.setAttribute("aria-hidden","true"))}window.aipkit_chatUI_attachGoogleGroundingToggleListener=h})();(function(){"use strict";function h(o,i,n,a){let{downloadButton:t}=o;if(!t||!i.enableDownload)return;let e=t.closest(".aipkit_download_wrapper"),r=e?e.querySelector(".aipkit_download_menu"):null,s=i.pdfDownloadActive===!0,w=window.aipkit_chatUI_closeActiveDownloadMenu,u=window.aipkit_chatUI_setActiveDownloadMenu,_=window.aipkit_chatUI_getDownloadMenuState;t.dataset.ariaSetup!=="true"&&(t.setAttribute("aria-haspopup",s&&r?"menu":"false"),t.setAttribute("aria-expanded","false"),r&&r.id&&t.setAttribute("aria-controls",r.id),t.dataset.ariaSetup="true"),r&&r.dataset.ariaSetup!=="true"&&(r.setAttribute("role","menu"),r.setAttribute("aria-hidden","true"),r.querySelectorAll(".aipkit_download_menu_item").forEach(f=>{f.hasAttribute("role")||f.setAttribute("role","menuitem")}),r.dataset.ariaSetup="true");let p=(d=!1)=>{typeof w=="function"&&w(),d&&typeof t.focus=="function"&&t.focus()},c=()=>r?Array.from(r.querySelectorAll(".aipkit_download_menu_item:not(:disabled)")):[],m=()=>{let d=c();d.length>0&&d[0].focus()},l=()=>{if(!(!r||!s)){if(p(!1),r.classList.add("aipkit_active"),r.setAttribute("aria-hidden","false"),t.setAttribute("aria-expanded","true"),typeof u=="function"){let d=g=>{(!e||!e.contains(g.target))&&p(!1)},f=g=>{g.key==="Escape"&&(g.preventDefault(),p(!0))};u(r,!0,d,t,f),document.addEventListener("click",d,!0),document.addEventListener("keydown",f,!0)}requestAnimationFrame(m)}},k=()=>{let d=typeof _=="function"?_():{isOpen:!1,activeMenu:null};d.isOpen&&d.activeMenu===r?p(!1):l()};t.dataset.listenerAttached!=="true"&&(t.addEventListener("click",d=>{if(d.stopPropagation(),typeof window.aipkit_chatUI_closeActiveInputActionMenu=="function"&&window.aipkit_chatUI_closeActiveInputActionMenu(o,n),s&&r){k();return}typeof a.downloadTranscriptTxtAction=="function"?a.downloadTranscriptTxtAction():console.error("AIPKit Chat Events: downloadTranscriptTxtAction action not provided.")}),t.addEventListener("keydown",d=>{s&&r&&(d.key==="ArrowDown"?(d.preventDefault(),l()):d.key==="Escape"&&(d.preventDefault(),p(!0)))}),t.dataset.listenerAttached="true"),r&&r.dataset.listenerAttached!=="true"&&(r.addEventListener("click",d=>{let f=d.target.closest(".aipkit_download_menu_item");if(!f)return;let g=f.getAttribute("data-format");g==="txt"?typeof a.downloadTranscriptTxtAction=="function"?a.downloadTranscriptTxtAction():console.error("AIPKit Chat Events: downloadTranscriptTxtAction action not provided."):g==="pdf"&&(typeof a.downloadTranscriptPdfAction=="function"?a.downloadTranscriptPdfAction():console.error("AIPKit Chat Events: downloadTranscriptPdfAction action not provided.")),p(!1)}),r.addEventListener("keydown",d=>{let f=c();if(d.key==="Escape"){d.preventDefault(),p(!0);return}if(d.key==="Tab"){p(!1);return}if(f.length===0)return;let g=document.activeElement,I=f.indexOf(g),b=I;if(d.key==="ArrowDown"||d.key==="ArrowRight")d.preventDefault(),b=I<0?0:(I+1)%f.length;else if(d.key==="ArrowUp"||d.key==="ArrowLeft")d.preventDefault(),b=I<=0?f.length-1:I-1;else if(d.key==="Home")d.preventDefault(),b=0;else if(d.key==="End")d.preventDefault(),b=f.length-1;else return;f[b]&&f[b].focus()}),r.dataset.listenerAttached="true")}window.aipkit_chatUI_attachDownloadMenuListeners=h})();(function(){"use strict";function h(o,i,n,a){let{inputActionMenu:t}=o;t&&typeof window.aipkit_chatUI_setupInputActionButton=="function"&&(t.dataset.itemClickListenerAttached!=="true"&&(t.addEventListener("click",async e=>{let r=e.target.closest(".aipkit_input_action_menu_item");if(!r)return;e.preventDefault();let s=r.getAttribute("aria-label");if(s&&s.toLowerCase().includes("image")){if(typeof window.aipkit_chatUI_prepareUploadsFeature=="function")try{await window.aipkit_chatUI_prepareUploadsFeature(o,i)}catch(w){console.error("AIPKit Chat Events: Failed to lazy-load image upload feature.",w)}o.imageUploadInput?o.imageUploadInput.click():(console.warn("AIPKit Chat Events: Image upload input not found for menu item."),typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice(i.text?.imageUploadInitError||"Image upload feature not properly initialized.","error",{elements:o,config:i},!0,7e3))}else if(s&&(s.toLowerCase().includes("pdf")||s.toLowerCase().includes("file"))){if(typeof window.aipkit_chatUI_prepareUploadsFeature=="function")try{await window.aipkit_chatUI_prepareUploadsFeature(o,i)}catch(w){console.error("AIPKit Chat Events: Failed to lazy-load file upload feature.",w)}o.fileUploadInput?o.fileUploadInput.click():(console.warn("AIPKit Chat Events: File upload input not found for menu item."),typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice(i.text?.uploadInitError||"File upload feature not properly initialized.","error",{elements:o,config:i},!0,7e3))}typeof window.aipkit_chatUI_closeActiveInputActionMenu=="function"&&window.aipkit_chatUI_closeActiveInputActionMenu(o,n)}),t.dataset.itemClickListenerAttached="true"),t.dataset.itemKeydownListenerAttached!=="true"&&(t.addEventListener("keydown",e=>{let r=Array.from(t.querySelectorAll(".aipkit_input_action_menu_item:not(:disabled)"));if(e.key==="Escape"){e.preventDefault(),typeof window.aipkit_chatUI_closeActiveInputActionMenu=="function"&&window.aipkit_chatUI_closeActiveInputActionMenu(o,n),o.inputActionButton&&typeof o.inputActionButton.focus=="function"&&o.inputActionButton.focus();return}if(e.key==="Tab"){typeof window.aipkit_chatUI_closeActiveInputActionMenu=="function"&&window.aipkit_chatUI_closeActiveInputActionMenu(o,n);return}if(r.length===0)return;let s=r.indexOf(document.activeElement),w=s;if(e.key==="ArrowDown"||e.key==="ArrowRight")e.preventDefault(),w=s<0?0:(s+1)%r.length;else if(e.key==="ArrowUp"||e.key==="ArrowLeft")e.preventDefault(),w=s<=0?r.length-1:s-1;else if(e.key==="Home")e.preventDefault(),w=0;else if(e.key==="End")e.preventDefault(),w=r.length-1;else return;r[w]&&r[w].focus()}),t.dataset.itemKeydownListenerAttached="true"))}window.aipkit_chatUI_attachInputActionMenuListener=h})();(function(){"use strict";function h(o,i,n,a){let{voiceInputButton:t}=o;t&&i.enableVoiceInputUI&&t.dataset.listenerAttached!=="true"&&(t.addEventListener("click",async()=>{if(typeof window.aipkit_chatUI_prepareSttFeature=="function")try{await window.aipkit_chatUI_prepareSttFeature()}catch(e){console.error("AIPKit Chat Events: Failed to lazy-load voice input feature.",e)}typeof window.aipkit_chatUI_handleVoiceInputAction=="function"?window.aipkit_chatUI_handleVoiceInputAction(o,i,n,n.consentUIInstance,a):(console.error("AIPKit Chat Events: aipkit_chatUI_handleVoiceInputAction function not found."),typeof window.aipkit_chatUI_showInlineNotice=="function"&&window.aipkit_chatUI_showInlineNotice(i.text?.voiceUnavailableScriptError||"Voice input is currently unavailable (script error).","error",{elements:o,config:i},!0,7e3))}),t.dataset.listenerAttached="true")}window.aipkit_chatUI_attachVoiceInputButtonListener=h})();(function(){"use strict";function h(o,i,n,a){let{fileUploadInput:t}=o;t&&i.fileUploadEnabledUI&&t.dataset.listenerAttached!=="true"&&(t.addEventListener("change",async e=>{let r=e.target.files[0];if(r&&typeof window.aipkit_chatUI_prepareUploadsFeature=="function")try{await window.aipkit_chatUI_prepareUploadsFeature(o,i)}catch(s){console.error("AIPKit Chat Events: Failed to lazy-load upload feature.",s)}if(r&&window.aipkitChatFileUpload&&typeof window.aipkitChatFileUpload.processFile=="function"){let s=o.inputArea||t.closest(".aipkit_chat_input");await window.aipkitChatFileUpload.processFile(r,t,s,i)}else r&&(console.error("AIPKit Chat Events: aipkitChatFileUpload.processFile not found."),typeof window.aipkit_displayChatFileUploadStatus=="function"&&window.aipkit_displayChatFileUploadStatus("File processing system error.","error",o.inputArea))}),t.dataset.listenerAttached="true")}window.aipkit_chatUI_attachFileUploadInputListener=h})();(function(){"use strict";function h(o,i,n,a){let{messagesEl:t}=o;t&&typeof a.handlePlayAction=="function"?t.dataset.playListenerAttached!=="true"&&(t.addEventListener("click",function(e){let r=e.target.closest(".aipkit_play_btn");r&&!r.disabled&&a.handlePlayAction(r)}),t.dataset.playListenerAttached="true"):t&&console.warn("AIPKit Chat Events: handlePlayAction function not provided or invalid during listener attachment.")}window.aipkit_chatUI_attachPlayButtonListener=h})();(function(){"use strict";function h(o,i,n,a){typeof n.isActionMenuOpen>"u"&&(n.isActionMenuOpen=!1,n.activeInputActionMenu=null,n.activeInputActionTrigger=null,n.closeActionMenuHandler=null);let t=["aipkit_chatUI_attachActionButtonListener","aipkit_chatUI_attachInputFieldListeners","aipkit_chatUI_attachFullscreenButtonListener","aipkit_chatUI_attachWebSearchToggleListener","aipkit_chatUI_attachGoogleGroundingToggleListener","aipkit_chatUI_attachDownloadMenuListeners"],e=["aipkit_chatUI_attachInputActionMenuListener","aipkit_chatUI_attachVoiceInputButtonListener","aipkit_chatUI_attachFileUploadInputListener","aipkit_chatUI_attachPlayButtonListener"],r=!0;if(t.forEach(s=>{typeof window[s]!="function"&&(console.error(`AIPKit AttachEventListeners Orchestrator: Missing dependency function -> ${s}.`),r=!1)}),e.forEach(s=>{typeof window[s]!="function"&&console.warn(`AIPKit AttachEventListeners Orchestrator: Optional dependency is unavailable -> ${s}.`)}),!r){console.error("AIPKit AttachEventListeners Orchestrator: Halting due to missing required dependencies. Some UI features may not work.");return}window.aipkit_chatUI_attachActionButtonListener(o,i,n,a),window.aipkit_chatUI_attachInputFieldListeners(o,i,n,a),window.aipkit_chatUI_attachFullscreenButtonListener(o,i,n,a),window.aipkit_chatUI_attachWebSearchToggleListener(o,i,n,a),window.aipkit_chatUI_attachGoogleGroundingToggleListener(o,i,n,a),window.aipkit_chatUI_attachDownloadMenuListeners(o,i,n,a),typeof window.aipkit_chatUI_attachInputActionMenuListener=="function"&&window.aipkit_chatUI_attachInputActionMenuListener(o,i,n,a),typeof window.aipkit_chatUI_attachVoiceInputButtonListener=="function"&&window.aipkit_chatUI_attachVoiceInputButtonListener(o,i,n,a),typeof window.aipkit_chatUI_attachFileUploadInputListener=="function"&&window.aipkit_chatUI_attachFileUploadInputListener(o,i,n,a),typeof window.aipkit_chatUI_attachPlayButtonListener=="function"&&window.aipkit_chatUI_attachPlayButtonListener(o,i,n,a)}window.aipkit_chatUI_attachEventListeners=h})();(function(){"use strict";function h(){let n=document.body,a=document.documentElement,t=Number(n.dataset.aipkitScrollLockCount||"0");t===0&&(n.dataset.aipkitScrollLockOverflow=n.style.overflow||"",n.dataset.aipkitScrollLockOverflowX=n.style.overflowX||"",n.dataset.aipkitScrollLockOverflowY=n.style.overflowY||"",n.dataset.aipkitScrollLockHtmlOverflow=a.style.overflow||"",n.dataset.aipkitScrollLockHtmlOverflowX=a.style.overflowX||"",n.dataset.aipkitScrollLockHtmlOverflowY=a.style.overflowY||"",n.style.overflow="hidden",n.style.overflowX="hidden",n.style.overflowY="hidden",a.style.overflow="hidden",a.style.overflowX="hidden",a.style.overflowY="hidden"),n.dataset.aipkitScrollLockCount=String(t+1)}function o(){let n=document.body,a=document.documentElement,t=Number(n.dataset.aipkitScrollLockCount||"0");t<=1?(n.style.overflow=n.dataset.aipkitScrollLockOverflow||"",n.style.overflowX=n.dataset.aipkitScrollLockOverflowX||"",n.style.overflowY=n.dataset.aipkitScrollLockOverflowY||"",a.style.overflow=n.dataset.aipkitScrollLockHtmlOverflow||"",a.style.overflowX=n.dataset.aipkitScrollLockHtmlOverflowX||"",a.style.overflowY=n.dataset.aipkitScrollLockHtmlOverflowY||"",delete n.dataset.aipkitScrollLockOverflow,delete n.dataset.aipkitScrollLockOverflowX,delete n.dataset.aipkitScrollLockOverflowY,delete n.dataset.aipkitScrollLockHtmlOverflow,delete n.dataset.aipkitScrollLockHtmlOverflowX,delete n.dataset.aipkitScrollLockHtmlOverflowY,delete n.dataset.aipkitScrollLockCount):n.dataset.aipkitScrollLockCount=String(t-1)}function i(n,a,t){let{container:e,fullscreenButton:r,messagesEl:s,inputField:w,startersContainer:u}=n,_=t.text||{};if(!e||!r){console.error("AIPKit Fullscreen: Container or fullscreen button element not found.");return}a.isFullscreen=!a.isFullscreen;let p=!!e.closest("#aipkit_admin_chat_preview_container");if(a.isFullscreen){if(!a.fullscreenPlaceholder){let k=document.createElement("div");k.id=`aipkit_fs_placeholder_${e.id}`,k.style.display="none",e.parentNode.insertBefore(k,e),a.fullscreenPlaceholder=k}document.body.appendChild(e),e.classList.add("aipkit-fullscreen"),p||h()}else e.classList.remove("aipkit-fullscreen"),a.fullscreenPlaceholder&&a.fullscreenPlaceholder.parentNode?(a.fullscreenPlaceholder.parentNode.insertBefore(e,a.fullscreenPlaceholder),a.fullscreenPlaceholder.remove(),a.fullscreenPlaceholder=null):console.warn("AIPKit Fullscreen: Could not find placeholder to return chat container to its original position."),p||o();let c=e.closest(".aipkit_popup_wrapper");c&&c.classList.toggle("aipkit-fullscreen-wrapper",a.isFullscreen);let m='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-arrows-maximize"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M16 4l4 0l0 4" /><path d="M14 10l6 -6" /><path d="M8 20l-4 0l0 -4" /><path d="M4 20l6 -6" /><path d="M16 20l4 0l0 -4" /><path d="M14 14l6 6" /><path d="M8 4l-4 0l0 4" /><path d="M4 4l6 6" /></svg>',l='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-arrows-minimize"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 9l4 0l0 -4" /><path d="M3 3l6 6" /><path d="M5 15l4 0l0 4" /><path d="M3 21l6 -6" /><path d="M19 9l-4 0l0 -4" /><path d="M15 9l6 -6" /><path d="M19 15l-4 0l0 4" /><path d="M15 15l6 6" /></svg>';if(r.innerHTML=a.isFullscreen?l:m,r.title=a.isFullscreen?_.exitFullscreen||"Exit Fullscreen":_.fullscreen||"Fullscreen",r.setAttribute("aria-label",r.title),r.setAttribute("aria-expanded",a.isFullscreen.toString()),a.isFullscreen&&typeof window.aipkit_chatUI_scrollToBottom=="function"&&window.aipkit_chatUI_scrollToBottom(s,!0),w&&setTimeout(()=>w.focus(),50),typeof window.aipkit_chatUI_triggerMessageAnimation=="function"&&s){let k=s.querySelector(".aipkit_initial_greeting");k&&window.aipkit_chatUI_triggerMessageAnimation(k)}typeof window.aipkit_chatUI_refreshStartersAnimation=="function"&&u&&window.aipkit_chatUI_refreshStartersAnimation(u)}window.aipkit_chatUI_toggleFullscreen=i})();function ut(h,o){let i=window.aipkit_chatUI_findElements(h,o);if(!i){let s=h.querySelector(".aipkit_chat_container")||h;return s&&typeof window.aipkit_chatUI_renderUIState=="function"?window.aipkit_chatUI_renderUIState(s,{message:"Chatbot UI error (DOM elements missing).",type:"error",scope:"messages"}):s&&(s.textContent="Chatbot UI error (DOM elements missing)."),null}let n=o.botId,a=!!h.closest("#aipkit_admin_chat_preview_container"),t=window.aipkit_chatUI_initState(o);t.consentUIInstance=null;let e={setButtonStateAction:(s,w=!1)=>window.aipkit_chatUI_setButtonStateAction(s,i,o,t,w),focusInputAction:()=>window.aipkit_chatUI_focusInputAction(i.inputField,o,t),sendMessageAction:(s=null)=>window.aipkit_chatUI_sendMessageAction(i,o,t,e,s),clearChatAction:()=>window.aipkit_chatUI_clearChatAction(i,o,t,e),handleError:(s,w,u=!0)=>window.aipkit_chatUI_handleError(s,w,u,i,o,t,e),handleCompletion:(s,w=!1)=>window.aipkit_chatUI_handleCompletion(s,w,i,o,t,e),toggleFullscreenAction:()=>window.aipkit_chatUI_toggleFullscreen(i,t,o),downloadTranscriptTxtAction:()=>window.aipkit_chatUI_downloadTranscriptActionTxt(i,o),downloadTranscriptPdfAction:async()=>{if(typeof window.aipkit_chatUI_preparePdfFeature=="function")try{if(!await window.aipkit_chatUI_preparePdfFeature(o))return console.warn(`AIPKit Chat Main (${n}): PDF download feature is unavailable.`),null}catch(s){return console.error(`AIPKit Chat Main (${n}): Failed to lazy-load PDF download feature.`,s),o?.text?.pdfError&&alert(o.text.pdfError),null}return typeof window.aipkit_chatUI_downloadTranscriptActionPdf=="function"?window.aipkit_chatUI_downloadTranscriptActionPdf(i,o):(console.warn(`AIPKit Chat Main (${n}): PDF download action is unavailable.`),null)},handlePlayAction:async s=>{if(typeof window.aipkit_chatUI_prepareTtsFeature=="function")try{await window.aipkit_chatUI_prepareTtsFeature()}catch(w){console.error(`AIPKit Chat Main (${n}): Failed to lazy-load TTS feature.`,w)}return typeof window.aipkit_handlePlayAction=="function"?window.aipkit_handlePlayAction(s):(console.warn(`AIPKit Chat Main (${n}): TTS play action is unavailable.`),null)}};if(o.requireConsentCompliance&&typeof window.aipkit_initConsentUI=="function"?t.consentUIInstance=window.aipkit_initConsentUI(i.mainContentEl,o,t,()=>{i.inputField.disabled=!1,e.setButtonStateAction("send",!1),e.focusInputAction(),i.voiceInputButton&&(i.voiceInputButton.disabled=!1),i.inputActionButton&&(i.inputActionButton.disabled=!1),i.webSearchToggleButton&&(i.webSearchToggleButton.disabled=!1),i.googleSearchGroundingToggleButton&&(i.googleSearchGroundingToggleButton.disabled=!1)}):o.requireConsentCompliance&&console.error(`AIPKit Chat Main (${n}): Consent required, but aipkit_initConsentUI function not found.`),o.imageUploadEnabledUI&&(i.container&&i.container.classList.add("aipkit-image-upload-enabled"),(!i.imageUploadInput||!i.imagePreviewContainer)&&console.warn(`AIPKit Chat UI Main (${n}): Image Upload UI enabled, but input or preview elements were not found/created by findElements.`)),typeof window.aipkit_chatUI_setupInputActionButton=="function"?window.aipkit_chatUI_setupInputActionButton(i,o,t):(console.error(`AIPKit Chat Main (${n}): setupInputActionButton function not found.`),i.inputActionButton&&(i.inputActionButton.hidden=!0),i.inputActionMenu&&(i.inputActionMenu.classList.remove("aipkit-action-menu-open"),i.inputActionMenu.setAttribute("aria-hidden","true"),i.inputActionMenu.setAttribute("hidden","hidden"))),typeof window.aipkit_chatUI_attachEventListeners=="function"?window.aipkit_chatUI_attachEventListeners(i,o,t,e):console.error(`AIPKit Chat Main (${n}): attachEventListeners not defined.`),typeof window.aipkit_chatUI_initMessageActions=="function"?window.aipkit_chatUI_initMessageActions(i.messagesEl,o):console.warn(`AIPKit Chat Main (${n}): aipkit_chatUI_initMessageActions missing; message actions might not work.`),typeof window.aipkit_chatUI_initScrollToBottomButton=="function"?window.aipkit_chatUI_initScrollToBottomButton(i,o,t):console.warn(`AIPKit Chat Main (${n}): aipkit_chatUI_initScrollToBottomButton missing; scroll button won't render.`),o.enableStarters){let s=t.consentUIInstance?t.consentUIInstance.isConsentGiven:()=>!o.requireConsentCompliance||t.consentGiven,w=()=>typeof window.aipkit_chatUI_prepareStartersFeature=="function"?window.aipkit_chatUI_prepareStartersFeature(h,o,i,e.sendMessageAction,o.requireConsentCompliance,s).catch(u=>{console.error(`AIPKit Chat Main (${n}): Failed to lazy-load starters feature.`,u)}):(console.warn(`AIPKit Chat Main (${n}): Starters feature loader is unavailable.`),Promise.resolve());o.popupEnabled&&!a?h.addEventListener("aipkit:popupOpened",()=>{w()},{once:!0}):i.startersContainer?w():console.warn(`AIPKit Chat Main (${n}): Starters enabled but container is missing.`)}o.enableSidebar&&i.sidebarEl&&i.sidebarToggleBtn?typeof window.aipkit_chatUI_prepareSidebarFeature=="function"?window.aipkit_chatUI_prepareSidebarFeature(h,i,o,e).catch(s=>{console.error(`AIPKit Chat Main (${n}): Failed to prepare sidebar feature.`,s)}):typeof window.aipkit_initConversationSidebar=="function"?(window.aipkit_initConversationSidebar(h,i,o,e),h.dataset.aipkitSidebarInitialized="true"):console.warn(`AIPKit Chat Main (${n}): Sidebar enabled but init function is missing.`):o.enableSidebar&&console.warn(`AIPKit Chat Main (${n}): Sidebar enabled but sidebar elements are missing.`);let r={openPopup:o.popupEnabled&&typeof window.aipkit_chatUI_openPopup=="function"?()=>window.aipkit_chatUI_openPopup(h,i.messagesEl,i.inputField,t):()=>{},closePopup:o.popupEnabled&&typeof window.aipkit_chatUI_closePopup=="function"?()=>window.aipkit_chatUI_closePopup(h,t):()=>{},setupPopupHandlers:o.popupEnabled&&typeof window.aipkit_chatUI_setupPopupHandlers=="function"?s=>window.aipkit_chatUI_setupPopupHandlers(h,s,i.messagesEl,i.inputField,t,o):()=>{},isPopupOpen:()=>t.isPopupOpen,scrollToBottom:()=>window.aipkit_chatUI_scrollToBottom(i.messagesEl,!0),sendMessage:e.sendMessageAction,clearChat:e.clearChatAction,toggleFullscreen:e.toggleFullscreenAction};if(o.enableRealtimeVoiceUI){let s=i.container.closest(".aipkit_popup_wrapper"),w=s?s.querySelector(".aipkit_popup_trigger"):null,u=o.directVoiceMode?w:i.container.querySelector(".aipkit_realtime_voice_agent_btn");if(u){let _=async p=>{if(p.preventDefault(),p.stopPropagation(),typeof window.aipkit_chatUI_prepareRealtimeFeature!="function"){console.error(`AIPKit Chat Main (${n}): Realtime feature loader is unavailable.`);return}try{await window.aipkit_chatUI_prepareRealtimeFeature(i,o,t,e,r)&&typeof u.click=="function"&&(u.removeEventListener("click",_),u.click())}catch(c){console.error(`AIPKit Chat Main (${n}): Failed to lazy-load realtime voice feature.`,c)}};u.addEventListener("click",_)}else console.warn(`AIPKit Chat Main (${n}): Realtime Voice enabled but no trigger button was found.`)}return typeof window.aipkit_chatUI_displayInitialMessage=="function"?window.aipkit_chatUI_displayInitialMessage(i.messagesEl,o):console.error(`AIPKit Chat Main (${n}): displayInitialMessage function not found.`),typeof window.aipkit_chatUI_finalizeSetup=="function"?window.aipkit_chatUI_finalizeSetup(i,o,t,e):console.error(`AIPKit Chat Main (${n}): finalizeSetup function not found.`),{publicApi:r,internalElements:i,internalActions:e}}window.aipkit_setupChatInstanceUI=ut;(function(){"use strict";window.aipkit_current_conversation_uuid=null,window.aipkit_is_fresh_session=!0,window.aipkit_current_post_id=0,window.aipkit_current_openai_response_id=null,window.aipkit_active_file_context_provider=null,window.aipkit_active_file_context_data=null,window.aipkit_regenerateConversationUUID=function(){let i=("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,n=>(n^crypto.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16));return sessionStorage.setItem("aipkit_current_conversation_uuid",i),window.aipkit_current_conversation_uuid=i,window.aipkit_current_openai_response_id=null,sessionStorage.removeItem("aipkit_current_openai_response_id"),window.aipkit_active_file_context_provider=null,window.aipkit_active_file_context_data=null,sessionStorage.removeItem("aipkit_active_file_context_provider"),sessionStorage.removeItem("aipkit_active_file_context_data"),document.dispatchEvent(new CustomEvent("aipkit:fileContextCleared")),i},typeof window.aipkit_getMarkdownRenderer=="function"?window.aipkit_md=window.aipkit_getMarkdownRenderer():(!window.aipkit_md||typeof window.aipkit_md.render!="function")&&(window.aipkit_md={aipkitIsFallback:!0,render:function(i){return(window.aipkit_escapeHtml||function(a){return typeof a!="string"?"":a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")})(i).replace(/\n/g,"<br>")}});function h(i){if(!i||i.classList.contains("aipkit-initializing")||i.classList.contains("aipkit-initialized"))return;i.classList.add("aipkit-initializing");let n=i.getAttribute("data-bot-id"),a=i.getAttribute("data-config"),t=null,e=(u,_)=>{if(u){if(typeof window.aipkit_chatUI_renderUIState=="function"){window.aipkit_chatUI_renderUIState(u,{message:_,type:"error",scope:"messages"});return}u.textContent=_}};try{a&&(t=JSON.parse(a),n&&(t.botId=n))}catch(u){console.error(`AIPKit Chat Init (${n||"Unknown"}): Failed to parse configuration.`,u,a);let _=i.querySelector(".aipkit_chat_container")||i;e(_,"Chatbot configuration error."),i.classList.remove("aipkit-initializing");return}if(!t){console.error(`AIPKit Chat Init (${n||"Unknown"}): Config object is null after parse attempt.`,i);let u=i.querySelector(".aipkit_chat_container")||i;e(u,"Chatbot config load error."),i.classList.remove("aipkit-initializing");return}if(!t.botId&&n&&(t.botId=n),window.aipkit_current_post_id=t.postId||0,t.enableSidebar)window.aipkit_current_conversation_uuid=null,window.aipkit_is_fresh_session=!0,window.aipkit_current_openai_response_id=null,sessionStorage.removeItem("aipkit_current_openai_response_id"),window.aipkit_active_file_context_provider=null,window.aipkit_active_file_context_data=null,sessionStorage.removeItem("aipkit_active_file_context_provider"),sessionStorage.removeItem("aipkit_active_file_context_data"),document.dispatchEvent(new CustomEvent("aipkit:fileContextCleared"));else{let u=sessionStorage.getItem("aipkit_current_conversation_uuid"),_=sessionStorage.getItem("aipkit_current_openai_response_id");if(u){if(window.aipkit_current_conversation_uuid=u,window.aipkit_is_fresh_session=!1,window.aipkit_current_openai_response_id=_||null,window.aipkit_current_openai_response_id)try{let p=localStorage.getItem(`aipkit_file_context_${u}`);if(p){let c=JSON.parse(p),m=!1;c&&c.provider&&(c.provider==="OpenAI"&&c.vector_store_id||c.provider==="Pinecone"&&c.index_name&&c.namespace||c.provider==="Qdrant"&&c.collection_name&&c.file_upload_context_id||c.provider==="Claude"&&c.file_id)&&(m=!0),m?(window.aipkit_active_file_context_provider=c.provider,window.aipkit_active_file_context_data=c,sessionStorage.setItem("aipkit_active_file_context_provider",window.aipkit_active_file_context_provider),sessionStorage.setItem("aipkit_active_file_context_data",JSON.stringify(window.aipkit_active_file_context_data)),document.dispatchEvent(new CustomEvent("aipkit:fileContextRestored",{detail:c}))):(console.warn(`AIPKit Chat Init (${t.botId}): Invalid file context data in localStorage for conv ${u}. Clearing. Data:`,c),localStorage.removeItem(`aipkit_file_context_${u}`),window.aipkit_active_file_context_provider=null,window.aipkit_active_file_context_data=null,sessionStorage.removeItem("aipkit_active_file_context_provider"),sessionStorage.removeItem("aipkit_active_file_context_data"),document.dispatchEvent(new CustomEvent("aipkit:fileContextCleared")))}else window.aipkit_active_file_context_provider=null,window.aipkit_active_file_context_data=null,sessionStorage.removeItem("aipkit_active_file_context_provider"),sessionStorage.removeItem("aipkit_active_file_context_data"),document.dispatchEvent(new CustomEvent("aipkit:fileContextCleared"))}catch(p){console.error("AIPKit Chat Init: Error loading file context from localStorage:",p),window.aipkit_active_file_context_provider=null,window.aipkit_active_file_context_data=null,sessionStorage.removeItem("aipkit_active_file_context_provider"),sessionStorage.removeItem("aipkit_active_file_context_data"),document.dispatchEvent(new CustomEvent("aipkit:fileContextCleared"))}}else window.aipkit_current_conversation_uuid=null,window.aipkit_is_fresh_session=!0,window.aipkit_current_openai_response_id=null,sessionStorage.removeItem("aipkit_current_openai_response_id"),window.aipkit_active_file_context_provider=null,window.aipkit_active_file_context_data=null,sessionStorage.removeItem("aipkit_active_file_context_provider"),sessionStorage.removeItem("aipkit_active_file_context_data"),document.dispatchEvent(new CustomEvent("aipkit:fileContextCleared"))}if(typeof aipkit_setupChatInstanceUI!="function"){console.error(`AIPKit Chat Init (${t.botId}): UI setup function (aipkit_setupChatInstanceUI) not found.`);let u=i.querySelector(".aipkit_chat_container")||i;e(u,"Chatbot script error."),i.classList.remove("aipkit-initializing");return}let r=i.classList.contains("aipkit_chat_container")?i:i.querySelector(".aipkit_chat_container");if(!r){console.error(`AIPKit Chat Init (${t.botId}): Chat container element not found within wrapper.`,i),e(i,"Chatbot structure error."),i.classList.remove("aipkit-initializing");return}if(t.guestUUID=window.aipkit_guest_uuid,t.conversationUUID=window.aipkit_current_conversation_uuid,t.previousOpenAIResponseId=window.aipkit_current_openai_response_id,t.activeFileContextProvider=window.aipkit_active_file_context_provider,t.activeFileContextData=window.aipkit_active_file_context_data,!t.botId||!t.ajaxUrl||!t.text||!t.guestUUID){console.error(`AIPKit Chat Init (${t.botId||"Unknown"}): Missing essential configuration.`,t,i);let u=i.querySelector(".aipkit_chat_container")||i;e(u,"Chatbot configuration error."),i.classList.remove("aipkit-initializing");return}if(typeof window.aipkit_chatUI_applyCustomThemeStyles=="function"&&t.theme==="custom"&&t.customThemeSettings&&Object.keys(t.customThemeSettings).length>0){let u={skipDimensionSync:!!t.customThemePresetKey};window.aipkit_chatUI_applyCustomThemeStyles(r,t.customThemeSettings,u)}else t.theme==="custom"&&console.warn(`AIPKit Chat Init (${t.botId}): Custom theme selected but aipkit_chatUI_applyCustomThemeStyles not found or no settings provided.`);let s=aipkit_setupChatInstanceUI(r,t);if(!s||!s.publicApi||!s.internalElements||!s.internalActions){console.error(`AIPKit Chat Init (${t.botId}): Failed to set up UI instance or get all necessary parts.`),i.classList.remove("aipkit-initializing");return}let w=s.publicApi;if(window.aipkitChatInstances||(window.aipkitChatInstances={}),window.aipkitChatInstances[r.id]={instance:w,elements:s.internalElements,actions:s.internalActions},t.popupEnabled){let u=i.querySelector(".aipkit_popup_trigger");if(!u){console.error(`AIPKit Chat Init (${t.botId}): Popup trigger button not found.`),i.classList.remove("aipkit-initializing");return}if(w.setupPopupHandlers){w.setupPopupHandlers(u);let _=t.popupDelay;_>0&&!t.directVoiceMode&&!i.dataset.aipkitAutoOpened&&(i.dataset.aipkitAutoOpened="true",setTimeout(()=>{w&&w.isPopupOpen&&!w.isPopupOpen()&&w.openPopup()},_*1e3))}else console.error(`AIPKit Chat Init (${t.botId}): setupPopupHandlers method missing in UI instance.`)}i.classList.remove("aipkit-initializing"),i.classList.add("aipkit-initialized")}function o(){document.querySelectorAll(".aipkit_chat_container:not(.aipkit-initializing):not(.aipkit-initialized)").forEach(a=>{a.closest(".aipkit_popup_wrapper")||h(a)}),document.querySelectorAll(".aipkit_popup_wrapper:not(.aipkit-initializing):not(.aipkit-initialized)").forEach(h)}if(document.addEventListener("DOMContentLoaded",o),typeof MutationObserver=="function"){let i=new MutationObserver(n=>{let a=!1;n.forEach(t=>{t.addedNodes&&t.addedNodes.forEach(e=>{e.nodeType===1&&(e.matches&&(e.matches(".aipkit_chat_container:not(.aipkit_popup_content)")||e.matches(".aipkit_popup_wrapper")||e.matches('[id^="aipkit-chatbot-container-"]'))||e.querySelector&&e.querySelector(".aipkit_chat_container:not(.aipkit_popup_content), .aipkit_popup_wrapper, [id^='aipkit-chatbot-container-']"))&&(a=!0)})}),a&&(i.scanTimeout&&clearTimeout(i.scanTimeout),i.scanTimeout=setTimeout(o,50))});i.observe(document.body,{childList:!0,subtree:!0,attributes:!0})}else console.warn("AIPKit Chat Init: MutationObserver not supported; dynamically added chatbots might not initialize automatically.");window.aipkit_initializeChatInstance=h})();(function(){"use strict";function h(o,i,n){if(!o)return console.error("AIPKit ShowConsentBox: mainChatEl not found."),null;let a=o.querySelector(".aipkit_consent_overlay"),t=o.querySelector(".aipkit_chat_input");if(!a){a=document.createElement("div"),a.className="aipkit_consent_overlay",a.innerHTML=`
<h5 class="aipkit_consent_title">${i.text.consentTitle||"Consent Required"}</h5>
<p class="aipkit_consent_message">${i.text.consentMessage||"Please agree to continue."}</p>
<button type="button" class="aipkit_btn aipkit_btn-primary aipkit_consent_agree_btn">
${i.text.consentButton||"I Agree"}
</button>
`,t?t.appendChild(a):o.appendChild(a);let e=a.querySelector(".aipkit_consent_agree_btn");e&&typeof n=="function"&&e.addEventListener("click",n)}return t&&t.classList.add("aipkit-consent-active"),a.classList.remove("aipkit_hidden"),a}window.aipkit_chatUI_showConsentBox=h})();(function(){"use strict";function h(o){if(o){o.classList.add("aipkit_hidden");let i=o.closest(".aipkit_chat_input");i&&i.classList.remove("aipkit-consent-active")}}window.aipkit_chatUI_hideConsentBox=h})();(function(){"use strict";function h(o,i,n,a,t,e){o.consentGiven=!0,localStorage.setItem(i,"true"),typeof t=="function"&&e&&t(e);let r=a.closest("[data-bot-id]")?.dataset.botId||"unknown";typeof n=="function"&&n();let s=a.closest(".aipkit_chat_container");s&&s.dispatchEvent(new CustomEvent("aipkit:consentGiven"))}window.aipkit_chatUI_handleConsentAgree=h})();(function(){"use strict";function h(o,i,n,a){let t=i.botId,e=`aipkit_chatbot_consent_given_${t}`;n.consentGiven=localStorage.getItem(e)==="true";let r=null;function s(){typeof window.aipkit_chatUI_handleConsentAgree=="function"?window.aipkit_chatUI_handleConsentAgree(n,e,a,o,u,r):console.error(`AIPKit Consent UI Init (${t}): aipkit_chatUI_handleConsentAgree helper function not found.`)}function w(){typeof window.aipkit_chatUI_showConsentBox=="function"?r=window.aipkit_chatUI_showConsentBox(o,i,s):console.error(`AIPKit Consent UI Init (${t}): aipkit_chatUI_showConsentBox helper function not found.`)}function u(){r&&typeof window.aipkit_chatUI_hideConsentBox=="function"?window.aipkit_chatUI_hideConsentBox(r):r&&console.error(`AIPKit Consent UI Init (${t}): aipkit_chatUI_hideConsentBox helper function not found.`)}return i.requireConsentCompliance&&!n.consentGiven&&w(),{showConsentBoxIfNeeded:()=>i.requireConsentCompliance&&!n.consentGiven?(w(),!0):!1,isConsentGiven:()=>n.consentGiven}}window.aipkit_initConsentUI=h})();})();