Current File : /home/kelaby89/cartel.express/wp-content/plugins/ai-engine/app/chatbot.js
/*! For license information please see chatbot.js.LICENSE.txt */
(()=>{"use strict";var __webpack_modules__={469:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{G:()=>ChatbotContextProvider,o:()=>useChatbotContext});var _app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(728),_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(137),_app_helpers__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(678),_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(213);const{useContext,createContext,useState,useMemo,useEffect,useCallback,useRef}=wp.element,rawAiName="AI: ",rawUserName="User: ",ChatbotContext=createContext(),useChatbotContext=()=>{const e=useContext(ChatbotContext);if(!e)throw new Error("useChatbotContext must be used within a ChatbotContextProvider");return e},ChatbotContextProvider=({children,...rest})=>{var _params$startSentence;const{params,system,theme,atts}=rest,{timeElapsed,startChrono,stopChrono}=(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__.dh)(),shortcodeStyles=useMemo((()=>(null==theme?void 0:theme.settings)||{}),[theme]),[restNonce,setRestNonce]=useState(system.restNonce||_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.getToken()),restNonceRef=useRef(system.restNonce||_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.getToken());useEffect((()=>_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.subscribe((e=>{setRestNonce(e),restNonceRef.current=e}))),[]);const[messages,setMessages]=useState([]),[shortcuts,setShortcuts]=useState([]),[blocks,setBlocks]=useState([]),[locked,setLocked]=useState(!1),[chatId,setChatId]=useState((0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)()),[inputText,setInputText]=useState(""),[chatbotTriggered,setChatbotTriggered]=useState(!1),[showIconMessage,setShowIconMessage]=useState(!1),[uploadedFile,setUploadedFile]=useState({localFile:null,uploadedId:null,uploadedUrl:null,uploadProgress:null}),[windowed,setWindowed]=useState(!0),[open,setOpen]=useState(!1),[error,setError]=useState(null),[busy,setBusy]=useState(!1),[busyNonce,setBusyNonce]=useState(!1),[lastFailedQuery,setLastFailedQuery]=useState(null),[serverReply,setServerReply]=useState(),[previousResponseId,setPreviousResponseId]=useState(null),chatbotInputRef=useRef(),conversationRef=useRef(),hasFocusRef=useRef(!1),{isListening,setIsListening,speechRecognitionAvailable}=(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__.Vw)((e=>{setInputText(e)})),stream=system.stream||!1,internalId=useMemo((()=>(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)()),[]),botId=system.botId,customId=system.customId,userData=system.userData,[sessionId,setSessionId]=useState(system.sessionId),contextId=system.contextId,pluginUrl=system.pluginUrl,restUrl=system.restUrl,debugMode=system.debugMode,eventLogs=system.eventLogs,virtualKeyboardFix=system.virtual_keyboard_fix,typewriter=(null==system?void 0:system.typewriter)??!1,speechRecognition=(null==system?void 0:system.speech_recognition)??!1,speechSynthesis=(null==system?void 0:system.speech_synthesis)??!1,startSentence=(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__.Mc)((null===(_params$startSentence=params.startSentence)||void 0===_params$startSentence?void 0:_params$startSentence.trim())??"",userData),initialActions=system.actions||[],initialShortcuts=system.shortcuts||[],initialBlocks=system.blocks||[],isMobile=document.innerWidth<=768,processedParams=(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__._$)(params,userData),{aiName,userName,guestName,aiAvatar,userAvatar,guestAvatar}=processedParams,{textSend,textClear,textInputMaxLength,textInputPlaceholder,textCompliance,window:isWindow,copyButton,headerSubtitle,fullscreen,localMemory:localMemoryParam,icon,iconText,iconTextDelay,iconAlt,iconPosition,iconBubble,imageUpload,fileUpload,fileSearch}=processedParams,isRealtime="realtime"===processedParams.mode,localMemory=localMemoryParam&&(!!customId||!!botId),localStorageKey=localMemory?`mwai-chat-${customId||botId}`:null,{cssVariables,iconUrl,aiAvatarUrl,userAvatarUrl,guestAvatarUrl}=useMemo((()=>{const e=e=>e?(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Ve)(e)||(0,_app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__.mv)(e)?e:`${pluginUrl}/images/${e}`:null,t=icon?e(icon):`${pluginUrl}/images/chat-traditional-1.svg`,a=e(processedParams.aiAvatarUrl),n=e(processedParams.userAvatarUrl),s=e(processedParams.guestAvatarUrl);return{cssVariables:Object.keys(shortcodeStyles).reduce(((e,t)=>(e[`--mwai-${t}`]=shortcodeStyles[t],e)),{}),iconUrl:t,aiAvatarUrl:a,userAvatarUrl:n,guestAvatarUrl:s}}),[icon,pluginUrl,shortcodeStyles,processedParams]),[draggingType,setDraggingType]=useState(!1),[isBlocked,setIsBlocked]=useState(!1),uploadIconPosition=useMemo((()=>"timeless"===(null==theme?void 0:theme.themeId)?"mwai-tools":"mwai-input"),[null==theme?void 0:theme.themeId]),submitButtonConf=useMemo((()=>({text:textSend,textSend,textClear,imageSend:"timeless"===(null==theme?void 0:theme.themeId)?pluginUrl+"/images/action-submit-blue.svg":null,imageClear:"timeless"===(null==theme?void 0:theme.themeId)?pluginUrl+"/images/action-clear-blue.svg":null})),[pluginUrl,textClear,textSend,null==theme?void 0:theme.themeId]),resetMessages=()=>{if(resetUploadedFile(),setPreviousResponseId(null),startSentence){const e=[{id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"assistant",content:startSentence,who:rawAiName,timestamp:(new Date).getTime()}];setMessages(e)}else setMessages([])},refreshRestNonce=useCallback((async(e=!1)=>{try{if(!e&&restNonce)return restNonce;setBusyNonce(!0);const t=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai/v1/start_session`),a=await t.json();if(setRestNonce(a.restNonce),restNonceRef.current=a.restNonce,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.setToken(a.restNonce),a.sessionId&&"N/A"!==a.sessionId&&setSessionId(a.sessionId),a.new_token){if(a.token_expires_at){const e=new Date(1e3*a.token_expires_at);console.log(`[MWAI] 🔐 New token received - expires at ${e.toLocaleTimeString()} (in ${a.token_expires_in}s)`)}return setRestNonce(a.new_token),restNonceRef.current=a.new_token,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.setToken(a.new_token),a.new_token}return a.restNonce}catch(e){console.error("Error while fetching the restNonce.",e)}finally{setBusyNonce(!1)}}),[restNonce,setRestNonce,restUrl,setSessionId]),[isResumingConversation,setIsResumingConversation]=useState(!1),[isConversationLoaded,setIsConversationLoaded]=useState(!1);useEffect((()=>{isConversationLoaded&&(isResumingConversation||messages.length>1||1===messages.length&&messages[0].content!==startSentence||(initialActions.length>0&&handleActions(initialActions),initialShortcuts.length>0&&handleShortcuts(initialShortcuts),initialBlocks.length>0&&handleBlocks(initialBlocks)))}),[isConversationLoaded,isResumingConversation,messages,startSentence]),useEffect((()=>{chatbotTriggered&&!restNonce&&refreshRestNonce()}),[chatbotTriggered]),useEffect((()=>{inputText.length>0&&!chatbotTriggered&&setChatbotTriggered(!0)}),[chatbotTriggered,inputText]),useEffect((()=>{resetMessages()}),[startSentence]),useEffect((()=>{if(customId||botId){const e=_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__.HX.chatbots.findIndex((e=>e.internalId===internalId)),t={internalId,botId,chatId,customId,localStorageKey,open:()=>{setTasks((e=>[...e,{action:"open"}]))},close:()=>{setTasks((e=>[...e,{action:"close"}]))},clear:e=>{const{chatId:t=null}=e||{};setTasks((e=>[...e,{action:"clear",data:{chatId:t}}]))},toggle:()=>{setTasks((e=>[...e,{action:"toggle"}]))},ask:(e,t=!1)=>{setTasks((a=>[...a,{action:"ask",data:{text:e,submit:t}}]))},lock:()=>{setLocked(!0)},unlock:()=>{setLocked(!1)},setShortcuts:e=>{setTasks((t=>[...t,{action:"setShortcuts",data:e}]))},setBlocks:e=>{setTasks((t=>[...t,{action:"setBlocks",data:e}]))},addBlock:e=>{setTasks((t=>[...t,{action:"addBlock",data:e}]))},removeBlockById:e=>{setTasks((t=>[...t,{action:"removeBlockById",data:e}]))},getBlocks:()=>blocks,setContext:({chatId:e,messages:t,previousResponseId:a})=>{console.warn("MwaiAPI: setContext is deprecated. Please use setConversation instead."),setTasks((n=>[...n,{action:"setContext",data:{chatId:e,messages:t,previousResponseId:a}}]))},setConversation:({chatId:e,messages:t,previousResponseId:a})=>{setTasks((n=>[...n,{action:"setContext",data:{chatId:e,messages:t,previousResponseId:a}}]))}};-1!==e?_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__.HX.chatbots[e]=t:_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__.HX.chatbots.push(t)}}),[botId,chatId,customId,internalId,localStorageKey,blocks]),useEffect((()=>{var e;busy?startChrono():(!isMobile&&hasFocusRef.current&&null!==(e=chatbotInputRef.current)&&void 0!==e&&e.focusInput&&chatbotInputRef.current.focusInput(),stopChrono())}),[busy,startChrono,stopChrono,isMobile]);const saveMessages=useCallback((e=>{localStorageKey&&localStorage.setItem(localStorageKey,(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.F1)({chatId,messages:e}))}),[localStorageKey,chatId]),resetError=()=>{setError(null)},addErrorMessage=useCallback(((e,t=null)=>{const a={id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"error",content:e,who:"Error",timestamp:(new Date).getTime(),isError:!0,failedQuery:t};setMessages((e=>[...e,a])),setLastFailedQuery(t)}),[]);useEffect((()=>{let e=[];if(localStorageKey&&(e=localStorage.getItem(localStorageKey),e))return e=JSON.parse(e),setMessages(e.messages),setChatId(e.chatId),setIsResumingConversation(!0),void setIsConversationLoaded(!0);setIsResumingConversation(!1),setIsConversationLoaded(!0),resetMessages()}),[botId]);const executedActionsRef=useRef(new Set),handleActions=useCallback(((actions,lastMessage)=>{actions=actions||[];let callsCount=0;for(const action of actions)if("function"===action.type){const data=action.data||{},{name=null,args=[]}=data,actionKey=`${name}_${JSON.stringify(args)}`;if(executedActionsRef.current.has(actionKey)){debugMode&&console.log(`[CHATBOT] Skipping duplicate execution of ${name}`);continue}const finalArgs=args?Object.values(args).map((e=>JSON.stringify(e))):[];try{debugMode&&console.log(`[CHATBOT] CALL ${name}(${finalArgs.join(", ")})`),executedActionsRef.current.add(actionKey),eval(`${name}(${finalArgs.join(", ")})`),callsCount++,setTimeout((()=>{executedActionsRef.current.delete(actionKey)}),5e3)}catch(e){console.error("Error while executing an action.",e),executedActionsRef.current.delete(actionKey)}}!lastMessage.content&&callsCount>0&&(lastMessage.content="*Done!*")}),[debugMode]),handleShortcuts=useCallback((e=>{setShortcuts(e||[])}),[]),handleBlocks=useCallback((e=>{setBlocks(e||[])}),[]);useEffect((()=>{if(!serverReply)return;setBusy(!1);const e=[...messages],t=e.length>0?e[e.length-1]:null;if(!serverReply.success){"assistant"===t.role&&t.isQuerying&&e.pop();const a=e.length-1;let n=null,s=null;if(a>=0&&"user"===e[a].role){const t=e[a].content,r=t.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);n=r?r[1]:t,r&&uploadedFile&&(s=uploadedFile)}return setMessages(e),saveMessages(e),void addErrorMessage(serverReply.message,n?{text:n,file:s}:null)}if("assistant"===t.role&&t.isQuerying)t.content=(0,_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__.W5)("ai.reply",serverReply.reply,{chatId,botId}),serverReply.images&&(t.images=serverReply.images),t.timestamp=(new Date).getTime(),delete t.isQuerying,handleActions(null==serverReply?void 0:serverReply.actions,t),handleBlocks(null==serverReply?void 0:serverReply.blocks),handleShortcuts(null==serverReply?void 0:serverReply.shortcuts);else if("assistant"===t.role&&t.isStreaming){if(t.content=(0,_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__.W5)("ai.reply",serverReply.reply,{chatId,botId}),serverReply.images&&(t.images=serverReply.images),t.timestamp=(new Date).getTime(),delete t.isStreaming,debugMode&&t.streamEvents){var a;const e=(new Date).getTime(),n=e-((null===(a=t.streamEvents[0])||void 0===a?void 0:a.timestamp)||e);let s;s=n<1e3?`${n}ms`:n<6e4?`${(n/1e3).toFixed(1)}s`:`${Math.floor(n/6e4)}m ${(n%6e4/1e3).toFixed(0)}s`,t.streamEvents.push({type:"event",subtype:"status",data:`Request completed in ${s}.`,timestamp:e})}handleActions(null==serverReply?void 0:serverReply.actions,t),handleBlocks(null==serverReply?void 0:serverReply.blocks),handleShortcuts(null==serverReply?void 0:serverReply.shortcuts)}else{const t={id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"assistant",content:(0,_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__.W5)("ai.reply",serverReply.reply,{botId,chatId,customId}),who:rawAiName,timestamp:(new Date).getTime()};serverReply.images&&(t.images=serverReply.images),handleActions(null==serverReply?void 0:serverReply.actions,t),handleBlocks(null==serverReply?void 0:serverReply.blocks),handleShortcuts(null==serverReply?void 0:serverReply.shortcuts),e.push(t)}serverReply.responseId&&setPreviousResponseId(serverReply.responseId),setMessages(e),saveMessages(e)}),[serverReply]);const onClear=useCallback((async({chatId:e=null}={})=>{e||(e=(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)()),await setChatId(e),localStorageKey&&localStorage.removeItem(localStorageKey),resetMessages(),setInputText(""),setIsResumingConversation(!1),setIsConversationLoaded(!0),initialShortcuts.length>0?handleShortcuts(initialShortcuts):setShortcuts([]),setBlocks([]),setPreviousResponseId(null)}),[botId,initialShortcuts,handleShortcuts]),onStartRealtimeSession=useCallback((async()=>{const e={botId,customId,contextId,chatId},t=restNonceRef.current??await refreshRestNonce(),a=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/start`,e,t);return await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(a,null,null,null,debugMode)}),[botId,customId,contextId,chatId,restNonce,refreshRestNonce,restUrl]),onCommitStats=useCallback((async(e,t=null)=>{try{const a=restNonceRef.current??await refreshRestNonce(),n=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/stats`,{botId,session:sessionId,refId:t||chatId,stats:e},a),s=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(n,null,null,null,debugMode);return{success:s.success,message:s.message,overLimit:s.overLimit||!1,limitMessage:s.limitMessage||null}}catch(e){return console.error("Error while committing stats.",e),{success:!1,message:"An error occurred while committing the stats."}}}),[botId,restNonce,refreshRestNonce,restUrl,sessionId,chatId]),onCommitDiscussions=useCallback((async(e=[])=>{try{const t=restNonceRef.current??await refreshRestNonce(),a={botId,session:sessionId,chatId,messages:(e??[]).filter((e=>"error"!==e.role&&!e.isError))},n=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/discussions`,a,t),s=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(n,null,null,null,debugMode);return{success:s.success,message:s.message}}catch(e){return console.error("Error while committing discussion.",e),{success:!1,message:"An error occurred while committing the discussion."}}}),[botId,chatId,restNonce,refreshRestNonce,restUrl,sessionId]),onRealtimeFunctionCallback=useCallback((async(functionId,functionType,functionName,functionTarget,args)=>{const body={functionId,functionType,functionName,functionTarget,arguments:args};if("js"!==functionTarget){const e=restNonceRef.current??await refreshRestNonce(),t=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/call`,body,e),a=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(t,null,null,null,debugMode);return a}{const finalArgs=args?Object.values(args).map((e=>JSON.stringify(e))):[];try{return debugMode&&console.log(`[CHATBOT] CALL ${functionName}(${finalArgs.join(", ")})`),eval(`${functionName}(${finalArgs.join(", ")})`),{success:!0,message:"The function was executed",data:null}}catch(e){return console.error("Error while executing an action.",e),{success:!1,message:"An error occurred while executing the function.",data:null}}}return null}),[restNonce,refreshRestNonce,restUrl,debugMode]),onSubmit=useCallback((async e=>{var t;if(busy)return void console.error("AI Engine: There is already a query in progress.");"string"!=typeof e&&(e=inputText);const a=uploadedFile,n=null==uploadedFile?void 0:uploadedFile.uploadedUrl,s=null==uploadedFile||null===(t=uploadedFile.localFile)||void 0===t?void 0:t.type,r=!!s&&s.startsWith("image");let o=e;n&&(o=r?`![Uploaded Image](${n})\n${e}`:`[Uploaded File](${n})\n${e}`),setBusy(!0),setInputText(""),setShortcuts([]),setBlocks([]),resetUploadedFile();const i=[...messages,{id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"user",content:o,who:rawUserName,timestamp:(new Date).getTime()}];saveMessages(i);const l=(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),c=[...i,{id:l,role:"assistant",content:stream?"":null,who:rawAiName,timestamp:null,isQuerying:!stream,isStreaming:!!stream,streamEvents:stream&&debugMode?[]:void 0}];if(setMessages(c),"[ERROR]"===e){setBusy(!1);const t=messages.slice(0,-1);setMessages(t);const n=["Connection timeout: The server took too long to respond.","Invalid API key: Please check your OpenAI API key in settings.","Rate limit exceeded: Too many requests. Please try again later.","Model overloaded: The AI model is currently experiencing high demand.","Network error: Failed to establish connection to the AI service.","Authentication failed: Your session has expired. Please refresh the page.","Service unavailable: The AI service is temporarily down for maintenance.","Invalid request: The message format was not recognized by the server.","Quota exceeded: You have reached your usage limit for this period.","Internal server error: An unexpected error occurred. Please try again."],s=n[Math.floor(Math.random()*n.length)],r={id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"error",content:`[TEST ERROR] ${s}`,who:"Error",timestamp:(new Date).getTime(),isError:!0,failedQuery:{text:e,file:a}},o=[...i,r];return setMessages(o),saveMessages(o),void setLastFailedQuery({text:e,file:a})}const u={botId,customId,session:sessionId,chatId,contextId,messages:messages.filter((e=>"error"!==e.role&&!e.isError)),newMessage:e,newFileId:null==a?void 0:a.uploadedId,stream,...atts};previousResponseId&&(u.previousResponseId=previousResponseId);try{debugMode&&console.log("[CHATBOT] OUT: ",u);const e=stream?(e,t)=>{debugMode&&t&&t.subtype&&console.log("[CHATBOT] STREAM EVENT:",t),setMessages((a=>{const n=[...a],s=n.length>0?n[n.length-1]:null;return s&&s.id===l&&(s.content=e,s.timestamp=(new Date).getTime(),t&&t.subtype&&(s.streamEvents||(s.streamEvents=[]),s.streamEvents.push({...t,timestamp:(new Date).getTime()}))),n}))}:null,t=restNonceRef.current??await refreshRestNonce();stream&&debugMode&&e&&e("",{type:"event",subtype:"status",data:"Request sent...",timestamp:(new Date).getTime()});const n=e=>{setRestNonce(e),restNonceRef.current=e,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.setToken(e)},s=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/chats/submit`,u,t,stream,void 0,n),r=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(s,e,debugMode?"CHATBOT":null,n,debugMode);if(!r.success&&r.message){const e=[...c];e.pop();const t=e.length-1;let n=null,s=null;if(t>=0&&"user"===e[t].role){const r=e[t].content,o=r.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);n=o?o[1]:r,o&&(s=a)}return setMessages(e),saveMessages(e),addErrorMessage(r.message,n?{text:n,file:s}:null),void setBusy(!1)}setServerReply(r)}catch(e){console.error("An error happened in the handling of the chatbot response.",{err:e}),setBusy(!1),setMessages((e=>{const t=e[e.length-1];return!t||"assistant"!==t.role||""!==t.content&&null!==t.content?e:e.slice(0,-1)}));const t=messages.length;let n=null,s=null;if(t>=0&&"user"===c[t].role){const e=c[t].content,r=e.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);n=r?r[1]:e,r&&(s=a)}addErrorMessage(e.message||"An error occurred while processing your request. Please try again.",n?{text:n,file:s}:null)}}),[busy,uploadedFile,messages,saveMessages,stream,botId,customId,sessionId,chatId,contextId,atts,inputText,debugMode,restNonce,refreshRestNonce,restUrl]),onSubmitAction=useCallback(((e=null)=>{var t;const a=!(null==uploadedFile||!uploadedFile.uploadedId);hasFocusRef.current=(null===(t=chatbotInputRef.current)||void 0===t?void 0:t.currentElement)&&document.activeElement===chatbotInputRef.current.currentElement(),e?onSubmit(e):(a||inputText.length>0)&&onSubmit(inputText)}),[inputText,onSubmit,null==uploadedFile?void 0:uploadedFile.uploadedId]),retryLastQuery=useCallback((()=>{var e;lastFailedQuery&&(setInputText(lastFailedQuery.text),lastFailedQuery.file&&setUploadedFile(lastFailedQuery.file),setLastFailedQuery(null),null!==(e=chatbotInputRef.current)&&void 0!==e&&e.focusInput&&setTimeout((()=>{chatbotInputRef.current.focusInput()}),100))}),[lastFailedQuery,setInputText,chatbotInputRef]),onFileUpload=async(e,t="N/A",a="N/A")=>{try{if(null===e)return void resetUploadedFile();const n={type:t,purpose:a},s=`${restUrl}/mwai-ui/v1/files/upload`,r=restNonceRef.current??await refreshRestNonce(),o=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.uE)(s,e,r,(t=>{setUploadedFile({localFile:e,uploadedId:null,uploadedUrl:null,uploadProgress:t})}),n);setUploadedFile({localFile:e,uploadedId:o.data.id,uploadedUrl:o.data.url,uploadProgress:null})}catch(e){console.error("onFileUpload Error",e),addErrorMessage(e.message||"An unknown error occurred"),resetUploadedFile()}},onUploadFile=async e=>(setMessages((e=>e.filter((e=>!e.isError)))),onFileUpload(e)),resetUploadedFile=()=>{setUploadedFile({localFile:null,uploadedId:null,uploadedUrl:null,uploadProgress:null})},runTimer=useCallback((()=>{const e=setTimeout((()=>{setOpen((e=>(e||setShowIconMessage(!0),e)))}),1e3*iconTextDelay);return()=>clearTimeout(e)}),[iconText,iconTextDelay]);useEffect((()=>{if(iconText&&!iconTextDelay)setShowIconMessage(!0);else if(iconText&&iconTextDelay)return runTimer()}),[iconText]);const[tasks,setTasks]=useState([]),runTasks=useCallback((async()=>{if(tasks.length>0){const e=tasks[0];if("ask"===e.action){const{text:t,submit:a}=e.data;a?onSubmit(t):setInputText(t)}else if("toggle"===e.action)setOpen((e=>!e));else if("open"===e.action)setOpen(!0);else if("close"===e.action)setOpen(!1);else if("clear"===e.action){const{chatId:t}=e.data;onClear({chatId:t})}else if("setContext"===e.action){const{chatId:t,messages:a,previousResponseId:n}=e.data;setChatId(t),setMessages(a),n&&setPreviousResponseId(n),setIsResumingConversation(!0),setIsConversationLoaded(!0),setShortcuts([]),saveMessages(a)}else if("setShortcuts"===e.action){const t=e.data;handleShortcuts(t)}else if("setBlocks"===e.action){const t=e.data;handleBlocks(t)}else if("addBlock"===e.action){const t=e.data;setBlocks((e=>[...e,t]))}else if("removeBlockById"===e.action){const t=e.data;setBlocks((e=>e.filter((e=>e.id!==t))))}setTasks((e=>e.slice(1)))}}),[tasks,onClear,onSubmit,setChatId,setInputText,setMessages,setOpen,handleShortcuts,handleBlocks]);useEffect((()=>{runTasks()}),[runTasks]);const actions={setInputText,saveMessages,setMessages,resetMessages,setError,resetError,addErrorMessage,retryLastQuery,onClear,onSubmit,onSubmitAction,onFileUpload,onUploadFile,resetUploadedFile,setUploadedFile,setOpen,setWindowed,setShowIconMessage,setIsListening,setDraggingType,setIsBlocked,onStartRealtimeSession,onRealtimeFunctionCallback,onCommitStats,onCommitDiscussions},state={theme,botId,customId,userData,pluginUrl,inputText,messages,shortcuts,blocks,busy,error,setBusy,typewriter,speechRecognition,speechSynthesis,virtualKeyboardFix,localMemory,isRealtime,imageUpload,fileUpload,uploadedFile,fileSearch,textSend,textClear,textInputMaxLength,textInputPlaceholder,textCompliance,aiName,userName,guestName,aiAvatar,userAvatar,guestAvatar,aiAvatarUrl,userAvatarUrl,guestAvatarUrl,isWindow,copyButton,headerSubtitle,fullscreen,icon,iconText,iconAlt,iconPosition,iconBubble,cssVariables,iconUrl,chatbotInputRef,conversationRef,isMobile,open,locked,windowed,showIconMessage,timeElapsed,isListening,speechRecognitionAvailable,uploadIconPosition,submitButtonConf,draggingType,isBlocked,busyNonce,debugMode,eventLogs,system};return React.createElement(ChatbotContext.Provider,{value:{state,actions}},children)}},137:(e,t,a)=>{a.d(t,{HX:()=>s,W5:()=>r});class n{constructor(){if("undefined"!=typeof window&&window.MwaiAPI)return window.MwaiAPI;this.chatbots=[],this.forms=[],this.filters={},this.actions={},"undefined"!=typeof window&&(window.MwaiAPI=this)}getChatbot(e=null){return e?this.chatbots.find((t=>t.botId===e||t.customId===e)):this.chatbots[0]}getForm(e=null){return e?this.forms.find((t=>t.formId===e)):this.forms[0]}addFilter(e,t,a=10){this.filters[e]||(this.filters[e]=[]),this.filters[e].push({callback:t,priority:a}),this.filters[e].sort(((e,t)=>e.priority-t.priority))}applyFilters(e,t,...a){return this.filters[e]?this.filters[e].reduce(((e,t)=>t.callback(e,...a)),t):t}addAction(e,t,a=10){this.actions[e]||(this.actions[e]=[]),this.actions[e].push({callback:t,priority:a}),this.actions[e].sort(((e,t)=>e.priority-t.priority))}doAction(e,...t){this.actions[e]&&this.actions[e].forEach((e=>{e.callback(...t)}))}}const s=(()=>{if("undefined"!=typeof window&&window.MwaiAPI)return window.MwaiAPI;const e=new n;return"undefined"!=typeof window&&(window.MwaiAPI=e),e})(),r=(e,t,...a)=>s.applyFilters(e,t,...a)},728:(e,t,a)=>{a.d(t,{tm:()=>u,bE:()=>f,Mc:()=>h,mv:()=>m,_$:()=>g,dh:()=>p,gR:()=>d,Vw:()=>_,kW:()=>y});const n=(0,a(407).A)("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},s.apply(this,arguments)}const{useState:r,useMemo:o,useEffect:i,useRef:l,useCallback:c}=wp.element,u=({active:e,disabled:t,...a})=>React.createElement("div",s({active:e?"true":"false",disabled:t},a),React.createElement(n,{size:"24"})),d=()=>o((()=>(e,t)=>(Array.isArray(e)||(e=[e]),t&&Object.entries(t).forEach((([t,a])=>{a&&e.push(t)})),e.join(" "))),[]);function m(e){return!(!e||"string"!=typeof e)&&0===e.indexOf("http")}function p(){const[e,t]=r(null),a=l(null);return i((()=>()=>{clearInterval(a.current)}),[]),{timeElapsed:e,startChrono:function(){if(null!==a.current)return;const e=Date.now();a.current=setInterval((()=>{const a=Math.floor((Date.now()-e)/1e3);var n;t((n=a,`${Math.floor(n/60)}:${(n%60).toString().padStart(2,"0")}`))}),500)},stopChrono:function(){clearInterval(a.current),a.current=null,t(null)}}}const h=(e,t)=>"string"==typeof e&&t?(Object.entries(t).forEach((([t,a])=>{e=e.replace(new RegExp(`{${t}}`,"g"),a)})),e):e,g=(e,t=[])=>{var a,n,s,r,o,i,l,c,u,d,m,p,g,_,f;const y=(null===(a=e.guestName)||void 0===a?void 0:a.trim())??"",b=(null===(n=e.textSend)||void 0===n?void 0:n.trim())??"",v=(null===(s=e.textClear)||void 0===s?void 0:s.trim())??"",E=parseInt(e.textInputMaxLength),R=(null===(r=e.textInputPlaceholder)||void 0===r?void 0:r.trim())??"";let w=(null===(o=e.textCompliance)||void 0===o?void 0:o.trim())??"",C="";const k=Boolean(e.window),x=Boolean(e.copyButton),S=Boolean(e.fullscreen),I=(null===(i=e.icon)||void 0===i?void 0:i.trim())??"";let M=(null===(l=e.iconText)||void 0===l?void 0:l.trim())??"";const T=parseInt(e.iconTextDelay||1),A=(null===(c=e.iconAlt)||void 0===c?void 0:c.trim())??"",N=(null===(u=e.iconPosition)||void 0===u?void 0:u.trim())??"",L=Boolean(e.iconBubble),D=(null===(d=e.aiName)||void 0===d?void 0:d.trim())??"",U=(null===(m=e.userName)||void 0===m?void 0:m.trim())??"",P=Boolean(null==e?void 0:e.aiAvatar),O=Boolean(null==e?void 0:e.userAvatar),B=Boolean(null==e?void 0:e.guestAvatar),F=P?(null==e||null===(p=e.aiAvatarUrl)||void 0===p?void 0:p.trim())??"":null,z=O?(null==e||null===(g=e.userAvatarUrl)||void 0===g?void 0:g.trim())??"":null,$=B?(null==e||null===(_=e.guestAvatarUrl)||void 0===_?void 0:_.trim())??"":null,j=Boolean(e.localMemory),W=Boolean(e.imageUpload),H=Boolean(e.fileUpload),V=Boolean(e.fileSearch),K=(null===(f=e.mode)||void 0===f?void 0:f.trim())??"chat";var q;return C=null===e.headerSubtitle||void 0===e.headerSubtitle?"Discuss with":(null===(q=e.headerSubtitle)||void 0===q?void 0:q.trim())??"",t&&(w=h(w,t),M=h(M,t)),{textSend:b,textClear:v,textInputMaxLength:E,textInputPlaceholder:R,textCompliance:w,mode:K,window:k,copyButton:x,fullscreen:S,localMemory:j,imageUpload:W,fileUpload:H,fileSearch:V,icon:I,iconText:M,iconTextDelay:T,iconAlt:A,iconPosition:N,iconBubble:L,headerSubtitle:C,aiName:D,userName:U,guestName:y,aiAvatar:P,userAvatar:O,guestAvatar:B,aiAvatarUrl:F,userAvatarUrl:z,guestAvatarUrl:$}},_=e=>{const[t,a]=r(!1),[n,s]=r(!1);return i((()=>{"undefined"!=typeof window&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)&&s(!0)}),[]),i((()=>{if(!n)return;const s=new(window.SpeechRecognition||window.webkitSpeechRecognition);let r=null;return navigator.userAgent.toLowerCase().indexOf("android")>-1?(s.interimResults=!1,s.continuous=!1,r=t=>{const n=Array.from(t.results).filter((e=>e.isFinal)).map((e=>e[0].transcript)).join("");e(n),a(!1)}):(s.interimResults=!0,s.continuous=!0,r=t=>{const a=Array.from(t.results).map((e=>e[0])).map((e=>e.transcript)).join("");e(a)}),t?(s.addEventListener("result",r),s.start()):(s.removeEventListener("result",r),s.abort()),()=>{s.abort()}}),[t,n]),{isListening:t,setIsListening:a,speechRecognitionAvailable:n}},f=({if:e,className:t,disableTransition:a=!1,children:n,...o})=>{const[l,c]=r(!1),[u,d]=r("mwai-transition");return i((()=>{a?c(e):e?(c(!0),setTimeout((()=>{d("mwai-transition mwai-transition-visible")}),150)):d("mwai-transition")}),[e,a]),l?React.createElement("div",s({className:`${t} ${a?"":u}`,onTransitionEnd:()=>{"mwai-transition"!==u||a||c(!1)}},o),n):null},y=()=>{const[e,t]=r(window.visualViewport.height),a=o((()=>/Android/.test(navigator.userAgent)),[]),n=o((()=>/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream),[]),s=l(window.visualViewport),u=c((()=>{t(s.current.height)}),[]);return i((()=>{const e=s.current;return e.addEventListener("resize",u),n?(window.addEventListener("resize",u),document.addEventListener("focusin",u)):e.addEventListener("scroll",u),()=>{e.removeEventListener("resize",u),n?(window.removeEventListener("resize",u),document.removeEventListener("focusin",u)):e.removeEventListener("scroll",u)}}),[u,n]),{viewportHeight:e,isIOS:n,isAndroid:a}}},678:(e,t,a)=>{a.d(t,{F1:()=>o,Pn:()=>i,Ve:()=>p,rn:()=>d,ti:()=>l,uE:()=>c,vx:()=>u});const{useMemo:n,useEffect:s,useState:r}=wp.element;function o(e,t=null,a=!0){const n=[];return JSON.stringify(e,((e,t)=>{if("object"==typeof t&&null!==t){if(n.includes(t)){if(!a)throw console.warn("Circular reference found.",{key:e,value:t,cache:n,cacheIndex:n.indexOf(t)}),new Error("Circular reference found. Cancelled.");return}n.push(t)}return t}),t)}async function i(e,t,a=null,n=null,s=!1){if(!t)try{const t=await e.json();return a&&console.log(`[${a}] IN: `,t),t.new_token&&(s&&console.log("[MWAI] Token refreshed!"),n&&n(t.new_token)),t}catch(e){return console.error("Could not parse the regular response.",{err:e,data}),{success:!1,message:"Could not parse the regular response."}}const r=e.body.getReader(),o=new TextDecoder("utf-8");let i="",l="";for(;;){const{value:e,done:c}=await r.read();if(i+=o.decode(e,{stream:!0}),c)break;const u=i.split("\n");for(let e=0;e<u.length-1;e++){if(0!==u[e].indexOf("data: "))continue;const r=JSON.parse(u[e].replace("data: ",""));if("live"===r.type)a&&console.log(`[${a} STREAM] LIVE: `,r),r.subtype?(t&&t(l,r),"content"===r.subtype&&(l+=r.data)):(l+=r.data,t&&t(l,r.data));else if("error"===r.type)try{return a&&console.error(`[${a} STREAM] ERROR: `,r.data),{success:!1,message:r.data}}catch(e){return console.error("Could not parse the 'error' stream.",{err:e,data:r}),{success:!1,message:"Could not parse the 'error' stream."}}else if("end"===r.type)try{const e=JSON.parse(r.data);return a&&console.log(`[${a} STREAM] END: `,e),e.new_token&&(s&&console.log("[MWAI] Token refreshed!"),n&&n(e.new_token)),e}catch(e){return console.error("Could not parse the 'end' stream.",{err:e,data:r}),{success:!1,message:"Could not parse the 'end' stream."}}}i=u[u.length-1]}try{const e=JSON.parse(i);return a&&console.log(`[${a} STREAM] IN: `,e),e}catch(e){return console.error("Could not parse the buffer.",{err:e,buffer:i}),{success:!1,message:"Could not parse the buffer."}}}async function l(e,t,a,n,s=void 0,r=null){const i={"Content-Type":"application/json"};a&&(i["X-WP-Nonce"]=a),n&&(i.Accept="text/event-stream");const l=await fetch(`${e}`,{method:"POST",headers:i,body:o(t),credentials:"same-origin",signal:s});if(403===l.status||401===l.status)try{const e=await l.clone().json();if("rest_cookie_invalid_nonce"===e.code||"rest_forbidden"===e.code)throw console.error("[MWAI] Authentication token has expired. Please refresh the page to continue."),new Error("Your session has expired. Please refresh the page to continue using AI Engine.")}catch(e){if(e.message&&e.message.includes("session has expired"))throw e}if(!n&&l.ok)try{const e=l.clone(),t=await e.json();t.new_token&&r&&r(t.new_token)}catch(e){}return l}async function c(e,t,a,n,s={}){return new Promise(((r,o)=>{const i=new FormData;i.append("file",t);for(const[e,t]of Object.entries(s))i.append(e,t);const l=new XMLHttpRequest;l.open("POST",e,!0),a&&l.setRequestHeader("X-WP-Nonce",a),l.upload.onprogress=function(e){if(e.lengthComputable&&n){const t=e.loaded/e.total*100;n(t)}},l.onload=function(){if(l.status>=200&&l.status<300)try{const e=JSON.parse(l.responseText);r(e)}catch(e){o({status:l.status,statusText:l.statusText,error:"The server response is not valid JSON"})}else{try{const e=JSON.parse(l.responseText);return void o({status:l.status,message:e.message})}catch(e){}o({status:l.status,statusText:l.statusText})}},l.onerror=function(){o({status:l.status,statusText:l.statusText})},l.send(i)}))}function u(){return Math.random().toString(36).substring(2)}const d=()=>{const[e,t]=r(!0);s((()=>{const e=setTimeout((()=>{const e=setInterval((()=>{t((e=>!e))}),500);return()=>clearInterval(e)}),200);return()=>clearTimeout(e)}),[]);const a={opacity:e?1:0,width:"1px",height:"1em",borderLeft:"8px solid",marginLeft:"2px"};return React.createElement("span",{style:a})},m=/([\u2700-\u27BF]|[\uE000-\uF8FF]|[\uD800-\uDFFF]|[\uFE00-\uFE0F]|[\u1F100-\u1F1FF]|[\u1F200-\u1F2FF]|[\u1F300-\u1F5FF]|[\u1F600-\u1F64F]|[\u1F680-\u1F6FF]|[\u1F700-\u1F77F]|[\u1F780-\u1F7FF]|[\u1F800-\u1F8FF]|[\u1F900-\u1F9FF]|[\u1FA00-\u1FA6F])/;function p(e){return e&&2===e.length&&m.test(e)}},213:(e,t,a)=>{a.d(t,{A:()=>s});const n=new class{constructor(){this.token=null,this.listeners=new Set}setToken(e){this.token!==e&&(this.token=e,this.notifyListeners())}getToken(){return this.token}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach((e=>e(this.token)))}};"undefined"!=typeof window&&window.mwai&&window.mwai.rest_nonce&&n.setToken(window.mwai.rest_nonce);const s=n},407:(e,t,a)=>{a.d(t,{A:()=>i});var n=a(594);const s=(...e)=>e.filter(((e,t,a)=>Boolean(e)&&""!==e.trim()&&a.indexOf(e)===t)).join(" ").trim();var r={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const o=(0,n.forwardRef)((({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:o,className:i="",children:l,iconNode:c,...u},d)=>(0,n.createElement)("svg",{ref:d,...r,width:t,height:t,stroke:e,strokeWidth:o?24*Number(a)/Number(t):a,className:s("lucide",i),...u},[...c.map((([e,t])=>(0,n.createElement)(e,t))),...Array.isArray(l)?l:[l]]))),i=(e,t)=>{const a=(0,n.forwardRef)((({className:a,...r},i)=>{return(0,n.createElement)(o,{ref:i,iconNode:t,className:s(`lucide-${l=e,l.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,a),...r});var l}));return a.displayName=`${e}`,a}},594:e=>{e.exports=React}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var a=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](a,a.exports,__webpack_require__),a.exports}__webpack_require__.d=(e,t)=>{for(var a in t)__webpack_require__.o(t,a)&&!__webpack_require__.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__={},ChatbotContext=__webpack_require__(469),helpers=__webpack_require__(728);const BouncingDots=()=>{const e={width:9,height:9,margin:"5px 0px 0px 5px",borderRadius:"50%",backgroundColor:"#a3a1a1",opacity:1,animation:"bouncing-loader 0.4s infinite alternate"};return React.createElement(React.Fragment,null,React.createElement("style",null,"\n          @keyframes bouncing-loader {\n            to {\n              opacity: 0.6;\n              transform: translateY(-10px);\n            }\n          }\n        "),React.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",width:"100%",height:26}},["0.1s","0.2s","0.3s"].map(((t,a)=>React.createElement("div",{key:a,style:{...e,animationDelay:t}})))))};function _extends(){return _extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},_extends.apply(this,arguments)}const{useState,useEffect,useRef,useCallback}=wp.element,svgPathDefault='<path d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" />',svgPathSuccess='<path d="M10.7673 18C10.3106 18 9.86749 17.8046 9.54432 17.4555L5.50694 13.1222C4.83102 12.3968 4.83102 11.2208 5.50694 10.4954C6.18287 9.76997 7.27871 9.76997 7.95505 10.4954L10.6794 13.4196L16.9621 5.63976C17.5874 4.86495 18.6832 4.78289 19.4031 5.45388C20.125 6.12487 20.2036 7.29638 19.5759 8.07391L12.0778 17.3589C11.7639 17.7475 11.3119 17.9801 10.8319 18C10.8087 18 10.788 18 10.7673 18Z" />',svgPathError='<path d="M17.7623 17.7626C17.0831 18.4418 15.9549 18.416 15.244 17.705L5.79906 8.26012C5.08811 7.54917 5.0623 6.42098 5.74145 5.74183C6.4206 5.06267 7.54879 5.08849 8.25975 5.79944L17.7047 15.2443C18.4156 15.9553 18.4414 17.0835 17.7623 17.7626Z" /><path d="M17.5508 8.52848L8.52842 17.5509C7.84927 18.23 6.72108 18.2042 6.01012 17.4933C5.29917 16.7823 5.27336 15.6541 5.95251 14.975L14.9749 5.95257C15.6541 5.27342 16.7823 5.29923 17.4932 6.01019C18.2042 6.72114 18.23 7.84933 17.5508 8.52848Z" />',ReplyActions=({enabled:e,content:t,children:a,className:n,...s})=>{const r=(0,helpers.gR)(),[o,i]=useState("idle"),[l,c]=useState(!0),u=useRef(null),d=useRef(!1),m=useCallback((()=>{d.current||(d.current=!0,u.current=setTimeout((()=>{c(!1)}),500))}),[]),p=useCallback((()=>{u.current&&clearTimeout(u.current),c(!0),d.current=!1}),[]);useEffect((()=>()=>{u.current&&clearTimeout(u.current)}),[]);const h="success"===o?svgPathSuccess:"error"===o?svgPathError:svgPathDefault;return React.createElement("div",_extends({},s,{onMouseLeave:p,onMouseEnter:m,onMouseOver:m}),React.createElement("span",{className:n},a),React.createElement("div",{className:r("mwai-reply-actions",{"mwai-hidden":l})},e&&React.createElement("div",{className:"mwai-copy-button",onClick:()=>{try{navigator.clipboard.writeText(t),i("success")}catch(e){i("error"),console.warn("Not allowed to copy to clipboard. Make sure your website uses HTTPS.",{content:t})}finally{setTimeout((()=>{i("idle")}),2e3)}}},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:h}}))))},components_ReplyActions=ReplyActions,{useState:ErrorReplyActions_useState}=wp.element,svgPathCopy='<path d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" />',ErrorReplyActions_svgPathSuccess='<path d="M10.7673 18C10.3106 18 9.86749 17.8046 9.54432 17.4555L5.50694 13.1222C4.83102 12.3968 4.83102 11.2208 5.50694 10.4954C6.18287 9.76997 7.27871 9.76997 7.95505 10.4954L10.6794 13.4196L16.9621 5.63976C17.5874 4.86495 18.6832 4.78289 19.4031 5.45388C20.125 6.12487 20.2036 7.29638 19.5759 8.07391L12.0778 17.3589C11.7639 17.7475 11.3119 17.9801 10.8319 18C10.8087 18 10.788 18 10.7673 18Z" />',ErrorReplyActions_svgPathError='<path d="M17.7623 17.7626C17.0831 18.4418 15.9549 18.416 15.244 17.705L5.79906 8.26012C5.08811 7.54917 5.0623 6.42098 5.74145 5.74183C6.4206 5.06267 7.54879 5.08849 8.25975 5.79944L17.7047 15.2443C18.4156 15.9553 18.4414 17.0835 17.7623 17.7626Z" /><path d="M17.5508 8.52848L8.52842 17.5509C7.84927 18.23 6.72108 18.2042 6.01012 17.4933C5.29917 16.7823 5.27336 15.6541 5.95251 14.975L14.9749 5.95257C15.6541 5.27342 16.7823 5.29923 17.4932 6.01019C18.2042 6.72114 18.23 7.84933 17.5508 8.52848Z" />',svgPathRetry='<path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>',svgPathDelete='<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>',ErrorReplyActions=({enabled:e,content:t,children:a,className:n,message:s,...r})=>{const o=(0,helpers.gR)(),{actions:i,state:l}=(0,ChatbotContext.o)(),{setMessages:c,saveMessages:u,retryLastQuery:d}=i,{messages:m}=l,[p,h]=ErrorReplyActions_useState("idle"),g=m.length>0&&m[m.length-1].id===s.id,_="success"===p?ErrorReplyActions_svgPathSuccess:"error"===p?ErrorReplyActions_svgPathError:svgPathCopy;return React.createElement("div",r,React.createElement("span",{className:n},a),React.createElement("div",{className:o("mwai-reply-actions")},React.createElement("div",{className:"mwai-copy-button",onClick:()=>{try{navigator.clipboard.writeText(t),h("success")}catch(e){h("error"),console.warn("Not allowed to copy to clipboard. Make sure your website uses HTTPS.",{content:t})}finally{setTimeout((()=>{h("idle")}),2e3)}},title:"Copy"},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:_}})),React.createElement("div",{className:"mwai-action-button",onClick:()=>{c((e=>{const t=e.findIndex((e=>e.id===s.id));let a;return a=t>0?e.filter(((e,a)=>a!==t&&a!==t-1)):e.filter((e=>e.id!==s.id)),u(a),a}))},title:"Delete"},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:svgPathDelete}})),s.failedQuery&&g&&React.createElement("div",{className:"mwai-action-button",onClick:()=>{s.failedQuery&&d&&(c((e=>{const t=e.findIndex((e=>e.id===s.id));let a;return a=t>0?e.filter(((e,a)=>a!==t&&a!==t-1)):e.filter((e=>e.id!==s.id)),u(a),a})),d())},title:"Retry"},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:svgPathRetry}}))))},chatbot_ErrorReplyActions=ErrorReplyActions;var js_helpers=__webpack_require__(678);const{useMemo}=wp.element,ChatbotName=({role:e="user"})=>{const{state:t}=(0,ChatbotContext.o)(),{pluginUrl:a,iconUrl:n,userData:s,userName:r,aiName:o,guestName:i,userAvatar:l,aiAvatar:c,guestAvatar:u,userAvatarUrl:d,aiAvatarUrl:m,guestAvatarUrl:p}=t,h=useMemo((()=>{const t="assistant"===e,h=!s&&!t,g=e=>React.createElement("div",{className:"mwai-name-text"},e),_=(e,t,n,s,r=!1)=>{if(!e)return null;if((0,js_helpers.Ve)(t))return o=t,React.createElement("div",{className:"mwai-avatar mwai-emoji",style:{fontSize:"32px",lineHeight:"32px"}},o);var o;const i=((e,t=!1)=>(0,helpers.mv)(e)?e:e&&!(0,js_helpers.Ve)(e)?t?e:`${a}/images/${e}`:(t||(0,js_helpers.Ve)(e)||console.warn("Invalid URL for avatar:",e),null))(t,r)||n;return i?((e,t)=>React.createElement("div",{className:"mwai-avatar"},React.createElement("img",{width:"32",height:"32",src:e,alt:t})))(i,s):null};if(t){const e=_(c,m,n,"AI Avatar");return e?(null===m&&n&&console.warn("Using iconUrl as a temporary fallback for AI avatar. Please set aiAvatarUrl."),e):g(o)}if(!h){return _(l,d,null==s?void 0:s.AVATAR_URL,"User Avatar",!0)||g(formatName(r,i,s))}if(h){return _(u,p,null,"Guest Avatar")||g(i||"Guest")}}),[e,o,r,i,s,n,c,l,u,m,d,p,a]);return React.createElement("span",{className:"mwai-name"},h)};function formatName(e,t,a){return a&&0!==Object.keys(a).length?Object.entries(a).reduce(((e,[t,a])=>{const n=`{${t}}`;return e.includes(n)?e.replace(n,a):e}),e):t||e||"Guest"}const chatbot_ChatbotName=ChatbotName;var external_React_=__webpack_require__(594);function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},t.apply(this,arguments)}const n=null,r={blockQuote:"0",breakLine:"1",breakThematic:"2",codeBlock:"3",codeFenced:"4",codeInline:"5",footnote:"6",footnoteReference:"7",gfmTask:"8",heading:"9",headingSetext:"10",htmlBlock:"11",htmlComment:"12",htmlSelfClosing:"13",image:"14",link:"15",linkAngleBraceStyleDetector:"16",linkBareUrlDetector:"17",linkMailtoDetector:"18",newlineCoalescer:"19",orderedList:"20",paragraph:"21",ref:"22",refImage:"23",refLink:"24",table:"25",tableSeparator:"26",text:"27",textBolded:"28",textEmphasized:"29",textEscaped:"30",textMarked:"31",textStrikethroughed:"32",unorderedList:"33"};var i;!function(e){e[e.MAX=0]="MAX",e[e.HIGH=1]="HIGH",e[e.MED=2]="MED",e[e.LOW=3]="LOW",e[e.MIN=4]="MIN"}(i||(i={}));const l=["allowFullScreen","allowTransparency","autoComplete","autoFocus","autoPlay","cellPadding","cellSpacing","charSet","className","classId","colSpan","contentEditable","contextMenu","crossOrigin","encType","formAction","formEncType","formMethod","formNoValidate","formTarget","frameBorder","hrefLang","inputMode","keyParams","keyType","marginHeight","marginWidth","maxLength","mediaGroup","minLength","noValidate","radioGroup","readOnly","rowSpan","spellCheck","srcDoc","srcLang","srcSet","tabIndex","useMap"].reduce(((e,t)=>(e[t.toLowerCase()]=t,e)),{for:"htmlFor"}),a={amp:"&",apos:"'",gt:">",lt:"<",nbsp:" ",quot:"“"},o=["style","script"],c=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,s=/mailto:/i,d=/\n{2,}$/,u=/^(\s*>[\s\S]*?)(?=\n{2,})/,p=/^ *> ?/gm,f=/^ {2,}\n/,h=/^(?:( *[-*_])){3,} *(?:\n *)+\n/,m=/^\s*(`{3,}|~{3,}) *(\S+)?([^\n]*?)?\n([\s\S]+?)\s*\1 *(?:\n *)*\n?/,g=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,y=/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,k=/^(?:\n *)*\n/,x=/\r\n?/g,b=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,v=/^\[\^([^\]]+)]/,S=/\f/g,E=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,$=/^\s*?\[(x|\s)\]/,w=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,C=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,z=/^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/,L=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,A=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,T=/^<!--[\s\S]*?(?:-->)/,O=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,B=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,M=/^\{.*\}$/,R=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,I=/^<([^ >]+@[^ >]+)>/,U=/^<([^ >]+:\/[^ >]+)>/,D=/-([a-z])?/gi,j=/^(.*\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,N=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,H=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,F=/^\[([^\]]*)\] ?\[([^\]]*)\]/,P=/(\[|\])/g,_=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,W=/\t/g,G=/(^ *\||\| *$)/g,Z=/^ *:-+: *$/,q=/^ *:-+ *$/,Q=/^ *-+: *$/,V="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|~~.*?~~|==.*?==|.|\\n)*?)",X=new RegExp(`^([*_])\\1${V}\\1\\1(?!\\1)`),J=new RegExp(`^([*_])${V}\\1(?!\\1|\\w)`),K=new RegExp(`^==${V}==`),Y=new RegExp(`^~~${V}~~`),ee=/^\\([^0-9A-Za-z\s])/,te=/^[\s\S]+?(?=[^0-9A-Z\s\u00c0-\uffff&#;.()'"]|\d+\.|\n\n| {2,}\n|\w+:\S|$)/i,ne=/^\n+/,re=/^([ \t]*)/,ie=/\\([^\\])/g,le=/ *\n+$/,ae=/(?:^|\n)( *)$/,oe="(?:\\d+\\.)",ce="(?:[*+-])";function se(e){return"( *)("+(1===e?oe:ce)+") +"}const de=se(1),ue=se(2);function pe(e){return new RegExp("^"+(1===e?de:ue))}const fe=pe(1),he=pe(2);function me(e){return new RegExp("^"+(1===e?de:ue)+"[^\\n]*(?:\\n(?!\\1"+(1===e?oe:ce)+" )[^\\n]*)*(\\n|$)","gm")}const ge=me(1),ye=me(2);function ke(e){const t=1===e?oe:ce;return new RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const xe=ke(1),be=ke(2);function ve(e,t){const a=1===t,n=a?xe:be,s=a?ge:ye,o=a?fe:he;return{match(e,t,a){const s=ae.exec(a);return s&&(t.list||!t.inline&&!t.simple)?n.exec(e=s[1]+e):null},order:1,parse(e,t,n){const r=a?+e[2]:void 0,i=e[0].replace(d,"\n").match(s);let l=!1;return{items:i.map((function(e,a){const s=o.exec(e)[0].length,r=new RegExp("^ {1,"+s+"}","gm"),c=e.replace(r,"").replace(o,""),u=a===i.length-1,d=-1!==c.indexOf("\n\n")||u&&l;l=d;const m=n.inline,p=n.list;let h;n.list=!0,d?(n.inline=!1,h=c.replace(le,"\n\n")):(n.inline=!0,h=c.replace(le,""));const g=t(h,n);return n.inline=m,n.list=p,g})),ordered:a,start:r}},render:(t,a,n)=>e(t.ordered?"ol":"ul",{key:n.key,start:t.type===r.orderedList?t.start:void 0},t.items.map((function(t,s){return e("li",{key:s},a(t,n))})))}}const Se=new RegExp("^\\[((?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*\\)"),Ee=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/,$e=[u,m,g,w,z,C,T,j,ge,xe,ye,be],we=[...$e,/^[^\n]+(?:  \n|\n{2,})/,L,B];function Ce(e){return e.replace(/[ÀÁÂÃÄÅàáâãä忯]/g,"a").replace(/[çÇ]/g,"c").replace(/[ðÐ]/g,"d").replace(/[ÈÉÊËéèêë]/g,"e").replace(/[ÏïÎîÍíÌì]/g,"i").replace(/[Ññ]/g,"n").replace(/[øØœŒÕõÔôÓóÒò]/g,"o").replace(/[ÜüÛûÚúÙù]/g,"u").replace(/[ŸÿÝý]/g,"y").replace(/[^a-z0-9- ]/gi,"").replace(/ /gi,"-").toLowerCase()}function ze(e){return Q.test(e)?"right":Z.test(e)?"center":q.test(e)?"left":null}function Le(e,t,a,n){const s=a.inTable;a.inTable=!0;let o=e.trim().split(/( *(?:`[^`]*`|<.*?>.*?<\/.*?>(?!<\/.*?>)|\\\||\|) *)/).reduce(((e,s)=>("|"===s.trim()?e.push(n?{type:r.tableSeparator}:{type:r.text,text:s}):""!==s&&e.push.apply(e,t(s,a)),e)),[]);a.inTable=s;let i=[[]];return o.forEach((function(e,t){e.type===r.tableSeparator?0!==t&&t!==o.length-1&&i.push([]):(e.type!==r.text||null!=o[t+1]&&o[t+1].type!==r.tableSeparator||(e.text=e.text.trimEnd()),i[i.length-1].push(e))})),i}function Ae(e,t,a){a.inline=!0;const n=e[2]?e[2].replace(G,"").split("|").map(ze):[],s=e[3]?function(e,t,a){return e.trim().split("\n").map((function(e){return Le(e,t,a,!0)}))}(e[3],t,a):[],o=Le(e[1],t,a,!!s.length);return a.inline=!1,s.length?{align:n,cells:s,header:o,type:r.table}:{children:o,type:r.paragraph}}function Te(e,t){return null==e.align[t]?{}:{textAlign:e.align[t]}}function Oe(e){return function(t,a){return a.inline?e.exec(t):null}}function Be(e){return function(t,a){return a.inline||a.simple?e.exec(t):null}}function Me(e){return function(t,a){return a.inline||a.simple?null:e.exec(t)}}function Re(e){return function(t){return e.exec(t)}}function Ie(e,t,a){if(t.inline||t.simple)return null;if(a&&!a.endsWith("\n"))return null;let n="";e.split("\n").every((e=>!$e.some((t=>t.test(e)))&&(n+=e+"\n",e.trim())));const s=n.trimEnd();return""==s?null:[n,s]}function Ue(e){try{if(decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"").match(/^\s*(javascript|vbscript|data(?!:image)):/i))return null}catch(e){return null}return e}function De(e){return e.replace(ie,"$1")}function je(e,t,a){const n=a.inline||!1,s=a.simple||!1;a.inline=!0,a.simple=!0;const r=e(t,a);return a.inline=n,a.simple=s,r}function Ne(e,t,a){const n=a.inline||!1,s=a.simple||!1;a.inline=!1,a.simple=!0;const r=e(t,a);return a.inline=n,a.simple=s,r}function He(e,t,a){const n=a.inline||!1;a.inline=!1;const s=e(t,a);return a.inline=n,s}const Fe=(e,t,a)=>({children:je(t,e[1],a)});function Pe(){return{}}function _e(){return null}function We(...e){return e.filter(Boolean).join(" ")}function Ge(e,t,a){let n=e;const s=t.split(".");for(;s.length&&(n=n[s[0]],void 0!==n);)s.shift();return n||a}function Ze(e="",n={}){function i(e,a,...s){const r=Ge(n.overrides,`${e}.props`,{});return n.createElement(function(e,t){const a=Ge(t,e);return a?"function"==typeof a||"object"==typeof a&&"render"in a?a:Ge(t,`${e}.component`,e):e}(e,n.overrides),t({},a,r,{className:We(null==a?void 0:a.className,r.className)||void 0}),...s)}function d(e){e=e.replace(E,"");let t=!1;n.forceInline?t=!0:n.forceBlock||(t=!1===_.test(e));const a=ae(Z(t?e:`${e.trimEnd().replace(ne,"")}\n\n`,{inline:t}));for(;"string"==typeof a[a.length-1]&&!a[a.length-1].trim();)a.pop();if(null===n.wrapper)return a;const s=n.wrapper||(t?"span":"div");let r;if(a.length>1||n.forceWrapper)r=a;else{if(1===a.length)return r=a[0],"string"==typeof r?i("span",{key:"outer"},r):r;r=null}return external_React_.createElement(s,{key:"outer"},r)}function V(e,t){const a=t.match(c);return a?a.reduce((function(t,a,s){const r=a.indexOf("=");if(-1!==r){const o=function(e){return-1!==e.indexOf("-")&&null===e.match(O)&&(e=e.replace(D,(function(e,t){return t.toUpperCase()}))),e}(a.slice(0,r)).trim(),i=function(e){const t=e[0];return('"'===t||"'"===t)&&e.length>=2&&e[e.length-1]===t?e.slice(1,-1):e}(a.slice(r+1).trim()),c=l[o]||o,u=t[c]=function(e,t,a,n){return"style"===t?a.split(/;\s?/).reduce((function(e,t){const a=t.slice(0,t.indexOf(":"));return e[a.trim().replace(/(-[a-z])/g,(e=>e[1].toUpperCase()))]=t.slice(a.length+1).trim(),e}),{}):"href"===t||"src"===t?n(a,e,t):(a.match(M)&&(a=a.slice(1,a.length-1)),"true"===a||"false"!==a&&a)}(e,o,i,n.sanitizer);"string"==typeof u&&(L.test(u)||B.test(u))&&(t[c]=external_React_.cloneElement(d(u.trim()),{key:s}))}else"style"!==a&&(t[l[a]||a]=!0);return t}),{}):null}n.overrides=n.overrides||{},n.sanitizer=n.sanitizer||Ue,n.slugify=n.slugify||Ce,n.namedCodesToUnicode=n.namedCodesToUnicode?t({},a,n.namedCodesToUnicode):a,n.createElement=n.createElement||external_React_.createElement;const q=[],G={},Q={[r.blockQuote]:{match:Me(u),order:1,parse:(e,t,a)=>({children:t(e[0].replace(p,""),a)}),render:(e,t,a)=>i("blockquote",{key:a.key},t(e.children,a))},[r.breakLine]:{match:Re(f),order:1,parse:Pe,render:(e,t,a)=>i("br",{key:a.key})},[r.breakThematic]:{match:Me(h),order:1,parse:Pe,render:(e,t,a)=>i("hr",{key:a.key})},[r.codeBlock]:{match:Me(g),order:0,parse:e=>({lang:void 0,text:e[0].replace(/^ {4}/gm,"").replace(/\n+$/,"")}),render:(e,a,n)=>i("pre",{key:n.key},i("code",t({},e.attrs,{className:e.lang?`lang-${e.lang}`:""}),e.text))},[r.codeFenced]:{match:Me(m),order:0,parse:e=>({attrs:V("code",e[3]||""),lang:e[2]||void 0,text:e[4],type:r.codeBlock})},[r.codeInline]:{match:Be(y),order:3,parse:e=>({text:e[2]}),render:(e,t,a)=>i("code",{key:a.key},e.text)},[r.footnote]:{match:Me(b),order:0,parse:e=>(q.push({footnote:e[2],identifier:e[1]}),{}),render:_e},[r.footnoteReference]:{match:Oe(v),order:1,parse:e=>({target:`#${n.slugify(e[1],Ce)}`,text:e[1]}),render:(e,t,a)=>i("a",{key:a.key,href:n.sanitizer(e.target,"a","href")},i("sup",{key:a.key},e.text))},[r.gfmTask]:{match:Oe($),order:1,parse:e=>({completed:"x"===e[1].toLowerCase()}),render:(e,t,a)=>i("input",{checked:e.completed,key:a.key,readOnly:!0,type:"checkbox"})},[r.heading]:{match:Me(n.enforceAtxHeadings?C:w),order:1,parse:(e,t,a)=>({children:je(t,e[2],a),id:n.slugify(e[2],Ce),level:e[1].length}),render:(e,t,a)=>i(`h${e.level}`,{id:e.id,key:a.key},t(e.children,a))},[r.headingSetext]:{match:Me(z),order:0,parse:(e,t,a)=>({children:je(t,e[1],a),level:"="===e[2]?1:2,type:r.heading})},[r.htmlBlock]:{match:Re(L),order:1,parse(e,t,a){const[,n]=e[3].match(re),s=new RegExp(`^${n}`,"gm"),r=e[3].replace(s,""),i=(l=r,we.some((e=>e.test(l)))?He:je);var l;const c=e[1].toLowerCase(),u=-1!==o.indexOf(c),d=(u?c:e[1]).trim(),m={attrs:V(d,e[2]),noInnerParse:u,tag:d};return a.inAnchor=a.inAnchor||"a"===c,u?m.text=e[3]:m.children=i(t,r,a),a.inAnchor=!1,m},render:(e,a,n)=>i(e.tag,t({key:n.key},e.attrs),e.text||a(e.children,n))},[r.htmlSelfClosing]:{match:Re(B),order:1,parse(e){const t=e[1].trim();return{attrs:V(t,e[2]||""),tag:t}},render:(e,a,n)=>i(e.tag,t({},e.attrs,{key:n.key}))},[r.htmlComment]:{match:Re(T),order:1,parse:()=>({}),render:_e},[r.image]:{match:Be(Ee),order:1,parse:e=>({alt:e[1],target:De(e[2]),title:e[3]}),render:(e,t,a)=>i("img",{key:a.key,alt:e.alt||void 0,title:e.title||void 0,src:n.sanitizer(e.target,"img","src")})},[r.link]:{match:Oe(Se),order:3,parse:(e,t,a)=>({children:Ne(t,e[1],a),target:De(e[2]),title:e[3]}),render:(e,t,a)=>i("a",{key:a.key,href:n.sanitizer(e.target,"a","href"),title:e.title},t(e.children,a))},[r.linkAngleBraceStyleDetector]:{match:Oe(U),order:0,parse:e=>({children:[{text:e[1],type:r.text}],target:e[1],type:r.link})},[r.linkBareUrlDetector]:{match:(e,t)=>t.inAnchor?null:Oe(R)(e,t),order:0,parse:e=>({children:[{text:e[1],type:r.text}],target:e[1],title:void 0,type:r.link})},[r.linkMailtoDetector]:{match:Oe(I),order:0,parse(e){let t=e[1],a=e[1];return s.test(a)||(a="mailto:"+a),{children:[{text:t.replace("mailto:",""),type:r.text}],target:a,type:r.link}}},[r.orderedList]:ve(i,1),[r.unorderedList]:ve(i,2),[r.newlineCoalescer]:{match:Me(k),order:3,parse:Pe,render:()=>"\n"},[r.paragraph]:{match:Ie,order:3,parse:Fe,render:(e,t,a)=>i("p",{key:a.key},t(e.children,a))},[r.ref]:{match:Oe(N),order:0,parse:e=>(G[e[1]]={target:e[2],title:e[4]},{}),render:_e},[r.refImage]:{match:Be(H),order:0,parse:e=>({alt:e[1]||void 0,ref:e[2]}),render:(e,t,a)=>G[e.ref]?i("img",{key:a.key,alt:e.alt,src:n.sanitizer(G[e.ref].target,"img","src"),title:G[e.ref].title}):null},[r.refLink]:{match:Oe(F),order:0,parse:(e,t,a)=>({children:t(e[1],a),fallbackChildren:t(e[0].replace(P,"\\$1"),a),ref:e[2]}),render:(e,t,a)=>G[e.ref]?i("a",{key:a.key,href:n.sanitizer(G[e.ref].target,"a","href"),title:G[e.ref].title},t(e.children,a)):i("span",{key:a.key},t(e.fallbackChildren,a))},[r.table]:{match:Me(j),order:1,parse:Ae,render(e,t,a){const n=e;return i("table",{key:a.key},i("thead",null,i("tr",null,n.header.map((function(e,s){return i("th",{key:s,style:Te(n,s)},t(e,a))})))),i("tbody",null,n.cells.map((function(e,s){return i("tr",{key:s},e.map((function(e,s){return i("td",{key:s,style:Te(n,s)},t(e,a))})))}))))}},[r.text]:{match:Re(te),order:4,parse:e=>({text:e[0].replace(A,((e,t)=>n.namedCodesToUnicode[t]?n.namedCodesToUnicode[t]:e))}),render:e=>e.text},[r.textBolded]:{match:Be(X),order:2,parse:(e,t,a)=>({children:t(e[2],a)}),render:(e,t,a)=>i("strong",{key:a.key},t(e.children,a))},[r.textEmphasized]:{match:Be(J),order:3,parse:(e,t,a)=>({children:t(e[2],a)}),render:(e,t,a)=>i("em",{key:a.key},t(e.children,a))},[r.textEscaped]:{match:Be(ee),order:1,parse:e=>({text:e[1],type:r.text})},[r.textMarked]:{match:Be(K),order:3,parse:Fe,render:(e,t,a)=>i("mark",{key:a.key},t(e.children,a))},[r.textStrikethroughed]:{match:Be(Y),order:3,parse:Fe,render:(e,t,a)=>i("del",{key:a.key},t(e.children,a))}};!0===n.disableParsingRawHTML&&(delete Q[r.htmlBlock],delete Q[r.htmlSelfClosing]);const Z=function(e){let t=Object.keys(e);function a(n,s){let r=[],o="";for(;n;){let i=0;for(;i<t.length;){const l=t[i],c=e[l],u=c.match(n,s,o);if(u){const e=u[0];n=n.substring(e.length);const t=c.parse(u,a,s);null==t.type&&(t.type=l),r.push(t),o=e;break}i++}}return r}return t.sort((function(t,a){let n=e[t].order,s=e[a].order;return n!==s?n-s:t<a?-1:1})),function(e,t){return a(function(e){return e.replace(x,"\n").replace(S,"").replace(W,"    ")}(e),t)}}(Q),ae=(se=function(e,t){return function(a,n,s){const r=e[a.type].render;return t?t((()=>r(a,n,s)),a,n,s):r(a,n,s)}}(Q,n.renderRule),function e(t,a={}){if(Array.isArray(t)){const n=a.key,s=[];let r=!1;for(let n=0;n<t.length;n++){a.key=n;const o=e(t[n],a),i="string"==typeof o;i&&r?s[s.length-1]+=o:null!==o&&s.push(o),r=i}return a.key=n,s}return se(t,e,a)});var se;const oe=d(e);return q.length?i("div",null,oe,i("footer",{key:"footer"},q.map((function(e){return i("div",{id:n.slugify(e.identifier,Ce),key:e.identifier},e.identifier,ae(Z(e.footnote,{inline:!0})))})))):oe}const index_modern=t=>{let{children:a="",options:s}=t,r=function(e,t){if(null==e)return{};var a,n,s={},r=Object.keys(e);for(n=0;n<r.length;n++)t.indexOf(a=r[n])>=0||(s[a]=e[a]);return s}(t,n);return e.cloneElement(Ze(a,s),r)},{useMemo:ChatbotContent_useMemo}=wp.element,LinkContainer=({href:e,children:t})=>{if(!e)return React.createElement("span",null,t);const a="_blank";if("Uploaded File"===String(t)){const t=e.split("/").pop();return React.createElement("a",{href:e,target:a,rel:"noopener noreferrer",className:"mwai-filename"},React.createElement("span",null,"✓ ",t))}return React.createElement("a",{href:e,target:a,rel:"noopener noreferrer"},t)},ChatbotContent=({message:e})=>{let t=e.content??"";(t.match(/```/g)||[]).length%2!=0&&(t+="\n```");const a=ChatbotContent_useMemo((()=>({overrides:{BlinkingCursor:{component:js_helpers.rn},a:{component:LinkContainer},img:{props:{onError:e=>{null!==e.target.src.match(/\.(jpeg|jpg|gif|png)$/)&&(e.target.src="https://placehold.co/600x200?text=Expired+Image")},className:"mwai-image"}}}})),[]),n=ChatbotContent_useMemo((()=>{let e="";try{e=Ze(t,a)}catch(a){console.error("Crash in markdown-to-jsx! Reverting to plain text.",{e:a,content:t}),e=t}return e}),[t,a]);return e.isStreaming?React.createElement(React.Fragment,null,n,React.createElement(js_helpers.rn,null)):n},chatbot_ChatbotContent=ChatbotContent,{useState:ChatbotReply_useState,useMemo:ChatbotReply_useMemo,useEffect:ChatbotReply_useEffect,useRef:ChatbotReply_useRef}=wp.element,RawMessage=({message:e,onRendered:t=(()=>{})})=>{const{state:a}=(0,ChatbotContext.o)(),{copyButton:n,debugMode:s}=a,[r]=ChatbotReply_useState(e.isQuerying||e.isStreaming),o=e.isQuerying,i=e.isStreaming;if(ChatbotReply_useEffect((()=>{r&&(!r||o||i)||t()}),[r,o,i]),o)return React.createElement(BouncingDots,null);const l=e.isError||"error"===e.role?chatbot_ErrorReplyActions:components_ReplyActions;return React.createElement(React.Fragment,null,React.createElement(chatbot_ChatbotName,{role:e.role}),React.createElement(l,{content:e.content,enabled:n,className:"mwai-text",message:e},React.createElement(chatbot_ChatbotContent,{message:e})))},ImagesMessage=({message:e,onRendered:t=(()=>{})})=>{const[a,n]=ChatbotReply_useState(null==e?void 0:e.images);return ChatbotReply_useEffect((()=>{t()})),e.isQuerying?React.createElement(BouncingDots,null):React.createElement(React.Fragment,null,React.createElement(chatbot_ChatbotName,{role:e.role}),React.createElement("span",{className:"mwai-text"},React.createElement("div",{className:"mwai-gallery"},null==a?void 0:a.map(((e,t)=>React.createElement("a",{key:t,href:e,target:"_blank",rel:"noopener noreferrer"},React.createElement("img",{key:t,src:e,onError:()=>(e=>{n((t=>t.map(((t,a)=>a===e?"https://placehold.co/600x200?text=Expired+Image":t))))})(t)})))))))},ChatbotReply=({message:e,conversationRef:t})=>{var a;const{state:n,actions:s}=(0,ChatbotContext.o)(),{typewriter:r}=n,{setMessages:o,retryLastQuery:i}=s,l=(0,helpers.gR)(),c=ChatbotReply_useRef(),u=l("mwai-reply",{"mwai-ai":"assistant"===e.role,"mwai-user":"user"===e.role,"mwai-system":"system"===e.role,"mwai-error":"error"===e.role||e.isError}),d=(null==e||null===(a=e.images)||void 0===a?void 0:a.length)>0,m="error"===e.role||e.isError,p=()=>{!c.current||e.isQuerying||c.current.classList.contains("mwai-rendered")||"undefined"==typeof hljs||(c.current.classList.add("mwai-rendered"),c.current.querySelectorAll("pre code").forEach((e=>{hljs.highlightElement(e)})))};return ChatbotReply_useMemo((()=>{if("user"===e.role)return React.createElement("div",{ref:c,className:u},React.createElement(RawMessage,{message:e}));if("assistant"===e.role)return d?React.createElement("div",{ref:c,className:u},React.createElement(ImagesMessage,{message:e,conversationRef:t,onRendered:p})):React.createElement("div",{ref:c,className:u},React.createElement(RawMessage,{message:e,conversationRef:t,onRendered:p}));if("system"===e.role&&!m)return React.createElement("div",{ref:c,className:u},React.createElement(RawMessage,{message:e,conversationRef:t,onRendered:p}));if(m){const a={...e,role:"assistant"};return React.createElement("div",{ref:c,className:u},React.createElement(RawMessage,{message:a,conversationRef:t,onRendered:p}))}return React.createElement("div",null,React.createElement("i",null,"Unhandled role."))}),[e,t,d,r])},chatbot_ChatbotReply=ChatbotReply,{useMemo:ChatbotHeader_useMemo}=wp.element;function formatAvatar(e,t,a,n){if((0,js_helpers.Ve)(n||a))return s=n||a,React.createElement("div",{className:"mwai-avatar mwai-emoji",style:{fontSize:"48px",lineHeight:"48px"}},s);var s;const r=(o=n,((0,helpers.mv)(o)?o:o?`${t}/images/${o}`:null)||a||`${t}/images/chat-openai.svg`);var o,i;return r?(i=r,"AI Engine",React.createElement("div",{className:"mwai-avatar"},React.createElement("img",{alt:"AI Engine",src:i}))):React.createElement("div",{className:"mwai-name-text"},e)}const ChatbotHeader=()=>{const{state:e,actions:t}=(0,ChatbotContext.o)(),{theme:a,isWindow:n,fullscreen:s,aiName:r,pluginUrl:o,open:i,iconUrl:l,aiAvatarUrl:c,windowed:u,headerSubtitle:d}=e,{setOpen:m,setWindowed:p}=t,h=ChatbotHeader_useMemo((()=>{if(!n)return null;const e="timeless"===(null==a?void 0:a.themeId),t=e?formatAvatar(r,o,l,c):null,h=null==d?"Discuss with":d;return React.createElement(React.Fragment,null,e&&React.createElement(React.Fragment,null,t,React.createElement("div",{className:"mwai-name"},h&&React.createElement("small",{className:"mwai-subtitle"},h),React.createElement("div",null,r)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-buttons"},s&&React.createElement("div",{className:"mwai-resize-button",onClick:()=>p(!u)}),React.createElement("div",{className:"mwai-close-button",onClick:()=>m(!i)})))}),[n,null==a?void 0:a.themeId,r,o,l,c,s,p,u,m,i,d]);return React.createElement("div",{className:"mwai-header"},h)},chatbot_ChatbotHeader=ChatbotHeader,{useMemo:ChatbotTrigger_useMemo,useEffect:ChatbotTrigger_useEffect}=wp.element,ChatbotTrigger=()=>{const{state:e,actions:t}=(0,ChatbotContext.o)(),{isWindow:a,iconText:n,showIconMessage:s,iconAlt:r,iconUrl:o,open:i}=e,{setShowIconMessage:l,setOpen:c}=t;ChatbotTrigger_useEffect((()=>{i&&s&&l(!1)}),[i,l,s]);const u=ChatbotTrigger_useMemo((()=>a?React.createElement("div",{className:"mwai-trigger mwai-open-button"},React.createElement(helpers.bE,{className:"mwai-icon-text-container",if:n&&s},React.createElement("div",{className:"mwai-icon-text-close",onClick:()=>l(!1)},"✕"),React.createElement("div",{className:"mwai-icon-text",onClick:()=>c(!0)},n)),React.createElement("div",{className:"mwai-icon-container",onClick:()=>c(!0)},(0,js_helpers.Ve)(o)?React.createElement("div",{className:"mwai-icon mwai-emoji",style:{fontSize:"48px",lineHeight:"64px",width:"64px",height:"64px",display:"flex",justifyContent:"center",alignItems:"center"}},o):React.createElement("img",{className:"mwai-icon",width:"64",height:"64",alt:r,src:o}))):null),[a,n,s,r,o,l,c]);return React.createElement(React.Fragment,null,u)},chatbot_ChatbotTrigger=ChatbotTrigger;function extends_extends(){return extends_extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},extends_extends.apply(this,arguments)}function _objectWithoutPropertiesLoose(e,t){if(null==e)return{};var a,n,s={},r=Object.keys(e);for(n=0;n<r.length;n++)a=r[n],t.indexOf(a)>=0||(s[a]=e[a]);return s}var index=external_React_.useLayoutEffect;const use_isomorphic_layout_effect_browser_esm=index;var useLatest=function(e){var t=external_React_.useRef(e);return use_isomorphic_layout_effect_browser_esm((function(){t.current=e})),t},updateRef=function(e,t){"function"!=typeof e?e.current=t:e(t)},useComposedRef=function(e,t){var a=(0,external_React_.useRef)();return(0,external_React_.useCallback)((function(n){e.current=n,a.current&&updateRef(a.current,null),a.current=t,t&&updateRef(t,n)}),[t])};const use_composed_ref_esm=useComposedRef;var HIDDEN_TEXTAREA_STYLE={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0"},forceHiddenStyles=function(e){Object.keys(HIDDEN_TEXTAREA_STYLE).forEach((function(t){e.style.setProperty(t,HIDDEN_TEXTAREA_STYLE[t],"important")}))},forceHiddenStyles$1=forceHiddenStyles,hiddenTextarea=null,getHeight=function(e,t){var a=e.scrollHeight;return"border-box"===t.sizingStyle.boxSizing?a+t.borderSize:a-t.paddingSize};function calculateNodeHeight(e,t,a,n){void 0===a&&(a=1),void 0===n&&(n=1/0),hiddenTextarea||((hiddenTextarea=document.createElement("textarea")).setAttribute("tabindex","-1"),hiddenTextarea.setAttribute("aria-hidden","true"),forceHiddenStyles$1(hiddenTextarea)),null===hiddenTextarea.parentNode&&document.body.appendChild(hiddenTextarea);var s=e.paddingSize,r=e.borderSize,o=e.sizingStyle,i=o.boxSizing;Object.keys(o).forEach((function(e){var t=e;hiddenTextarea.style[t]=o[t]})),forceHiddenStyles$1(hiddenTextarea),hiddenTextarea.value=t;var l=getHeight(hiddenTextarea,e);hiddenTextarea.value=t,l=getHeight(hiddenTextarea,e),hiddenTextarea.value="x";var c=hiddenTextarea.scrollHeight-s,u=c*a;"border-box"===i&&(u=u+s+r),l=Math.max(u,l);var d=c*n;return"border-box"===i&&(d=d+s+r),[l=Math.min(d,l),c]}var noop=function(){},pick=function(e,t){return e.reduce((function(e,a){return e[a]=t[a],e}),{})},SIZING_STYLE=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak"],isIE=!!document.documentElement.currentStyle,getSizingData=function(e){var t=window.getComputedStyle(e);if(null===t)return null;var a=pick(SIZING_STYLE,t),n=a.boxSizing;return""===n?null:(isIE&&"border-box"===n&&(a.width=parseFloat(a.width)+parseFloat(a.borderRightWidth)+parseFloat(a.borderLeftWidth)+parseFloat(a.paddingRight)+parseFloat(a.paddingLeft)+"px"),{sizingStyle:a,paddingSize:parseFloat(a.paddingBottom)+parseFloat(a.paddingTop),borderSize:parseFloat(a.borderBottomWidth)+parseFloat(a.borderTopWidth)})},getSizingData$1=getSizingData;function useListener(e,t,a){var n=useLatest(a);external_React_.useLayoutEffect((function(){var a=function(e){return n.current(e)};if(e)return e.addEventListener(t,a),function(){return e.removeEventListener(t,a)}}),[])}var useWindowResizeListener=function(e){useListener(window,"resize",e)},useFontsLoadedListener=function(e){useListener(document.fonts,"loadingdone",e)},_excluded=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],TextareaAutosize=function(e,t){var a=e.cacheMeasurements,n=e.maxRows,s=e.minRows,r=e.onChange,o=void 0===r?noop:r,i=e.onHeightChange,l=void 0===i?noop:i,c=_objectWithoutPropertiesLoose(e,_excluded),u=void 0!==c.value,d=external_React_.useRef(null),m=use_composed_ref_esm(d,t),p=external_React_.useRef(0),h=external_React_.useRef(),g=function(){var e=d.current,t=a&&h.current?h.current:getSizingData$1(e);if(t){h.current=t;var r=calculateNodeHeight(t,e.value||e.placeholder||"x",s,n),o=r[0],i=r[1];p.current!==o&&(p.current=o,e.style.setProperty("height",o+"px","important"),l(o,{rowHeight:i}))}};return external_React_.useLayoutEffect(g),useWindowResizeListener(g),useFontsLoadedListener(g),external_React_.createElement("textarea",extends_extends({},c,{onChange:function(e){u||g(),o(e)},ref:m}))},react_textarea_autosize_browser_esm_index=external_React_.forwardRef(TextareaAutosize);const{useState:ChatUploadIcon_useState,useMemo:ChatUploadIcon_useMemo,useRef:ChatUploadIcon_useRef}=wp.element,ChatUploadIcon=()=>{const e=(0,helpers.gR)(),{state:t,actions:a}=(0,ChatbotContext.o)(),{uploadedFile:n,busy:s,imageUpload:r,fileUpload:o,fileSearch:i,draggingType:l}=t,{onUploadFile:c}=a,[u,d]=ChatUploadIcon_useState(!1),m=ChatUploadIcon_useRef(),p=null==n?void 0:n.uploadedId,h=r||i||o,g=n,_=ChatUploadIcon_useMemo((()=>null!=g&&g.localFile?g.localFile.type.startsWith("image/")?"image":"document":l),[g,l]),f=ChatUploadIcon_useMemo((()=>{let e="idle";return null!=g&&g.uploadProgress?e="up":l?e="add":u&&p?e="del":p?e="ok":u&&!p&&(e="add"),`mwai-file-upload-icon mwai-${_?_.toLowerCase():"idle"}-${e}`}),[_,g,l,u,p]),y=ChatUploadIcon_useMemo((()=>null!=g&&g.uploadProgress?g.uploadProgress>99?99:Math.round(g.uploadProgress):""),[g]);return h?React.createElement("div",{disabled:s,onClick:()=>{null!=n&&n.localFile?c(null):s||m.current.click()},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),className:e("mwai-file-upload",{"mwai-enabled":null==n?void 0:n.uploadedId,"mwai-busy":(null==n?void 0:n.localFile)&&!(null!=n&&n.uploadedId)}),style:{cursor:s?"default":"pointer"}},React.createElement("div",{className:f},React.createElement("span",{className:"mwai-file-upload-progress"},y)),React.createElement("input",{type:"file",ref:m,onChange:e=>{const t=e.target.files[0];t&&c(t)},style:{display:"none"}})):null},chatbot_ChatUploadIcon=ChatUploadIcon,{useRef:ChatbotInput_useRef,useState:ChatbotInput_useState,useEffect:ChatbotInput_useEffect,useImperativeHandle}=wp.element,ChatbotInput=()=>{const e=(0,helpers.gR)(),{state:t,actions:a}=(0,ChatbotContext.o)(),{inputText:n,textInputMaxLength:s,textInputPlaceholder:r,error:o,speechRecognitionAvailable:i,isMobile:l,conversationRef:c,open:u,uploadIconPosition:d,locked:m,isListening:p,busy:h,speechRecognition:g,chatbotInputRef:_}=t,{onSubmitAction:f,setIsListening:y,resetError:b,setInputText:v}=a,[E,R]=ChatbotInput_useState(!1),w=ChatbotInput_useRef();useImperativeHandle(_,(()=>({focusInput:()=>{var e;null===(e=w.current)||void 0===e||e.focus()},currentElement:()=>w.current}))),ChatbotInput_useEffect((()=>{!l&&u&&w.current.focus(),c.current&&(c.current.scrollTop=c.current.scrollHeight)}),[u,l,c]);const C=e("mwai-input-text",{});return React.createElement("div",{ref:_,className:C},"mwai-input"===d&&React.createElement(chatbot_ChatUploadIcon,null),React.createElement(react_textarea_autosize_browser_esm_index,{ref:w,disabled:h||m,placeholder:r,value:n,maxLength:s,onCompositionStart:()=>R(!0),onCompositionEnd:()=>R(!1),onKeyDown:e=>{E||"Enter"!==e.code||e.shiftKey||(e.preventDefault(),f())},onChange:e=>{return t=e.target.value,p&&y(!1),o&&b(),void v(t);var t}}),g&&React.createElement(helpers.tm,{active:p,disabled:!i||h,className:"mwai-microphone",onClick:()=>y(!p)}))},chatbot_ChatbotInput=ChatbotInput;var createLucideIcon=__webpack_require__(407);const Send=(0,createLucideIcon.A)("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]),Eraser=(0,createLucideIcon.A)("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),{useMemo:ChatbotSubmit_useMemo,useCallback:ChatbotSubmit_useCallback}=wp.element,ChatbotSubmit=()=>{const{state:e,actions:t}=(0,ChatbotContext.o)(),{onClear:a,onSubmitAction:n,setIsListening:s}=t,{textClear:r,textSend:o,uploadedFile:i,inputText:l,messages:c,isListening:u,timeElapsed:d,busy:m,submitButtonConf:p,locked:h}=e,g=!(null==i||!i.uploadProgress),_=!(null!=i&&i.uploadedId)&&l.length<1&&(null==c?void 0:c.length)>1,f=ChatbotSubmit_useMemo((()=>m?d?React.createElement("div",{className:"mwai-timer"},d):null:null!=p&&p.imageSend&&null!=p&&p.imageClear?React.createElement("img",{src:_?p.imageClear:p.imageSend,alt:_?r:o}):_||o?_&&!r?React.createElement(Eraser,{size:"20"}):React.createElement("span",null,_?r:o):React.createElement(Send,{size:"20",style:{marginLeft:10}})),[m,d,_,r,o,p]),y=ChatbotSubmit_useMemo((()=>"mwai-input-submit "+(m?"mwai-busy":"")),[m]),b=ChatbotSubmit_useCallback((()=>{u&&s(!1),_?a():n()}),[_,u,a,n,s]),v=ChatbotSubmit_useCallback((()=>{m||b()}),[m,b]);return React.createElement("button",{className:y,disabled:m||g||h,onClick:v},f)},chatbot_ChatbotSubmit=ChatbotSubmit,Play=(0,createLucideIcon.A)("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]),Loader=(0,createLucideIcon.A)("Loader",[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]]),Square=(0,createLucideIcon.A)("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),Pause=(0,createLucideIcon.A)("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]),Users=(0,createLucideIcon.A)("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]),Captions=(0,createLucideIcon.A)("Captions",[["rect",{width:"18",height:"14",x:"3",y:"5",rx:"2",ry:"2",key:"12ruh7"}],["path",{d:"M7 15h4M15 15h2M7 11h2M13 11h4",key:"1ueiar"}]]),Bug=(0,createLucideIcon.A)("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]),{useState:AudioVisualizer_useState,useRef:AudioVisualizer_useRef,useEffect:AudioVisualizer_useEffect}=wp.element;function measureVolume(e,t){e.getByteTimeDomainData(t);let a=0;for(let e=0;e<t.length;e++){const n=t[e]-128;a+=n*n}return Math.sqrt(a/t.length)}function AudioVisualizerTwoStreams({assistantStream:e=null,userStream:t=null,assistantColor:a=null,userColor:n=null,userUI:s={emoji:null,text:null,image:null,use:"text"},assistantUI:r={emoji:null,text:null,image:null,use:"text"},attackSpeed:o=.3,releaseSpeed:i=.05,circleSize:l=50,pulseMaxSize:c=30}){const[u,d]=AudioVisualizer_useState(0),[m,p]=AudioVisualizer_useState(0),h=AudioVisualizer_useRef(0),g=AudioVisualizer_useRef(0),_=AudioVisualizer_useRef(null),f=AudioVisualizer_useRef(null),y=AudioVisualizer_useRef(null),b=AudioVisualizer_useRef(null),v=AudioVisualizer_useRef(null);AudioVisualizer_useEffect((()=>{if(!e&&!t)return;_.current||(_.current=new AudioContext);const a=_.current;let n,s,r;e&&(n=a.createMediaStreamSource(e),f.current=a.createAnalyser(),f.current.fftSize=1024,y.current=new Uint8Array(f.current.frequencyBinCount),n.connect(f.current)),t&&(s=a.createMediaStreamSource(t),b.current=a.createAnalyser(),b.current.fftSize=1024,v.current=new Uint8Array(b.current.frequencyBinCount),s.connect(b.current));const l=()=>{let e=0;f.current&&y.current&&(e=measureVolume(f.current,y.current));let t=0;b.current&&v.current&&(t=measureVolume(b.current,v.current)),e>h.current?h.current=h.current*(1-o)+e*o:h.current=h.current*(1-i)+e*i,t>g.current?g.current=g.current*(1-o)+t*o:g.current=g.current*(1-i)+t*i,d(h.current),p(g.current),r=requestAnimationFrame(l)};return l(),()=>{n&&n.disconnect(),f.current&&f.current.disconnect(),s&&s.disconnect(),b.current&&b.current.disconnect(),r&&cancelAnimationFrame(r)}}),[e,t,o,i]);const E=l+Math.min(u/20,1)*c,R=l+Math.min(m/20,1)*c,w=l+c,C={width:R,height:R,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",opacity:.5};n&&(C.backgroundColor=n);const k={width:E,height:E,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",opacity:.5};a&&(k.backgroundColor=a);const x={width:l,height:l,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"flex",justifyContent:"center",alignItems:"center",overflow:"hidden",color:"#fff"};n&&(x.backgroundColor=n);const S={width:l,height:l,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"flex",justifyContent:"center",alignItems:"center",overflow:"hidden",color:"#fff"};a&&(S.backgroundColor=a);let I="mwai-visualizer";m>u?I+=" mwai-user-talking":u>m&&(I+=" mwai-assistant-talking");const M=e=>{if(!e)return null;const{emoji:t,text:a,image:n,use:s}=e;switch(s){case"emoji":return t?React.createElement("span",null,t):a?React.createElement("span",null,a.slice(0,1)):null;case"image":return n?React.createElement("img",{src:n,alt:"",style:{width:"100%",height:"100%",borderRadius:"50%"}}):t?React.createElement("span",null,t):a?React.createElement("span",null,a.slice(0,1)):null;default:return a?React.createElement("span",null,a.slice(0,1)):t?React.createElement("span",null,t):null}};return React.createElement("div",{className:I},React.createElement("div",{className:"mwai-visualizer-user",style:{position:"relative",width:w,height:w,overflow:"visible"}},React.createElement("div",{className:"mwai-animation",style:C}),React.createElement("div",{style:x},M(s))),React.createElement("hr",{className:"mwai-visualizer-line"}),React.createElement("div",{className:"mwai-visualizer-assistant",style:{position:"relative",width:w,height:w,overflow:"visible"}},React.createElement("div",{className:"mwai-animation",style:k}),React.createElement("div",{style:S},M(r))))}const STREAM_TYPES={CONTENT:"content",THINKING:"thinking",CODE:"code",TOOL_CALL:"tool_call",TOOL_ARGS:"tool_args",TOOL_RESULT:"tool_result",MCP_DISCOVERY:"mcp_discovery",WEB_SEARCH:"web_search",FILE_SEARCH:"file_search",IMAGE_GEN:"image_gen",EMBEDDINGS:"embeddings",DEBUG:"debug",STATUS:"status",ERROR:"error",WARNING:"warning",TRANSCRIPT:"transcript",START:"start",END:"end",HEARTBEAT:"heartbeat"},STREAM_VISIBILITY={VISIBLE:"visible",HIDDEN:"hidden",COLLAPSED:"collapsed"},getDefaultVisibility=e=>{const t=[STREAM_TYPES.TOOL_ARGS,STREAM_TYPES.DEBUG,STREAM_TYPES.HEARTBEAT],a=[STREAM_TYPES.THINKING,STREAM_TYPES.MCP_DISCOVERY,STREAM_TYPES.STATUS];return t.includes(e)?STREAM_VISIBILITY.HIDDEN:a.includes(e)?STREAM_VISIBILITY.COLLAPSED:STREAM_VISIBILITY.VISIBLE};class RealtimeEventEmitter{constructor(e,t=!1){this.onEvent=e,this.eventLogsEnabled=t,this.sessionStartTime=null}emit(e,t,a={}){if(!this.eventLogsEnabled||!this.onEvent)return;const n={type:"event",subtype:e,data:t,timestamp:(new Date).getTime(),...a};this.onEvent("",n)}sessionStarting(){this.sessionStartTime=(new Date).getTime(),this.emit(STREAM_TYPES.STATUS,"Starting realtime session...")}sessionConnected(){const e=this.sessionStartTime?(new Date).getTime()-this.sessionStartTime:0;this.emit(STREAM_TYPES.STATUS,`Realtime session connected in ${e}ms.`)}sessionEnding(){this.emit(STREAM_TYPES.STATUS,"Ending realtime session...")}sessionError(e){this.emit(STREAM_TYPES.ERROR,`Realtime session error: ${e}`)}userStartedSpeaking(){this.emit(STREAM_TYPES.STATUS,"User speaking...",{visibility:"collapsed"})}userStoppedSpeaking(){this.emit(STREAM_TYPES.STATUS,"User finished speaking.",{visibility:"collapsed"})}assistantStartedSpeaking(){this.emit(STREAM_TYPES.STATUS,"Assistant speaking...",{visibility:"collapsed"})}assistantStoppedSpeaking(){this.emit(STREAM_TYPES.STATUS,"Assistant finished speaking.",{visibility:"collapsed"})}functionCalling(e,t){this.emit(STREAM_TYPES.TOOL_CALL,`Calling ${e}...`,{metadata:{tool_name:e,arguments:t}})}functionResult(e,t){this.emit(STREAM_TYPES.TOOL_RESULT,`Got result from ${e}.`,{metadata:{tool_name:e,result:t}})}functionError(e,t){this.emit(STREAM_TYPES.ERROR,`Function ${e} failed: ${t}`,{metadata:{tool_name:e}})}userTranscribed(e){this.emit(STREAM_TYPES.STATUS,`User: "${e}"`,{visibility:"collapsed"})}assistantTranscribed(e){this.emit(STREAM_TYPES.STATUS,`Assistant: "${e}"`,{visibility:"collapsed"})}usageUpdated(e){const{text_input_tokens:t,audio_input_tokens:a,text_output_tokens:n,audio_output_tokens:s}=e,r=t+a+n+s;this.emit(STREAM_TYPES.STATUS,`Tokens used: ${r} (Text: ${t}/${n}, Audio: ${a}/${s})`,{visibility:"collapsed",metadata:{usage:e}})}}const helpers_RealtimeEventEmitter=RealtimeEventEmitter,{useState:ChatbotRealtime_useState,useRef:ChatbotRealtime_useRef,useCallback:ChatbotRealtime_useCallback,useMemo:ChatbotRealtime_useMemo,useEffect:ChatbotRealtime_useEffect}=wp.element,DEBUG_LEVELS={none:0,low:1,normal:2,high:3,verbose:4},CURRENT_DEBUG=DEBUG_LEVELS.low;function debugLog(e,...t){CURRENT_DEBUG>=e&&console.log(...t)}function parseUsage(e){if(!e)return null;const{input_token_details:{text_tokens:t=0,audio_tokens:a=0,cached_tokens_details:{text_tokens:n=0,audio_tokens:s=0}={}}={},output_token_details:{text_tokens:r=0,audio_tokens:o=0}={}}=e;return{text_input_tokens:t,audio_input_tokens:a,text_output_tokens:r,audio_output_tokens:o,text_cached_tokens:n,audio_cached_tokens:s}}function getChatbotRepresentation(e,t="user"){const{pluginUrl:a,iconUrl:n,userData:s,userName:r,aiName:o,guestName:i,userAvatar:l,aiAvatar:c,guestAvatar:u,userAvatarUrl:d,aiAvatarUrl:m,guestAvatarUrl:p}=e,h=(e,t,n,s,r=!1)=>{if(t){const e=((e,t=!1)=>(0,helpers.mv)(e)?e:e&&!(0,js_helpers.Ve)(e)?t?e:`${a}/images/${e}`:null)(n,r)||s;if(e)return{emoji:null,text:null,image:e,use:"image"}}return(0,js_helpers.Ve)(e)?{emoji:e,text:null,image:null,use:"emoji"}:{emoji:null,text:e,image:null,use:"text"}};return"assistant"===t?h(o,c,m,n):s?h(ChatbotRealtime_formatName(r,i,s),l,d,null==s?void 0:s.AVATAR_URL,!0):s||"user"!==t?{emoji:null,text:"Unknown",image:null,use:"text"}:h(i||"Guest",u,p,null)}function ChatbotRealtime_formatName(e,t,a){return a&&0!==Object.keys(a).length?Object.entries(a).reduce(((e,[t,a])=>{const n=`{${t}}`;return e.includes(n)?e.replace(n,a):e}),e):t||e||"Guest"}const ChatbotRealtime=({onMessagesUpdate:e,onStreamEvent:t})=>{const{state:a,actions:n}=(0,ChatbotContext.o)(),{busy:s,locked:r,open:o,popup:i,system:l}=a,{onStartRealtimeSession:c,onRealtimeFunctionCallback:u,onCommitStats:d,onCommitDiscussions:m,setError:p}=n,h=(null==l||l.debugMode,(null==l?void 0:l.eventLogs)||!1),[g,_]=ChatbotRealtime_useState(!1),[f,y]=ChatbotRealtime_useState(!1),[b,v]=ChatbotRealtime_useState(!1),[E,R]=ChatbotRealtime_useState(null),[w,C]=ChatbotRealtime_useState(null),[k,x]=ChatbotRealtime_useState({text_input_tokens:0,audio_input_tokens:0,text_output_tokens:0,audio_output_tokens:0,text_cached_tokens:0,audio_cached_tokens:0}),[S,I]=ChatbotRealtime_useState([]),M=ChatbotRealtime_useRef(new Set),T=ChatbotRealtime_useCallback(((e,a)=>{a&&a.subtype&&t&&t({...a,timestamp:a.timestamp||(new Date).getTime(),messageId:"realtime-session"})}),[t]),A=ChatbotRealtime_useRef(null);ChatbotRealtime_useEffect((()=>{A.current=new helpers_RealtimeEventEmitter(T,h)}),[T,h]);const N=ChatbotRealtime_useRef(null),L=ChatbotRealtime_useRef(null),D=ChatbotRealtime_useRef(null),U=ChatbotRealtime_useRef(null),[P,O]=ChatbotRealtime_useState(!0),[B,F]=ChatbotRealtime_useState(!0),[z,$]=ChatbotRealtime_useState(!1),[j,W]=ChatbotRealtime_useState(!1),[H,V]=ChatbotRealtime_useState(null),K=ChatbotRealtime_useRef([]),q=ChatbotRealtime_useMemo((()=>getChatbotRepresentation(a,"user")),[a]),G=ChatbotRealtime_useMemo((()=>getChatbotRepresentation(a,"assistant")),[a]);ChatbotRealtime_useEffect((()=>{!o&&f&&i&&X()}),[o,i,f]),ChatbotRealtime_useEffect((()=>{e&&e(S)}),[S,e]);const Y=ChatbotRealtime_useCallback((async e=>{const t=await d(e);t.overLimit&&(h&&A.current&&A.current.emit(STREAM_TYPES.ERROR,t.limitMessage||"Usage limit exceeded",{visibility:"visible",error:!0}),console.warn("Usage limit exceeded, stopping realtime connection:",t.limitMessage),U.current&&U.current())}),[d,h]),Q=ChatbotRealtime_useCallback((()=>{L.current&&"open"===L.current.readyState?(L.current.send(JSON.stringify({type:"session.update",session:{input_audio_transcription:{model:"whisper-1"}}})),debugLog(DEBUG_LEVELS.low,"Sent session.update to enable Whisper.")):console.error("Data channel is not open yet; cannot enable transcription.")}),[]),J=ChatbotRealtime_useCallback((async(e,t,a)=>{let n={};try{n=JSON.parse(a||"{}")}catch(e){console.error("Could not parse function arguments.",a)}const s=K.current.find((e=>e.name===t));if(s)try{var r;const a=await u(s.id,s.type,s.name,s.target,n);if(null==a||!a.success)return void console.error("Callback failed.",null==a?void 0:a.message);const o=a.data;if(h&&A.current){const a="string"==typeof o?o:JSON.stringify(o),n=a.length>100?a.substring(0,100)+"...":a;A.current.emit(STREAM_TYPES.TOOL_RESULT,`Got result from ${t}.`,{metadata:{tool_name:t,result:n,call_id:e}})}"open"===(null===(r=L.current)||void 0===r?void 0:r.readyState)&&(debugLog(DEBUG_LEVELS.low,"Send callback value:",o),L.current.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(o)}})),L.current.send(JSON.stringify({type:"response.create",response:{instructions:"Reply based on the function's output."}})))}catch(e){console.error("Error in handleFunctionCall.",e)}else console.error(`No match for callback: '${t}'.`)}),[u,h]),Z=ChatbotRealtime_useCallback((async(e,t)=>{_(!0),h&&A.current&&A.current.emit(STREAM_TYPES.STATUS,"Starting realtime session...",{visibility:"visible"});const a=new RTCPeerConnection;let n;N.current=a;try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("MediaDevices API not available. Please ensure you are using HTTPS and a modern browser.");n=await navigator.mediaDevices.getUserMedia({audio:!0}),D.current=n,n.getTracks().forEach((e=>a.addTrack(e,n)))}catch(e){return console.error("Error accessing microphone.",e),h&&A.current&&A.current.emit(STREAM_TYPES.STATUS,"Failed to access microphone: "+e.message,{visibility:"visible",error:!0}),p("Failed to access microphone. Please ensure microphone permissions are granted and try again."),void _(!1)}a.ontrack=e=>{const t=document.getElementById("mwai-audio");t&&(t.srcObject=e.streams[0]),V(e.streams[0])};const s=a.createDataChannel("oai-events");L.current=s,s.addEventListener("open",(()=>{debugLog(DEBUG_LEVELS.low,"Data channel open."),h&&A.current&&A.current.emit(STREAM_TYPES.STATUS,"Realtime session connected",{visibility:"visible"}),Q()})),s.addEventListener("message",(e=>{let t;try{t=JSON.parse(e.data)}catch(t){return void console.error("Could not parse Realtime message.",e.data)}if(CURRENT_DEBUG>=DEBUG_LEVELS.high)console.log("Incoming message from Realtime API.",t);else if(CURRENT_DEBUG===DEBUG_LEVELS.low){var a;((null===(a=t.type)||void 0===a?void 0:a.endsWith(".done"))||"input_audio_buffer.committed"===t.type||"conversation.item.input_audio_transcription.completed"===t.type||"response.done"===t.type)&&console.log("Key event from Realtime API.",t)}if(h&&t.type&&A.current){let e="",a=STREAM_TYPES.STATUS,n=!1;switch(t.type){case"input_audio_buffer.speech_started":e="User started talking...",n=!0;break;case"input_audio_buffer.speech_stopped":e="User stopped speaking.",n=!0;break;case"response.audio.started":e="Assistant started speaking.",n=!0;break;case"response.audio.done":e="Assistant stopped speaking.",n=!0;break;case"conversation.item.input_audio_transcription.completed":e="Got transcript from user.",a=STREAM_TYPES.TRANSCRIPT,n=!0;break;case"response.audio_transcript.done":e="Got transcript from assistant.",a=STREAM_TYPES.TRANSCRIPT,n=!0;break;case"response.function_call_arguments.done":e=`Calling ${t.name}...`,a=STREAM_TYPES.TOOL_CALL,n=!0}n&&A.current.emit(a,e,{visibility:"visible",metadata:{event_type:t.type,event_id:t.event_id}})}switch(t.type){case"input_audio_buffer.committed":{const e=t.item_id;M.current.has(e)||(M.current.add(e),I((t=>[...t,{id:e,role:"user",content:"[Audio]"}]))),C("user");break}case"conversation.item.input_audio_transcription.completed":{const e=t.item_id,a=(t.transcript||"[Audio]").trim();I((t=>t.map((t=>t.id===e&&"user"===t.role?{...t,content:a}:t))));break}case"response.audio_transcript.done":{const e=t.item_id,a=(t.transcript||"[Audio]").trim();C("assistant"),M.current.has(e)||(M.current.add(e),I((t=>[...t,{id:e,role:"assistant",content:a}])));break}case"response.function_call_arguments.done":{const{call_id:e,name:a,arguments:n}=t;debugLog(DEBUG_LEVELS.low,"Function call requested.",e,a),J(e,a,n);break}case"response.done":{const e=t.response;if(null!=e&&e.usage){const t=parseUsage(e.usage);t&&x((e=>{const a={text_input_tokens:(e.text_input_tokens||0)+t.text_input_tokens,audio_input_tokens:(e.audio_input_tokens||0)+t.audio_input_tokens,text_output_tokens:(e.text_output_tokens||0)+t.text_output_tokens,audio_output_tokens:(e.audio_output_tokens||0)+t.audio_output_tokens,text_cached_tokens:(e.text_cached_tokens||0)+t.text_cached_tokens,audio_cached_tokens:(e.audio_cached_tokens||0)+t.audio_cached_tokens};return Y(a),a}))}C("user");break}}}));const r=await a.createOffer();await a.setLocalDescription(r);const o=t||"gpt-4o-preview-2024-12-17",i=await fetch(`https://api.openai.com/v1/realtime?model=${o}`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/sdp"},body:r.sdp});if(!i.ok)return console.error("SDP exchange failed.",i),void _(!1);const l=await i.text();await a.setRemoteDescription({type:"answer",sdp:l}),debugLog(DEBUG_LEVELS.low,"Realtime connection established."),_(!1),y(!0),v(!1),C("user")}),[Q,J,Y,p]),X=ChatbotRealtime_useCallback((()=>{h&&A.current&&A.current.emit(STREAM_TYPES.STATUS,"Ending realtime session...",{visibility:"visible"});try{N.current&&(N.current.close(),N.current=null),D.current&&(D.current.getTracks().forEach((e=>e.stop())),D.current=null),L.current=null,_(!1),y(!1),v(!1),C(null),m(S),I([]),x({text_input_tokens:0,audio_input_tokens:0,text_output_tokens:0,audio_output_tokens:0,text_cached_tokens:0,audio_cached_tokens:0}),debugLog(DEBUG_LEVELS.low,"Stopped Realtime connection.")}catch(e){console.error("Error stopping connection.",e)}}),[S,k,m]);ChatbotRealtime_useEffect((()=>{U.current=X}),[X]);const ee=ChatbotRealtime_useCallback((()=>{if(!D.current)return;const e=D.current.getAudioTracks();e.length&&(b?(e.forEach((e=>{e.enabled=!0})),debugLog(DEBUG_LEVELS.low,"Resumed microphone."),v(!1)):(e.forEach((e=>{e.enabled=!1})),debugLog(DEBUG_LEVELS.low,"Paused microphone."),v(!0)))}),[b]),te=ChatbotRealtime_useCallback((async()=>{_(!0);try{const e=await c();if(null==e||!e.success){console.error("Could not start realtime session.",e),_(!1);const t=(null==e?void 0:e.message)||"Could not start realtime session.";return void p(t)}K.current=e.function_callbacks||[],R(e.session_id),await Z(e.client_secret,e.model)}catch(e){console.error("Error in handlePlay.",e),_(!1);const t=e.message||"An error occurred while starting the realtime session.";p(t)}}),[c,Z,p]),ae=ChatbotRealtime_useCallback((()=>X()),[X]),ne=ChatbotRealtime_useCallback((()=>F((e=>!e))),[]),se=ChatbotRealtime_useCallback((()=>W((e=>!e))),[]),re=ChatbotRealtime_useCallback((()=>$((e=>!e))),[]),oe=ChatbotRealtime_useMemo((()=>b?"mwai-pause mwai-active":"mwai-pause"),[b]),ie=ChatbotRealtime_useMemo((()=>{const e=[...S].reverse().find((e=>"assistant"===e.role));return e?e.content.length>256?`${e.content.slice(0,256)}...`:e.content:"..."}),[S]),le=ChatbotRealtime_useMemo((()=>B?"mwai-option mwai-option-users mwai-active":"mwai-option mwai-option-users"),[B]),ce=ChatbotRealtime_useMemo((()=>z?"mwai-option mwai-option-captions mwai-active":"mwai-option mwai-option-captions"),[z]),ue=ChatbotRealtime_useMemo((()=>j?"mwai-option mwai-option-statistics mwai-active":"mwai-option mwai-option-statistics"),[j]);return React.createElement("div",null,React.createElement("audio",{id:"mwai-audio",autoPlay:!0}),B&&React.createElement("div",{style:{display:"flex",justifyContent:"center"}},React.createElement(AudioVisualizerTwoStreams,{assistantStream:H,userUI:q,assistantUI:G,userStream:D.current})),React.createElement("div",{className:"mwai-controls"},!f&&!g&&React.createElement("button",{onClick:te,className:"mwai-play",disabled:s||r,"aria-label":"Play"},React.createElement(Play,{size:16})),g&&React.createElement("button",{className:"mwai-play",disabled:!0},React.createElement(Loader,{size:16,style:{animation:"spin 0.8s linear infinite"}})),f&&!g&&React.createElement(React.Fragment,null,React.createElement("button",{onClick:ae,className:"mwai-stop",disabled:s||r,"aria-label":"Stop"},React.createElement(Square,{size:16})),React.createElement("button",{onClick:ee,className:oe,disabled:s||r,"aria-label":"Pause"},React.createElement(Pause,{size:16})))),z&&ie&&ie.length>0&&React.createElement("div",{className:"mwai-last-transcript"},ie),j&&React.createElement("div",{className:"mwai-statistics"},React.createElement("div",null,React.createElement("label",null,"Text In"),React.createElement("span",null,k.text_input_tokens)),React.createElement("div",null,React.createElement("label",null,"Text Out"),React.createElement("span",null,k.text_output_tokens)),React.createElement("div",null,React.createElement("label",null,"Text Cached"),React.createElement("span",null,k.text_cached_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio In"),React.createElement("span",null,k.audio_input_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio Out"),React.createElement("span",null,k.audio_output_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio Cached"),React.createElement("span",null,k.audio_cached_tokens))),P&&React.createElement("div",{className:"mwai-options"},React.createElement(Users,{size:13,title:"Show Users",className:le,onClick:ne}),React.createElement(Captions,{size:18,title:"Show Captions",className:ce,onClick:re}),React.createElement(Bug,{size:14,title:"Show Statistics",className:ue,onClick:se})))},chatbot_ChatbotRealtime=ChatbotRealtime,Wrench=(0,createLucideIcon.A)("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]),Activity=(0,createLucideIcon.A)("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]),Brain=(0,createLucideIcon.A)("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]),Search=(0,createLucideIcon.A)("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]),CircleAlert=(0,createLucideIcon.A)("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),x_X=(0,createLucideIcon.A)("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Minimize2=(0,createLucideIcon.A)("Minimize2",[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]),Maximize2=(0,createLucideIcon.A)("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]),ChevronDown=(0,createLucideIcon.A)("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),ChevronRight=(0,createLucideIcon.A)("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),{useState:ChatbotEvents_useState,useMemo:ChatbotEvents_useMemo,useEffect:ChatbotEvents_useEffect}=wp.element,ChatbotEvents=({allStreamData:e,debugMode:t,onClear:a,hasData:n,isWindow:s})=>{const[r,o]=ChatbotEvents_useState({}),[i,l]=ChatbotEvents_useState(!1),[c,u]=ChatbotEvents_useState(!s),d=ChatbotEvents_useMemo((()=>{if(!e||0===e.length)return[];const t=e.map(((e,t)=>({...e,id:`${e.messageId}-${t}`,displayTime:new Date(e.timestamp).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}))).reverse();return c?t.slice(0,20):t.slice(0,1)}),[e,c]),m=(e,t)=>{switch(e){case"tool_call":case"tool_args":return"function";case"tool_result":return!0===(null==t?void 0:t.is_mcp)||null!=t&&t.tool_name&&d.some((e=>{var a;return"mcp_tool_call"===e.subtype&&(null===(a=e.metadata)||void 0===a?void 0:a.name)===t.tool_name}))?"mcp":"function";case"mcp_discovery":case"mcp_tool_call":case"mcp_tool_result":return"mcp";case"thinking":return"thinking";case"status":case"content":return"output";case"web_search":case"file_search":return"search";case"error":return"error";case"warning":return"warning";default:return e}},p=(e,t)=>{switch(e){case"function":return"#3b82f6";case"mcp":case"thinking":return"#8b5cf6";case"output":return t&&t.includes("completed")?"#10b981":t&&t.includes("started")||t&&t.includes("...")?"#06b6d4":"#6b7280";case"search":return"#f59e0b";case"error":return"#ef4444";case"warning":return"#f97316";default:return"#6b7280"}},h=ChatbotEvents_useMemo((()=>{if(0===d.length)return null;for(const e of d){const t=m(e.subtype,e.metadata);if("debug"!==e.subtype&&"heartbeat"!==e.subtype){if(e.data.includes("Stream completed")){const t=d.findIndex((e=>e.data.includes("Request completed")));if(t>=0&&t<d.indexOf(e)){const e=d[t];return{data:e.data,category:m(e.subtype,e.metadata),color:p(m(e.subtype,e.metadata),e.data)}}}return{data:e.data,category:t,color:p(t,e.data)}}}return null}),[d]);return React.createElement("div",{className:"mwai-chunks "+(i?"":"mwai-chunks-collapsed")},React.createElement("div",{className:"mwai-chunks-header"},React.createElement(Activity,{size:12}),React.createElement("span",{className:"mwai-chunks-title"},"Events",h&&React.createElement("span",{className:"mwai-chunks-status",style:{color:h.color}},": ",h.data)),i&&React.createElement(React.Fragment,null,d.length>0&&a&&React.createElement("div",{className:"mwai-chunks-toggle",onClick:a,title:"Clear stream events"},React.createElement(x_X,{size:12})),!s&&React.createElement("div",{className:"mwai-chunks-toggle",onClick:()=>u(!c),title:c?"Show minimal (last event only)":"Show detailed (all events)"},c?React.createElement(Minimize2,{size:12}):React.createElement(Maximize2,{size:12}))),React.createElement("div",{className:"mwai-chunks-toggle",onClick:()=>l(!i),title:i?"Hide events":"Show events"},i?React.createElement(ChevronDown,{size:12}):React.createElement(ChevronRight,{size:12}))),i&&(0===d.length?React.createElement("div",{className:"mwai-chunk"},React.createElement("div",{className:"mwai-chunk-header"},React.createElement("span",{className:"mwai-chunk-time"},"--:--:--"),React.createElement("span",{className:"mwai-chunk-type",style:{backgroundColor:"#6b7280"}},React.createElement(Activity,{size:14}),"waiting"),React.createElement("span",{className:"mwai-chunk-data"},"No events yet."))):d.map((e=>{const t=r[e.id],a=m(e.subtype,e.metadata),n=e.metadata&&Object.keys(e.metadata).length>0||"thinking"===a;return React.createElement("div",{key:e.id,className:"mwai-chunk"},React.createElement("div",{className:"mwai-chunk-header",onClick:()=>{return n&&(t=e.id,void o((e=>({...e,[t]:!e[t]}))));var t}},React.createElement("span",{className:"mwai-chunk-time"},e.displayTime),React.createElement("span",{className:"mwai-chunk-type",style:{backgroundColor:p(a,e.data)}},(e=>{switch(e){case"function":return React.createElement(Wrench,{size:14});case"mcp":case"output":default:return React.createElement(Activity,{size:14});case"thinking":return React.createElement(Brain,{size:14});case"search":return React.createElement(Search,{size:14});case"error":case"warning":return React.createElement(CircleAlert,{size:14})}})(a),a),React.createElement("span",{className:"mwai-chunk-data"},(()=>{const t="string"==typeof e.data?e.data:JSON.stringify(e.data);if("thinking"===a){const e=t.match(/^\*\*([^*]+)\*\*/);return e?e[1]:t.substring(0,50)+(t.length>50?"...":"")}return t})()),n&&React.createElement(ChevronRight,{size:12,className:"mwai-chunk-expand",style:{transform:t?"rotate(90deg)":"none"}})),t&&n&&React.createElement("div",{className:"mwai-chunk-details"},"thinking"===a?React.createElement("div",{style:{padding:"0px 10px",fontFamily:"system-ui"}},(()=>{const t="string"==typeof e.data?e.data:JSON.stringify(e.data);try{return Ze(t)}catch(e){return React.createElement("pre",null,t)}})()):React.createElement("pre",null,JSON.stringify(e.metadata,null,2))))}))))},chatbot_ChatbotEvents=ChatbotEvents,{useState:ChatbotBody_useState,useEffect:ChatbotBody_useEffect,useRef:ChatbotBody_useRef,useMemo:ChatbotBody_useMemo}=wp.element,ChatbotBody=({conversationRef:e,onScroll:t,messageList:a,jsxShortcuts:n,jsxBlocks:s,inputClassNames:r,handleDrop:o,handleDrag:i,needsFooter:l,needTools:c,uploadIconPosition:u})=>{const{state:d,actions:m}=(0,ChatbotContext.o)(),{debugMode:p,eventLogs:h,messages:g,isRealtime:_,textCompliance:f,chatbotInputRef:y,isWindow:b}=d,[v,E]=ChatbotBody_useState([]),[R,w]=ChatbotBody_useState(new Set),C=ChatbotBody_useRef([]),[k,x]=(ChatbotBody_useRef(0),ChatbotBody_useState([]));return ChatbotBody_useEffect((()=>{(0===g.length||1===g.length&&"assistant"===g[0].role)&&w(new Set)}),[g]),ChatbotBody_useEffect((()=>{const e=[];[...g,...k].forEach((t=>{t.streamEvents&&p&&!R.has(t.id)&&t.streamEvents.forEach((a=>{e.push({...a,messageId:t.id})}))})),_||(C.current=e,E(e))}),[g,k,p,_,R]),React.createElement("div",{className:"mwai-body"},!_&&React.createElement(React.Fragment,null,React.createElement("div",{ref:e,className:"mwai-conversation",onScroll:t},a,n),s,React.createElement("div",{className:r,onClick:()=>{var e;return null===(e=y.current)||void 0===e?void 0:e.focusInput()},onDrop:o,onDragEnter:e=>i(e,!0),onDragLeave:e=>i(e,!1),onDragOver:e=>i(e,!0)},React.createElement(chatbot_ChatbotInput,null),React.createElement(chatbot_ChatbotSubmit,null))),_&&React.createElement("div",{className:"mwai-realtime"},React.createElement(chatbot_ChatbotRealtime,{onMessagesUpdate:x,onStreamEvent:e=>{E((t=>[...t,e]))}})),l&&React.createElement("div",{className:"mwai-footer"},c&&React.createElement("div",{className:"mwai-tools"},"mwai-tools"===u&&React.createElement(chatbot_ChatUploadIcon,null)),f&&React.createElement("div",{className:"mwai-compliance",dangerouslySetInnerHTML:{__html:f}})),h&&React.createElement(chatbot_ChatbotEvents,{allStreamData:v,debugMode:p,onClear:()=>{E([]),C.current=[];const e=new Set;[...g,...k].forEach((t=>{t.streamEvents&&e.add(t.id)})),w(e)},hasData:v.length>0,isWindow:b}))},chatbot_ChatbotBody=ChatbotBody,{useState:ChatbotUI_useState,useMemo:ChatbotUI_useMemo,useLayoutEffect,useCallback:ChatbotUI_useCallback,useEffect:ChatbotUI_useEffect,useRef:ChatbotUI_useRef}=wp.element,isImage=e=>e.type.startsWith("image/"),isDocument=e=>["text/x-c","text/x-csharp","text/x-c++","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/html","text/x-java","application/json","text/markdown","application/pdf","text/x-php","application/vnd.openxmlformats-officedocument.presentationml.presentation","text/x-python","text/x-script.python","text/x-ruby","text/x-tex","text/plain","text/css","text/javascript","application/x-sh","application/typescript"].includes(e.type),ChatbotUI=e=>{const t=(0,helpers.gR)(),{style:a}=e,[n,s]=ChatbotUI_useState(!0),{state:r,actions:o}=(0,ChatbotContext.o)(),{theme:i,botId:l,customId:c,messages:u,textCompliance:d,isWindow:m,fullscreen:p,iconPosition:h,iconBubble:g,shortcuts:_,blocks:f,imageUpload:y,fileSearch:b,fileUpload:v,draggingType:E,isBlocked:R,virtualKeyboardFix:w,windowed:C,cssVariables:k,conversationRef:x,open:S,busy:I,uploadIconPosition:M}=r,{onSubmit:T,setIsBlocked:A,setDraggingType:N,onUploadFile:L}=o,D=ChatbotUI_useMemo((()=>"css"===(null==i?void 0:i.type)?null==i?void 0:i.style:null),[i]),U=y||b||v,P=U||d,O=ChatbotUI_useRef(null),{viewportHeight:B,isIOS:F,isAndroid:z}=(0,helpers.kW)();ChatbotUI_useEffect((()=>{if(!w)return;if(!F&&!z)return;if(!m)return;const e=document.querySelector(".mwai-window");e&&(S?(e.style.height=`${B}px`,F&&(()=>{if("INPUT"===document.activeElement.tagName||"TEXTAREA"===document.activeElement.tagName){window.scrollTo({top:0});const e=setInterval((()=>{window.scrollTo({top:0})}),100);setTimeout((()=>{clearInterval(e)}),1e3)}})()):e.style.height="")}),[p,z,F,m,C,S,B,w]);const $=t("mwai-chatbot",{[`mwai-${null==i?void 0:i.themeId}-theme`]:!0,"mwai-window":m,"mwai-bubble":g,"mwai-open":S,"mwai-fullscreen":!C||!m&&p,"mwai-bottom-left":"bottom-left"===h,"mwai-top-right":"top-right"===h,"mwai-top-left":"top-left"===h});useLayoutEffect((()=>{n&&x.current&&(x.current.scrollTop=x.current.scrollHeight)}),[u,n,x,I]);const j=ChatbotUI_useRef(new Set);ChatbotUI_useEffect((()=>{f&&f.length>0&&f.forEach((e=>{const{type:t,data:a}=e;"content"===t&&a.script&&(e=>{const t=(e=>{let t,a,n=0;if(0===e.length)return n;for(t=0;t<e.length;t++)a=e.charCodeAt(t),n=(n<<5)-n+a,n|=0;return n})(e);if(!j.current.has(t)){const a=document.createElement("script");a.type="text/javascript",a.textContent=e,document.body.appendChild(a),j.current.add(t)}})(a.script)}))}),[f]);const W=ChatbotUI_useMemo((()=>null==u?void 0:u.map((e=>React.createElement(chatbot_ChatbotReply,{key:e.id,message:e})))),[u]),H=ChatbotUI_useMemo((()=>_&&0!==_.length?React.createElement("div",{className:"mwai-shortcuts"},_.map(((e,a)=>{const{type:n,data:s}=e,{label:r,variant:o,icon:i,className:c}=s??{};let u=t("mwai-shortcut",{"mwai-success":"success"===o,"mwai-danger":"danger"===o,"mwai-warning":"warning"===o,"mwai-info":"info"===o});c&&(u+=` ${c}`);const d=i&&i.startsWith("http"),m=i&&!d&&i.length>=1&&i.length<=2;switch(n){case"message":{const{message:e}=s,t=()=>{T(e)};return React.createElement("button",{className:u,key:a,onClick:t},(d||m)&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},d&&React.createElement("img",{src:i,alt:r||"AI Shortcut"}),m&&React.createElement("span",{role:"img","aria-label":"AI Shortcut"},i)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-label"},r||"N/A"))}case"callback":{const{onClick:e}=s,t=()=>{if("function"==typeof e)e();else if("string"==typeof e){const t=e.replace(/{CHATBOT_ID}/g,l),a=new Function(`return (${t});`)();s.onClick=a,a()}else console.warn("No valid callback function provided in data.onClick.")};return React.createElement("button",{className:u,key:a,onClick:t},(d||m)&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},d&&React.createElement("img",{src:i,alt:r||"AI Shortcut"}),m&&React.createElement("span",{role:"img","aria-label":"AI Shortcut"},i)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-label"},r||"N/A"))}default:return console.warn(`This shortcut type is not supported: ${n}.`),null}}))):null),[t,T,_]),V=ChatbotUI_useMemo((()=>f&&0!==f.length?React.createElement("div",{className:"mwai-blocks"},f.map(((e,a)=>{const{type:n,data:s}=e;if("content"!==n)return console.warn(`Block type ${n} is not supported.`),null;const{html:r,variant:o}=s,i=t("mwai-block",{"mwai-success":"success"===o,"mwai-danger":"danger"===o,"mwai-warning":"warning"===o,"mwai-info":"info"===o});return React.createElement("div",{className:i,key:a,dangerouslySetInnerHTML:{__html:r}})}))):null),[t,f]),K=ChatbotUI_useCallback(((e,t)=>{e.preventDefault(),e.stopPropagation();const a=e.dataTransfer.items[0];t?(O.current&&(clearTimeout(O.current),O.current=null),y&&isImage(a)?(N("image"),A(!1)):(b||v)&&isDocument(a)?(N("document"),A(!1)):(N(!1),A(!0))):O.current||(O.current=setTimeout((()=>{N(!1),A(!1),O.current=null}),100))}),[y,b,v]),q=ChatbotUI_useCallback((e=>{if(e.preventDefault(),K(e,!1),I)return;const t=e.dataTransfer.files[0];t&&("image"===E&&y||"document"===E&&(b||v)?L(t):(A(!0),setTimeout((()=>A(!1)),2e3)))}),[I,E,y,v,b,L]),G=t("mwai-input",{"mwai-dragging":E,"mwai-blocked":R});return React.createElement(helpers.bE,{dir:"auto",id:`mwai-chatbot-${c||l}`,className:$,style:{...k,...a},if:!0,disableTransition:!m},D&&React.createElement("style",null,D),React.createElement(chatbot_ChatbotTrigger,null),React.createElement(chatbot_ChatbotHeader,null),React.createElement(chatbot_ChatbotBody,{conversationRef:x,onScroll:()=>{if(x.current){const{scrollTop:e,scrollHeight:t,clientHeight:a}=x.current;s(t-e<=a+1)}},messageList:W,jsxShortcuts:H,jsxBlocks:V,inputClassNames:G,handleDrop:q,handleDrag:K,needsFooter:P,needTools:U,uploadIconPosition:M}))},chatbot_ChatbotUI=ChatbotUI,ChatbotSystem=e=>React.createElement(ChatbotContext.G,e,React.createElement(chatbot_ChatbotUI,e)),chatbot_ChatbotSystem=ChatbotSystem;var tokenManager=__webpack_require__(213);const{useContext,createContext,useState:DiscussionsContext_useState,useMemo:DiscussionsContext_useMemo,useEffect:DiscussionsContext_useEffect,useCallback:DiscussionsContext_useCallback,useRef:DiscussionsContext_useRef}=wp.element,DiscussionsContext=createContext(),useDiscussionsContext=()=>{const e=useContext(DiscussionsContext);if(!e)throw new Error("useDiscussionsContext must be used within a DiscussionsContextProvider");return e},DiscussionsContextProvider=({children:e,...t})=>{const{system:a,theme:n}=t,[s,r]=DiscussionsContext_useState([]),[o,i]=DiscussionsContext_useState(null),[l,c]=DiscussionsContext_useState(null),[u,d]=DiscussionsContext_useState(!1),[m,p]=DiscussionsContext_useState(0),[h,g]=DiscussionsContext_useState(0),[_,f]=DiscussionsContext_useState(!1),y=DiscussionsContext_useRef(!1),b=DiscussionsContext_useMemo((()=>(null==n?void 0:n.settings)||{}),[n]),v=a.botId,E=a.customId,[R,w]=DiscussionsContext_useState(a.restNonce||tokenManager.A.getToken()),C=DiscussionsContext_useRef(a.restNonce||tokenManager.A.getToken());DiscussionsContext_useEffect((()=>tokenManager.A.subscribe((e=>{w(e),C.current=e}))),[]);const k=a.pluginUrl,x=a.restUrl,S=a.debugMode,I=DiscussionsContext_useMemo((()=>Object.keys(b).reduce(((e,t)=>(e[`--mwai-${t}`]=b[t],e)),{})),[b]),M=DiscussionsContext_useMemo((()=>s.some((e=>0===e.messages.length))),[s]),T=DiscussionsContext_useCallback((()=>{const e=MwaiAPI.getChatbot(v),t=null==e?void 0:e.localStorageKey;if(t)try{const e=localStorage.getItem(t);if(e)return JSON.parse(e).chatId}catch(e){console.error("[DISCUSSIONS] Error reading chatbot storage:",e)}return null}),[v]),A=DiscussionsContext_useCallback((async(e=!1,t=m,n=!1)=>{if(y.current)return;let s;y.current=!0;try{e||(s=Date.now(),n?f(!0):d(!0));const l=(null==a?void 0:a.paging)||0,c=l>0?l:void 0,u={botId:v||E,...c&&{limit:c,offset:l>0?t*l:0}},m=e=>{w(e),C.current=e,tokenManager.A.setToken(e)},p=await(0,js_helpers.ti)(`${x}/mwai-ui/v1/discussions/list`,u,C.current,!1,void 0,m),h=await(0,js_helpers.Pn)(p,null,S?"DISCUSSIONS":null,m,S);if(!h.success)throw new Error(`Could not retrieve the discussions: ${h.message}`);const _=h.chats.map((e=>{const t=JSON.parse(e.messages),a=JSON.parse(e.extra);return{...e,messages:t,extra:a,metadata_display:e.metadata_display}}));void 0!==h.total&&g(h.total),r((e=>{if(((null==a?void 0:a.paging)||0)>0)return _;{const t=new Map;e.forEach((e=>{t.set(e.chatId,e)})),_.forEach((e=>{t.set(e.chatId,e)}));const a=Array.from(t.values());if(o){const e=a.find((e=>e.chatId===o.chatId));e&&e!==o&&i(e)}return a}}))}catch(e){console.error(e)}finally{if(y.current=!1,!e&&s){const e=Date.now()-s,t=Math.max(0,200-e);setTimeout((()=>{n?f(!1):d(!1)}),t)}}}),[o,m,null==a?void 0:a.paging]),N=(null==a?void 0:a.refreshInterval)||5e3;DiscussionsContext_useEffect((()=>{const e=T();if(e&&!l&&c(e),A(),N>0){const e=setInterval((()=>{A(!0)}),N);return()=>clearInterval(e)}}),[N,m]),DiscussionsContext_useEffect((()=>{if(l&&!o){const t=s.find((e=>e.chatId===l));if(t){i(t);try{var e;const a=L(v),n=(null===(e=t.extra)||void 0===e?void 0:e.previousResponseId)||null;a.setContext({chatId:t.chatId,messages:t.messages,previousResponseId:n})}catch(e){console.debug("Chatbot not ready for auto-selected discussion",e)}}}else if(o){const e=s.find((e=>e.chatId===o.chatId));e&&e!==o&&i(e)}}),[s,l,v]);const L=e=>{const t=MwaiAPI.getChatbot(e);if(!t)throw new Error("Chatbot not found.",{botId:e,chatbots:MwaiAPI.chatbots});return t},D={onDiscussionClick:async e=>{var t;const a=s.find((t=>t.chatId===e));if(!a)return void console.error("Discussion not found.",{chatId:e,discussions:s});const n=L(v),r=(null===(t=a.extra)||void 0===t?void 0:t.previousResponseId)||null;n.setConversation({chatId:e,messages:a.messages,previousResponseId:r}),i(a),c(e)},onNewChatClick:async()=>{const e=L(v),t=(0,js_helpers.vx)();e.clear({chatId:t}),i(null),c(t)},onEditDiscussion:async e=>{const t=prompt("Enter a new title for the discussion:",e.title||"");if(null===t)return;const a=t.trim();if(""!==a)try{d(!0);const t={chatId:e.chatId,title:a},n=e=>{w(e),C.current=e,tokenManager.A.setToken(e)},s=await(0,js_helpers.ti)(`${x}/mwai-ui/v1/discussions/edit`,t,C.current,!1,void 0,n),o=await(0,js_helpers.Pn)(s,null,S?"DISCUSSIONS":null,n,S);if(!o.success)throw new Error(`Could not update the discussion: ${o.message}`);r((t=>t.map((t=>t.chatId===e.chatId?{...t,title:a}:t))))}catch(e){console.error(e),alert("An error occurred while updating the discussion.")}finally{d(!1)}else alert("Title cannot be empty.")},onDeleteDiscussion:async e=>{if(confirm("Are you sure you want to delete this discussion?"))try{d(!0);const t={chatIds:[e.chatId]},a=e=>{w(e),C.current=e,tokenManager.A.setToken(e)},n=await(0,js_helpers.ti)(`${x}/mwai-ui/v1/discussions/delete`,t,C.current,!1,void 0,a),l=await(0,js_helpers.Pn)(n,null,S?"DISCUSSIONS":null,a,S);if(!l.success)throw new Error(`Could not delete the discussion: ${l.message}`);if(r((t=>t.filter((t=>t.chatId!==e.chatId)))),(null==o?void 0:o.chatId)===e.chatId&&(i(null),c(null)),1===s.length&&m>0){const e=m-1;p(e),A(!1,e,!0)}else A(!1,m,!0)}catch(e){console.error(e),alert("An error occurred while deleting the discussion.")}finally{d(!1)}},refresh:A,setCurrentPage:p},U={botId:v,pluginUrl:k,busy:u,setBusy:d,cssVariables:I,discussions:s,discussion:o,theme:n,hasEmptyDiscussion:M,currentPage:m,totalCount:h,system:a,paginationBusy:_};return React.createElement(DiscussionsContext.Provider,{value:{state:U,actions:D}},e)},Pencil=(0,createLucideIcon.A)("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]),Trash=(0,createLucideIcon.A)("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]),Calendar=(0,createLucideIcon.A)("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]),Clock=(0,createLucideIcon.A)("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]),MessageSquare=(0,createLucideIcon.A)("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]),Ellipsis=(0,createLucideIcon.A)("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]),RefreshCw=(0,createLucideIcon.A)("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),LoaderCircle=(0,createLucideIcon.A)("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),ChevronLeft=(0,createLucideIcon.A)("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),external_ReactDOM_namespaceObject=ReactDOM,{useEffect:ContextMenu_useEffect,useRef:ContextMenu_useRef,useState:ContextMenu_useState}=wp.element,ContextMenu=({isOpen:e,anchorEl:t,onClose:a,menuItems:n=[],className:s="",theme:r,context:o})=>{const i=(0,helpers.gR)(),l=ContextMenu_useRef(null),[c,u]=ContextMenu_useState({top:0,left:0});if(ContextMenu_useEffect((()=>{if(e&&t){const e=t.getBoundingClientRect(),a=120,n=80;let s=e.bottom+4,r=e.right-a;r<0&&(r=e.left),s+n>window.innerHeight&&(s=e.top-n-4),u({top:s,left:r})}}),[e,t]),ContextMenu_useEffect((()=>{const n=e=>{l.current&&!l.current.contains(e.target)&&t&&!t.contains(e.target)&&a()},s=e=>{"Escape"===e.key&&a()};if(e)return document.addEventListener("mousedown",n),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",n),document.removeEventListener("keydown",s)}}),[e,a,t]),!e)return null;const d=React.createElement("div",{ref:l,className:i("mwai-context-menu-portal",{[`mwai-${null==r?void 0:r.themeId}-theme`]:null==r?void 0:r.themeId}),style:{position:"fixed",top:`${c.top}px`,left:`${c.left}px`,zIndex:999999}},React.createElement("div",{className:i("mwai-context-menu"),style:{minWidth:"120px",overflow:"hidden"}},n.map(((e,t)=>{if("separator"===e.type)return React.createElement("div",{key:e.id||`separator-${t}`,className:i("mwai-menu-separator"),style:{height:"1px",margin:"4px 0",background:"var(--mwai-backgroundPrimaryColor, rgba(0,0,0,0.1))"}});if("title"===e.type)return React.createElement("div",{key:e.id||`title-${t}`,className:i("mwai-menu-title"),style:{padding:"8px 12px",fontSize:"11px",fontWeight:"bold",opacity:.7,textTransform:"uppercase"},dangerouslySetInnerHTML:e.html?{__html:e.html}:void 0},!e.html&&e.label);const n=e.icon;return e.html?React.createElement("div",{key:e.id,className:i(e.className||"mwai-menu-item"),onClick:()=>{e.onClick&&(e.onClick(o),a())},style:e.style,dangerouslySetInnerHTML:{__html:e.html}}):React.createElement("div",{key:e.id,className:i(e.className||"mwai-menu-item"),onClick:()=>{e.onClick&&(e.onClick(o),a())},style:e.style},n&&React.createElement(n,{size:14}),React.createElement("span",null,e.label))}))));return(0,external_ReactDOM_namespaceObject.createPortal)(d,document.body)},components_ContextMenu=ContextMenu;var chatbot_MwaiAPI=__webpack_require__(137);const{useMemo:DiscussionsUI_useMemo,useEffect:DiscussionsUI_useEffect,useState:DiscussionsUI_useState,useCallback:DiscussionsUI_useCallback,useRef:DiscussionsUI_useRef}=wp.element,Discussion=({discussion:e,onClick:t=(()=>{}),selected:a=!1,onEdit:n=(()=>{}),onDelete:s=(()=>{}),theme:r,system:o})=>{var i,l,c,u;const d=(0,helpers.gR)(),[m,p]=DiscussionsUI_useState(!1),h=DiscussionsUI_useRef(null),g=e.messages,_=g[g.length-1],f=DiscussionsUI_useMemo((()=>e.title?e.title:((null==_?void 0:_.content.length)>64?_.content.substring(0,64)+"...":_.content)||"No messages yet"),[e,_]),y=d("mwai-discussion",{"mwai-active":a}),b=DiscussionsUI_useCallback((e=>{e.stopPropagation(),p(!m)}),[m]),v=DiscussionsUI_useCallback((()=>{p(!1),n(e)}),[e,n]),E=DiscussionsUI_useCallback((()=>{p(!1),s(e)}),[e,s]),R=(()=>{const t=[{id:"rename",icon:Pencil,label:"Rename",onClick:v,className:"mwai-menu-item"},{id:"delete",icon:Trash,label:"Delete",onClick:E,className:"mwai-menu-item mwai-danger"}];return(0,chatbot_MwaiAPI.W5)("mwai_discussion_menu_items",t,e)})();return React.createElement(React.Fragment,null,React.createElement("li",{className:y,onClick:t},React.createElement("div",{className:d("mwai-discussion-content")},React.createElement("span",{className:d("mwai-discussion-title")},f),(null==o||null===(i=o.metadata)||void 0===i?void 0:i.enabled)&&React.createElement("div",{className:d("mwai-discussion-info")},o.metadata.startDate&&React.createElement("span",{className:d("mwai-info-item")},React.createElement(Calendar,{size:12}),React.createElement("span",null,(null===(l=e.metadata_display)||void 0===l?void 0:l.start_date)||e.created)),o.metadata.lastUpdate&&React.createElement("span",{className:d("mwai-info-item")},React.createElement(Clock,{size:12}),React.createElement("span",null,(null===(c=e.metadata_display)||void 0===c?void 0:c.last_update)||e.updated)),o.metadata.messageCount&&React.createElement("span",{className:d("mwai-info-item")},React.createElement(MessageSquare,{size:12}),React.createElement("span",null,(null===(u=e.metadata_display)||void 0===u?void 0:u.message_count)||g.length)))),React.createElement("div",{className:d("mwai-discussion-actions")},React.createElement("div",{ref:h,className:d("mwai-menu-icon"),onClick:b},React.createElement(Ellipsis,{size:18})))),React.createElement(components_ContextMenu,{isOpen:m,anchorEl:h.current,onClose:()=>p(!1),menuItems:R,theme:r,context:e}))},DiscussionsUI=e=>{const{theme:t,style:a,params:n}=e,s=(0,helpers.gR)(),r=DiscussionsUI_useMemo((()=>"css"===(null==t?void 0:t.type)?null==t?void 0:t.style:null),[t]),{state:o,actions:i}=useDiscussionsContext(),{botId:l,cssVariables:c,discussions:u,discussion:d,busy:m,hasEmptyDiscussion:p,currentPage:h,totalCount:g,system:_,paginationBusy:f}=o,{onDiscussionClick:y,onNewChatClick:b,onEditDiscussion:v,onDeleteDiscussion:E,refresh:R,setCurrentPage:w}=i,{textNewChat:C}=n;DiscussionsUI_useEffect((()=>{}));const k=s("mwai-discussions",{[`mwai-${null==t?void 0:t.themeId}-theme`]:!0});return React.createElement(React.Fragment,null,React.createElement("div",{id:`mwai-discussions-${l}`,className:k,style:{...c,...a}},r&&React.createElement("style",null,r),React.createElement("div",{className:s("mwai-header")},React.createElement("button",{onClick:()=>b(),disabled:m||p},React.createElement("span",null,C??"+ New chat")),-1===(null==_?void 0:_.refreshInterval)&&React.createElement("button",{className:s("mwai-refresh-btn"),onClick:()=>R(),disabled:m},React.createElement(RefreshCw,{size:16}))),React.createElement("div",{className:s("mwai-content"),style:{position:"relative"}},f&&React.createElement("div",{className:s("mwai-loading-overlay")},React.createElement(LoaderCircle,{size:24,className:s("mwai-spinner")})),React.createElement("ul",{style:{listStyle:"none",padding:0,margin:0}},u.map((e=>React.createElement(Discussion,{key:e.id,discussion:e,selected:(null==d?void 0:d.id)===e.id,onClick:()=>y(e.chatId),onEdit:v,onDelete:E,theme:t,system:_}))))),(null==_?void 0:_.paging)>0&&g>_.paging&&React.createElement("div",{className:s("mwai-pagination")},React.createElement("button",{onClick:()=>{const e=h-1;w(e),R(!1,e,!0)},disabled:0===h||m||f},React.createElement(ChevronLeft,{size:16})),React.createElement("span",{className:s("mwai-page-indicator")},`Page ${h+1} of ${Math.ceil(g/_.paging)}`),React.createElement("button",{onClick:()=>{const e=h+1;w(e),R(!1,e,!0)},disabled:h>=Math.ceil(g/_.paging)-1||m||f},React.createElement(ChevronRight,{size:16})))))},chatbot_DiscussionsUI=DiscussionsUI,DiscussionsSystem=e=>React.createElement(DiscussionsContextProvider,e,React.createElement(chatbot_DiscussionsUI,e)),chatbot_DiscussionsSystem=DiscussionsSystem,{render}=wp.element;function decodeHtmlEntities(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}function initializeMwai(){function e(e,t){e.forEach((e=>{if(e.hasAttribute("data-mwai-initialized"))return;const a=e.getAttribute("data-params"),n=e.getAttribute("data-system"),s=e.getAttribute("data-theme");if(!a||!n||!s)return void console.warn("MWAI: Missing required attributes for initialization",e);const r=JSON.parse(decodeHtmlEntities(a)),o=JSON.parse(decodeHtmlEntities(n)),i=JSON.parse(decodeHtmlEntities(s));e.setAttribute("data-mwai-initialized","true"),e.removeAttribute("data-params"),e.removeAttribute("data-system"),e.removeAttribute("data-theme"),render(t({system:o,params:r,theme:i}),e)}))}e(document.querySelectorAll(".mwai-chatbot-container"),chatbot_ChatbotSystem),e(document.querySelectorAll(".mwai-discussions-container"),chatbot_DiscussionsSystem)}document.addEventListener("DOMContentLoaded",initializeMwai),window.mwaiInitialize=initializeMwai})();
Page not found – Hello World !