Current File : /home/kelaby89/cartel.express/wp-content/plugins/ai-engine/app/index.js
(()=>{"use strict";var __webpack_modules__={1469:(__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__(6966),_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(1137),_app_helpers__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(7678),_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(2213);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),l=e(processedParams.guestAvatarUrl);return{cssVariables:Object.keys(shortcodeStyles).reduce(((e,t)=>(e[`--mwai-${t}`]=shortcodeStyles[t],e)),{}),iconUrl:t,aiAvatarUrl:a,userAvatarUrl:n,guestAvatarUrl:l}}),[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((()=>{if(!isConversationLoaded)return;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,l=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&&(l=uploadedFile)}return setMessages(e),saveMessages(e),void addErrorMessage(serverReply.message,n?{text:n,file:l}: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 l;if(n<1e3)l=`${n}ms`;else if(n<6e4)l=`${(n/1e3).toFixed(1)}s`;else{l=`${Math.floor(n/6e4)}m ${(n%6e4/1e3).toFixed(0)}s`}t.streamEvents.push({type:"event",subtype:"status",data:`Request completed in ${l}.`,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),l=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(n,null,null,null,debugMode);return{success:l.success,message:l.message,overLimit:l.overLimit||!1,limitMessage:l.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),l=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(n,null,null,null,debugMode);return{success:l.success,message:l.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,l=null==uploadedFile||null===(t=uploadedFile.localFile)||void 0===t?void 0:t.type,r=!!l&&l.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 c=(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),s=[...i,{id:c,role:"assistant",content:stream?"":null,who:rawAiName,timestamp:null,isQuerying:!stream,isStreaming:!!stream,streamEvents:stream&&debugMode?[]:void 0}];if(setMessages(s),"[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."],l=n[Math.floor(Math.random()*n.length)],r={id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"error",content:`[TEST ERROR] ${l}`,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 d={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&&(d.previousResponseId=previousResponseId);try{debugMode&&console.log("[CHATBOT] OUT: ",d);const e=stream?(e,t)=>{debugMode&&t&&t.subtype&&console.log("[CHATBOT] STREAM EVENT:",t),setMessages((a=>{const n=[...a],l=n.length>0?n[n.length-1]:null;return l&&l.id===c&&(l.content=e,l.timestamp=(new Date).getTime(),t&&t.subtype&&(l.streamEvents||(l.streamEvents=[]),l.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)},l=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/chats/submit`,d,t,stream,void 0,n),r=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(l,e,debugMode?"CHATBOT":null,n,debugMode);if(!r.success&&r.message){const e=[...s];e.pop();const t=e.length-1;let n=null,l=null;if(t>=0&&"user"===e[t].role){const r=e[t].content,o=r.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);n=o?o[1]:r,o&&(l=a)}return setMessages(e),saveMessages(e),addErrorMessage(r.message,n?{text:n,file:l}: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,l=null;if(t>=0&&"user"===s[t].role){const e=s[t].content,r=e.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);n=r?r[1]:e,r&&(l=a)}addErrorMessage(e.message||"An error occurred while processing your request. Please try again.",n?{text:n,file:l}: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},l=`${restUrl}/mwai-ui/v1/files/upload`,r=restNonceRef.current??await refreshRestNonce(),o=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.uE)(l,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)}},1137:(e,t,a)=>{a.d(t,{HX:()=>l,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 l=(()=>{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)=>l.applyFilters(e,t,...a)},6966:(e,t,a)=>{a.d(t,{Mc:()=>E,Vw:()=>h,_$:()=>g,bE:()=>R,dh:()=>p,gR:()=>m,kW:()=>y,mv:()=>u,tm:()=>d});var n=a(8614);function l(){return l=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},l.apply(this,arguments)}const{useState:r,useMemo:o,useEffect:i,useRef:c,useCallback:s}=wp.element,d=({active:e,disabled:t,...a})=>React.createElement("div",l({active:e?"true":"false",disabled:t},a),React.createElement(n.A,{size:"24"}));const m=()=>o((()=>(e,t)=>(Array.isArray(e)||(e=[e]),t&&Object.entries(t).forEach((([t,a])=>{a&&e.push(t)})),e.join(" "))),[]);function u(e){return!(!e||"string"!=typeof e)&&0===e.indexOf("http")}function p(){const[e,t]=r(null),a=c(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);t(function(e){const t=Math.floor(e/60);return`${t}:${(e%60).toString().padStart(2,"0")}`}(a))}),500)},stopChrono:function(){clearInterval(a.current),a.current=null,t(null)}}}const E=(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,l,r,o,i,c,s,d,m,u,p,g,h,R;const y=(null===(a=e.guestName)||void 0===a?void 0:a.trim())??"",v=(null===(n=e.textSend)||void 0===n?void 0:n.trim())??"",f=(null===(l=e.textClear)||void 0===l?void 0:l.trim())??"",b=parseInt(e.textInputMaxLength),w=(null===(r=e.textInputPlaceholder)||void 0===r?void 0:r.trim())??"";let _=(null===(o=e.textCompliance)||void 0===o?void 0:o.trim())??"",C="";const T=Boolean(e.window),O=Boolean(e.copyButton),N=Boolean(e.fullscreen),I=(null===(i=e.icon)||void 0===i?void 0:i.trim())??"";let M=(null===(c=e.iconText)||void 0===c?void 0:c.trim())??"";const S=parseInt(e.iconTextDelay||1),k=(null===(s=e.iconAlt)||void 0===s?void 0:s.trim())??"",A=(null===(d=e.iconPosition)||void 0===d?void 0:d.trim())??"",x=Boolean(e.iconBubble),P=(null===(m=e.aiName)||void 0===m?void 0:m.trim())??"",D=(null===(u=e.userName)||void 0===u?void 0:u.trim())??"",L=Boolean(null==e?void 0:e.aiAvatar),F=Boolean(null==e?void 0:e.userAvatar),B=Boolean(null==e?void 0:e.guestAvatar),U=L?(null==e||null===(p=e.aiAvatarUrl)||void 0===p?void 0:p.trim())??"":null,H=F?(null==e||null===(g=e.userAvatarUrl)||void 0===g?void 0:g.trim())??"":null,j=B?(null==e||null===(h=e.guestAvatarUrl)||void 0===h?void 0:h.trim())??"":null,G=Boolean(e.localMemory),$=Boolean(e.imageUpload),z=Boolean(e.fileUpload),W=Boolean(e.fileSearch),q=(null===(R=e.mode)||void 0===R?void 0:R.trim())??"chat";var V;null===e.headerSubtitle||void 0===e.headerSubtitle?C="Discuss with":C=(null===(V=e.headerSubtitle)||void 0===V?void 0:V.trim())??"";return t&&(_=E(_,t),M=E(M,t)),{textSend:v,textClear:f,textInputMaxLength:b,textInputPlaceholder:w,textCompliance:_,mode:q,window:T,copyButton:O,fullscreen:N,localMemory:G,imageUpload:$,fileUpload:z,fileSearch:W,icon:I,iconText:M,iconTextDelay:S,iconAlt:k,iconPosition:A,iconBubble:x,headerSubtitle:C,aiName:P,userName:D,guestName:y,aiAvatar:L,userAvatar:F,guestAvatar:B,aiAvatarUrl:U,userAvatarUrl:H,guestAvatarUrl:j}},h=e=>{const[t,a]=r(!1),[n,l]=r(!1);return i((()=>{"undefined"!=typeof window&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)&&l(!0)}),[]),i((()=>{if(!n)return;const l=new(window.SpeechRecognition||window.webkitSpeechRecognition);let r=null;return navigator.userAgent.toLowerCase().indexOf("android")>-1?(l.interimResults=!1,l.continuous=!1,r=t=>{const n=Array.from(t.results).filter((e=>e.isFinal)).map((e=>e[0].transcript)).join("");e(n),a(!1)}):(l.interimResults=!0,l.continuous=!0,r=t=>{const a=Array.from(t.results).map((e=>e[0])).map((e=>e.transcript)).join("");e(a)}),t?(l.addEventListener("result",r),l.start()):(l.removeEventListener("result",r),l.abort()),()=>{l.abort()}}),[t,n]),{isListening:t,setIsListening:a,speechRecognitionAvailable:n}},R=({if:e,className:t,disableTransition:a=!1,children:n,...o})=>{const[c,s]=r(!1),[d,m]=r("mwai-transition");i((()=>{a?s(e):e?(s(!0),setTimeout((()=>{m("mwai-transition mwai-transition-visible")}),150)):m("mwai-transition")}),[e,a]);return c?React.createElement("div",l({className:`${t} ${a?"":d}`,onTransitionEnd:()=>{"mwai-transition"!==d||a||s(!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),[]),l=c(window.visualViewport),d=s((()=>{t(l.current.height)}),[]);return i((()=>{const e=l.current;return e.addEventListener("resize",d),n?(window.addEventListener("resize",d),document.addEventListener("focusin",d)):e.addEventListener("scroll",d),()=>{e.removeEventListener("resize",d),n?(window.removeEventListener("resize",d),document.removeEventListener("focusin",d)):e.removeEventListener("scroll",d)}}),[d,n]),{viewportHeight:e,isIOS:n,isAndroid:a}}},7678:(e,t,a)=>{a.d(t,{CI:()=>p,F1:()=>i,Pn:()=>c,Ve:()=>g,rn:()=>u,ti:()=>s,uE:()=>d,vx:()=>m});var n=a(6841);const{useMemo:l,useEffect:r,useState:o}=wp.element;function i(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 c(e,t,a=null,n=null,l=!1){if(!t)try{const t=await e.json();return a&&console.log(`[${a}] IN: `,t),t.new_token&&(l&&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="",c="";for(;;){const{value:e,done:s}=await r.read();if(i+=o.decode(e,{stream:!0}),s)break;const d=i.split("\n");for(let e=0;e<d.length-1;e++){if(0!==d[e].indexOf("data: "))continue;const r=JSON.parse(d[e].replace("data: ",""));if("live"===r.type)a&&console.log(`[${a} STREAM] LIVE: `,r),r.subtype?(t&&t(c,r),"content"===r.subtype&&(c+=r.data)):(c+=r.data,t&&t(c,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&&(l&&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=d[d.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 s(e,t,a,n,l=void 0,r=null){const o={"Content-Type":"application/json"};a&&(o["X-WP-Nonce"]=a),n&&(o.Accept="text/event-stream");const c=await fetch(`${e}`,{method:"POST",headers:o,body:i(t),credentials:"same-origin",signal:l});if(403===c.status||401===c.status)try{const e=await c.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&&c.ok)try{const e=c.clone(),t=await e.json();t.new_token&&r&&r(t.new_token)}catch(e){}return c}async function d(e,t,a,n,l={}){return new Promise(((r,o)=>{const i=new FormData;i.append("file",t);for(const[e,t]of Object.entries(l))i.append(e,t);const c=new XMLHttpRequest;c.open("POST",e,!0),a&&c.setRequestHeader("X-WP-Nonce",a),c.upload.onprogress=function(e){if(e.lengthComputable&&n){const t=e.loaded/e.total*100;n(t)}},c.onload=function(){if(c.status>=200&&c.status<300)try{const e=JSON.parse(c.responseText);r(e)}catch(e){o({status:c.status,statusText:c.statusText,error:"The server response is not valid JSON"})}else{try{const e=JSON.parse(c.responseText);return void o({status:c.status,message:e.message})}catch(e){}o({status:c.status,statusText:c.statusText})}},c.onerror=function(){o({status:c.status,statusText:c.statusText})},c.send(i)}))}function m(){return Math.random().toString(36).substring(2)}const u=()=>{const[e,t]=o(!0);r((()=>{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})},p=e=>{const{content:t,error:a,isStreaming:r,baseClass:o="mwai-output-handler"}=e;let i=(!!a?a:t)??"";(i.match(/```/g)||[]).length%2!=0?i+="\n```":r&&(i+="<BlinkingCursor />");const c=l((()=>{const e=[o];return a&&e.push("mwai-error"),e}),[a]),s=l((()=>({wrapper:"div",forceWrapper:!0,overrides:{BlinkingCursor:{component:u},a:{props:{target:"_blank"}}}})),[]);return React.createElement(n.Ay,{options:s,className:c.join(" "),children:i})},E=/([\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 g(e){return e&&2===e.length&&E.test(e)}},2213:(e,t,a)=>{a.d(t,{A:()=>l});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 l=n},2701:(e,t,a)=>{var n=a(5323),l=a(7665),r=a(2564),o=a(9270),i=a(7097),c=a(4977),s=a(7039),d=a(4536),m=a(5263),u=a(6913),p=a(1829),E=a(4547),g=a(3676),h=a(9296),R=a(4461),y=a(8135);const v=mwai.prefix,f=mwai.domain,b=mwai.rest_url.replace(/\/+$/,""),w=mwai.api_url.replace(/\/+$/,""),_=mwai.plugin_url.replace(/\/+$/,""),C=mwai.user_data,T="1"===mwai.is_pro,O=T&&"1"===mwai.is_registered;let N=mwai.rest_nonce;const I=mwai.options,M=mwai.session,S=mwai.themes,k=!!mwai.stream,A=mwai.chatbots,x=e=>{N=e,"undefined"!=typeof mwai&&(mwai.rest_nonce=e)},P=()=>N;var D=a(197),L=a(3185);const F=L.Ay.div`
  color: white;
  padding: 15px;
  margin-bottom: -15px;

  a {
    color: #7dedff;
    text-decoration: none;
  }

  p {
    font-size: 15px;
  }
`,B=(0,L.Ay)(R.z)`

  .neko-block-title {
    display: none;
  }

  .plugin-desc {
    display: flex;
    flex-direction: column;
    margin-left: 15px;
  }

  .neko-block-content {
    display: flex;
    padding: 15px;

    h2 {
      font-size: 18px;
      margin: 0;

      a {
        text-decoration: none;
      }
    }

    p {
      margin: 0px;
      margin-top: 10px;
      font-size: 13px;
      line-height: 1.5;
    }

    .plugin-actual-desc {
      font-size: 13px;
      font-weight: 500;
    }
  }
`,U=L.Ay.img`
  height: 125px;
  width: auto;
  border-radius: 10px;
  background: lightgray;
`,H=L.Ay.div`

  margin: 15px;

  .center {
    background: white;
    color: black;
    border-radius: 10px;
    padding: 10px;
    max-width: 100%
    overflow: none;

    h2 {
      font-size: 26px;
    }

    table {
      width: 100%;

      tr td:first-child {
        width: 220px;
        font-weight: bold;
        color: #1e7cba;
      }

      * {
        overflow-wrap: anywhere;
      }
    }
  }

  hr {
    border-color: #1e7cba;
  }
`,j=L.Ay.ul`
  margin-top: 10px;
  background: rgb(0, 72, 88);
  padding: 10px;
  color: rgb(58, 212, 58);
  max-height: 600px;
  min-height: 200px;
  display: block;
  font-family: monospace;
  font-size: 12px;
  white-space: pre;
  overflow-x: auto;
  width: calc(100vw - 276px);
  color: white;

  .log-date {
    color: var(--neko-yellow);
    margin-left: 8px;
  }

  .log-type {
    background: #0000004d;
    padding: 2px 5px;
    border-radius: 8px;
    text-transform: uppercase;
  }

  .log-content {
    display: block;
  }

  .log-warning .log-type {
    background: var(--neko-yellow);
    color: white;
  }

  .log-fatal .log-type {
    background: var(--neko-red);
    color: white;
  }
`,{useState:G,useEffect:$}=wp.element,z=`${b}/meow-common/v1`,W=({request:e,title:t,max:a})=>{const[n,l]=G(!1),[r,o]=G([]),i=r.length>0?r.reduce((function(e,t){return e+t})):0,s=r.length>0?Math.ceil(i/r.length):0,d=!r.length&&n;$((()=>{n&&setTimeout((async()=>{const t=(new Date).getTime();await(0,y.IU)(`${z}/${e}`,{method:"POST",nonce:N});const a=(new Date).getTime()-t;o((e=>[...e,a]))}),1e3)}),[r]);return React.createElement(F,{style:{width:200,textAlign:"center"}},React.createElement(c.s,{h2:!0,style:{color:"white"}},t),React.createElement(D.X,{size:200,value:d?a:s,max:a},React.createElement("span",{style:{fontSize:20}},d?"START":s+" ms"),React.createElement("span",{style:{fontSize:12}},d?"YOUR ENGINE":r.length+" requests")),React.createElement(h.M,{style:{width:"100%",marginTop:10},color:n?"#cc3627":"#ccb027",onClick:()=>{n||o([]),l(!n)}},n?"Stop":"Start"))},{useState:q,useEffect:V}=wp.element;w&&b&&_||console.error("[@common/dashboard] apiUrl, restUrl and pluginUrl are mandatory.");const Y=`${b}/meow-common/v1`,K=React.createElement(F,null,React.createElement(c.s,{p:!0,style:{lineHeight:"1.5",margin:"0 0 15px 0"}},"Hi! ☀️ Meow Apps isn't your typical plugin suite—it's a passion project led by me, ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://jordymeow.com"},"Jordy Meow"),", and a stellar team! 💕 Based in ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://offbeatjapan.org"},"Japan"),", we're all about making your WordPress experience smoother and speedier. Our plugins are all about boosting your site's performance and user-friendliness. Ready to level up your WordPress game? Check out ",React.createElement("a",{href:"http://meowapps.com",rel:"noreferrer",target:"_blank"},"Meow Apps")," and let's make magic happen! 🌴🙀")),X=React.createElement(F,null,React.createElement(c.s,{p:!0},"The ",React.createElement("b",null,"Empty Request Time")," measures your installation's basic performance by showing the average time needed to process an empty request on your server. To see how disabling plugins affects the results, turn some off and run the test again. Aim for a time under 2,000 ms, but ideally, keep it below 500 ms. The ",React.createElement("b",null,"File Operation Time")," creates a temporary 10MB file each time it runs. ",React.createElement("b",null,"The SQL Request Time")," calculates the total number of posts. This process should be quick and have a similar duration to the Empty Request Time.")),Q=React.createElement(F,null,React.createElement(c.s,{p:!0},"Maintain a streamlined WordPress setup by using essential plugins and a dependable hosting provider. Refrain from self-hosting unless you're an expert. Go further by reading our tutorials:",React.createElement("ul",null,React.createElement("li",null,"⭐️ ",React.createElement("a",{href:"https://meowapps.com/tutorial-improve-seo-wordpress/",rel:"noreferrer",target:"_blank"},"SEO Checklist & Optimization")),React.createElement("li",null,"⭐️ ",React.createElement("a",{href:"https://meowapps.com/tutorial-faster-wordpress-optimize/",rel:"noreferrer",target:"_blank"},"Optimize your WordPress Speed")),React.createElement("li",null,"⭐️ ",React.createElement("a",{href:"https://meowapps.com/tutorial-optimize-images-wordpress/",rel:"noreferrer",target:"_blank"},"Optimize Images (CDN, and so on)")),React.createElement("li",null,"⭐️ ",React.createElement("a",{href:"https://meowapps.com/tutorial-hosting-service-wordpress/",rel:"noreferrer",target:"_blank"},"The Best Hosting Services for WordPress"))))),J=async()=>(await(0,y.IU)(`${Y}/all_settings/`,{method:"POST",nonce:N})).data,Z=async({value:e,id:t})=>await(0,y.IU)(`${Y}/update_option`,{method:"POST",nonce:N,json:{name:t,value:e}}),ee=async()=>(await(0,y.IU)(`${Y}/error_logs`,{method:"POST",nonce:N})).data.reverse(),te=()=>{const e=(0,l.jE)(),[t,a]=q(!1),[n,r]=q(""),{data:y,error:v}=(0,o.I)({queryKey:["all_settings"],queryFn:J}),f=(0,i.n)({mutationFn:Z,onSuccess:()=>{e.invalidateQueries(["all_settings"])}}),b=(0,i.n)({mutationFn:ee}),w=null==y?void 0:y.meowapps_hide_meowapps,_=null==y?void 0:y.force_sslverify;V((()=>{v&&!t&&(a(!0),console.error("Error from useQuery",v.message))}),[v]),V((()=>{const e=document.getElementById("meow-common-phpinfo");e&&r(e.innerHTML)}),[]);const C=(e,t)=>{f.mutate({value:e,id:t})},T=React.createElement(s.d,{title:"Main Menu"},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"meowapps_hide_meowapps",label:"Hide (Not Recommended)",description:React.createElement(c.s,{p:!0},"This will hide the Meow Apps Menu (on the left side) and everything it contains. You can re-enable it through though an option that will be added in Settings → General."),value:"1",disabled:f.isPending,checked:w,onChange:C}))),O=React.createElement(s.d,{title:"SSL Verify"},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"force_sslverify",label:"Force (Not Recommended)",description:React.createElement(c.s,{p:!0},"This will enforce the usage of SSL when checking the license or updating the plugin."),value:"1",disabled:f.isPending,checked:_,onChange:C})));return React.createElement(u.z,{showRestError:t},React.createElement(p.n,{title:"The Dashboard"}),React.createElement(E.N,null,React.createElement(E.Y,{full:!0},React.createElement(g._,{keepTabOnReload:!0},React.createElement(g.V,{title:"Meow Apps"},K,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},React.createElement(B,{title:"AI Engine",className:"primary"},React.createElement(U,{src:"https://ps.w.org/ai-engine/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/ai-engine/",rel:"noreferrer"},"AI Engine")),React.createElement("p",{className:"plugin-actual-desc"},"This is the ultimate AI plugin for WordPress. From a chatbot adapted to your needs to an AI that can write your content for you, API, REST, and more."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/ai-engine/",rel:"noreferrer"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{target:"_blank",href:"https://meowapps.com/ai-engine/",rel:"noreferrer"},"Meow Apps"))))),React.createElement(B,{title:"Media Cleaner",className:"primary"},React.createElement(U,{src:"https://ps.w.org/media-cleaner/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/media-cleaner/",rel:"noreferrer"},"Media Cleaner")),React.createElement("p",{className:"plugin-actual-desc"},"Is your Media Library bloated, your database heavy, and your website running slow? Media Cleaner will clean your Media Library from the media entries (and files) which aren't used in your website, as well as broken entries."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/media-cleaner/",rel:"noreferrer"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{target:"_blank",href:"https://meowapps.com/media-cleaner/",rel:"noreferrer"},"Meow Apps"))))),React.createElement(B,{title:"Database Cleaner",className:"primary"},React.createElement(U,{src:"https://ps.w.org/database-cleaner/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/database-cleaner/",rel:"noreferrer"},"Database Cleaner")),React.createElement("p",{className:"plugin-actual-desc"},"Not only does Database Cleaner have a user-friendly UI, but it's also equipped to handle large DBs, giving it an edge over other plugins. It's a must-have for any WordPress site."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/database-cleaner/",rel:"noreferrer"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{target:"_blank",href:"https://meowapps.com/database-cleaner/",rel:"noreferrer"},"Meow Apps"))))),React.createElement(B,{title:"Media File Renamer",className:"primary"},React.createElement(U,{src:"https://ps.w.org/media-file-renamer/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/media-file-renamer/",rel:"noreferrer"},"Media File Renamer")),React.createElement("p",{className:"plugin-actual-desc"},"Rename and move files directly from the dashboard, manually, automatically or via AI, either individually or in bulk. It's the best way to rename your files."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/media-file-renamer/",rel:"noreferrer"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{target:"_blank",href:"https://meowapps.com/media-file-renamer/",rel:"noreferrer"},"Meow Apps"))))),React.createElement(B,{title:"Social Engine",className:"primary"},React.createElement(U,{src:"https://ps.w.org/social-engine/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/social-engine/",rel:"noreferrer"},"Social Engine")),React.createElement("p",{className:"plugin-actual-desc"},'Effortlessly schedule and automate the perfect posts for all your networks. Unlimited capabilities and infinite className="plugin-actual-desc" extensibility, for free!'),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/social-engine/",rel:"noreferrer"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{target:"_blank",href:"https://meowapps.com/social-engine/",rel:"noreferrer"},"Meow Apps"))))),React.createElement(B,{title:"Meow Analytics",className:"primary"},React.createElement(U,{src:"https://ps.w.org/meow-analytics/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/meow-analytics/"},"Meow Analytics")),React.createElement("p",{className:"plugin-actual-desc"},"Google Analytics for your website. Simple and fast."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/meow-analytics/"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://meowapps.com/meow-analytics/"},"Meow Apps")))))),React.createElement(E.Y,{minimal:!0},React.createElement(B,{title:"Contact Form Block",className:"primary"},React.createElement(U,{src:"https://ps.w.org/seo-engine/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{target:"_blank",href:"https://wordpress.org/plugins/seo-engine/",rel:"noreferrer"},"SEO Engine")),React.createElement("p",{className:"plugin-actual-desc"},"Optimize your content for SEO and for the AI world, with AI assistants... while keeping everything simple and fast, as it should be! ✌️"),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/seo-engine/"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://meowapps.com/seo-engine/"},"Meow Apps"))))),React.createElement(B,{title:"Meow Gallery",className:"primary"},React.createElement(U,{src:"https://ps.w.org/meow-gallery/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/meow-gallery/"},"Meow Gallery")),React.createElement("p",{className:"plugin-actual-desc"},"Fast and beautiful galleries with many layouts. Forget the heavy and slow plugins, use the Meow Gallery for a better experience! 💕"),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/meow-gallery/"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://meowapps.com/meow-gallery/"},"Meow Apps"))))),React.createElement(B,{title:"Meow Lightbox",className:"primary"},React.createElement(U,{src:"https://ps.w.org/meow-lightbox/assets/icon-256x256.gif"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/meow-lightbox/"},"Meow Lightbox")),React.createElement("p",{className:"plugin-actual-desc"},"Sleek and performant lightbox with EXIF support."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/meow-lightbox/"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://meowapps.com/meow-lightbox/"},"Meow Apps"))))),React.createElement(B,{title:"Perfect Images (Retina)",className:"primary"},React.createElement(U,{src:"https://ps.w.org/wp-retina-2x/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/wp-retina-2x/"},"Perfect Images")),React.createElement("p",{className:"plugin-actual-desc"},"Manage, Optimize, Replace your images with Perfect Images."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/wp-retina-2x/"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://meowapps.com/wp-retina-2x/"},"Meow Apps"))))),React.createElement(B,{title:"Photo Engine",className:"primary"},React.createElement(U,{src:"https://ps.w.org/wplr-sync/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/wplr-sync/"},"Photo Engine")),React.createElement("p",{className:"plugin-actual-desc"},"Organize your photos in folders and collections. Synchronize with Lightroom. Simplify and speed up your workflow."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/wplr-sync/"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://meowapps.com/wplr-sync/"},"Meow Apps"))))),React.createElement(B,{title:"Contact Form Block",className:"primary"},React.createElement(U,{src:"https://ps.w.org/contact-form-block/assets/icon-256x256.png"}),React.createElement("div",{className:"plugin-desc"},React.createElement("h2",null,React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/contact-form-block/"},"Contact Form Block")),React.createElement("p",{className:"plugin-actual-desc"},"Need a very simple but straightforward contact form? This is the one you need. It's fast, simple, and efficient."),React.createElement("p",null,React.createElement("div",null,"Free Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://wordpress.org/plugins/contact-form-block/"},"WordPress.org")),React.createElement("div",null,"Pro Version: ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://meowapps.com/contact-form-block/"},"Meow Apps")))))))),React.createElement(g.V,{title:"Performance"},X,React.createElement("div",{style:{display:"flex",justifyContent:"space-around",marginBottom:25}},React.createElement(W,{title:"Empty Request Time",request:"empty_request",max:2500}),React.createElement(W,{title:"File Operation Time",request:"file_operation",max:2600}),React.createElement(W,{title:"SQL Request Time",request:"sql_request",max:2800})),Q),React.createElement(g.V,{title:"PHP Info"},React.createElement(H,{dangerouslySetInnerHTML:{__html:n}})),React.createElement(g.V,{title:"PHP Error Logs"},React.createElement(F,null,React.createElement(h.M,{style:{marginBottom:10},color:"#ccb027",onClick:()=>{b.mutate()},disabled:b.isPending,isBusy:b.isPending},"Load PHP Error Logs"),React.createElement(j,null,(b.data||[]).map((e=>React.createElement("li",{className:`log-${e.type}`,key:e.id},React.createElement("span",{className:"log-type"},e.type),React.createElement("span",{className:"log-date"},e.date),React.createElement("span",{className:"log-content"},e.content))))),React.createElement(c.s,{p:!0},"If you don't see any errors, your host might not allow remote access to PHP error logs. Contact them for assistance, or look in your hosting control panel."))),React.createElement(g.V,{title:"Settings"},React.createElement(R.z,{title:"Settings",className:"primary"},T,O))))))};var ae=a(4677),ne=a(8696),le=a(6734),re=a(1543),oe=a(1843),ie=a(9794),ce=a(7213);const{useState:se,useEffect:de}=wp.element,me=`${b}/meow-licenser/${v}/v1`,ue=()=>{const[e,t]=se(!1),[a,n]=se(!1),[l,r]=se(null),[o,i]=se(null),[s,d]=se(""),m=O&&(!o||"valid"!==o.license),u=async()=>{if("MEOW_OVERRIDE"===s)return n(!0),i(null),void d("");t(!0);try{const e=await(0,y.IU)(`${me}/set_license`,{method:"POST",nonce:N,json:{serialKey:s}});e.success&&(i(e.data),e.data&&!e.data.issue&&r("licenseAdded"))}catch(e){alert("Error while validating the license. Check your console for more information."),console.error(e)}t(!1)};de((()=>{(async()=>{if(T){t(!0);try{const e=await(0,y.IU)(`${me}/get_license`,{method:"POST",nonce:N});i(e.data),e.data.key&&d(e.data.key)}catch(e){alert("Error while checking the license. Check your console for more information."),console.error(e)}t(!1)}})()}),[]);const p=m?"Forced License":O?"Enabled":"Disabled",E=m||o&&"valid"===o.license;let g="Your license is active. Thanks a lot for your support :)";m&&(g="This license has been force-enabled for you.",o&&o.check_url&&(g=React.createElement(React.Fragment,null,React.createElement("span",null,g),React.createElement("br",null),React.createElement("small",null,"To check your license status, please click ",React.createElement("a",{target:"_blank",href:o.check_url+"&cache="+642e3*Math.random(),rel:"noreferrer"},"here"),".")))),E||(o?"no_activations_left"===o.issue?g=React.createElement("span",null,"There are no activations left for this license. You can visit your account at ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com"},"Meow Apps"),", unregister a site, and click on ",React.createElement("i",null,"Retry to validate"),"."):"expired"===o.issue?g=React.createElement("span",null,"Your license has expired. You can get another license or renew the current one by visiting your account at ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com"},"Meow Apps"),"."):"missing"===o.issue?g="This license does not exist.":"disabled"===o.issue?g="This license has been disabled.":"item_name_mismatch"===o.issue?g="This license seems to be for a different plugin... isn't it? :)":"forced"===o.issue?g="ABC":(g=React.createElement("span",null,"There is an unknown error related to the system or this serial key. Really sorry about this! Make sure your security plugins and systems are off temporarily. If you are still experiencing an issue, please ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com/contact/"},"contact us"),"."),console.error({license:o})):g="Unknown error :(");const v=React.createElement(R.z,{title:"Pro Version (Not Installed)",className:"primary"},"You will find more information about the Pro Version ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com"},"here"),". If you actually bought the Pro Version already, please remove the current plugin and download the Pro Version from your account at ",React.createElement("a",{target:"_blank",rel:"noreferrer",href:"https://meowapps.com/"},"Meow Apps"),"."),f=React.createElement(R.z,{title:`Pro Version (${p})`,busy:e,className:"primary"},!m&&!(o&&o.key===s)&&React.createElement(React.Fragment,null,React.createElement("div",{style:{marginBottom:10}},"License Key:"),React.createElement(ne.A,{id:"mfrh_pro_serial",name:"mfrh_pro_serial",disabled:e,value:s,onChange:e=>d(e),placeholder:"Type your license key..."}),React.createElement(c.s,{p:!0},"Insert your serial key above. If you don't have one yet, you can get one ",React.createElement("a",{href:"https://meowapps.com"},"here"),". If there was an error during the validation, try the ",React.createElement("i",null,"Retry")," to ",React.createElement("i",null,"validate")," button.")),o&&!E&&React.createElement(ce.X,{variant:"danger"},g),(m||o)&&E&&React.createElement(ce.X,{variant:"success"},g),React.createElement("div",{style:{marginTop:15,display:"flex",justifyContent:"end"}},o&&!E&&React.createElement(h.M,{className:"secondary",disabled:e||!s,onClick:u},"Retry to validate"),o&&o.key===s&&React.createElement(h.M,{className:"secondary",disabled:e||!s,onClick:async()=>{t(!0);try{(await(0,y.IU)(`${me}/set_license`,{method:"POST",nonce:N,json:{serialKey:null}})).success&&(d(""),i(null),r("licenseRemoved"))}catch(e){alert("Error while removing the license. Check your console for more information."),console.error(e)}t(!1)}},"Remove License"),React.createElement(h.M,{disabled:e||!s||o&&o.key===s,onClick:u},"Validate License"),a&&!E&&React.createElement(h.M,{disabled:e||!s||o&&o.key===s,onClick:async()=>{t(!0);try{const e=await(0,y.IU)(`${me}/set_license`,{method:"POST",nonce:N,json:{serialKey:s,override:!0}});e.success&&(i(e.data),e.data&&!e.data.issue&&r("licenseAdded"))}catch(e){alert("Error while forcing the license. Check your console for more information."),console.error(e)}t(!1)},className:"danger"},"Force License")),React.createElement(ie.n,{isOpen:"licenseAdded"===l,title:"Thank you :)",content:"The Pro features have been enabled. This page should be now reloaded.",okButton:{label:"Reload",onClick:()=>location.reload()}}),React.createElement(ie.n,{isOpen:"licenseRemoved"===l,title:"Goodbye :(",content:"The Pro features have been disabled. This page should be now reloaded.",okButton:{label:"Reload",onClick:()=>location.reload()}}));return T?f:v},{__:pe}=wp.i18n,Ee={};Ee.COMMON={GENERAL:pe("General","ai-engine"),MODULES:pe("Modules","ai-engine"),CLIENT_MODULES:pe("Client Modules","ai-engine"),BACKEND_MODULES:pe("Admin Modules","ai-engine"),SERVER_MODULES:pe("Server Modules","ai-engine"),ADVISOR:pe("Advisor","ai-engine"),SETTINGS:pe("Settings","ai-engine"),CHATBOT:pe("Chatbot","ai-engine"),CHATBOTS:pe("Chatbots","ai-engine"),CHATBOT_HELP:pe("Build intelligent conversational experiences with fully customizable AI-powered chatbots.","ai-engine"),INSIGHTS:pe("Insights","ai-engine"),STYLE:pe("Style","ai-engine"),ENABLE:pe("Enable","ai-engine"),NAME:pe("Name","ai-engine"),SUBMIT:pe("Submit","ai-engine"),MODEL:pe("Model","ai-engine"),AI_MODEL:pe("AI Model","ai-engine"),TEMPERATURE:pe("Temperature","ai-engine"),MAX_TOKENS:pe("Max Tokens","ai-engine"),CONTEXT_MAX_LENGTH:pe("Context Max Length","ai-engine"),STOP_SEQUENCE:pe("Stop Sequence","ai-engine"),MODE:pe("Mode","ai-engine"),CONTEXT:pe("Context","ai-engine"),IMAGES_NUMBER:pe("Number of Images","ai-engine"),AVATAR:pe("Avatar","ai-engine"),AI_NAME:pe("AI Name","ai-engine"),GUEST_NAME:pe("Guest Name","ai-engine"),USER_NAME:pe("User Name","ai-engine"),PLACEHOLDER:pe("Placeholder","ai-engine"),START_SENTENCE:pe("Start Sentence","ai-engine"),SEND:pe("Send","ai-engine"),CLEAR:pe("Clear","ai-engine"),CLOSE:pe("Close","ai-engine"),VIEW:pe("View","ai-engine"),EDIT:pe("Edit","ai-engine"),SYSTEM_NAME:pe("System Name","ai-engine"),ID:pe("ID","ai-engine"),SCOPE:pe("Scope","ai-engine"),POPUP:pe("Popup","ai-engine"),POSITION:pe("Position","ai-engine"),VOICE:pe("Voice","ai-engine"),ICON:pe("Icon","ai-engine"),ICON_TEXT:pe("Icon Text","ai-engine"),ICON_TEXT_DELAY:pe("Icon Text Delay","ai-engine"),FULL_SCREEN:pe("Full Screen","ai-engine"),CASUALLY_FINE_TUNED:pe("Casually Fine-Tuned","ai-engine"),CONTENT_AWARE:pe("Content Aware","ai-engine"),TITLE:pe("Title","ai-engine"),TOPIC:pe("Topic","ai-engine"),TOPICS:pe("Topics","ai-engine"),SPACING:pe("Spacing","ai-engine"),BORDER_RADIUS:pe("Border Radius","ai-engine"),FONT_SIZE:pe("Font Size","ai-engine"),FONT_COLOR:pe("Font Color","ai-engine"),BACK_PRIMARY_COLOR:pe("Back Primary Color","ai-engine"),BACK_SECONDARY_COLOR:pe("Back 2nd Color","ai-engine"),HEADER_BUTTONS_COLOR:pe("Header Buttons Color","ai-engine"),HEADER_BACKGROUND_COLOR:pe("Header Back Color","ai-engine"),HEADER_SUBTITLE:pe("Header Subtitle","ai-engine"),BUBBLE_COLOR:pe("Bubble Color","ai-engine"),BACK_USER_COLOR:pe("Back User Color","ai-engine"),BACK_AI_COLOR:pe("Back AI Color","ai-engine"),BACK_AI_SECONDARY_COLOR:pe("Back AI 2nd Color","ai-engine"),AVATAR_MESSAGE_BACKGROUND_COLOR:pe("Message Background","ai-engine"),AVATAR_MESSAGE_FONT_COLOR:pe("Message Color","ai-engine"),POPUP_ICON:pe("Popup Icon","ai-engine"),CUSTOM_ICON:pe("Custom Icon (URL or Emoticon)","ai-engine"),FEATURES:pe("Features","ai-engine"),TIMEFRAME:pe("Timeframe","ai-engine"),ABSOLUTE:pe("Absolute","ai-engine"),NONE:pe("None","ai-engine"),EDITORS_ADMINS:pe("Editors & Admins","ai-engine"),ADMINS_ONLY:pe("Admins Only","ai-engine"),MAINTENANCE:pe("Maintenance","ai-engine"),CREDITS:pe("Credits","ai-engine"),TYPE:pe("Type","ai-engine"),LIMITS:pe("Limits","ai-engine"),USERS:pe("Users","ai-engine"),USER:pe("User","ai-engine"),GUESTS:pe("Guests","ai-engine"),GUEST:pe("Guest","ai-engine"),OPENAI:pe("Open AI","ai-engine"),LICENSE_TAB:pe("License","ai-engine"),FINETUNES:pe("Finetunes","ai-engine"),MODELS:pe("Models","ai-engine"),FILES:pe("Files","ai-engine"),ASSISTANT:pe("Assistant","ai-engine"),ASSISTANTS:pe("Assistants","ai-engine"),UTILITIES:pe("Utilities","ai-engine"),POSTS_SUGGESTIONS:pe("AI Copilot, AI Suggestions, Magic Wands","ai-engine"),POSTS_SUGGESTIONS_HELP:pe("Tools to brainstorm/write faster and better.","ai-engine"),GENERATORS:pe("Generators","ai-engine"),CONTENT_GENERATOR:pe("Content Generator","ai-engine"),CONTENT_GENERATOR_HELP:pe("Transform ideas into polished articles with AI-powered content creation.","ai-engine"),IMAGES_GENERATOR:pe("Images Generator","ai-engine"),IMAGES_GENERATOR_HELP:pe("Bring your vision to life with stunning AI-generated visuals.","ai-engine"),IMAGES_GENERATOR_INTRO:pe("Create stunning visuals with AI-powered image generation. Use detailed prompts, customize styles and resolutions, and generate multiple variations. Perfect for creative projects, marketing materials, and visual content.","ai-engine"),PLAYGROUND:pe("Playground","ai-engine"),PLAYGROUND_HELP:pe("Experiment with AI models and unlock endless creative possibilities.","ai-engine"),FORMS:pe("Forms","ai-engine"),FORMS_HELP:pe("Create dynamic, intelligent forms that adapt and respond based on user input with conditional logic.","ai-engine"),SEARCH:pe("Search","ai-engine"),SEARCH_HELP:pe("Override the default WordPress search with AI powered keywords or embeddings.","ai-engine"),INSIGHTS_HELP:pe("Enable Query Logs, Usage and Limits.","ai-engine"),CLIENT_DEBUG:pe("Client Debug","ai-engine"),CLIENT_DEBUG_HELP:pe("Debugging information for Chatbots and Forms will be displayed in the Browser Console.","ai-engine"),SERVER_DEBUG:pe("Server Debug","ai-engine"),SERVER_DEBUG_HELP:pe("API calls and server events will be logged and displayed in the Logs Console.","ai-engine"),MCP_DEBUG:pe("MCP Debug","ai-engine"),MCP_DEBUG_HELP:pe("Debugging information from MCP will be written directly to the PHP error logs using error_log().","ai-engine"),QUERIES_DEBUG:pe("Queries Debug","ai-engine"),QUERIES_DEBUG_HELP:pe("Full queries and responses will be written directly to the PHP error logs using error_log().","ai-engine"),DEV_MODE:pe("Dev Mode","ai-engine"),DEV_MODE_HELP:pe("Run tasks frequently for debugging.","ai-engine"),CLEAR_LOGS:pe("Clear Logs","ai-engine"),REFRESH_LOGS:pe("Refresh Logs","ai-engine"),API_KEY:pe("API Key","ai-engine"),USAGE_HELP:pe("Estimates only. Check your AI service for actual costs. Insights module provides better accuracy.","ai-engine"),RESET_USAGE_SURE:pe("Are you sure you want to reset the usage data?","ai-engine"),USAGE_PRO_HELP:pe('If you would like to have better control on the amounts, add conditions or set limits to the usage of the AI, consider <a href="https://meowapps.com/ai-engine/" target="_blank">AI Engine Pro</a>.',"ai-engine"),LANGUAGE:pe("Language","ai-engine"),HIDE:pe("Hide","ai-engine"),SHOW:pe("Show","ai-engine"),CONTENT:pe("Content","ai-engine"),IMAGES:pe("Images","ai-engine"),IMAGES_AND_FILES:pe("Images & Files","ai-engine"),EXCERPT:pe("Excerpt","ai-engine"),GENERATE:pe("Generate","ai-engine"),MODEL_PARAMS:pe("Model Params","ai-engine"),CONTEXT_PARAMS:pe("Context Params","ai-engine"),PROMPT:pe("Prompt","ai-engine"),PROMPTS:pe("Prompts","ai-engine"),LABEL:pe("Label","ai-engine"),SYSTEM:pe("System","ai-engine"),SHORTCODE:pe("Shortcode","ai-engine"),SHORTCODES:pe("Shortcodes","ai-engine"),RESOLVE:pe("Resolve","ai-engine"),MAX_MESSAGES:pe("Max Messages","ai-engine"),INPUT_MAX_LENGTH:pe("Input Max Length","ai-engine"),COMPLIANCE_TEXT:pe("Compliance Text","ai-engine"),MODERATION:pe("Moderation","ai-engine"),MODERATION_HELP:pe("Moderation features with AI.","ai-engine"),FORMATTING:pe("Formatting","ai-engine"),FORMATTING_HELP:pe("Format the reply from AI into HTML. This is already done automatically if Markdown is detected in the reply.","ai-engine"),LOGS:pe("Logs","ai-engine"),QUERY:pe("Query","ai-engine"),REPLY:pe("Reply","ai-engine"),CODE:pe("Code","ai-engine"),EMBEDDINGS:pe("Embeddings","ai-engine"),QUERY_LOGS:pe("Query Logs","ai-engine"),KNOWLEDGE:pe("Knowledge","ai-engine"),KNOWLEDGE_HELP:pe("Searchable data for AI. Powered by <b>embeddings</b> for now, alternatives will come later.","ai-engine"),REMOTE_ACCESS:pe("Remote Access","ai-engine"),OTHERS:pe("Others","ai-engine"),PINECONE_APIKEY_HELP:pe('You can get your API Keys in your <a href="https://app.pinecone.io/organizations/keys" target="_blank">Pinecone Account</a>.',"ai-engine"),QDRANT_APIKEY_HELP:pe('You can get your API Keys in your <a href="https://cloud.qdrant.io/accounts/" target="_blank">Qdrant Account</a>.',"ai-engine"),SERVER:pe("Server","ai-engine"),PINECONE_SERVER_HELP:pe("The URL of your host (check your Indexes).","ai-engine"),PINECONE_NAMESPACE_HELP:pe("The namespace is used to separate the data from other data. This allows you to use the same server/index on more than one website. This is optional.","ai-engine"),QDRANT_SERVER_HELP:pe("The URL of your cluster (known as Cluster URL).","ai-engine"),QDRANT_COLLECTION_HELP:pe("The collection keeps data apart so you can use one cluster for many websites. If there's no collection, Qdrant makes one with 1536 dimensions and uses cosine similarity.","ai-engine"),COST:pe("Cost","ai-engine"),USAGE:pe("Usage","ai-engine"),USAGE_ESTIMATES_NOTE:pe("Costs and tokens are estimates. For accurate data and detailed analytics, visit the Insights tab.","ai-engine"),ACTIVITY:pe("Activity","ai-engine"),TRANSCRIPTION:pe("Transcription","ai-engine"),TRANSCRIPTION_HELP:pe("Introduces a 'Transcribe' tab to easily transform audio/images into text and get AI answers in JSON format.","ai-engine"),AUDIO_TRANSCRIPTION:pe("Audio-to-Text","ai-engine"),IMAGE_TRANSCRIPTION:pe("Image-to-Text","ai-engine"),AUDIO_TO_TEXT:pe("Audio ➡ Text","ai-engine"),IMAGE_TO_TEXT:pe("Image ➡ Text","ai-engine"),EMBEDDINGS_ENV:pe("Environment","ai-engine"),EMBEDDINGS_INDEX:pe("Index","ai-engine"),NAMESPACE:pe("Namespace","ai-engine"),NAMESPACES:pe("Namespaces","ai-engine"),NAMESPACE_HELP:pe("The namespace is used to separate the data from other data. This allows you to use the same index on more than one website.","ai-engine"),NAMESPACES_HELP:pe("Enter the namespaces you would like to use on this site, separated by commas.","ai-engine"),ERROR:pe("Error","ai-engine"),RETRY:pe("Retry","ai-engine"),AUTO_RETRY:pe("Auto Retry","ai-engine"),SKIP:pe("Skip","ai-engine"),AUTO_SKIP:pe("Auto Skip","ai-engine"),STOP:pe("Stop","ai-engine"),AUTO_RETRY_DESCRIPTION:pe("Auto Retry retries actions up to 10 times with increasing delay to avoid timeouts.","ai-engine"),WIDTH:pe("Width","ai-engine"),MAX_HEIGHT:pe("Max Height","ai-engine"),APPEARANCE:pe("Appearance","ai-engine"),THRESHOLDS:pe("Thresholds","ai-engine"),DASHBOARD:pe("Dashboard","ai-engine"),ADVANCED:pe("Advanced","ai-engine"),DISCUSSIONS:pe("Discussions","ai-engine"),DISCUSSION_TITLES:pe("Discussion Titles","ai-engine"),SUMMARIZE:pe("Summarize","ai-engine"),ROWS:pe("Rows","ai-engine"),POST_TYPE:pe("Post Type","ai-engine"),GENERATE_CONTENT:pe("Generate Content","ai-engine"),GENERATE_IMAGES:pe("Generate Images","ai-engine"),REST_API:pe("REST API","ai-engine"),ADMIN_BAR:pe("Admin Bar","ai-engine"),REFRESH:pe("Refresh","ai-engine"),DELETE:pe("Delete","ai-engine"),DELETE_ALL:pe("Delete All","ai-engine"),DELETE_SELECTED:pe("Delete Selected","ai-engine"),OPENAI_ORGANIZATION_ID:pe("Organization ID","ai-engine"),OPENAI_AZURE_API_KEY:pe("API Key","ai-engine"),OPENAI_AZURE_DEPLOYMENT_NAME:pe("Deployment Name","ai-engine"),OPENAI_AZURE_DEPLOYMENTS:pe("Deployments","ai-engine"),ENDPOINT:pe("Endpoint","ai-engine"),HUGGINGFACE_MODELS:pe("Models","ai-engine"),HUGGINGFACE_MODEL_NAME:pe("Name","ai-engine"),HUGGINGFACE_MODEL_URL:pe("API URL","ai-engine"),THEME:pe("Theme","ai-engine"),THEMES:pe("Themes","ai-engine"),BANNED_WORDS:pe("Banned Words","ai-engine"),WORD_BOUNDARIES:pe("Word Boundaries","ai-engine"),IGNORE:pe("Ignore","ai-engine"),BANNED_IPS:pe("Banned IPs","ai-engine"),SECURITY:pe("Security","ai-engine"),POST_TYPES:pe("Post Types","ai-engine"),COPY_BUTTON:pe("Copy Button","ai-engine"),AI_AVATAR:pe("AI Avatar","ai-engine"),GUEST_AVATAR:pe("Guest Avatar","ai-engine"),SITE_WIDE_CHATBOT:pe("Site-Wide Chatbot","ai-engine"),QUERIES_DATA:pe("Queries Data","ai-engine"),QUERIES_FORMS_DATA:pe("Queries Form Data","ai-engine"),WEBSPEECH_API:pe("Web Speech API","ai-engine"),VIRTUAL_KEYBOARD:pe("Virtual Keyboard","ai-engine"),GDPR_CONSENT:pe("GDPR Consent","ai-engine"),GDPR_TEXT:pe("GDPR Text","ai-engine"),GDPR_BUTTON:pe("GDPR Button","ai-engine"),FIX:pe("Fix","ai-engine"),SPEECH_RECOGNITION:pe("Speech Recognition","ai-engine"),SPEECH_SYNTHESIS:pe("Speech Synthesis","ai-engine"),QUERIES:pe("Queries","ai-engine"),LOCAL_MEMORY:pe("Local Memory","ai-engine"),ACTIONS:pe("Actions","ai-engine"),RESET:pe("Reset","ai-engine"),INCIDENTS_OPENAI:pe("Incidents (OpenAI)","ai-engine"),PREVIEW:pe("Preview","ai-engine"),LEGACY_FORMS:pe("Legacy Forms","ai-engine"),LEGACY_FEATURES:pe("Legacy Features","ai-engine"),DUPLICATE:pe("Duplicate","ai-engine"),CHATBOT_EDITOR:pe("Chatbot Editor","ai-engine"),THEME_EDITOR:pe("Theme Editor","ai-engine"),STREAMING:pe("Streaming","ai-engine"),SYNTAX_HIGHLIGHT:pe("Syntax Highlight","ai-engine"),EVENT_LOGS:pe("Event Logs","ai-engine"),PRIVACY_FIRST:pe("Privacy First","ai-engine"),DATA_NOT_AVAILABLE:pe("Data not available.","ai-engine"),EXPORT:pe("Export","ai-engine"),IMPORT:pe("Import","ai-engine"),MODIFY_EMBEDDING:pe("Modify Embedding","ai-engine"),ADD_EMBEDDING:pe("Add Embedding","ai-engine"),DEV_TOOLS:pe("Dev Tools","ai-engine"),SINGLE_GENERATE:pe("Single Generate","ai-engine"),PUBLIC_API:pe("Public API","ai-engine"),USER_INTERFACE:pe("User Interface","ai-engine"),INTRO_MESSAGE:pe("Intro Message","ai-engine"),ADDONS:pe("Add-ons","ai-engine"),AI_ENVIRONMENT_DEFAULTS:pe("Default Environments for AI","ai-engine"),ENVIRONMENTS_FOR_AI:pe("Environments for AI","ai-engine"),ENVIRONMENT_ID:pe("Environment ID","ai-engine"),EMBEDDINGS_ENVIRONMENT_DEFAULT:pe("Default Embeddings Environment","ai-engine"),ENVIRONMENT:pe("Environment","ai-engine"),PLUGIN_DATA:pe("Plugin Data","ai-engine"),PLUGIN_DATA_DESCRIPTION:pe("The database and all the options of the plugin will be removed on uninstall.","ai-engine"),RESET_LIMITS:pe("Reset Limits","ai-engine"),VISION:pe("Vision","ai-engine"),FILE_SEARCH:pe("File Search","ai-engine"),PROMPT_TO_JSON:pe("Prompt ➡ JSON","ai-engine"),RESOLUTION:pe("Resolution","ai-engine"),DEFAULT:pe("Default","ai-engine"),DEFAULTS:pe("Defaults","ai-engine"),DEFAULT_FAST:pe("Default (Fast)","ai-engine"),REFRESH_MODELS:pe("Refresh Models","ai-engine"),AUDIO:pe("Audio","ai-engine"),JSON:pe("JSON","ai-engine"),AI_ENVIRONMENT:pe("AI Environment","ai-engine"),OVERRIDE_DEFAULTS:pe("Override Defaults","ai-engine"),REGION:pe("Region","ai-engine"),PROJECT_ID:pe("Project ID","ai-engine"),BEARER_TOKEN:pe("Bearer Token","ai-engine"),DIMENSIONS:pe("Dimensions","ai-engine"),EMBEDDINGS_MODEL:pe("Embeddings Model","ai-engine"),MIN_SCORE:pe("Min Score","ai-engine"),MAX_SELECT:pe("Max Results","ai-engine"),QDRANT_COLLECTION:pe("Collection","ai-engine"),INSTRUCTIONS:pe("Instructions","ai-engine"),FUNCTIONS:pe("Functions","ai-engine"),TOOLS:pe("Tools","ai-engine"),WEB_SEARCH:pe("Web Search","ai-engine"),IMAGE_GENERATION:pe("Image Generation","ai-engine"),HISTORY_STRATEGY:pe("History Strategy","ai-engine"),AUTOMATIC:pe("Automatic","ai-engine"),FULL_HISTORY:pe("Full History","ai-engine"),INCREMENTAL:pe("Incremental","ai-engine"),BUBBLE:pe("Bubble","ai-engine"),TABS:pe("Tabs","ai-engine"),DROPDOWN:pe("Dropdown","ai-engine"),CHATBOT_SELECT:pe("Chatbot Select","ai-engine"),CONDITIONS:pe("Conditions","ai-engine"),CONDITION:pe("Condition","ai-engine"),ADD_CONDITION:pe("Add Condition","ai-engine"),REMOVE:pe("Remove","ai-engine"),MCP_NO_OPTIONS:pe("MCP is enabled but no options are selected. Please enable at least one option.","ai-engine"),ORCHESTRATION:pe("Orchestration","ai-engine"),ORCHESTRATION_HELP:pe("Connect AI models to external tools and services through MCP servers. Currently, MCP servers need to be set up in Settings > Orchestration.","ai-engine"),MCP_SERVERS:pe("MCP Servers","ai-engine"),MCP_FUNCTIONS:pe("MCP Functions","ai-engine"),URL:pe("URL","ai-engine"),TOKEN:pe("Token","ai-engine"),SERVER_ID:pe("Server ID","ai-engine")},Ee.FORMS={PROMPT_INFO:pe("The template of your prompt. To re-use the data entered by the user, use the name of that field between curly braces. Example: Recommend me {MUSIC_TYPE} artists. You can also use an ID as an input, like this: ${#myfield}. Finally, if you wish the output to be formatted, add: 'Use Markdown.'.\"","ai-engine"),OUTPUT:pe("Output","ai-engine"),OUTPUT_ELEMENT:pe("Output Element","ai-engine"),OUTPUT_ELEMENT_INFO:pe("The result will be written to this element. If you wish to simply display the result in an Output Block, use its ID. For instance, if its ID is mwai-666, use '#mwai-666'.","ai-engine")},Ee.HELP={TEMPERATURE:pe("Between 0 and 1. Higher values means the model will take more risks.","ai-engine"),MAX_TOKENS:pe("The maximum number of tokens to generate. The model will stop generating once it hits this limit.","ai-engine"),STOP_SEQUENCE:pe("The sequence of tokens that will cause the model to stop generating text. You absolutely need this with fine-tuned models.","ai-engine"),COST:pe("Keeps track of the current costs.","ai-engine"),RESOLVE_SHORTCODE:pe("Will resolve the shortcode in your content when needed (Content-Aware will use this, for instance).","ai-engine"),FINETUNES:pe("Train your own AI models.","ai-engine"),DISCUSSIONS:pe("Keep the conversations and enable browsing them via the Conversations tab.","ai-engine"),DISCUSSION_TITLES:pe("Generate titles for the discussions automatically with AI.","ai-engine"),DISCUSSION_SUMMARY:pe("Automatically generate a brief summary of the discussion using the default (fast) model. It will be used as the discussion title.","ai-engine"),AZURE_DEPLOYMENTS:pe("Add your deployments below and define what kind of model they are.","ai-engine"),BANNED_WORDS:pe("Reject queries containing these words; separate with commas.","ai-engine"),WORD_BOUNDARIES:pe("Ignore standard word separation (space) and match banned words anywhere in the text.","ai-engine"),BANNED_IPS:pe("Block access from specified IP addresses or ranges using CIDR notation; separate with commas.","ai-engine"),VIRTUAL_KEYBOARD:pe("Prevent the virtual keyboard from pushing the chatbot up on mobile devices. This is experimental and might cause issues.","ai-engine"),GDPR_CONSENT:pe("If enabled, the user will have to accept the conditions before using the chatbot.","ai-engine"),POST_TYPES:pe("Enable for these post types; separate with commas.","ai-engine"),POST_STATUS:pe("Enable for these post statuses (publish, draft, future, private, etc); separate with commas.","ai-engine"),POST_CATEGORIES:pe("Enable for these categories (slugs); separate with commas. If none, it will be enabled for all.","ai-engine"),CONTEXT_MAX_LENGTH:pe("Truncate the context (Content-Aware, Embeddings, etc) to make sure it is below this number of characters.","ai-engine"),MAX_MESSAGES:pe("Maximum number of historical messages that is sent to the AI model.","ai-engine"),INPUT_MAX_LENGTH:pe("Maximum number of characters that can be input by the user.","ai-engine"),STATISTICS:pe(" In the Insights tab, you can browse through all your users' activity. Contextual data is excluded unless you activate the options below. Make sure your users are aware of this.","ai-engine"),QUERIES_DATA:pe("Record the queries and their replies.","ai-engine"),QUERIES_FORMS_DATA:pe("Capture form data neatly for simple reuse.","ai-engine"),SPEECH_RECOGNITION:pe("Enable speech-to-text. Depends on the browser and OS used by the user.","ai-engine"),SPEECH_SYNTHESIS:pe("Enable text-to-speech.","ai-engine"),CUSTOM_SHORTCODE:pe("Prefer the above version. If you need many chatbots, you can custom shortcodes, like the one below. Custom shortcodes are based on the default chatbot, and their attributes override the default ones.","ai-engine"),USER_FILTER:pe("Type an User ID, or an IP.","ai-engine"),STREAMING:pe("The AI's response will appear as it's being created. Be cautious: this feature's ability to manage statistics, limits, and filters is still in its beta phase.","ai-engine"),SYNTAX_HIGHLIGHT:pe("Enable syntax highlighting for the code blocks.","ai-engine"),EVENT_LOGS:pe("Display streaming events and function calls in the chatbot interface for debugging. Requires Streaming to be enabled. Currently only visible in chatbots.","ai-engine"),PRIVACY_FIRST:pe("Only essential data is stored. IPs, conversations, and other private details are minimized and kept as anonymous as possible.","ai-engine"),DEV_TOOLS:pe("Enable a new tab with debugging tools. For developers only.","ai-engine"),DEV_MODE:pe("Run tasks very frequently for debugging.","ai-engine"),PUBLIC_API:pe("Enable the Public REST API.","ai-engine"),INTRO_MESSAGE:pe("Enable introduction messages on some modules.","ai-engine"),ADDONS:pe("Enable the AI Addons section under the Meow Apps menu.","ai-engine"),OPENAI_API_KEY:pe('You can get your API Keys in your <a href="https://platform.openai.com/api-keys" target="_blank">OpenAI Account</a>.',"ai-engine"),OPENAI_ORGANIZATION_ID:pe('You can link this environment to an <a href="https://platform.openai.com/account/organization" target="_blank">Organization</a>. This is optional.',"ai-engine"),AZURE_API_KEY:pe('You can get your API Keys in your <a href="https://oai.azure.com/portal" target="_blank">Azure Account</a>.',"ai-engine"),ANTHROPIC_API_KEY:pe('You can get your API Keys in your <a href="https://console.anthropic.com/settings/keys" target="_blank">Anthropic Account</a>.',"ai-engine"),OPENROUTER_API_KEY:pe('You can get your API Keys in your <a href="https://openrouter.ai/keys" target="_blank">OpenRouter Account</a>.',"ai-engine"),QDRANT:pe('Use the code <b>#AIENGINE5</b> when you <a href="https://qdrant.to/cloud" target="_blank">Create a Qdrant Account</a>. You will get 5% off.',"ai-engine"),ASSISTANTS:pe("The Assistants API is designed to help developers build powerful AI assistants capable of performing a variety of tasks.","ai-engine"),ASSISTANTS_INTRO:pe('The Assistants API is designed to help developers build powerful AI assistants capable of performing a variety of tasks. To create them, head to the <a href="https://beta.openai.com/assistants" target="_blank">OpenAI Assistants</a> dashboard, then <b>Refresh Assistants</b> here. You can use an assistant in your chatbots by switching the <b>Mode</b> to <b>Assistant</b>.',"ai-engine"),ASSISTANTS_WARNINGS:pe('Assistants are also <a href="https://platform.openai.com/docs/api-reference/assistants" target="_blank">in beta</a>, both for OpenAI and AI Engine. OpenAI did not add streaming support for them yet. Pricing is still quite unclear and <a href="https://openai.com/pricing" target="_blank">tricky</a>. AI Engine can only perform an estimation. If you want to discuss assistants with other users, visit the <a href="https://discord.gg/bHDGh38" target="_blank">Meow Apps Discord Server</a>.',"ai-engine"),BEARER_TOKEN:pe('The Public API will be usable by using this Bearer Token. If not set, you will need to <a href="https://meowapps.com/ai-engine/api/#public-rest-api" target="_blank">build your own authentication</a> by using the <i>mwai_allow_public_api</i> filter.',"ai-engine"),REST_API_INTRO:pe('The REST API enables integration with automation platforms and external applications. Use it with <a href="https://www.make.com/en/integrations/ai-engine" target="_blank">Make.com</a>, n8n, Zapier, or any platform that supports REST APIs to automate AI workflows and connect your WordPress site with other services.',"ai-engine"),MCP_BEARER_TOKEN:pe("MCP will be usable by using this Bearer Token. If not set, you will need to build your own authentication by using the <i>mwai_allow_mcp</i> filter.","ai-engine"),MCP_INTRO:pe('Enabling the SSE Endpoint creates a Model Context Protocol (MCP) server that provides various tools depending on the options selected below. <a href="https://meowapps.com/claude-wordpress-mcp/" target="_blank">This tutorial is highly recommended</a>. Currently, Claude works well with MCP servers but cannot handle SSE directly, so a relay is needed. The /labs/mcp.js script should be run locally next to your Claude instance.',"ai-engine"),MCP_SERVER_URL:pe("The URL of the MCP server. Must start with https://","ai-engine"),MCP_SERVER_TOKEN:pe("Bearer token for authenticating with the MCP server.","ai-engine"),NO_EMBEDDINGS_RESULTS:pe("No results for this search. Make sure the Minimum Score is not too high.","ai-engine"),NO_EMBEDDINGS_ROWS:pe("No embeddings yet in this environment.","ai-engine"),MIN_SCORE:pe("The minimum score the embeddings need to have to be returned. Between 0 and 100 and defaults to 35.","ai-engine"),MAX_SELECT:pe("The maximum number of embeddings to return and to use as context. Between 1 and 100 and defaults to 10.","ai-engine"),FUNCTIONS:pe("Select the functions to make available for the AI model's choice. It will use them to enhance responses and perform specific actions. This feature is known as Function Calling or Tools.","ai-engine"),FUNCTIONS_UNAVAILABLE:pe('There are no functions available. Please use <a href="https://wordpress.org/plugins/code-engine/" target="_blank">Code Engine</a> to add some. The Pro Version of AI Engine is also required for this feature.',"ai-engine"),MCP_SERVERS:pe("Select the MCP servers to make available for the AI model. These servers provide external tools and capabilities that the AI can use to enhance responses and perform specialized actions.","ai-engine"),MCP_SERVERS_UNAVAILABLE:pe("No MCP servers are available. Configure them in Settings > Orchestration.","ai-engine"),TOOLS:pe("Enable AI tools like web search and image generation to enhance your chatbot capabilities.","ai-engine"),WEB_SEARCH:pe("Allow the AI to search the web for current information","ai-engine"),IMAGE_GENERATION:pe("Allow the AI to generate images based on text descriptions","ai-engine"),HISTORY_STRATEGY:pe("Control how conversation history is sent to the Responses API. Incremental uses previous_response_id for efficiency, Full History sends all messages.","ai-engine"),ADVISOR:pe("In your Dashboard will be displayed daily recommendations tailored to your WordPress setup. Admins only.","ai-engine"),BUBBLE:pe("The popup will be displayed as a bubble.","ai-engine"),ICON_TEXT:pe("If set, this text will appear next to the icon/bubble.","ai-engine"),ICON_TEXT_DELAY:pe("The delay before the text appears.","ai-engine"),CHATBOT_SELECT:pe("Choose how you want to select the chatbot. By default, tabs are used, but you can also use a filterable dropdown if you have many chatbots.","ai-engine")},Ee.SETTINGS={AI_ENV_SETUP:pe('To leverage the functionalities of AI Engine, it needs to be connected directly to AI services. We recommend starting with OpenAI. Create an account and generate an API Key by visiting the <a href="https://platform.openai.com/api-keys" target="_blank">OpenAI</a> website. Once obtained, navigate to the <b>Settings</b> tab and input your OpenAI API Key in the "Environments for AI" section.',"ai-engine"),PINECONE_SETUP:pe('You choose to use Embeddings. To use them, you need to a Pinecone account. Visit the <a href="https://app.pinecone.io" target="_blank">Pinecone</a> website to create an account, then insert your Pinecone API Key in the <b>Settings</b> tab.',"ai-engine"),INTRO:pe('Boost your WordPress with AI, now! Please start with our <a href="https://meowapps.com/ai-engine/tutorial/" target="_blank">tutorial</a>. Then move to our <a href="https://ai.thehiddendocs.com/" target="_blank">documentation</a>. Have a look at our <a href="https://meowapps.com/products/category/ai-add-ons/" target="_blank">add-ons</a>. And make sure you read the <a href="https://meowapps.com/ai-engine/disclaimer/" target="_blank">disclaimer</a>. Have fun! 🎵',"ai-engine"),MODULES_INTRO:pe("To avoid cluttering the UI and your WP, only enable the features you need.","ai-engine"),ALERT_INJECT_BUT_NO_POPUP:pe("You choose to inject the chatbot in your website. You probably also want to use the chatbot in a Popup.","ai-engine"),ALERT_CASUALLY_BUT_NO_FINETUNE:pe("Normally, you should not check the Casually Fine Tuned option with a non-finetuned model. Make sure that's what you want.","ai-engine"),ALERT_CONTENTAWARE_BUT_NO_CONTENT:pe('Content Aware requires your Context to use the {CONTENT} placeholder. It will be replaced by the content of page the chatbot is on. More info <a href="https://meowapps.com/ai-engine/tutorial/#contextualization" target="_blank">here</a>.',"ai-engine"),SET_AS_DEFAULT_PARAMETERS:pe("Set as Default Parameters","ai-engine"),SET_AS_DEFAULT_PARAMETERS_HELP:pe("Set the parameters above as the default parameters for the chatbot. You can then use the shortcode [mwai_chat] anywhere on your website.","ai-engine"),INJECT_DEFAULT_CHATBOT:pe("Inject Default Chatbot in Entire Website","ai-engine"),INJECT_DEFAULT_CHATBOT_HELP:pe("Inject the chatbot [mwai_chat] in the entire website.","ai-engine"),CHATGPT_STYLE_INTRO:pe('Keep in mind that you can also style the chatbot (or a specific chatbot, if you use many) by injecting CSS. Have a look <a target="_blank" href="https://meowapps.com/ai-engine/tutorial/#apply-custom-style-to-the-chatbot">here</a>. More information in the <a target="_blank" href="https://meowapps.com/ai-engine/faq">FAQ</a>.',"ai-engine"),TYPEWRITER_EFFECT:pe("Typewriter Effect","ai-engine"),TYPEWRITER_EFFECT_HELP:pe("The reply from AI will be typewrited. This delays the final output! Absolutely not recommended. Please use <b>Streaming</b> instead.","ai-engine"),CHATBOT_MODERATION_HELP:pe("If the conversation seems offensive, the chatbot will reject it.","ai-engine"),CUSTOM_URL:pe("Custom URL","ai-engine"),ASSISTANT_NO_FILE_SEARCH:pe('This assistant does not support File Search. You can activate it on the <a href="https://platform.openai.com/assistants" target="_blank">OpenAI Assistants</a> dashboard. Then, use the Refresh button in the Assistants tab.',"ai-engine"),ASSISTANT_FILE_SEARCH:pe("File Search will be used when the users upload documents. If the user uploads images, those will be handled by AI Vision if the model supports it and if it is enabled.","ai-engine"),MCP_SERVERS_INFO:pe("MCP (Model Context Protocol) servers enable AI models to interact with external tools and systems. The URL must be a secure HTTPS endpoint that implements the MCP protocol. You can configure multiple servers to provide different capabilities to your AI models.","ai-engine"),REMOTE_ACCESS_INFO:pe("AI Engine provides two ways to integrate with external systems: REST API and Model Context Protocol (MCP).<h2>REST API</h2><p>Ideal for automation platforms like Make.com, Zapier, or n8n. Use this when you want to trigger AI operations from external services or integrate AI Engine into your existing workflows.</p><h2>MCP</h2><p><u>How to Use</u></p><ul><li>- <b>Claude Desktop App:</b> Use the <code>mcp.js</code> relay. Check <code>/labs/mcp.md</code> for setup instructions.</li><li>- <b>OpenAI/ChatGPT:</b> Limited to Deep Research mode with only <code>search</code> and <code>fetch</code> tools (requires Tuned Core enabled).</li><li>- <b>Claude.ai:</b> Currently not supported.</li></ul><p><u>Available Tools</u></p><ul><li>- <b>Full access (Claude Desktop):</b> WordPress management, plugin/theme development, SEO Engine, Code Engine snippets</li><li>- <b>Limited access (OpenAI):</b> Only search and fetch WordPress posts/pages</li></ul><p><u>For Developers</u></p><p>Extend functionality using <code>mwai_mcp_tools</code> and <code>mwai_mcp_callback</code> filters. See <code>dev-notes.md</code> for details.</p><p><b>Note:</b> This makes WordPress an MCP server. For connecting TO external MCP servers, use the Orchestration module.</p>","ai-engine"),KNOWLEDGE_INFO:pe('Embeddings are textual data converted into vectors for similarity search. You can manage embeddings in the Knowledge tab, where you can switch from EDIT to AI SEARCH mode to query your knowledge base.<br/><br/>Embeddings are synchronized with vector databases like <a target="_blank" href="https://www.pinecone.io/">Pinecone</a> or Qdrant. You can create, edit, and search embeddings, then use Sync to process your posts and create/update embeddings as needed.<br/><br/>Both chatbots and AI Forms can use embeddings to enrich their answers with relevant context from your knowledge base.<br/><br/><b>If you want to discuss embeddings with other users, visit the <a href="https://discord.gg/bHDGh38" target="_blank">Meow Apps Discord Server</a>.</b>',"ai-engine"),ORCHESTRATION_INFO:pe("MCP servers extend AI capabilities by providing tools and functions that AI models can call during conversations. Configure external MCP servers here to give your chatbots access to specialized tools like web browsing, file system access, database queries, or custom business logic.<br/><br/>Each server requires a secure HTTPS URL implementing the MCP protocol and may require authentication via bearer token. Once configured, the tools from these servers become available to AI models through function calling.<br/><br/><b>Note:</b> This is for connecting TO external MCP servers. To make your WordPress accessible AS an MCP server for AI agents like Claude, use the MCP option under Remote Access.","ai-engine")},Ee.CHATBOT={CHATBOT_BUILDER:pe("Chatbot Builder","ai-engine"),RESET_PARAMS:pe("Reset Parameters","ai-engine")},Ee.STATISTICS={ABSOLUTE_HELP:pe("Using Absolute, Day represents <i>today</i>. Otherwise, the <i>past 24 hours</i>. Same logic applies to the other timeframes.","ai-engine"),NO_CREDITS_MESSAGE:pe("Message for No Credits","ai-engine"),FULL_ACCESS_USERS:pe("Full-Access Users","ai-engine"),ENABLE_LIMITS:pe("Enable Limits","ai-engine")},Ee.CONTENT_GENERATOR={INTRO:pe("Generate high-quality articles with AI assistance. Create comprehensive content with customizable templates, writing styles, and automatic SEO optimization. Perfect for blogs, documentation, and marketing materials.","ai-engine"),TITLE_MISSING:pe("Title is missing!","ai-engine"),SECTIONS_MISSING:pe("Sections are missing!","ai-engine"),SINGLE_GENERATE:pe("Single Generate","ai-engine"),BULK_GENERATE:pe("Bulk Generate","ai-engine"),CONTENT_PARAMS:pe("Content Params","ai-engine"),POST_PARAMS:pe("Post Params","ai-engine"),CONTENT_PARAMS_INTRO:pe("Input fields are displayed for certain placeholders used in prompts, such as {LANGUAGE} or {WRITING_TONE}","ai-engine"),CUSTOM_LANGUAGE:pe("Custom Language","ai-engine"),WRITING_STYLE:pe("Writing Style","ai-engine"),WRITING_TONE:pe("Writing Tone","ai-engine"),CUSTOM_LANGUAGE_HELP:pe('AI supports all languages with varying quality. <a href="https://meowapps.com/ai-engine/faq/#languages" target="_blank">Learn more</a>.',"ai-engine"),MODEL_HELP:pe("It is recommended to use Turbo or GPT-4 to write texts.","ai-engine"),PROMPTS_INTRO:pe("Prompts represent the exact request sent to the AI. The variables between curly braces will be replaced by the content of the corresponding field. Prompts are saved in your templates.","ai-engine"),PROMPT_TITLE:pe("Prompt for <b>Title</b>","ai-engine"),PROMPT_SECTIONS:pe("Prompt for <b>Sections</b>","ai-engine"),PROMPT_CONTENT:pe("Prompt for <b>Content</b>","ai-engine"),PROMPT_EXCERPT:pe("Prompt for <b>Excerpt</b>","ai-engine"),POST_CREATED:pe("Post Created","ai-engine"),POST_CREATED_AS_DRAFT:pe("The post was created as a draft.","ai-engine"),CONTENT_HELP:pe('You can modify the content before using "Create Post". Markdown is supported, and will be converted to HTML when the post is created.',"ai-engine"),SECTIONS_HELP:pe('Add, rewrite, remove, or reorganize those sections as you wish before (re)clicking on "Generate Content". Markdown format is recommended.',"ai-engine"),GENERATE_EXCERPT:pe("Generate Excerpt","ai-engine"),GENERATE_CONTENT:pe("Generate Content","ai-engine"),GENERATE_SECTIONS:pe("Generate Sections","ai-engine"),PARAGRAPHS_PER_SECTION:pe("# of Paragraphs per Section","ai-engine"),NUMBER_OF_SECTIONS:pe("# of Sections","ai-engine"),ADVICE:pe("Advice","ai-engine"),SECTIONS:pe("Sections","ai-engine"),USE_MAX_TOKENS:pe("Use Max Tokens","ai-engine"),TOPICS_HELP:pe("Write or paste your topics below. Each line will be used as a topic. The <b>Context</b> on the left will be applied to all topics. The same <b>Params</b> and <b>Prompts</b> will be used as with the <b>Single Generate</b>, so make sure you get satisfying results with it first. This <b>takes time</b>, so relax and enjoy some coffee ☕️ and tea 🍵 :)","ai-engine"),GENERATED_POSTS:pe("Generated Posts","ai-engine"),USE_TOPICS_AS_TITLES:pe("Use Topics as Titles","ai-engine"),NOTHING_YET:pe("Nothing yet.","ai-engine"),BULK_ERROR_CONFIRM:pe("An error was caught ({MESSAGE}). Should we continue?","ai-engine"),GENERATE_ALL:pe("Generate All","ai-engine"),EDIT_POST:pe("Edit Post","ai-engine"),CREATE_POST:pe("Create Post","ai-engine"),TITLE_TOO_SHORT:pe("The title is too short. It should be at least 3 words.","ai-engine"),TITLE_TOO_SHORT_2:pe("The title is too short.  It should be at least 40 characters.","ai-engine"),TITLE_TOO_LONG:pe("The title is too long. It should be less than 8 words.","ai-engine"),TITLE_TOO_LONG_2:pe("The title is too long. It should be less than 70 characters.","ai-engine")},Ee.TEMPLATES={TEMPLATE:pe("Template","ai-engine"),TEMPLATES:pe("Templates","ai-engine"),DELETE_CONFIRM:pe("Are you sure you want to delete this template?","ai-engine"),DELETE_ALL_CONFIRM:pe("Are you sure you want to delete all the templates?","ai-engine"),NEW_TEMPLATE_NAME:pe("New Template","ai-engine"),EDIT:pe("EDIT","ai-engine")},Ee.PLAYGROUND={INTRO:pe("Welcome to the AI Playground! Here, you can play with different AI models and ask the UI to perform various tasks for you. You can ask it to write, rewrite, or translate an article, categorize words or elements into groups, write an email, etc. <b>Let me know if there are any new features you would like to see!</b> Have fun 🥳","ai-engine"),PROMPT:pe("Query / Prompt","ai-engine"),REPLY:pe("Reply","ai-engine")},Ee.ALERTS={FINETUNING_STARTED:pe("Fine-tuning started! Check its progress in the Models section. Depending on your dataset size, it may take a while (from a few minutes to days).","ai-engine"),RESET_BUILDER:pe("This will delete all the rows in the builder. Are you sure?","ai-engine"),DELETE_FINETUNE:pe("You are going to delete this fine-tune. Are you sure?\n\nPlease note that it will take a while before it is actually deleted. This might be a temporary issue of OpenAI.","ai-engine"),FINETUNE_ALREADY_DELETED:pe("This fine-tune was already deleted. It will be removed from the list.","ai-engine"),CHECK_CONSOLE:pe("Error! Check your console for more details.","ai-engine"),DATASET_UPLOADED:pe("Uploaded successfully! You can now train a model based on this dataset.","ai-engine"),ONLY_SUPPORTS_FILES:pe("This only supports JSON, JSONL, and CSV files. Check the Instructions section below.","ai-engine"),EMPTY_LINES_DATASET:pe("Some lines were empty. Make sure the CSV has a header row and that the columns are named 'prompt' and 'completion'. For debugging, an empty line was logged to the console.","ai-engine"),EMPTY_LINES_EMBEDDINGS:pe("Some lines were empty. Make sure the CSV has a header row and that the columns are named 'title' and 'content'. For debugging, an empty line was logged to the console.","ai-engine"),ARE_YOU_SURE:pe("Are you sure?","ai-engine")},Ee.FINETUNING={MODELS_INTRO:pe("The AI models you have fine-tuned. To create more, visit <b>Files</b>.","ai-engine"),LEGACY_MODELS_INTRO:pe('The AI models you have fine-tuned. <b>Do not use legacy fine-tuning anymore (based on models prior to GPT 3.5). Their deprecation has been <a href="https://platform.openai.com/docs/guides/legacy-fine-tuning" target="_blank">announced by OpenAI</a> for January 4th, 2024.</b><br />',"ai-engine"),FILES_INTRO:pe("The files you have uploaded to OpenAI. To create a new dataset file, switch from <b>Model & Files</b> to <b>Dataset Editor</b>. To train a new model, click on the <i>magic wand</i>.","ai-engine"),MODEL_FINETUNE:pe("Model Finetune","ai-engine"),MODELS_FILES:pe("Models & Files","ai-engine"),DATASET_EDITOR:pe("Dataset Editor","ai-engine"),EDITOR:pe("Editor","ai-engine"),GENERATOR:pe("Generator","ai-engine"),HUGE_DATASET_WARNING:pe("Caution: The data is too large to be saved in your browser's local storage.","ai-engine"),NO_FINETUNES_YET:pe("No fine-tunes found. Refresh the list, or create a new one (via a dataset).","ai-engine"),CLEAN_MODELS_LIST:pe("Clean Models List","ai-engine"),DELETED_FINETUNE_ISSUE:pe("For some reason, OpenAI still return the models even after you deleted them. Don't worry, AI Engine will do the cleanup for you! You can force the cleanup by using this button. It takes a bit of time depending on the total of models you have.","ai-engine")},Ee.EMBEDDINGS={EDIT:pe("EDIT","ai-engine"),AI_SEARCH:pe("AI SEARCH","ai-engine"),SYNC_POSTS:pe("Sync Posts","ai-engine"),AUTO_SYNC_POSTS:pe("Auto-Sync Posts","ai-engine"),AUTO_SYNC_POSTS_DESCRIPTION:pe("Embeddings will be created, updated or removed based on the activity related to your posts.","ai-engine"),REWRITE_CONTENT:pe("Rewrite Content","ai-engine"),REWRITE_CONTENT_DESCRIPTION:pe("Shorten and improve the content for your embedding using the default model.","ai-engine"),FORCE_RECREATE:pe("Force Recreate","ai-engine"),FORCE_RECREATE_DESCRIPTION:pe("Force recreation of existing embeddings even when content, model, and dimensions haven't changed. Note: New posts without embeddings will always be synced regardless of this setting.","ai-engine"),DELETE_ALL_EMBEDDINGS:pe("Delete All Embeddings","ai-engine"),DELETE_ALL_EMBEDDINGS_CONFIRM:pe("Are you sure you want to delete all the embeddings in this environment?","ai-engine"),REWRITE_PROMPT_DESCRIPTION:pe("Prompt for the rewrite. Supports {CONTENT}, {TITLE}, {URL}, {EXCERPT}, {LANGUAGE}, {ID}.","ai-engine"),SYNC_ALL:pe("Sync All","ai-engine"),SYNC_ONE:pe("Sync One","ai-engine"),ADD_INDEX:pe("Add Index","ai-engine"),ADD_INDEX_DESCRIPTION:pe("An index is like a database, and contains embeddings. You can have many indexes and switch between them. The indexes are hosted on Pinecone.","ai-engine"),NO_NAMESPACE_SUPPORT:pe("Note: This server does not support namespaces.","ai-engine")},Ee.ERROR={UPDATING_OPTIONS:pe("An error occurred while updating the options."),GETTING_OPTIONS:pe("An error occurred while getting the options."),CHECK_YOUR_CONSOLE:pe('For more information, check <a target="_blank" href="https://meowapps.com/tutorial-network-activity-dev-tools/">your console</a>. You might also want to check your <a target="_blank" href="https://meowapps.com/tutorial-php-error-logs/">PHP Error Logs</a>.',"ai-engine")};const ge=Ee;function he(){return he=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},he.apply(this,arguments)}const{useMemo:Re,useState:ye,useEffect:ve,useRef:fe}=wp.element,be=async(e,t)=>{try{const a=await(0,y.IU)(e,t);if(!a||a.error){const e=(null==a?void 0:a.message)||(null==a?void 0:a.error)||"Request failed";if("rest_cookie_invalid_nonce"===(null==a?void 0:a.code)||"rest_forbidden"===(null==a?void 0:a.code))throw new Error("Your session has expired. Please refresh the page to continue using AI Engine.");throw new Error(e)}return a&&a.new_token&&(x(a.new_token),console.log("[MWAI] Token refreshed!")),a}catch(e){if(e instanceof Error)throw e;throw new Error(e.message||e.toString()||"Unknown error occurred")}},we={title:"",content:"",refId:null,type:"manual",behavior:"context"},_e=({options:e})=>{const{ai_envs:t}=e,a=t.find((e=>e.apikey&&e.apikey.length>0)),n=!(null!=e&&e.module_embeddings)||(null==e?void 0:e.embeddings_envs)&&(null==e?void 0:e.embeddings_envs.length)>0;return React.createElement(React.Fragment,null,!a&&React.createElement(ce.X,{variant:"danger",style:{marginTop:0,marginBottom:25}},(0,y.FE)(ge.SETTINGS.AI_ENV_SETUP)),!n&&React.createElement(ce.X,{variant:"danger",style:{marginTop:0,marginBottom:25}},(0,y.FE)(ge.SETTINGS.PINECONE_SETUP)))};const Ce=(e,t,a=!1)=>{const[n,l]=ye(null==e?void 0:e.ai_default_model),r=fe(new Set),o=t||(null==e?void 0:e.ai_default_env),i=(null==e?void 0:e.ai_envs)??[],c=Re((()=>{if(a&&null!=e&&e.ai_envs){const e={fake:!0,finetunes:[],legacy_finetunes:[],legacy_finetunes_deleted:[],finetunes_deleted:[],deployments:[]};return i.forEach((t=>{t.finetunes&&e.finetunes.push(...t.finetunes),t.legacy_finetunes&&e.legacy_finetunes.push(...t.legacy_finetunes),t.legacy_finetunes_deleted&&e.legacy_finetunes_deleted.push(...t.legacy_finetunes_deleted),t.finetunes_deleted&&e.finetunes_deleted.push(...t.finetunes_deleted),t.deployments&&e.deployments.push(...t.deployments)})),e}return null}),[i,a]),s=Re((()=>{var t;if(a)return c;if(!o)return console.warn("useModels: Environment ID is null. Please provide a valid envId."),null;const n=null==e||null===(t=e.ai_envs)||void 0===t?void 0:t.find((e=>e.id===o));return n||(console.warn(`useModels: Environment with ID ${o} could not be resolved.`,{envs:i,envId:o}),null)}),[i,o,a,c]),d=Re((()=>{let e=(null==s?void 0:s.finetunes_deleted)||[];return Array.isArray(null==s?void 0:s.legacy_finetunes_deleted)&&(e=[...e,...s.legacy_finetunes_deleted]),e}),[s]),m=e=>({background:{deprecated:"var(--neko-red)",tuned:"var(--neko-green)",preview:"var(--neko-orange)",experimental:"var(--neko-red)"}[e],color:"white",padding:"3px 4px",margin:"1px 0px 0px 3px",borderRadius:4,fontSize:9,lineHeight:"100%"}),u={deprecated:"DEPRECATED",tuned:"TUNED",preview:"PREVIEW",experimental:"EXPERIMENTAL"},p=(e,t)=>{var a;const n=(null===(a=e.tags)||void 0===a?void 0:a.find((e=>["deprecated","preview","experimental"].includes(e))))||(t?"tuned":"");return React.createElement(React.Fragment,null,e.name??e.suffix??e.model,n&&React.createElement("small",{style:m(n)},u[n]))},E=Re((()=>{let t=[];if(!0===(null==s?void 0:s.fake))for(const a of e.ai_engines)Array.isArray(a.models)&&(t=[...t,...a.models]);else if("azure"===(null==s?void 0:s.type)){const a=e.ai_engines.find((e=>"openai"===e.type)),n=(null==a?void 0:a.models)??[];t=(null==n?void 0:n.filter((e=>{var t;return null===(t=s.deployments)||void 0===t?void 0:t.find((t=>t.model===e.model))})))??[]}else if("huggingface"===(null==s?void 0:s.type)){var a;t=(null==s||null===(a=s.customModels)||void 0===a?void 0:a.map((e=>{const t=e.tags?[...new Set([...e.tags,"core","chat"])]:["core","chat"],a=t.includes("image")?"text-to-image":"completion";return{model:e.name,name:e.name,features:a,tags:t,options:[]}})))??[]}else{const a=e.ai_engines.find((e=>e.type===(null==s?void 0:s.type)));t=(null==a?void 0:a.models)??[]}let n=(null==s?void 0:s.finetunes)??[];return Array.isArray(null==s?void 0:s.legacy_finetunes)&&(n=[...n,...s.legacy_finetunes]),n=n.filter((e=>"succeeded"===e.status&&e.model)),t=t.map((e=>({...e,name:p(e),rawName:e.name}))),n.length&&(t=[...t,...n.map((e=>{const t=e.model.split(":")[0];return{model:e.model,name:p(e,!0),rawName:e.suffix,suffix:e.suffix,features:["completion"],family:t,description:"finetuned",finetuned:!0,tags:["chat","finetune"]}}))]),t}),[e,s]),g=Re((()=>E.filter((e=>!d.includes(e.model)))),[E,d]),h=Re((()=>E.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("core")}))),[E]),R=Re((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("image")}))),[g]),y=Re((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("embedding")}))),[g]),v=Re((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("vision")}))),[g]),f=Re((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("chat")}))),[g]),b=Re((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("audio")}))),[g]),w=Re((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("json")}))),[g]),_=Re((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("realtime")}))),[g]),C=t=>{if(!t)return null;let a=E.find((e=>e.model===t));return a||(t.startsWith("gpt-3.5-turbo-")||t.startsWith("gpt-35-turbo")?t="gpt-3.5-turbo":t.startsWith("gpt-4o-mini")?t="gpt-4o-mini":t.startsWith("gpt-4o")?t="gpt-4o":t.startsWith("gpt-4")?t="gpt-4":t.startsWith("o1-preview")?t="o1-preview":t.startsWith("o1-mini")?t="o1-mini":t.startsWith("o1-")?t="o1":t.startsWith("claude-opus-4")?t="claude-opus-4-20250514":t.startsWith("claude-sonnet-4")?t="claude-sonnet-4-20250514":t.startsWith("claude-3-7-sonnet")?t="claude-3-7-sonnet-latest":t.startsWith("claude-3-5-sonnet-2024")?t="claude-3-5-sonnet-20241022"===t?"claude-3-5-sonnet-20241022":"claude-3-5-sonnet-20240620"===t?"claude-3-5-sonnet-20240620":"claude-3-5-sonnet-latest":t.startsWith("claude-3-5-sonnet")||t.startsWith("claude-3.5-sonnet")?t="claude-3-5-sonnet-latest":t.startsWith("claude-3-opus-2024")||t.startsWith("claude-3-opus")?t="claude-3-opus-latest":t.startsWith("claude-3-sonnet")?t="claude-3-sonnet-20240229":t.startsWith("claude-3-5-haiku")?t="claude-3-5-haiku-20241022":t.startsWith("claude-3-haiku")&&(t="claude-3-haiku-20240307"),a=E.find((e=>e.model===t)),a||r.current.has(t)||(console.warn(`Model ${t} not found.`,{allModels:E,options:e}),r.current.add(t)),a)},T=e=>{const t=C(e),a=h.find((e=>(null==e?void 0:e.family)===(null==t?void 0:t.family)));return a||null},O=(e,t="1024x1024")=>{const a=T(e);if("image"===(null==a?void 0:a.type)&&null!=a&&a.resolutions){const e=a.resolutions.find((e=>e.name===t));return(null==e?void 0:e.price)||null}return(null==a?void 0:a.price)||null};return{allModels:E,model:n,models:g,completionModels:f,imageModels:R,visionModels:v,coreModels:h,embeddingsModels:y,audioModels:b,jsonModels:w,realtimeModels:_,setModel:l,isFineTunedModel:e=>{const t=C(e);return(null==t?void 0:t.finetuned)||!1},getModelName:(e,t=!1)=>{const a=C(e);return a?t&&a?a.rawName:(null==a?void 0:a.name)||(null==a?void 0:a.model)||e:e},getFamilyName:e=>{const t=C(e);return(null==t?void 0:t.family)||null},getPrice:O,getModel:C,calculatePrice:(e,t,a,n="1024x1024")=>{const l=T(e),r=O(e,n);let o=r,i=r;return"object"==typeof r&&null!==r&&(o=r.in,i=r.out),o&&i?o*t*l.unit+i*a*l.unit:0}}},Te=async e=>{const t=await be(`${w}/vectors/remote_list`,{nonce:P(),method:"POST",json:e});return t?{total:t.total,vectors:t.vectors}:{total:0,vectors:[]}},Oe=async e=>{const t={...e,offset:(e.page-1)*e.limit},a=await be(`${w}/discussions/list`,{nonce:P(),method:"POST",json:t});if(a&&!1===a.success)throw new Error(a.message||"Failed to retrieve discussions");return a?{total:a.total,chats:a.chats}:{total:0,chats:[]}},Ne=async e=>{var t,a,n;const l=null!==(null==e||null===(t=e.filters)||void 0===t?void 0:t.search);if(""===(null==e||null===(a=e.filters)||void 0===a?void 0:a.search))return[];if(!e.filters.envId)return{total:0,vectors:[]};const r=await be(`${w}/vectors/list`,{nonce:P(),method:"POST",json:e});if(l&&null!=r&&null!==(n=r.vectors)&&void 0!==n&&n.length){const t=r.vectors.sort(((t,a)=>{var n;return"asc"===(null==e||null===(n=e.sort)||void 0===n?void 0:n.by)?t.score-a.score:a.score-t.score}));r.vectors=t}return r?{total:r.total,vectors:r.vectors}:{total:0,vectors:[]}};function Ie(e){let t=new Date(e);t=new Date(t.getTime()-60*t.getTimezoneOffset()*1e3);const a=t.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"}),n=t.toLocaleTimeString("ja-JP",{hour:"2-digit",minute:"2-digit",second:"2-digit"});return React.createElement(React.Fragment,null,a,React.createElement("br",null),React.createElement("small",null,n))}function Me(e,t){const a=t?(()=>{let e=t.substring(0,16);return e.length<t.length?(e.endsWith(".")&&(e=e.slice(0,-1)),e+"~"):e})():"";return React.createElement("div",null,!e&&React.createElement(React.Fragment,null,ge.COMMON.GUEST),e&&React.createElement(React.Fragment,null,React.createElement("a",{target:"_blank",href:`/wp-admin/user-edit.php?user_id=${e}`,rel:"noreferrer"},ge.COMMON.USER," #",e)),React.createElement("br",null),React.createElement("small",{style:{color:"var(--neko-gray)"}},a))}const Se=(e=6)=>{const t="abcdefghijklmnopqrstuvwxyz0123456789";let a="";for(let n=0;n<e;n++)a+=t[Math.floor(36*Math.random())];return a},ke=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",he({width:e,height:e},n,{style:l,alt:"OpenAI",src:_+"/images/chat-openai.svg"}))},Ae=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",he({width:e,height:e},n,{style:l,alt:"Anthropic",src:_+"/images/chat-anthropic.svg"}))},xe=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",he({width:e,height:e},n,{style:l,alt:"Google",src:_+"/images/chat-google.svg"}))},Pe=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",he({width:e,height:e},n,{style:l,alt:"JavaScript",src:_+"/images/code-js.svg"}))},De=({size:e=14,disabled:t=!1,style:a,...n})=>{const l={...{position:"relative",top:2,borderRadius:2,filter:t?"grayscale(100%)":"none"},...a};return React.createElement("img",he({width:e,height:e},n,{style:l,alt:"PHP",src:_+"/images/code-php.svg"}))},Le=(e=null)=>{const{getBlocks:t,getSelectedBlockClientId:a}=wp.data.select("core/block-editor"),{getEditedPostAttribute:n}=wp.data.select("core/editor"),l=t(),r=n("title"),o=a();let i=r+"\n\n";return l.forEach(((t,a)=>{e&&t.clientId===o?i+=e+"\n\n":i+=(t.attributes.content||"")+"\n\n"})),i.trim()},{useState:Fe,useEffect:Be,useMemo:Ue}=wp.element,He=React.createElement("g",null,React.createElement("g",null,React.createElement("path",{d:"m391 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#39326c"}),React.createElement("path",{d:"m331 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#39326c"}),React.createElement("path",{d:"m271 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#39326c"}),React.createElement("path",{d:"m211 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#5f55af"}),React.createElement("path",{d:"m151 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#5f55af"}),React.createElement("path",{d:"m91 81h30v-66c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15z",fill:"#5f55af"}),React.createElement("path",{d:"m406 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z",fill:"#39326c"}),React.createElement("path",{d:"m346 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z",fill:"#39326c"}),React.createElement("path",{d:"m286 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z",fill:"#39326c"}),React.createElement("g",{fill:"#5f55af"},React.createElement("path",{d:"m226 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m166 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m106 512c8.284 0 15-6.716 15-15v-66h-30v66c0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 121h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 181h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 241h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 301h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 361h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"}),React.createElement("path",{d:"m15 421h66v-30h-66c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15z"})),React.createElement("path",{d:"m431 91v30h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15z",fill:"#39326c"}),React.createElement("path",{d:"m431 181h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"}),React.createElement("path",{d:"m431 241h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"}),React.createElement("path",{d:"m431 301h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"}),React.createElement("path",{d:"m431 361h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"}),React.createElement("path",{d:"m431 421h66c8.284 0 15-6.716 15-15 0-8.284-6.716-15-15-15h-66z",fill:"#39326c"})),React.createElement("g",null,React.createElement("path",{d:"m446 51h-380c-8.284 0-15 6.716-15 15v380c0 8.284 6.716 15 15 15h380c8.284 0 15-6.716 15-15v-380c0-8.284-6.716-15-15-15z",fill:"#aed0ff"}),React.createElement("g",null,React.createElement("path",{d:"m461 446v-380c0-8.284-6.716-15-15-15h-190v410h190c8.284 0 15-6.716 15-15z",fill:"#7c84e8"})),React.createElement("path",{d:"m386 111h-260c-8.284 0-15 6.716-15 15v260c0 8.284 6.716 15 15 15h260c8.284 0 15-6.716 15-15v-260c0-8.284-6.716-15-15-15z",fill:"#5f55af"}),React.createElement("g",null,React.createElement("path",{d:"m401 386v-260c0-8.284-6.716-15-15-15h-130v290h130c8.284 0 15-6.716 15-15z",fill:"#39326c"}))),React.createElement("g",null,React.createElement("path",{d:"m247.626 192.389c-.052-.138-.106-.274-.162-.411-2.744-6.671-9.175-10.978-16.387-10.978-.006 0-.012 0-.018 0-7.219.007-13.65 4.329-16.383 11.01-.046.113-.091.227-.134.341l-45.06 118.31c-2.949 7.742.937 16.408 8.679 19.356 7.742 2.95 16.408-.937 19.356-8.679l7.543-19.804h51.691l7.458 19.762c2.267 6.007 7.974 9.708 14.036 9.708 1.76 0 3.55-.312 5.294-.97 7.75-2.925 11.663-11.579 8.737-19.33zm-31.14 79.146 14.538-38.171 14.406 38.171z",fill:"#f9f9f9"}),React.createElement("g",{fill:"#e2dff4"},React.createElement("path",{d:"m264.209 321.296c2.267 6.007 7.974 9.708 14.036 9.708 1.76 0 3.55-.312 5.294-.97 7.75-2.925 11.663-11.579 8.737-19.33l-36.276-96.126v86.956h.751z"}),React.createElement("path",{d:"m328.5 181c-8.284 0-15 6.716-15 15v120c0 8.284 6.716 15 15 15s15-6.716 15-15v-120c0-8.284-6.716-15-15-15z"})))),je=React.createElement("g",null,React.createElement("path",{d:"m213.46 341.461-139.26 156.08c-16.17 18.48-44.53 19.33-61.8 2.06-17.32-17.32-16.37-45.67 2.06-61.8l156.08-139.26s13.46-2.54 29.46 13.46 13.46 29.46 13.46 29.46z",fill:"#0052be"}),React.createElement("path",{d:"m213.46 341.461-139.26 156.08c-16.17 18.48-44.53 19.33-61.8 2.06l187.6-187.6c16 16 13.46 29.46 13.46 29.46z",fill:"#00429b"}),React.createElement("path",{d:"m304 240.001-90.54 101.46c-14.997-14.997-27.922-27.922-42.92-42.92l101.46-90.54z",fill:"#00429b"}),React.createElement("path",{d:"m304 240.001-90.54 101.46-21.46-21.46 96-96z",fill:"#00337a"}),React.createElement("path",{d:"m400 279.001h-64.4l-42.47 57.87c-7.88 10.735-24.824 6.606-26.91-6.52l-11.56-73.01-73.01-11.56c-13.139-2.087-17.244-19.042-6.52-26.91l57.87-42.47v-64.4c0-12.176 13.797-19.289 23.72-12.21l50.15 35.83 70.92-19.9c11.25-3.168 21.656 7.245 18.49 18.49l-19.9 70.92 35.83 50.15c7.071 9.913-.02 23.72-12.21 23.72z",fill:"#ffdd54"}),React.createElement("path",{d:"m412.21 255.281c7.071 9.913-.02 23.72-12.21 23.72h-64.4l-42.47 57.87c-7.875 10.728-24.823 6.616-26.91-6.52l-11.56-73.01 137.79-137.79c3.83 3.84 5.3 9.44 3.83 14.66l-19.9 70.92z",fill:"#ffb454"}),React.createElement("path",{d:"m512 39.001c0 8.28-6.72 15-15 15h-9v9c0 8.28-6.72 15-15 15s-15-6.72-15-15v-9h-9c-8.28 0-15-6.72-15-15s6.72-15 15-15h9v-9c0-8.28 6.72-15 15-15s15 6.72 15 15v9h9c8.28 0 15 6.719 15 15z",fill:"#bee75e"}),React.createElement("path",{d:"m512 39.001c0 8.28-6.72 15-15 15h-9v9c0 8.28-6.72 15-15 15s-15-6.72-15-15v-9l30-30h9c8.28 0 15 6.719 15 15z",fill:"#00cb75"}),React.createElement("path",{d:"m336 41.001h-9v-9c0-8.284-6.716-15-15-15s-15 6.716-15 15v9h-9c-8.284 0-15 6.716-15 15s6.716 15 15 15h9v9c0 8.284 6.716 15 15 15s15-6.716 15-15v-9h9c8.284 0 15-6.716 15-15s-6.716-15-15-15z",fill:"#f6f9f9"}),React.createElement("path",{d:"m441 224.001c0 8.284 6.716 15 15 15s15-6.716 15-15v-9h9c8.284 0 15-6.716 15-15s-6.716-15-15-15h-9v-9c0-8.284-6.716-15-15-15s-15 6.716-15 15v9h-9c-8.284 0-15 6.716-15 15s6.716 15 15 15h9z",fill:"#e2dff4"}),React.createElement("path",{d:"m497 329.001h-9v-9c0-8.284-6.716-15-15-15s-15 6.716-15 15v9h-9c-8.284 0-15 6.716-15 15s6.716 15 15 15h9v9c0 8.284 6.716 15 15 15s15-6.716 15-15v-9h9c8.284 0 15-6.716 15-15s-6.716-15-15-15z",fill:"#ff4a4a"}),React.createElement("path",{d:"m192 24.001h-9v-9c0-8.284-6.716-15-15-15s-15 6.716-15 15v9h-9c-8.284 0-15 6.716-15 15s6.716 15 15 15h9v9c0 8.284 6.716 15 15 15s15-6.716 15-15v-9h9c8.284 0 15-6.716 15-15s-6.716-15-15-15z",fill:"#ff8659"}),React.createElement("path",{d:"m159.442 122.977-56-32c-7.191-4.109-16.355-1.611-20.466 5.581-4.11 7.193-1.611 16.355 5.581 20.466l56 32c7.16 4.093 16.337 1.644 20.466-5.581 4.111-7.193 1.612-16.355-5.581-20.466z",fill:"#f6f9f9"}),React.createElement("path",{d:"m118.14 169.117-64 8c-8.221 1.027-14.052 8.524-13.023 16.744 1.027 8.218 8.523 14.054 16.744 13.023l64-8c8.221-1.027 14.052-8.524 13.023-16.744-1.028-8.22-8.527-14.062-16.744-13.023z",fill:"#acceff"}),React.createElement("path",{d:"m389.023 352.558c-4.111-7.193-13.274-9.693-20.466-5.581-7.192 4.11-9.691 13.272-5.581 20.466l32 56c2.769 4.845 7.83 7.561 13.037 7.561 11.319 0 18.784-12.341 13.01-22.445z",fill:"#e2dff4"}),React.createElement("path",{d:"m329.86 377.117c-8.222-1.031-15.717 4.804-16.744 13.023l-8 64c-1.117 8.925 5.834 16.862 14.902 16.862 7.455 0 13.917-5.553 14.865-13.142l8-64c1.029-8.219-4.802-15.716-13.023-16.743z",fill:"#6ba7ff"})),Ge=({icon:e="ai",size:t=20,style:a={}}={})=>{const n=Ue((()=>{switch(e){case"ai":default:return He;case"wand":return je}}),[e]);return React.createElement("svg",{style:{width:t,height:t,marginRight:5,...a},"enable-background":"new 0 0 512 512",height:"512",viewBox:"0 0 512 512",width:"512",xmlns:"http://www.w3.org/2000/svg"},n)},$e=({title:e=ge.COMMON.SETTINGS,options:t=I})=>{const a=null==t?void 0:t.module_playground,n=null==t?void 0:t.module_generator_content,l=null==t?void 0:t.module_generator_images;return React.createElement(p.n,{title:`AI Engine | ${e}`},React.createElement("div",{style:{display:"flex",justifyContent:"flex-end"}},n&&React.createElement(h.M,{className:"header",onClick:()=>location.href="edit.php?page=mwai_content_generator"},React.createElement(Ge,{icon:"wand",style:{marginRight:8}}),ge.COMMON.CONTENT),l&&React.createElement(h.M,{className:"header",icon:"",onClick:()=>location.href="edit.php?page=mwai_images_generator"},React.createElement(Ge,{icon:"wand",style:{marginRight:8}}),ge.COMMON.IMAGES),a&&React.createElement(h.M,{className:"header",icon:"",onClick:()=>location.href="tools.php?page=mwai_dashboard"},React.createElement(Ge,{icon:"wand",style:{marginRight:8}}),ge.COMMON.PLAYGROUND),React.createElement(h.M,{className:"header",icon:"tools",onClick:()=>location.href="admin.php?page=mwai_settings"})))},ze=((0,L.Ay)(h.M)`
`,L.Ay.div`
  display: flex;
  justify-content: unset;
  align-items: center;
  justify-content: space-between;
  padding: 0 0 2px 0;

  h2 {
    margin: 7px 0 0 0;
    padding: 0;
  }
`),We=L.Ay.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(30%, 1fr));
  grid-template-rows: repeat(auto-fit, minmax(30%, 1fr));
  grid-gap: 10px;
  margin-top: 20px;

  img, div {
    width: 100%;
    cursor: pointer;
  }
  .image-wrapper {
    position: relative;
  }
  .delete-icon {
    display: none;
    position: absolute;
    top: 5px;
    right: 5px;
    background: rgba(0,0,0,0.7);
    color: #fff;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    align-items: center;
    justify-content: center;
    font-size: 14px;
  }
  .image-wrapper:hover .delete-icon {
    display: flex;
  }
  .media-label {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,0.6);
    color: #fff;
    text-align: center;
    font-size: 12px;
    padding: 2px 0;
    text-decoration: underline;
    cursor: pointer;
  }
  .empty-image {
    width: 100%;
    padding-bottom: 100%;
    background-color: #f5f5f5;
  }
`;var qe=a(4809),Ve=a.n(qe),Ye=a(8922),Ke=a(3896),Xe=a(5900),Qe=a(7494),Je=a(8482),Ze=a(209),et=a(8668),tt=a(520),at=a(851),nt=a(6897);const lt=async(e,t={})=>{const a=P(),n={...t,nonce:a};try{const t=await(0,y.IU)(e,n);if(t&&t.new_token){if(t.token_expires_at){const e=new Date(1e3*t.token_expires_at);console.log(`[MWAI] 🔐 New token received - expires at ${e.toLocaleTimeString()} (in ${t.token_expires_in}s)`)}else console.log("[MWAI] 🔐 New token received");x(t.new_token)}return t}catch(a){if(a.message&&a.message.includes("nonce")){console.log("[MWAI] Nonce error detected, attempting to refresh...");const a=await(0,y.IU)(`${w}/start_session`,{method:"POST"});if(a&&a.restNonce)return x(a.restNonce),await(0,y.IU)(e,{...t,nonce:a.restNonce})}throw a}},rt=async()=>{const e=await lt(`${w}/helpers/post_types`);if(!e.success)throw new Error(e.message);return e.postTypes},ot=async(e=null,t=!1)=>{const a=await lt(`${w}/openai/finetunes/list_deleted?envId=${e}&legacy=${t}`);if(!a.success)throw new Error(a.message);return null==a?void 0:a.finetunes},it=async()=>{const e=await lt(`${w}/settings/themes`,{method:"GET"});return null==e?void 0:e.themes},ct=async e=>{const t=[];for(let a=0;a<e.length;a++){let n=e[a].themeId;if(t.includes(n)){let e=1;for(;t.includes(n+"-"+e);)e++;n=n+"-"+e}t.push(n),e[a].themeId=n}const a=await lt(`${w}/settings/themes`,{method:"POST",json:{themes:e}});return null==a?void 0:a.themes},st=async()=>{const e=await lt(`${w}/settings/chatbots`,{method:"GET"});if(!e.success)throw new Error(null==e?void 0:e.message);return null==e?void 0:e.chatbots},dt=async e=>{const t=await lt(`${w}/settings/chatbots`,{method:"POST",json:{chatbots:e}});if(!t.success)throw new Error(null==t?void 0:t.message);return null==t?void 0:t.chatbots},mt=async()=>{const e=await lt(`${w}/settings/options`,{method:"GET"});return null==e?void 0:e.options},ut=async()=>{try{return(await lt(`${w}/get_logs`,{method:"GET"})).data}catch(e){throw new Error(e.message)}},pt=async()=>{try{await lt(`${w}/clear_logs`)}catch(e){throw new Error(e.message)}},{useState:Et,useRef:gt}=wp.element,ht=({instructions:e,setMessages:t})=>{const[a,n]=Et("post"),[l,r]=Et(0),[i,c]=Et(!1),[s,d]=Et("Generate 30 questions and answers from this text. Questions use a neutral tone. Answers use the same tone as the text."),m=gt(),{isLoading:u,data:p}=(0,o.I)({queryKey:["postTypes"],queryFn:rt}),{isLoading:E,data:g}=(0,o.I)({queryKey:["postsCount-"+a],queryFn:()=>(async e=>{const t=await lt(`${w}/helpers/count_posts?postType=${e}`);return null!=t&&t.count?parseInt(null==t?void 0:t.count):null})(a)}),R=(0,nt.XS)({i18n:ge,onStop:()=>{c(),R.reset()}}),v=i||R.busy||E||u,f=async(t=0,n=void 0,l=void 0)=>{let o=s+"\n\nUse this format:\n\nQ: Question?\nA: Answer.\n\nQ: Question?\nA: Answer.\nText:\n\n{CONTENT}";const i=await(async(e,t=0,a=0)=>await lt(`${w}/helpers/post_content?postType=${e}&offset=${t}&postId=${a}`))(a,t,n||void 0);let c=null,d=null;const m=null==i?void 0:i.content,u=null==i?void 0:i.url,p=null==i?void 0:i.title;let E=0;if(i.success)if(m.length<64)console.log("Issue: Content is too short! Skipped.",{content:m});else{var g;o=o.replace("{CONTENT}",m),o=o.replace("{URL}",u),o=o.replace("{TITLE}",p);const e=await(0,y.IU)(`${w}/ai/completions`,{method:"POST",json:{scope:"admin-tools",session:M,message:o},signal:l,nonce:N});if(!e.success){var h;if(null!==(h=e.error)&&void 0!==h&&h.cancelledByUser)return null;throw console.error(e),new Error(e.message??"Unknown error, check your console logs.")}d=null==e?void 0:e.data,null!=e&&null!==(g=e.usage)&&void 0!==g&&g.total_tokens&&(E=e.usage.total_tokens,r((t=>t+e.usage.total_tokens)))}else alert(i.message),c=i.message;null!=l&&l.aborted&&b();const R=(t=>{if(!t)return[];const a=t.split("\n").filter((e=>""!==e.trim())),n=[];let l=[];for(let t=0;t<a.length;t++)a[t].startsWith("Q:")?(l.length&&(n.push({messages:[...l]}),l=[]),l.push({role:"system",content:e}),l.push({role:"user",content:a[t].slice(2).trim()})):a[t].startsWith("A:")&&(l.push({role:"assistant",content:a[t].slice(2).trim()}),n.push({messages:[...l]}),l=[]);return l.length&&n.push({messages:l}),n})(d),v={content:m,prompt:o,rawData:d,entries:R,error:c,tokens:E};return console.log("Result:",v),v},b=()=>{console.log("User aborted."),setBusy(!1),R.reset()};return React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",width:"100%"}},React.createElement(h.M,{disabled:v,onClick:async()=>{try{r(0);const e=prompt("Enter the ID of a post (leave blank to use the very first one).");if(null===e)return;c("singleGenerate"),m.current=new AbortController;const a=await f(0,e,m.current.signal);if(a.entries.length){confirm(`Got ${a.entries.length} entries! Do you want to add them to your data? If not, they will be displayed in your console.`)&&t((e=>[...e,...a.entries]))}else alert("No entries were generated. Check the console for more information.")}catch(e){console.error(e),alert(e.message)}finally{c(!1)}},isBusy:"singleGenerate"===i},ge.COMMON.SINGLE_GENERATE),React.createElement("span",{style:{color:"#d1e8f2",fontSize:"22px",padding:5}},"|"),React.createElement(h.M,{disabled:v,onClick:()=>(async()=>{r(0);const e=Array.from(Array(g).keys()),a=prompt("There are "+e.length+" entries. If you want to start from a certain entry offset, type it here. Otherwise, just press OK, and everything will be processed."),n=e.map((e=>async n=>{var l;if(console.log("Task "+e),a&&e<a)return{success:!0};const r=await f(e,null,n);return(null==r||null===(l=r.entries)||void 0===l?void 0:l.length)>0&&t((e=>[...e,...r.entries])),{success:!0}}));await R.start(n),c(!1),alert("All done!"),R.reset()})()},"Bulk Generate"),React.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",paddingLeft:10}},"Based on ",E&&"...",!E&&g),React.createElement(ae.u,{id:"postType",scrolldown:!0,disabled:v,name:"postType",style:{width:100,marginLeft:10},onChange:n,value:a},null==p?void 0:p.map((e=>React.createElement(ae.j,{key:e.type,value:e.type,label:e.name})))),React.createElement(at.j,{busy:R.busy,style:{marginLeft:10,flex:"auto"},value:R.value,max:R.max,onStopClick:R.stop}),React.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",paddingLeft:10}},"Tokens: ",l)),React.createElement("div",{style:{width:"100%"}},React.createElement(Ke.m,{id:"generatePrompt",name:"generatePrompt",rows:2,style:{marginTop:10,marginBottom:5},value:s,onBlur:d,disabled:v})),R.TasksErrorModal)},{useState:Rt,useMemo:yt,useRef:vt,useEffect:ft}=wp.element,bt=({createdOn:e,estimatedOn:t})=>{if(!e||!t)return null;const a=new Date;e=new Date(e),t=new Date(t);const n=e=>new Date(e).toLocaleString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"});return React.createElement("div",null,"Start: ",n(e),".",React.createElement("br",null),"Finish: ",n(t),".",React.createElement("br",null),"Time Left: ",React.createElement("b",null,((e,t)=>{const a=t-e,n=Math.floor(a/6e4),l=Math.floor(n/60);return l>0?`${l} hour${l>1?"s":""} and ${n%60} minute${n%60!=1?"s":""}`:`${n} minute${1!==n?"s":""}`})(a,t)),".",React.createElement("br",null),React.createElement("br",null),React.createElement("small",null,"Use Refresh Models to update the status."))},wt=[{accessor:"row",title:"#",width:"25px",verticalAlign:"top"},{accessor:"question",title:"Question",width:"50%",verticalAlign:"top"},{accessor:"answer",title:"Answer",width:"50%",verticalAlign:"top"},{accessor:"actions",title:"",width:"36px",align:"center"}],_t=[{accessor:"row",title:"#",width:"25px",verticalAlign:"top"},{accessor:"messages",title:"Messages",width:"100%",verticalAlign:"top"},{accessor:"actions",title:"",width:"68px",align:"top"}],Ct=[{accessor:"status",title:"Status",sortable:!0,width:"120px"},{accessor:"id",title:"ID",width:"120px"},{accessor:"filename",title:"File",width:"50%"},{accessor:"purpose",title:"Purpose",width:"50%"},{accessor:"filesize",title:"Size",width:"80px",sortable:!0},{accessor:"createdOn",title:"Date",sortable:!0,width:"120px"},{accessor:"actions",title:"",width:"200px"}],Tt=[{accessor:"status",title:"Status",sortable:!0,width:"120px"},{accessor:"id",title:"ID",width:"120px"},{accessor:"suffix",title:"Suffix",width:"20%"},{accessor:"model",title:"Model",width:"40%"},{accessor:"base_model",title:"Based On",width:"40%"},{accessor:"createdOn",title:"Date",sortable:!0,width:"120px"},{accessor:"actions",title:"",width:"40px"}],Ot=({status:e,includeText:t=!1})=>{const{colors:a}=(0,r.z)(),n=a.orange,l=a.green,o=a.red;let i=null;switch(e){case"pending":case"running":i=React.createElement(Ye.z,{title:e,icon:"replay",spinning:!0,width:24,color:n});break;case"succeeded":case"processed":i=React.createElement(Ye.z,{title:e,icon:"check-circle",width:24,color:l});break;case"failed":i=React.createElement(Ye.z,{title:e,icon:"close",width:24,color:o});break;case"cancelled":i=React.createElement(Ye.z,{title:e,icon:"close",width:24,color:n});break;default:i=React.createElement(Ye.z,{title:e,icon:"alert",width:24,color:n})}return t?React.createElement("div",{style:{display:"flex",alignItems:"center"}},i,React.createElement("span",{style:{textTransform:"uppercase",fontSize:9,marginLeft:3}},e)):i},Nt=({children:e,data:t,onChange:a=(()=>{})})=>{const[n,l]=Rt(!1),r=e=>{l(!1),e!==t&&a(e)},o=e=>{"Escape"===e.key&&r(t)};return n?React.createElement("div",{onKeyUp:o,style:{height:"100%",display:"flex",flexDirection:"column",width:"100%"}},React.createElement(Ke.m,{onBlurForce:!0,autoFocus:!0,fullHeight:!0,rows:3,style:{height:"100%",width:"100%"},onEnter:r,onBlur:r,value:t}),React.createElement(h.M,{onClick:r,fullWidth:!0,style:{marginTop:2,height:35}},"Save")):React.createElement("pre",{style:{width:"100%",height:"100%",whiteSpace:"break-spaces",margin:0,padding:0,fontSize:13,fontFamily:"inherit"},onClick:()=>l(!0)},e)},It=({options:e,updateOption:t,refreshOptions:a})=>{var n;const{colors:i}=(0,r.z)(),c=(0,l.jE)(),[s,d]=Rt(!1),[u,p]=Rt(),[R,v]=Rt(!1),[f,b]=Rt("finetunes"),[_,C]=Rt("current"),[T,O]=Rt("fine-tune"),[I,M]=Rt("meow"),[S,k]=Rt(!1),[A,x]=Rt(4),[P,D]=Rt(4),[L,F]=Rt(.1),[B,U]=Rt(.01),[H,j]=Rt(!1),[G,$]=Rt(null==e||null===(n=e.ai_envs)||void 0===n||null===(n=n[0])||void 0===n?void 0:n.id),z=yt((()=>(null==e?void 0:e.ai_envs)||[]),[e]),W=yt((()=>null==z?void 0:z.find((e=>e.id===G))),[G,z]),q=(null==W?void 0:W.finetunes_deleted)||[],V=(null==W?void 0:W.finetunes)||[],{isFetching:Y,error:K,data:X}=(0,o.I)({queryKey:["datasets-"+G+"-"+T],enabled:H,queryFn:()=>(async(e=null,t=null)=>{var a;let n=`${w}/openai/files/list?envId=${e}`;t&&(n+=`&purpose=${t}`);const l=await lt(n);if(!l.success)throw new Error(l.message);return null==l||null===(a=l.files)||void 0===a?void 0:a.data})(G,T)}),[Q,J]=Rt("gpt-4o-mini-2024-07-18"),Z=async(e,a)=>{const n=z.map((t=>t.id===G?{...t,[e]:a}:t));return t(n,"ai_envs")};ft((()=>{"files"!==f||H||j(!0)}),[f]),ft((()=>{K&&!s&&d(K)}),[K]);const ee=10,[te,se]=Rt(!0),[de,me]=Rt(1),[ue,pe]=Rt([]),[Ee,he]=Rt(!1),[Re,ye]=Rt("You are Chihiro, an AI Assistant. Your primary objective is to assist website visitors by directing them to the appropriate page or succinctly answering their questions with precision."),[ve,fe]=Rt(""),[be,we]=Rt(!1),[_e,Ce]=Rt([]),Te=yt((()=>ue.length),[ue]);ft((()=>{if(0===ue.length)return void we(!1);const e=ue.map(((e,t)=>{if(!e.messages||e.messages.length<3)return t+1;if("system"!==e.messages[0].role||"user"!==e.messages[1].role||"assistant"!==e.messages[2].role)return t+1;for(let a=3;a<e.messages.length;a++)if(e.messages[a].role===e.messages[a-1].role)return t+1;return null})).filter((e=>null!==e));Ce(e),we(0===e.length)}),[ue]);const Oe=({messages:e,currentRow:t,onUpdateDataRow:a,onDeleteDataRow:n})=>React.createElement(React.Fragment,null,e.map(((e,l)=>React.createElement("div",{key:l,style:{display:"flex"}},React.createElement(h.M,{rounded:!0,icon:"trash",onClick:()=>n(t,l+1)}),React.createElement("div",{style:{width:120,paddingLeft:5,paddingTop:0,paddingBottom:4,marginRight:10}},React.createElement(ae.u,{scrolldown:!0,name:"role",value:e.role,style:{width:120},onChange:n=>a(t,n,e.content,l+1)},React.createElement(ae.j,{value:"assistant",label:"Assistant"}),React.createElement(ae.j,{value:"user",label:"User"}),React.createElement(ae.j,{value:"system",label:"System"}))),React.createElement(Nt,{data:e.content,style:{flex:"auto"},onChange:n=>a(t,e.role,n,l+1)},e.content))))),Ne=async()=>{await c.invalidateQueries("datasets")},Ie=async()=>{v("finetunes"),V.length?await(async(e=null,t=!1)=>{const a=await lt(`${w}/openai/finetunes/list?envId=${e}&legacy=${t}`);if(!a.success)throw new Error(a.message);return null==a?void 0:a.finetunes})(G):await ot(G),await a(),v(!1)},Me=(e=!0)=>{e&&!confirm(ge.ALERTS.RESET_BUILDER)||(pe([]),Ae({instructions:Re,entries:[]}))};ft((()=>{if(!ue||0===ue.length){const e=localStorage.getItem("mwai_builder_data_v2");if(e){const t=JSON.parse(e);pe(t.entries),t.instructions&&ye(t.instructions)}}}),[]);const Se=e=>{let t=!1,a=!1;for(let n=0;n<ue.length;n++){const l=ue[n].messages;if(l&&l.length>0)if("system"===l[0].role){if(l[0].content!==e){if(!t){if(!confirm("The instructions in your data do not match the ones in your entries. Do you want to replace it for every entry?"))return;t=!0}const a=[...ue];a[n].messages[0].content=e,pe((()=>a))}}else{if(!a){if(!confirm("Some entries are missing the system role as the first message. Do you want to add it for every entry where it's missing?"))return;a=!0}const t=[...ue];t[n].messages.unshift({role:"system",content:e}),pe((()=>t))}else{if(!a){if(!confirm("Some entries are missing the system role as the first message. Do you want to add it for every entry where it's missing?"))return;a=!0}const t=[...ue];t[n].messages=[{role:"system",content:e},...l],pe((()=>t))}}},ke=e=>{ye(e),Ee||Se(e)},Ae=e=>{(()=>{const e=new Date;let t=e.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"});t=t.replace(/\//g,"."),t+="-"+e.getHours().toString().padStart(2,"0")+"."+e.getMinutes().toString().padStart(2,"0"),fe(`MEOW-${t}.jsonl`)})();try{e?localStorage.setItem("mwai_builder_data_v2",(0,y.F1)(e)):localStorage.removeItem("mwai_builder_data_v2"),se(!0)}catch(e){localStorage.removeItem("mwai_builder_data_v2"),se(!1)}};ft((()=>{ue&&(null==ue?void 0:ue.length)>0&&Ae({instructions:Re,entries:ue})}),[ue]),ft((()=>{Re&&(null==Re?void 0:Re.length)>0&&Ae({instructions:Re,entries:ue})}),[Re]);const xe=(e,t)=>{const a=[...ue];a[e-1].messages.splice(t-1,1),pe(a)},Pe=(e,t,a,n=null)=>{const l=ue.map(((l,r)=>{if(r===e-1){if(n)return{...l,messages:l.messages.map(((e,l)=>l===n-1?{...e,role:t,content:a}:e))};if("assistant"===t)return{...l,messages:l.messages.map((e=>"assistant"===e.role?{...e,content:a}:e))};if("user"===t)return{...l,messages:l.messages.map((e=>"user"===e.role?{...e,content:a}:e))}}return l}));pe(l)},De=yt((()=>{let e=(de-1)*ee;const t=null==ue?void 0:ue.slice((de-1)*ee,(de-1)*ee+ee);return null==t?void 0:t.map((t=>{const a=++e;let n="",l="",r=[];if(Ee)r=t.messages;else{const e=t.messages.find((e=>"user"===e.role));e&&(n=e.content);const a=t.messages.find((e=>"assistant"===e.role));a&&(l=a.content)}return{row:a,messages:React.createElement(Oe,{entries:ue,messages:r,currentRow:a,onUpdateDataRow:Pe,onDeleteDataRow:xe}),question:React.createElement(Nt,{data:n,onChange:e=>Pe(a,"user",e)},n),answer:React.createElement(Nt,{data:l,onChange:e=>Pe(a,"assistant",e)},l),actions:React.createElement(React.Fragment,null,Ee&&React.createElement(h.M,{rounded:!0,icon:"plus",onClick:()=>ze(a)}),React.createElement(h.M,{rounded:!0,icon:"trash",onClick:()=>(e=>{const t=ue.filter(((t,a)=>a!==e-1));pe(t),0===t.length&&Ae({instructions:Re,entries:[]})})(a)}))}}))}),[ue,de,ee,Ee,Pe,xe]),Le=async e=>{if(confirm(ge.ALERTS.DELETE_FINETUNE)){v(!0);try{await Z("finetunes_deleted",[...q,e])}catch(e){console.error(e),alert(ge.ALERTS.CHECK_CONSOLE)}v(!1)}},Fe=yt((()=>null==X?void 0:X.sort(((e,t)=>t.created_at-e.created_at)).map((e=>{const t=e.id,a=e.filename,n=new Date(1e3*e.created_at),l="fine-tune"===e.purpose;return{status:React.createElement(Ot,{status:e.status,includeText:!0}),id:t,filename:a,purpose:e.purpose,filesize:(0,y.z3)(e.bytes),createdOn:React.createElement(React.Fragment,null,n.toLocaleDateString(),React.createElement("br",null),n.toLocaleTimeString()),actions:React.createElement(React.Fragment,null,React.createElement(h.M,{disabled:!l,icon:"wand",onClick:()=>p(t)},"Train Model"),React.createElement(h.M,{rounded:!0,icon:"arrow-down",onClick:()=>(async(e,t)=>{v(!0);try{const a=await(0,y.IU)(`${w}/openai/files/download`,{method:"POST",nonce:N,json:{envId:G,fileId:e}});if(a.success){const e=new Blob([a.data],{type:"text/plain"}),n=window.URL.createObjectURL(e),l=document.createElement("a");l.setAttribute("href",n),l.setAttribute("download",`${t}`),document.body.appendChild(l),l.click(),l.remove()}else alert(a.message)}catch(e){console.error(e),alert(ge.ALERTS.CHECK_CONSOLE)}v(!1)})(t,a)}),React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>(async e=>{v(!0);try{const t=await(0,y.IU)(`${w}/openai/files/delete`,{method:"POST",nonce:N,json:{envId:G,fileId:e}});t.success?await Ne():alert(t.message)}catch(e){console.error(e),alert(ge.ALERTS.CHECK_CONSOLE)}v(!1)})(t)}))}}))),[X]),Be=e=>q.includes(e.model)||q.includes(e.id),Ue=e=>"failed"===e.status||"cancelled"===e.status,He=e=>!Ue(e)&&!Be(e),je=yt((()=>{if(!V)return[];let e=V;return"current"===_?e=e.filter(He):"deleted"===_?e=e.filter(Be):"failed"===_&&(e=e.filter(Ue)),e.map((e=>{const t=new Date(e.createdOn);return{...e,model:e.model?e.model:React.createElement(bt,{createdOn:e.createdOn,estimatedOn:e.estimatedOn}),status:React.createElement(Ot,{status:e.status,includeText:!0}),createdOn:React.createElement(React.Fragment,null,t.toLocaleDateString(),React.createElement("br",null),t.toLocaleTimeString()),actions:React.createElement(React.Fragment,null,"succeeded"===e.status&&React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>(async e=>{if(confirm(ge.ALERTS.DELETE_FINETUNE)){v(!0);try{const t=await(0,y.IU)(`${w}/openai/finetunes/delete`,{method:"POST",nonce:N,json:{envId:G,modelId:e}});t.success?await Z("finetunes_deleted",[...q,e]):t.message.indexOf("does not exist")>-1?(alert(ge.ALERTS.FINETUNE_ALREADY_DELETED),await Z("finetunes_deleted",[...q,e])):alert(t.message)}catch(e){console.error(e),alert(ge.ALERTS.CHECK_CONSOLE)}v(!1)}})(e.model)}),"cancelled"===e.status&&React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>Le(e.id)}),"failed"===e.status&&React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>Le(e.id)}),"pending"===e.status&&React.createElement(h.M,{className:"danger",rounded:!0,icon:"close",onClick:()=>(async e=>{v(!0);try{const t=await(0,y.IU)(`${w}/openai/finetunes/cancel`,{method:"POST",nonce:N,json:{envId:G,finetuneId:e}});t.success?Ie():alert(t.message)}catch(e){console.error(e),alert(ge.ALERTS.CHECK_CONSOLE)}v(!1)})(e.id)}))}}))}),[_,q,V]),Ge=Y||R,$e=yt((()=>{const e=new Date,t=e.getFullYear(),a=e.getMonth()+1,n=e.getDate(),l=e.getHours(),r=e.getMinutes(),o=e.getSeconds();return`${Q}:ft-your-org:${I}-${t}-${a<10?"0"+a:a}-${n<10?"0"+n:n}-${l<10?"0"+l:l}-${r<10?"0"+r:r}-${o<10?"0"+o:o}`}),[I,Q]),ze=(e,t="user",a="Hello!")=>{const n=ue.map(((n,l)=>l===e-1?{...n,messages:[...n.messages,{role:t,content:a}]}:n));pe(n)},We=vt(null),qe=null==V?void 0:V.filter(He).length,Ye=null==V?void 0:V.filter(Ue).length,at=null==V?void 0:V.filter(Be).length,nt=yt((()=>React.createElement(ae.u,{scrolldown:!0,value:G,onChange:$,style:{marginLeft:5}},z.filter((e=>"openai"===e.type)).map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))))),[G,z]),rt=yt((()=>{if(0===_e.length)return null;const e=_e.slice(0,10).map(((e,t)=>React.createElement("span",{key:e,style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>(e=>{const t=Math.floor(e/ee);me(t+1)})(e)},e,t<_e.slice(0,10).length-1?", ":"")));return _e.length>10?React.createElement(React.Fragment,null,"Some entries are invalid, for example those ones: ",e,", and ",_e.length-10," more."):React.createElement(React.Fragment,null,"Some entries are invalid, for example those ones: ",e)}),[_e,ee]);return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{fullWidth:!0,minimal:!0,style:{margin:8}},React.createElement(g._,{inversed:!0,currentTab:f,onChange:(e,t)=>{b(t.key)},action:React.createElement(React.Fragment,null,React.createElement("div",{style:{flex:"auto"}}),"finetunes"===f&&React.createElement(React.Fragment,null,React.createElement(h.M,{disabled:R,busy:"finetunes"===R,onClick:Ie,className:"secondary"},ge.COMMON.REFRESH_MODELS),nt),"files"===f&&React.createElement(React.Fragment,null,React.createElement(h.M,{disabled:R,onClick:async()=>{v(!0),await Ne(),v(!1)},className:"secondary"},"Refresh Files"),nt),"editor"===f&&React.createElement(React.Fragment,null,React.createElement("label",{style:{marginRight:10}},"Filename:"),React.createElement(ne.A,{disabled:!Te||R,value:Te?ve:"",onChange:fe,style:{width:220,marginRight:5}}),React.createElement(h.M,{className:"secondary",disabled:!be||R,icon:"upload",onClick:async()=>{v(!0);try{const e=ue.map((e=>(0,y.F1)(e))).join("\n"),t=await(0,y.IU)(`${w}/openai/files/upload`,{method:"POST",nonce:N,json:{envId:G,filename:ve,data:e}});await Ne(),t.success?(Me(!1),alert(ge.ALERTS.DATASET_UPLOADED),b("files")):alert(t.message)}catch(e){console.error(e),alert(ge.ALERTS.CHECK_CONSOLE)}v(!1)}},"Upload to OpenAI"),nt))},React.createElement(g.V,{title:ge.COMMON.MODELS,key:"finetunes"},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("div",null,(0,y.FE)(ge.FINETUNING.MODELS_INTRO)),React.createElement(oe.o,{value:_,onChange:e=>{C(e)}},React.createElement(oe.K,{title:"Current",value:"current",count:qe??"-"}),React.createElement(oe.K,{title:"Failed",value:"failed",count:Ye??"-"}),React.createElement(oe.K,{title:"Deleted",value:"deleted",count:at??"-"}))),React.createElement(le.g,null),React.createElement(Xe.o,{busy:Ge,data:je,columns:Tt,emptyMessage:ge.FINETUNING.NO_FINETUNES_YET}),React.createElement("div",{style:{marginTop:5,display:"flex",justifyContent:"end",lineHeight:"12px",alignItems:"center"}},React.createElement(h.M,{small:!0,disabled:R,busy:"clean"===R,onClick:async()=>{v("clean"),await ot(G),await a(),v(!1)},className:"primary"},ge.FINETUNING.CLEAN_MODELS_LIST),React.createElement("small",{style:{marginLeft:5}},ge.FINETUNING.DELETED_FINETUNE_ISSUE))),React.createElement(g.V,{title:ge.COMMON.FILES,key:"files"},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("div",null,(0,y.FE)(ge.FINETUNING.FILES_INTRO)),React.createElement(oe.o,{value:T,onChange:e=>{O(e)}},React.createElement(oe.K,{title:"Datasets",value:"fine-tune"}),React.createElement(oe.K,{title:"All",value:null}))),React.createElement(le.g,null),React.createElement(Xe.o,{busy:Ge,data:Fe,columns:Ct,emptyMessage:React.createElement(React.Fragment,null,"You do not have any dataset files yet.")})),React.createElement(g.V,{title:ge.FINETUNING.DATASET_EDITOR,key:"editor"},!te&&React.createElement("p",{style:{color:"red"}},ge.FINETUNING.HUGE_DATASET_WARNING),React.createElement(Qe.V,{style:{display:"flex"}},React.createElement(h.M,{icon:"plus",onClick:()=>((e="Question?",t="Answer.")=>{pe([...ue,{messages:[{role:"system",content:Re},{role:"user",content:e},{role:"assistant",content:t}]}])})(),disabled:R},"Add Entry"),Ee&&React.createElement(h.M,{onClick:()=>Se(Re),disabled:R},"Rewrite Instructions"),React.createElement("div",{style:{flex:"auto"}}),React.createElement(Je.S,{style:{marginLeft:5},onLabel:"Expert",offLabel:"Easy",width:90,onBackgroundColor:i.purple,offBackgroundColor:i.green,onChange:he,checked:Ee}),React.createElement(Ze.Z,{ref:We,onSelectFiles:async e=>{for(let t=0;t<e.length;t++){const a=e[t],n=new FileReader,l=a.name.endsWith(".json"),r=a.name.endsWith(".jsonl"),o=a.name.endsWith(".csv");let i=!1;l||r||o?(n.onload=async e=>{const t=e.target.result;let a=[];if(l)try{a=JSON.parse(t)}catch(e){return console.error(e),void alert(ge.ALERTS.ONLY_SUPPORTS_FILES)}else if(r){a=t.split("\n").map((e=>{e=e.trim();try{return JSON.parse(e)}catch(t){return console.error(t,e),null}}));const e=a.every((e=>e.messages));e||(i=!0)}else if(o){a=Ve().parse(t,{header:!0,skipEmptyLines:!0}).data,console.log("The CSV was loaded!",a),i=!0}i&&(a=a.map((e=>{const t=Object.keys(e).reduce(((t,a)=>(t[a.toLowerCase()]=e[a],t)),{});i=!0;const a=["prompt","question","q"].find((e=>t[e])),n=["completion","reply","a"].find((e=>t[e])),l=t[a],r=t[n],o=null==r?void 0:r.replace(/\n\n$/g,""),c=null==l?void 0:l.replace(/\n\n###\n\n$/g,"");return l&&r?{messages:[{role:"system",content:Re},{role:"user",content:c.trim()},{role:"assistant",content:o.trim()}]}:null}))),a=a.filter((e=>e));const n=a.every((e=>null==e?void 0:e.messages));n?pe(a):alert(ge.ALERTS.ONLY_SUPPORTS_FILES)},n.readAsText(a)):(alert(ge.ALERTS.ONLY_SUPPORTS_FILES),console.warn(a))}},accept:"",style:{paddingLeft:5}},React.createElement(h.M,{className:"secondary",onClick:()=>We.current.click()},"Import")),React.createElement(h.M,{disabled:!Te,onClick:Me,className:"secondary"},"Clear")),React.createElement(le.g,null),ue.length>0&&(null==_e?void 0:_e.length)>0&&React.createElement(React.Fragment,null,React.createElement(ce.X,{variant:"danger"},rt),React.createElement(le.g,null)),React.createElement(et.Zc,{keepState:"datasetEditor"},React.createElement(et.y2,{title:"Dataset"},React.createElement(le.g,{tiny:!0}),React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(tt.Q,{currentPage:de,limit:ee,total:Te,onCurrentPageChanged:me,onClick:me})),React.createElement(le.g,{tiny:!0}),React.createElement(Xe.o,{busy:R,data:De,columns:Ee?_t:wt,emptyMessage:React.createElement(React.Fragment,null,"You can import a file, or create manually each entry by clicking ",React.createElement("b",null,"Add"),".")}),React.createElement(le.g,{tiny:!0}),React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(tt.Q,{currentPage:de,limit:ee,total:Te,onCurrentPageChanged:me,onClick:me}),React.createElement(h.M,{disabled:!Te,style:{marginLeft:5},onClick:()=>{const e=(0,y.F1)(ue,2),t=new Blob([e],{type:"text/plain"}),a=URL.createObjectURL(t),n=document.createElement("a");n.href=a;const l=new Date,r=`${l.getFullYear()}-${l.getMonth()+1}-${l.getDate()}-WP.json`;n.download=r,document.body.appendChild(n),n.click(),document.body.removeChild(n)}},"Export as JSON"))),React.createElement(et.y2,{title:ge.COMMON.CONTEXT},React.createElement(le.g,null),React.createElement("span",null,"The instructions are the same for all entries. It is used as the ",React.createElement("i",null,"system")," (and first) message in each conversation. More information ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset",target:"_blank",rel:"noreferrer"},"here"),"."),React.createElement(le.g,null),React.createElement(Ke.m,{id:"instructions",name:"instructions",rows:2,value:Re,onBlur:ke,onEnter:ke})),React.createElement(et.y2,{title:"Generator"},React.createElement(le.g,null),React.createElement(ht,{options:e,instructions:Re,setMessages:pe}),React.createElement(ce.X,{variant:"danger"},"Use this feature with caution. The AI will generate questions and answers for each of your post based on the given prompt, and they will be added to your dataset. Keep in mind that this process may be ",React.createElement("u",null,"extremely slow")," and require a ",React.createElement("u",null,"significant number of API calls"),", resulting in a ",React.createElement("u",null,"high cost"),".")),React.createElement(et.y2,{title:"Instructions"},React.createElement("p",null,"You can create your dataset by importing a file (two columns, in the CSV, JSON or JSONL format) or manually by clicking ",React.createElement("b",null,"Add Entry"),". For the format, check this ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://gist.github.com/jordymeow/a855df4a1f644bb3df8c78ea87c1a2ca"},"JSON Example")," (more complex) or this ",React.createElement("a",{rel:"noreferrer",target:"_blank",href:"https://gist.github.com/jordymeow/e0c80ebeefe4d4d07ae39995c561ba4a"},"CSV Example")," (simpler). ",React.createElement("b",null,"Writing datasets is actually complex.")," Please have a look at OpenAI's ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/fine-tuning/conditional-generation",target:"_blank",rel:"noreferrer"},"tutorials"),". And here is Meow Apps' ",React.createElement("a",{href:"https://meowapps.com/wordpress-chatbot-finetuned-model-ai/",target:"_blank",rel:"noreferrer"},"simplified tutorial"),". Is your dataset ready? Modify the filename to your liking and click ",React.createElement("b",null,"Upload to OpenAI"),"."),React.createElement("p",null,"To avoid losing your work, this data is kept in your browser's local storage."))))))),React.createElement(re.L,{style:{margin:10}},React.createElement(ie.n,{isOpen:s,title:"Error",onRequestClose:()=>d(),okButton:{label:"Ok",onClick:()=>d()},content:React.createElement(React.Fragment,null,React.createElement("p",null,null==s?void 0:s.message))}),React.createElement(ie.n,{isOpen:u,title:"Train a new model",onRequestClose:()=>p(),okButton:{label:"Start",disabled:R,onClick:async()=>{const e=u,t=I;v(!0);let a={envId:G,fileId:e,model:Q,suffix:t};S&&(a={...a,nEpochs:A,batchSize:P,learningRateMultiplier:L,promptLossWeight:B});try{const e=await(0,y.IU)(`${w}/openai/files/finetune`,{method:"POST",nonce:N,json:a});e.success?(Ie(),alert(ge.ALERTS.FINETUNING_STARTED),b("finetunes"),p()):alert(e.message)}catch(e){console.log(e.message),alert(e.message)}v(!1)}},cancelButton:{label:"Close",disabled:R,onClick:()=>p()},content:React.createElement(React.Fragment,null,React.createElement("p",null,"Exciting! 🎵 You are about to create your own new model, based on your dataset. You simply need to select a base model, and optionally, to modify the ",React.createElement("a",{href:"https://beta.openai.com/docs/guides/fine-tuning/hyperparameters",target:"_blank",rel:"noreferrer"},"hyperparameters"),". Before starting the process, make sure that:"),React.createElement("ul",null,React.createElement("li",null,"✅ The dataset is well-defined."),React.createElement("li",null,"✅ You understand ",React.createElement("a",{href:"https://openai.com/api/pricing/#faq-fine-tuning-pricing-calculation",target:"_blank",rel:"noreferrer"},"OpenAI pricing")," about fine-tuning.")),React.createElement("label",null,"Base model:"),React.createElement(le.g,{height:5}),React.createElement(ne.A,{value:Q,onChange:J,description:React.createElement(React.Fragment,null,"As of August 2024, you can use ",React.createElement("a",{href:"#",onClick:()=>J("gpt-4o-mini-2024-07-18")},"gpt-4o-mini-2024-07-18"),", ",React.createElement("a",{href:"#",onClick:()=>J("gpt-3.5-turbo-0125")},"gpt-3.5-turbo-0125"),", or any of your previously fine-tuned models. Check all the available models ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/fine-tuning/which-models-can-be-fine-tuned",target:"_blank",rel:"noreferrer"},"here"),".")}),React.createElement(le.g,{height:10}),React.createElement("label",null,"Suffix (for new model name):"),React.createElement(le.g,{height:5}),React.createElement(ne.A,{value:I,onChange:M}),React.createElement(le.g,{height:5}),React.createElement("small",null,"The name of the new model name will be decided by OpenAI. You can customize it a bit with a ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/fine-tuning/create-a-fine-tuned-model",target:"_blank",rel:"noreferrer"},"suffix"),". Preview: ",React.createElement("b",null,$e),"."),React.createElement(le.g,{line:!0,height:20}),React.createElement(m.R,{label:"Enable HyperParams",checked:S,onChange:k}),S&&React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",flexDirection:"row",alignItems:"center"}},React.createElement("label",{style:{marginRight:5}},"Number of Epochs:"),React.createElement(ne.A,{style:{marginRight:5},value:A,onChange:x,type:"number"}),React.createElement("label",{style:{marginRight:5}},"Batch Size:"),React.createElement(ne.A,{value:P,onChange:D,type:"number"})),React.createElement("div",{style:{display:"flex",flexDirection:"row",alignItems:"center"}},React.createElement("label",{style:{marginRight:5}},"Learning Rate Multiplier:"),React.createElement(ne.A,{style:{marginRight:5},value:L,onChange:F,type:"number"}),React.createElement("label",{style:{marginRight:5}},"Prompt Loss Weight:"),React.createElement(ne.A,{value:B,onChange:U,type:"number"}))))})))},{useState:Mt}=wp.element,St=({options:e,updateOption:t,busy:a})=>{const[n,l]=Mt("I would love to live on a tropical island with beautiful and sexy felines, where we could bask in the sun on the sandy beaches, sip on refreshing coconut milk, and enjoy each other's company. While we might occasionally fight in the trees, our days would mostly be spent in peaceful slumber. However, I am not sure of how we would handle any potential disruptions to our idyllic existence if human were to come..."),[r,o]=Mt([]),[i,c]=Mt(""),[d,u]=Mt(!1),p=null==e?void 0:e.chatbot_moderation,g=d||a,v=React.createElement(s.d,{title:ge.COMMON.CHATBOT},React.createElement(m.R,{name:"chatbot_moderation",label:ge.COMMON.ENABLE,value:"1",checked:p,description:ge.SETTINGS.CHATBOT_MODERATION_HELP,onChange:t}));return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{busy:g,title:ge.COMMON.SETTINGS,className:"primary"},React.createElement("p",null,"You can enable moderation various parts of WordPress. It will slow down the processing a little."),v)),React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{busy:g,title:"AI Moderation Tester",className:"primary"},React.createElement("p",null,"Paste a text below, and check if it is safe for your website. ",React.createElement("b",null,"OpenAI Moderation Model is free!")," Learn more about it ",React.createElement("a",{href:"https://platform.openai.com/docs/guides/moderation/overview",target:"_blank"},"here"),"."),React.createElement(Ke.m,{name:"context",rows:8,value:n,onChange:l}),React.createElement(le.g,null),React.createElement(h.M,{fullWidth:!0,onClick:async()=>{u(!0);const e=await(0,y.IU)(`${w}/ai/moderate`,{method:"POST",nonce:N,json:{text:n}});if(e.success){let t=e.results;o(null==t?void 0:t.results)}else c(e.message);u(!1)}},"Moderation Check"),React.createElement(le.g,null),React.createElement("label",null,"Results:"),React.createElement("pre",null,(0,y.F1)(r,2))))))},{useState:kt,useEffect:At,useMemo:xt}=wp.element,Pt=({modal:e,busy:t,setModal:a,onAddEmbedding:n,onModifyEmbedding:l})=>{const[r,o]=kt(!1),i=t;At((()=>{"edit"!==(null==e?void 0:e.type)&&"add"!==(null==e?void 0:e.type)||o((null==e?void 0:e.data)||{})}),[e]);const c=xt((()=>{var t,a,n,l,o;return null==e||!e.data||((null==e||null===(t=e.data)||void 0===t?void 0:t.title)!==(null==r?void 0:r.title)||((null==e||null===(a=e.data)||void 0===a?void 0:a.content)!==(null==r?void 0:r.content)||((null==e||null===(n=e.data)||void 0===n?void 0:n.behavior)!==(null==r?void 0:r.behavior)||((null==e||null===(l=e.data)||void 0===l?void 0:l.type)!==(null==r?void 0:r.type)||(null==e||null===(o=e.data)||void 0===o?void 0:o.refId)!==(null==r?void 0:r.refId)))))}),[e,r]);return React.createElement(React.Fragment,null,React.createElement(ie.n,{isOpen:"edit"===(null==e?void 0:e.type)||"add"===(null==e?void 0:e.type),title:"edit"===(null==e?void 0:e.type)?ge.COMMON.MODIFY_EMBEDDING:ge.COMMON.ADD_EMBEDDING,okButton:{label:"edit"===(null==e?void 0:e.type)?ge.COMMON.MODIFY_EMBEDDING:ge.COMMON.ADD_EMBEDDING,disabled:!c||t,isBusy:"addEmbedding"===t,onClick:()=>{"edit"===e.type?(async()=>{try{await l(r),a(null)}catch(e){alert(e.message)}})():(async()=>{try{await n(r),a(null)}catch(e){alert(e.message)}})()}},cancelButton:{disabled:t,onClick:()=>a(null)},onRequestClose:()=>a(null),content:React.createElement(React.Fragment,null,React.createElement("p",null,"A custom embedding can be a sentence, a paragraph or a whole article. When an user input is made, the AI will search for the best embedding that matches the user input and will be able to reply with more accuracy."),React.createElement(le.g,null),React.createElement("label",null,"Title:"),React.createElement(le.g,{tiny:!0}),React.createElement(ne.A,{value:null==r?void 0:r.title,placeholder:'Title, like "My Website Information"',description:"This is for your convenience only, it's not used anywhere.",onChange:e=>o({...r,title:e})}),React.createElement(le.g,null),React.createElement("label",null,"Content:"),React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{countable:"chars",maxLength:64e3,description:"The content of your embeddings that will be used by the AI if it matches the user input.",value:null==r?void 0:r.content,onChange:e=>o({...r,content:e})}),React.createElement(le.g,null),React.createElement("div",{style:{display:"flex",justifyContent:"space-between"}},React.createElement("div",{style:{flex:3}},React.createElement("label",null,"Behavior:"),React.createElement(le.g,{tiny:!0}),React.createElement(ae.u,{scrolldown:!0,name:"behavior",disabled:i||!0,value:null==r?void 0:r.behavior,onChange:e=>{o({...r,behavior:e})}},React.createElement(ae.j,{value:"context",label:"Context"}),React.createElement(ae.j,{value:"reply",label:"Reply"}))),React.createElement("div",{style:{flex:3,marginLeft:5}},React.createElement("label",null,"Type:"),React.createElement(le.g,{tiny:!0}),React.createElement(ae.u,{scrolldown:!0,name:"type",disabled:i||!0,value:null==r?void 0:r.type,onChange:e=>{o({...r,type:e})}},React.createElement(ae.j,{value:"manual",label:"Manual"}),React.createElement(ae.j,{value:"postId",label:"Related to Post"}))),"postId"===(null==r?void 0:r.type)&&React.createElement("div",{style:{flex:1,marginLeft:5}},React.createElement("label",null,"Post ID:"),React.createElement(le.g,{tiny:!0}),React.createElement(ne.A,{value:null==r?void 0:r.refId,disabled:!0,onChange:e=>o({...r,refId:e})}))))}))},{useState:Dt}=wp.element;function Lt(e,t){const a=new Blob([e],{type:"text/plain;charset=utf-8;"}),n=document.createElement("a");n.href=URL.createObjectURL(a),n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}const Ft=({modal:e,setModal:t})=>{const[a,n]=Dt(!1),[l,r]=Dt(0),[o,i]=Dt(0),c=null==e?void 0:e.data,s=async()=>{let e=!1;const t={page:1,limit:20,filters:{envId:c.envId,dbIndex:c.dbIndex,dbNS:c.dbNS}};let a=[];for(;!e;){const n=await Ne(t);n.vectors.length<2&&(e=!0),r((()=>n.total)),a=a.concat(n.vectors),i((()=>a.length)),t.page++}return a};return React.createElement(React.Fragment,null,React.createElement(ie.n,{isOpen:"export"===(null==e?void 0:e.type),title:"Export Embeddings",onRequestClose:()=>t(null),okButton:{label:"Close",disabled:a,onClick:()=>t(null)},customButtons:React.createElement(React.Fragment,null,React.createElement(h.M,{onClick:async()=>{try{n(!0);const e=await s(),t=Ve().unparse(e),a=new Date,l=a.getFullYear(),o=a.getMonth()+1;Lt(t,`vectors-${l}-${o}-${a.getDate()}.csv`),setTimeout((()=>{r(0)}),1e3)}catch(e){console.error(e),alert("An error occurred while exporting vectors. Check your console.")}finally{n(!1)}},disabled:a},"Export CSV"),React.createElement(h.M,{onClick:async()=>{try{n(!0);const e=await s(),t=(0,y.F1)(e,2),a=new Date,l=a.getFullYear(),o=a.getMonth()+1;Lt(t,`vectors-${l}-${o}-${a.getDate()}.json`),setTimeout((()=>{r(0)}),1e3)}catch(e){console.error(e),alert("An error occurred while exporting vectors. Check your console.")}finally{n(!1)}},disabled:a},"Export JSON")),content:React.createElement(React.Fragment,null,React.createElement(at.j,{busy:a,style:{flex:"auto"},value:o,max:l}))}))},{useState:Bt}=wp.element,Ut=({modal:e,setModal:t,onAddEmbedding:a,onModifyEmbedding:n})=>{var l;const[r,o]=Bt(!1),[i,c]=Bt(0),[s,d]=Bt(0),[u,p]=Bt({add:[],modify:[],same:[],total:0,isReady:!1}),E=(null==e||null===(l=e.data)||void 0===l?void 0:l.importVectors)??[],[g,R]=Bt({envId:!1,dbId:!1,dbIndex:!1,dbNS:!1,title:!0,refId:!0}),y=null==e?void 0:e.data,v=e=>({id:e.id??null,type:e.type??"manual",title:e.title??"N/A",behavior:e.behavior??"context",envId:(null==y?void 0:y.envId)??null,dbId:e.dbId??null,dbIndex:y.dbIndex??null,dbNS:y.dbNS??null,content:e.content??"",refId:e.refId??null}),f=(e,t,a)=>Object.keys(a).every((n=>!a[n]||e[n]===t[n])),b=()=>{t(null),o(!1),c(0),d(0),p({add:[],modify:[],same:[],total:0,isReady:!1})};return React.createElement(React.Fragment,null,React.createElement(ie.n,{isOpen:"import"===(null==e?void 0:e.type),title:"Import Embeddings",onRequestClose:b,okButton:{label:"Close",onClick:b,disabled:r},customButtons:React.createElement(React.Fragment,null,React.createElement(h.M,{onClick:async()=>{try{let e=!1;const t={page:1,limit:20,filters:{envId:y.envId,dbIndex:y.dbIndex,dbNS:y.dbNS}};let a=[];for(o("stepOne");!e;){const n=await Ne(t);n.vectors.length<2&&(e=!0),c((()=>n.total)),a=a.concat(n.vectors),d((()=>a.length)),t.page++}(async(e,t)=>{const a=[],n=[],l=[];console.log("Calculate Diff",{currentVectors:e,importVectors:t});for(const r of t){const t=v(r),o=e.find((e=>f(e,t,g)));console.log("Matched Vector",{cleanVector:{...t},matchedVector:{...o}}),o?t.id=o.id:delete t.id;const i=e.find((e=>e.id===t.id));i&&t.content===i.content&&t.title===i.title?l.push(t):t.id?n.push(t):a.push(t)}const r=a.length+n.length;p({add:a,modify:n,same:l,total:r,isReady:!0}),console.log("Embeddings Diff",{add:a,modify:n,same:l,total:r})})(a,E)}catch(e){console.error(e),alert("An error occurred while retrieving your current embeddings. Check your console.")}finally{o(!1)}},disabled:r},"Check Differences"),React.createElement(h.M,{onClick:async()=>{try{c(u.add.length+u.modify.length),d(0),o("stepTwo");for(const e of u.add)await a(e,!0),d((e=>e+1));for(const e of u.modify)await n(e,!0),d((e=>e+1));alert("All embeddings have been updated."),p({add:[],modify:[],same:[],total:0,isReady:!1}),b()}catch(e){console.error(e),alert("An error occurred while updating embeddings. Check your console.")}finally{o(!1)}},disabled:r||0===u.total},"Apply Changes")),content:React.createElement(React.Fragment,null,React.createElement("p",null,"There are ",React.createElement("b",null,E.length," embeddings")," in the file."),React.createElement(le.g,null),React.createElement(et.y2,{title:"1 - Check Differences"}),React.createElement("p",null,"Calculates the differences between the embeddings in your file and the ones currently registered in AI Engine. Based on that, a list of changes will be created. Please note that the environment, index and namespace that might be set in the file will be ignored."),React.createElement("p",{style:{marginTop:10}},"An embedding will be considered the same entry based on:"),React.createElement(le.g,null),React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{marginLeft:15}},React.createElement(m.R,{small:!0,label:"DB ID",disabled:!1,checked:g.dbId,onChange:()=>R({...g,dbId:!g.dbId})})),React.createElement("div",{style:{marginLeft:15}},React.createElement(m.R,{small:!0,label:"Title",disabled:!1,checked:g.title,onChange:()=>R({...g,title:!g.title})})),React.createElement("div",{style:{marginLeft:15}},React.createElement(m.R,{small:!0,label:"Ref (Post ID)",disabled:!1,checked:g.refId,onChange:()=>R({...g,refId:!g.refId})}))),"stepOne"===r&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement(at.j,{busy:r,style:{flex:"auto"},value:s,max:i})),React.createElement(le.g,null),React.createElement(et.y2,{title:"2 - Apply Changes"}),!u.isReady&&React.createElement("i",null,"Waiting for diff..."),u.isReady&&React.createElement(React.Fragment,null,React.createElement("p",null,"There are ",u.same.length>=1&&React.createElement("span",null,React.createElement("b",null,u.same.length," identical embeddings")," (with the same title and content). They will be ignored. "),React.createElement("span",null,"Changes to apply:")),React.createElement("ul",null,React.createElement("li",null,"👉 Add: ",React.createElement("b",null,u.add.length)),React.createElement("li",null,"👉 Modify: ",React.createElement("b",null,u.modify.length)))),"stepTwo"===r&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement(at.j,{busy:r,style:{flex:"auto"},value:s,max:i})),React.createElement(le.g,null))}))},{useState:Ht}=wp.element;let jt=null;const Gt=({fileInputRef:e,pdfFile:t,setPdfFile:n,pdfData:l,setPdfData:o,chunks:i,setChunks:s,editableChunks:d,setEditableChunks:m,chunkingDensity:u,busy:p,setBusy:E,error:g,setError:v})=>{var f;const{colors:b}=(0,r.z)(),[C,T]=Ht(0),[O,I]=Ht(0),[M,S]=Ht(""),k=e=>{const t=[];let a=null,n=[];const l=[];var r,o;(e.items.forEach((e=>{if(null===a||Math.abs(e.transform[5]-a)>2){var t,r;if(n.length>0)l.push({text:n.map((e=>e.str)).join(" ").trim(),items:n,y:a,height:(null===(t=n[0])||void 0===t?void 0:t.height)||0,fontName:(null===(r=n[0])||void 0===r?void 0:r.fontName)||""});n=[e],a=e.transform[5]}else n.push(e)})),n.length>0)&&l.push({text:n.map((e=>e.str)).join(" ").trim(),items:n,y:a,height:(null===(r=n[0])||void 0===r?void 0:r.height)||0,fontName:(null===(o=n[0])||void 0===o?void 0:o.fontName)||""});const i=l.reduce(((e,t)=>e+t.height),0)/l.length;return l.forEach(((e,a)=>{const n=e.text,l=e.height>1.2*i,r=n.split(" ").length<=10,o=/^(Chapter\s+\d+|CHAPTER\s+\d+|\d+\.|Part\s+\d+|Section\s+\d+)/i.test(n),c=n===n.toUpperCase()&&n.length>3,s=n.endsWith(":");n.length>3&&(l&&r||o||c&&r||s&&r)&&t.push({text:n,pageIndex:0,lineIndex:a,confidence:(l?.3:0)+(o?.4:0)+(c?.2:0)+(s?.1:0)})})),t.filter((e=>e.confidence>=.3))},A=async(e,t,a,n)=>{if(E(!0),v(null),S("analyzing"),console.log("[PDF Import] Starting chunking with density:",a),5===a&&e.length>1e4){const t=Math.ceil(e.length/1e3);console.log("[PDF Import] Very high density warning - estimated chunks:",t),t>50&&v(`Note: Very High density may create ${t}+ small chunks. This might take a moment...`)}try{const l=new AbortController,r=3e4,o=Math.ceil(e.length/5e4),i=a>=4?2:1,c=r*o*i;console.log("[PDF Import] Sending chunking request to server..."),console.log("[PDF Import] Timeout set to:",c/1e3,"seconds (size multiplier:",o,", density multiplier:",i,")"),setTimeout((()=>{p&&S("titles")}),3e3);const d=setTimeout((()=>l.abort()),c),u=await(0,y.IU)(`${w}/vectors/chunk`,{nonce:N,method:"POST",json:{text:e,pageTexts:t,density:a,fileName:(null==n?void 0:n.fileName)||"document.pdf"},signal:l.signal});clearTimeout(d),u.chunks&&(console.log("[PDF Import] Received chunks:",u.chunks.length),s(u.chunks),m(u.chunks.map(((e,t)=>({...e,id:`chunk_${t}`,enabled:!0})))),v(null))}catch(t){if(console.error("[PDF Import] Chunking error:",t),"AbortError"===t.name){const t=Math.ceil(baseTimeout*Math.ceil(e.length/5e4)*(a>=4?2:1)/1e3);v(`Processing is taking longer than expected (>${t}s). This might be due to the PDF size or selected density. Try a lower density setting or split the PDF into smaller sections.`)}else v("Failed to generate chunks: "+t.message)}finally{E(!1),S("")}};return React.createElement("div",{style:{display:"flex",flexDirection:"column",flex:1}},React.createElement("input",{ref:e,type:"file",accept:".pdf",onChange:async e=>{const t=e.target.files[0];if(t&&t.type.includes("pdf")){console.log("[PDF Import] File selected:",t.name,"Size:",t.size),n(t),v(null),E(!0);try{console.log("[PDF Import] Starting PDF parsing...");const e=await(async()=>(jt||(jt=await a.e(854).then(a.bind(a,1100)),jt.GlobalWorkerOptions.workerSrc=`${_}/app/pdf.worker.min.js`),jt))(),n=await t.arrayBuffer(),l=await e.getDocument({data:n}).promise;console.log("[PDF Import] PDF loaded, pages:",l.numPages);let r="";const i=[],c=[];for(let e=1;e<=l.numPages;e++){console.log(`[PDF Import] Extracting text from page ${e}/${l.numPages}`);const t=await l.getPage(e),a=await t.getTextContent();k(a).forEach((t=>{t.pageIndex=e-1,c.push(t)}));const n=a.items.map((e=>e.str)).join(" ");i.push(n),r+=n+"\n\n",I(e),T(e/l.numPages*100)}const s=r.split(/\s+/).filter((e=>e.length>0)).length;console.log("[PDF Import] Text extraction complete. Words:",s,"Characters:",r.length),console.log("[PDF Import] Detected headings:",c.length);const d={numPages:l.numPages,wordCount:s,fullText:r,pageTexts:i,fileName:t.name,detectedHeadings:c.length>=3?c:[]};o(d),await A(r,i,u,d)}catch(e){console.error("[PDF Import] PDF parsing error:",e),v("Failed to parse PDF: "+e.message)}finally{E(!1)}}else v("Please select a valid PDF file")},style:{display:"none"},disabled:p}),React.createElement("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center"}},React.createElement(R.z,{className:"primary",style:{maxWidth:400}},React.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:20}},React.createElement(c.s,{h3:!0,style:{marginBottom:10}},"Upload PDF Document"),React.createElement(c.s,{p:!0,style:{color:b.grey,textAlign:"center",marginBottom:10}},"Select a PDF file to extract its content and create embeddings"),!l&&React.createElement(h.M,{className:"primary",onClick:()=>{var t;return null===(t=e.current)||void 0===t?void 0:t.click()},disabled:p,isBusy:p,style:{height:50,fontSize:16,minWidth:250}},React.createElement(Ye.z,{icon:"upload",style:{marginRight:8}}),"Select PDF"),p&&React.createElement("div",{style:{marginTop:20,textAlign:"center"}},React.createElement(c.s,{small:!0,style:{color:b.grey}},l?"titles"===M?"Generating descriptive titles...":"Creating sections...":"Parsing PDF pages..."),u>=4&&l&&React.createElement(c.s,{small:!0,style:{color:b.orange,marginTop:10}},"High density setting may take longer")),l&&!p&&i.length>0&&React.createElement(React.Fragment,null,React.createElement("div",{style:{background:b.lightGrey,padding:20,display:"flex",flexDirection:"column",alignItems:"center",borderRadius:8,marginTop:20,marginBottom:20,width:"100%"}},React.createElement(Ye.z,{icon:"check-circle",width:24,color:b.green,style:{marginBottom:10}}),React.createElement(c.s,{h4:!0,style:{margin:0}},l.fileName),React.createElement(c.s,{small:!0,style:{color:b.grey,textAlign:"center",margin:"4px 0"}},l.numPages," pages • ",l.wordCount.toLocaleString()," words"),React.createElement(c.s,{small:!0,style:{color:b.grey,margin:0}},i.length," sections created"),(null===(f=l.detectedHeadings)||void 0===f?void 0:f.length)>0&&React.createElement(c.s,{small:!0,style:{color:b.primary,marginTop:4}},l.detectedHeadings.length," chapters detected")),React.createElement(h.M,{className:"primary",onClick:()=>window.dispatchEvent(new CustomEvent("pdf-import-continue")),style:{height:50,fontSize:16,minWidth:200}},"Continue"))))))},{}=wp.element,$t=({chunk:e,viewMode:t,onToggle:a,onUpdateTitle:n,onGenerateTitle:l,busy:r,colors:o})=>React.createElement("div",{style:{marginBottom:10}},React.createElement("div",{style:{display:"flex",alignItems:"flex-start",gap:10}},React.createElement(m.R,{checked:e.enabled,onChange:()=>a(e.id)}),React.createElement("div",{style:{flex:1}},React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},React.createElement(ne.A,{value:e.title,onChange:t=>n(e.id,t),style:{flex:1},disabled:!e.enabled,placeholder:"Enter section title..."}),e.enabled&&React.createElement(h.M,{size:"small",className:"secondary",onClick:()=>l(e),disabled:r,title:"Generate AI title",style:{padding:"6px 10px"}},React.createElement(Ge,{icon:"wand",style:{width:16,height:16}}))),e.enabled&&React.createElement("div",{style:{fontSize:12,color:o.grey,marginTop:2,display:"flex",gap:5}},React.createElement("span",null,e.pageRange),React.createElement("span",null,"•"),React.createElement("span",null,e.tokens," tokens")),"detailed"===t&&React.createElement("div",{style:{color:o.darkGrey,marginTop:8,marginBottom:8,maxHeight:80,overflow:"hidden",lineHeight:1.5,position:"relative"}},e.content.substring(0,200),e.content.length>200&&React.createElement("span",{style:{position:"absolute",bottom:0,right:0,background:`linear-gradient(to right, transparent, ${o.lightGrey})`,padding:"0 10px"}},"..."))))),{}=wp.element,zt=({density:e,onDensityChange:t,busy:a})=>React.createElement(R.z,{className:"primary",title:"Chunking Density"},React.createElement(ae.u,{value:e,onChange:t,disabled:a,isBusy:a,style:{width:"100%"}},React.createElement(ae.j,{value:1,label:"Very Low (~3000 tokens)"}),React.createElement(ae.j,{value:2,label:"Low (~2000 tokens)"}),React.createElement(ae.j,{value:3,label:"Medium (~1000 tokens)"}),React.createElement(ae.j,{value:4,label:"High (~500 tokens)"}),React.createElement(ae.j,{value:5,label:"Very High (~250 tokens)"}))),{useState:Wt,useMemo:qt}=wp.element,Vt=({editableChunks:e,setEditableChunks:t,chunks:a,setChunks:n,chunkingDensity:l,setChunkingDensity:o,pdfData:i,busy:c,setBusy:s,setError:d})=>{var m,u;const{colors:p}=(0,r.z)(),[g,v]=Wt("compact"),[f,b]=Wt("tokens"),_=qt((()=>e.filter((e=>e.enabled)).length),[e]),C=e=>{t((t=>t.map((t=>t.id===e?{...t,enabled:!t.enabled}:t))))},T=(e,a)=>{t((t=>t.map((t=>t.id===e?{...t,title:a}:t))))},O=async(e,a="tokens")=>{s(!0),d(null);try{const l=await(0,y.IU)(`${w}/vectors/chunk`,{nonce:N,method:"POST",json:{text:i.fullText,pageTexts:i.pageTexts,density:e,fileName:i.fileName,chunkingType:a,detectedHeadings:"chapters"===a?i.detectedHeadings:[]}});l.chunks&&(n(l.chunks),t(l.chunks.map(((e,t)=>({...e,id:`chunk_${t}`,enabled:!0})))))}catch(e){d("Failed to regenerate chunks: "+e.message)}finally{s(!1)}},I=async e=>{s(!0),d(null);try{const t=`Read this text section and create a clear, descriptive title (max 50 characters) that captures its main topic. Reply with ONLY the title, nothing else:\n\n${e.content.substring(0,1e3).trim()}`,a=await(0,y.IU)(`${w}/simpleTextQuery`,{nonce:N,method:"POST",json:{message:t,options:{scope:"embeddings-title",max_tokens:25,temperature:.2}}});if(a.success&&a.data){const t=a.data.trim().replace(/^["']|["']$/g,"");t&&t.length>5&&t.length<=100&&T(e.id,t)}else d(a.message||"Failed to generate title")}catch(e){d(e.message||"Failed to generate title")}finally{s(!1)}};return React.createElement("div",{style:{display:"flex",flexDirection:"row",flex:1}},React.createElement(E.Y,{minimal:!0,style:{flex:3,display:"flex",backgroundColor:"var(--neko-main-color)"}},React.createElement(R.z,{className:"primary",title:`Sections (${_}/${e.length})`,style:{flex:1,display:"flex",flexDirection:"column"}},React.createElement("div",{style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden"}},e.map((e=>React.createElement($t,{key:e.id,chunk:e,viewMode:g,onToggle:C,onUpdateTitle:T,onGenerateTitle:I,busy:c,colors:p})))))),React.createElement(E.Y,{minimal:!0,style:{flex:1,marginLeft:10,backgroundColor:"var(--neko-main-color)"}},(!(null!=i&&null!==(m=i.detectedHeadings)&&void 0!==m&&m.length)||"tokens"===f)&&React.createElement(React.Fragment,null,React.createElement(zt,{density:l,onDensityChange:async e=>{o(e),i&&await O(e,f)},busy:c}),React.createElement(le.g,{tiny:!0})),(null==i||null===(u=i.detectedHeadings)||void 0===u?void 0:u.length)>0&&React.createElement(React.Fragment,null,React.createElement(R.z,{className:"primary",title:"Chunking Type"},React.createElement(ae.u,{value:f,onChange:async e=>{b(e),i&&await O(l,e)},disabled:c,style:{width:"100%"}},React.createElement(ae.j,{value:"tokens",label:"By Tokens - Split based on token count"}),React.createElement(ae.j,{value:"chapters",label:`By Chapters - Use ${i.detectedHeadings.length} detected chapters`}))),React.createElement(le.g,{tiny:!0})),React.createElement(R.z,{className:"primary",title:"AI Title Generation"},React.createElement(h.M,{fullWidth:!0,className:"secondary",onClick:async()=>{s(!0),d(null);try{const a=e.filter((e=>e.enabled)),n=5;for(let e=0;e<a.length;e+=n){const l=a.slice(e,e+n).map((async e=>{try{const t=`Read this text section and create a clear, descriptive title (max 50 characters) that captures its main topic. Reply with ONLY the title, nothing else:\n\n${e.content.substring(0,1e3).trim()}`,a=await(0,y.IU)(`${w}/simpleTextQuery`,{nonce:N,method:"POST",json:{message:t,options:{scope:"embeddings-title",max_tokens:25,temperature:.2}}});if(a.success&&a.data){const t=a.data.trim().replace(/^["']|["']$/g,"");if(t&&t.length>5&&t.length<=100)return{chunkId:e.id,title:t}}}catch(e){console.error("Failed to generate title for chunk:",e)}return null})),r=await Promise.all(l);t((e=>{const t=[...e];return r.forEach((e=>{if(e&&e.title){const a=t.findIndex((t=>t.id===e.chunkId));a>=0&&(t[a].title=e.title)}})),t}))}}catch(e){d("Failed to generate titles with AI")}finally{s(!1)}},disabled:0===_,isBusy:c,style:{height:50,fontSize:16}},React.createElement(Ge,{icon:"wand",style:{marginRight:8,width:16,height:16}}),"Auto-Generate All Titles")),React.createElement(le.g,{tiny:!0}),React.createElement(R.z,{className:"primary",title:"View Mode"},React.createElement(ae.u,{value:g,onChange:v,style:{flex:1}},React.createElement(ae.j,{value:"compact",label:"Compact"}),React.createElement(ae.j,{value:"detailed",label:"Detailed"}))),React.createElement(le.g,{tiny:!0}),React.createElement(R.z,{className:"primary",title:"Information"},React.createElement("p",null,"Each section will become a separate embedding in your knowledge base."))))},{useEffect:Yt}=wp.element,Kt=({editableChunks:e,uploadProgress:t,setUploadProgress:a,uploadedCount:n,setUploadedCount:l,onAddEmbedding:o,environment:i,busy:s,setBusy:d,error:m,setError:u,onComplete:p})=>{const{colors:E}=(0,r.z)(),g=e.filter((e=>e.enabled));return Yt((()=>{const e=()=>(async()=>{if(0!==g.length){d(!0),l(0),u(null);try{for(let e=0;e<g.length;e++){const t=g[e];await o({type:"manual",title:t.title,content:t.content,envId:null==i?void 0:i.id,behavior:"context"},!0),l(e+1),a((e+1)/g.length*100)}p()}catch(e){console.error("Upload error:",e),u("Failed to upload embeddings: "+e.message)}finally{d(!1)}}else u("Please select at least one chunk to upload")})();return window.addEventListener("pdf-import-upload",e),()=>window.removeEventListener("pdf-import-upload",e)}),[g]),React.createElement("div",{style:{display:"flex",flexDirection:"column",flex:1}},React.createElement("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center"}},React.createElement(R.z,{className:"primary",style:{maxWidth:500}},React.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:20}},0===t&&!s&&React.createElement(React.Fragment,null,React.createElement(Ye.z,{icon:"database",width:48,color:E.blue,style:{marginBottom:20}}),React.createElement(c.s,{h3:!0,style:{marginBottom:10}},"Ready to Create Embeddings"),React.createElement(c.s,{p:!0,style:{color:E.grey,textAlign:"center"}},g.length," sections will be processed and added to your knowledge base")),t>0&&t<100&&React.createElement(React.Fragment,null,React.createElement(c.s,{h3:!0,style:{marginBottom:20}},"Creating Embeddings..."),React.createElement(at.j,{value:t,max:100,style:{marginBottom:10}}),React.createElement(c.s,{small:!0,style:{color:E.grey}},"Processing section ",n," of ",g.length)),100===t&&React.createElement(React.Fragment,null,React.createElement(Ye.z,{icon:"check-circle",width:48,color:E.green,style:{marginBottom:20}}),React.createElement(c.s,{h3:!0,style:{marginBottom:10}},"All Done!"),React.createElement(c.s,{p:!0,style:{color:E.grey,textAlign:"center"}},"Successfully created ",g.length," embeddings"))))))},{useState:Xt,useRef:Qt,useEffect:Jt}=wp.element,Zt=({modal:e,setModal:t,onAddEmbedding:a,environment:n})=>{const{colors:l}=(0,r.z)(),[o,i]=Xt("analyze"),[c,s]=Xt(null),[d,m]=Xt(null),[u,p]=Xt([]),[E,g]=Xt([]),[R,y]=Xt(3),[v,f]=Xt(0),[b,w]=Xt(0),[_,C]=Xt(!1),[T,O]=Xt(null),N=Qt(null),I=()=>{i("analyze"),s(null),m(null),p([]),g([]),f(0),w(0),C(!1),O(null)};Jt((()=>{const e=()=>{"analyze"!==o||null===d||_||i("optimize")};return window.addEventListener("pdf-import-continue",e),()=>window.removeEventListener("pdf-import-continue",e)}),[o,d,_]);return React.createElement(ie.n,{title:"Import from PDF",size:"full-size",style:{backgroundColor:"var(--neko-main-color)"},isOpen:"pdf-import"===(null==e?void 0:e.type),onRequestClose:()=>{t(null),I()},customButtons:React.createElement(React.Fragment,null,React.createElement(h.M,{onClick:()=>{t(null),I()},disabled:_},"Close"),"analyze"!==o&&React.createElement(h.M,{onClick:()=>{"optimize"===o?i("analyze"):"integrate"===o&&i("optimize")},disabled:_},"Back"),"integrate"!==o&&React.createElement(h.M,{className:"primary",onClick:()=>{"analyze"===o?i("optimize"):"optimize"===o&&i("integrate")},disabled:!(()=>{switch(o){case"analyze":return null!==d&&!_;case"optimize":return E.some((e=>e.enabled))&&!_;default:return!1}})()},"Continue"),"integrate"===o&&100!==v&&React.createElement(h.M,{className:"primary",onClick:()=>{0!==E.filter((e=>e.enabled)).length?window.dispatchEvent(new CustomEvent("pdf-import-upload")):O("Please select at least one chunk to upload")},disabled:_},"Upload Embeddings")),content:React.createElement(React.Fragment,null,T&&React.createElement(React.Fragment,null,React.createElement(ce.X,{variant:"danger"},T),React.createElement(le.g,null)),React.createElement("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"}},(()=>{switch(o){case"analyze":return React.createElement(Gt,{fileInputRef:N,pdfFile:c,setPdfFile:s,pdfData:d,setPdfData:m,chunks:u,setChunks:p,editableChunks:E,setEditableChunks:g,chunkingDensity:R,busy:_,setBusy:C,error:T,setError:O});case"optimize":return React.createElement(Vt,{editableChunks:E,setEditableChunks:g,chunks:u,setChunks:p,chunkingDensity:R,setChunkingDensity:y,pdfData:d,busy:_,setBusy:C,error:T,setError:O});case"integrate":return React.createElement(Kt,{editableChunks:E,uploadProgress:v,setUploadProgress:f,uploadedCount:b,setUploadedCount:w,onAddEmbedding:a,environment:n,busy:_,setBusy:C,error:T,setError:O,onComplete:()=>{setTimeout((()=>{t(null),I()}),1e3)}})}})())),contentStyle:{margin:"0 -15px",padding:"10px 15px",height:"100%",boxSizing:"border-box",display:"flex",flexDirection:"column",backgroundColor:"var(--neko-main-color)"}})},{useState:ea,useMemo:ta,useEffect:aa,useRef:na}=wp.element,la=[{accessor:"status",title:"Status",width:"90px"},{accessor:"title",title:"Title / Model",sortable:!1,width:"100%"},{accessor:"type",title:"Ref",sortable:!1,width:"90px"},{accessor:"score",title:"Score",sortable:!0,width:"75px"},{accessor:"updated",title:"Updated",sortable:!1,width:"90px"},{accessor:"actions",title:"",width:"110px"}],ra=[{accessor:"status",title:"Status",sortable:!0,width:"90px"},{accessor:"title",title:"Title / Model",sortable:!1,width:"100%"},{accessor:"type",title:"Ref",sortable:!0,width:"90px"},{accessor:"updated",title:"Updated",sortable:!0,width:"90px"},{accessor:"actions",title:"",width:"110px"}],oa=({embedding:e,envName:t,isDifferentModel:a})=>{const{colors:n}=(0,r.z)(),{status:l,content:o,error:i}=e,c=ta((()=>{if("ok"===l){if(!t)return"env_issue";if(!o)return"empty";if(a)return"warning"}return l}),[l,t,o,a]),s=ta((()=>"orphan"===c?"This embedding was retrieved from the Vector DB, but it has no content. Add some, or delete it.":"env_issue"===c?"This embedding is not related to any Embeddings Environment. Make sure you have an Embeddings Environment selected, and Sync/Refresh it; it will be linked to the current environment. You can also delete it.":"empty"===c?"This embedding has no content.":"warning"===c?"This embedding was created with a different model. Sync will update it to use the current model.":i||null),[c,i]),{icon:d,color:m}=ta((()=>{const e={outdated:{icon:"alert",color:n.orange},ok:{icon:"check-circle",color:n.green},error:{icon:"alert",color:n.red},orphan:{icon:"pencil",color:n.orange},env_issue:{icon:"database",color:n.red},empty:{icon:"alert",color:n.orange},warning:{icon:"alert",color:n.orange},default:{icon:"alert",color:n.orange}};return e[c]||e.default}),[c,n]);return React.createElement("div",{style:{display:"flex",alignItems:"center"},title:s},React.createElement(Ye.z,{icon:d,width:24,color:m,title:s}),React.createElement("span",{style:{textTransform:"uppercase",fontSize:9,marginLeft:3}},c))},ia=({options:e,updateOption:t})=>{const a=(0,l.jE)(),{colors:n}=(0,r.z)(),[i,s]=ea("post"),[d,u]=ea(!1),[p,v]=ea("edit"),[f,b]=ea(null),[_,C]=ea(""),[T,O]=ea(!1),[I,M]=ea([]),[S,k]=ea({type:null,data:null}),[A,x]=ea(null),[D,L]=ea(!1),[F,B]=ea(null),[U,H]=ea(null),j=e.embeddings||{},G=na(null),$=Ce(e,!1,!0),z=e.embeddings_envs||[],[W,q]=ea((()=>{const e=localStorage.getItem("mwai-admin-embeddings");try{const t=JSON.parse(e);return{environmentId:(null==t?void 0:t.environmentId)||null}}catch(e){return{environmentId:null}}})().environmentId),V=ta((()=>z.find((e=>e.id===W))||null),[z,W]),Y=(null==V?void 0:V.min_score)>=0?V.min_score:35,K=(null==V?void 0:V.max_select)>=0?V.max_select:10,X=ta((()=>null!=V&&V.ai_embeddings_override&&null!=V&&V.ai_embeddings_env&&null!=V&&V.ai_embeddings_model?$.getModel(V.ai_embeddings_model):$.getModel(e.ai_embeddings_default_model)),[V,j.model]),{isLoading:Q,data:J}=(0,o.I)({queryKey:["postTypes"],queryFn:rt}),{isLoading:Z,data:ee}=(0,o.I)({queryKey:["postsCount-"+i+"-"+(null==j?void 0:j.syncPostStatus)??"publish"],queryFn:()=>(async(e,t="publish")=>{const a=await be(`${w}/helpers/count_posts?postType=${e}&postStatus=${t}`,{nonce:P()});return null!=a&&a.count?parseInt(null==a?void 0:a.count):null})(i,(null==j?void 0:j.syncPostStatus)??"publish")}),[te,re]=ea({filters:{envId:W,search:f,debugMode:!1},sort:{accessor:"updated",by:"desc"},page:1,limit:20}),{isFetching:oe,data:se,error:de}=(0,o.I)({queryKey:["vectors",(0,y.F1)(te)],queryFn:()=>Ne(te),staleTime:3e5,gcTime:6e5}),me=oe||"searchVectors"===d,ue="search"===p?la:ra,pe=(0,nt.XS)({i18n:ge,onStop:()=>{u(),pe.reset()}}),Ee=d||me||pe.isBusy||Q,he=async e=>{u("updateSettings"),await t({...e},"embeddings"),u(null)},Re=ta((()=>j.syncPosts&&(null==j?void 0:j.syncPostsEnvId)!==W),[W,j]);aa((()=>{!j.syncPosts&&j.syncPostsEnvId&&he({...j,syncPostsEnvId:null})}),[j.syncPosts]);const ye=ta((()=>z.find((e=>e.id===j.syncPostsEnvId))||null),[j.syncPostsEnvId]);aa((()=>{re((e=>e.filters.envId===W&&e.filters.search===f&&e.filters.debugMode===A?e:{...e,filters:{envId:W,search:f,debugMode:A}})),(({environmentId:e})=>{const t={environmentId:e||null};localStorage.setItem("mwai-admin-embeddings",(0,y.F1)(t))})({environmentId:W})}),[W,A,f]),aa((()=>{const e="edit"===p?null:"";b(e),C(e||""),re((t=>{const a="edit"===p?"created":"score";return t.filters.search===e&&t.sort.accessor===a&&"desc"===t.sort.by&&1===t.page&&20===t.limit?t:{...t,filters:{...t.filters,search:e},sort:{accessor:a,by:"desc"},page:1,limit:20}}))}),[p]),aa((()=>{var e,t;null!=j&&null!==(e=j.syncPostTypes)&&void 0!==e&&e.length&&null!=j&&null!==(t=j.syncPostStatus)&&void 0!==t&&t.length||he({...j,syncPostTypes:["post","page","product"],syncPostStatus:["publish"]})}),[j.syncPostTypes]);const ve=ta((()=>{const e={padding:"8px 15px",textAlign:"center"};return j.syncPosts&&!ye?React.createElement(ce.X,{variant:"danger",style:e},"Pick a valid environment for the sync."):j.syncPosts?React.createElement(ce.X,{variant:"special",style:e},"Enabled on ",React.createElement("b",null,null==ye?void 0:ye.name)):React.createElement(ce.X,{variant:"info",style:e},"Disabled")}),[j]),fe=async()=>{b(_),_!==te.filters.search?re((e=>({...e,filters:{...e.filters,search:_}}))):a.invalidateQueries({queryKey:["vectors"]})},_e=async(e=T,t=!1)=>{t||u("addEmbedding");try{const t={...e};t.envId||(t.envId=V.id);const a=await(0,y.IU)(`${w}/vectors/add`,{nonce:N,method:"POST",json:{vector:t}});Ae(null==a?void 0:a.vector,!0),O(!1),console.log("Embedding Added",e)}catch(e){throw console.error(e),new Error(e.message??"Unknown error, check your console logs.")}finally{t||u(!1)}return!0},Oe=async(e=T,t)=>{t||u("addEmbedding");try{const t={...e};t.envId=V.id;const a=await(0,y.IU)(`${w}/vectors/update`,{nonce:N,method:"POST",json:{vector:t}});Ae(null==a?void 0:a.vector),O(!1),console.log("Embeddings updated.",a)}catch(e){throw console.error(e),new Error(e.message??"Unknown error, check your console logs.")}finally{t||u(!1)}return!0},Ie=async(e,t)=>{t||u("deleteEmbedding");try{await(0,y.IU)(`${w}/vectors/delete`,{nonce:N,method:"POST",json:{envId:V.id,ids:e}})}catch(t){if(console.error(t),!confirm(`Got an error from the vector database:\n\n${t.message}\n\nDo you want to force the deletion locally?`))throw new Error(t.message??"Unknown error, check your console logs.");await(0,y.IU)(`${w}/vectors/delete`,{nonce:N,method:"POST",json:{envId:V.id,ids:e,force:!0}})}finally{t||u(!1)}console.log("Embeddings deleted.",{ids:e}),a.invalidateQueries({queryKey:["vectors"]}),"search"===p&&console.error("We should update the vectors data with the deleted embeddings.")},Me=ta((()=>(null==se?void 0:se.total)||0),[se]),Se=ta((()=>{const e=se;return null!=e&&e.vectors?null==e?void 0:e.vectors.map((e=>{var t;let a=new Date(e.updated);a=new Date(a.getTime()-60*a.getTimezoneOffset()*1e3);const l=a.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"}),r=a.toLocaleTimeString("ja-JP",{hour:"2-digit",minute:"2-digit",second:"2-digit"}),o=React.createElement("span",null,l,React.createElement("br",null),r);let i=new Date(e.created);i=new Date(i.getTime()-60*i.getTimezoneOffset()*1e3);const c=i.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),s=e.score?React.createElement("span",{style:{color:e.score>Y/100?"var(--neko-green)":"inherit"}},(100*e.score.toFixed(4)).toFixed(2)):"-";let d=null;e.subType&&"string"==typeof e.subType&&(d=e.subType.toUpperCase());const m=$.getModel(e.model),u=(null==m?void 0:m.rawName)??e.model,p=e.model,E=e.model&&e.model!==(null==X?void 0:X.model),g=e.envId!==W,R=null===(t=z.find((t=>t.id===e.envId)))||void 0===t?void 0:t.name,y="ok"!==e.status||E||g;let v=null;if("error"===e.status&&e.error){let t=e.error;t.includes("Error code:")&&(t=t.split("Error code:")[0].trim(),t.endsWith(".")&&(t=t.slice(0,-1))),v=React.createElement(React.Fragment,null,React.createElement("b",{style:{color:n.red}},"Error: "),React.createElement("span",{style:{color:n.red}},t," "))}else if(E){const t=$.getModel(null==X?void 0:X.model),a=(null==t?void 0:t.rawName)||(null==t?void 0:t.name)||(null==X?void 0:X.model);v=React.createElement(React.Fragment,null,React.createElement("b",{style:{color:n.red}},"Mismatch:")," Expected ",a,", but found "),console.error(`Embeddings Model Mismatch for #${e.id}: "${e.title}". Should be "${null==X?void 0:X.model}" but "${e.model}" was found.`)}else g&&R&&(v=React.createElement("b",{style:{color:n.green}},"[ENV: ",R,"] "));return{id:e.id,type:React.createElement("small",null,e.refId?React.createElement(React.Fragment,null,"ID ",React.createElement("a",{href:`/wp-admin/post.php?post=${e.refId}&action=edit`,target:"_blank",rel:"noreferrer"},"#",e.refId),React.createElement("br",null),React.createElement("div",{style:{fontSize:"80%",marginTop:-5}},d)):"MANUAL"),score:s,title:React.createElement("div",null,React.createElement("span",null,e.title),React.createElement("div",{style:{lineHeight:"1.2",marginTop:2}},React.createElement("small",{style:{color:E||"error"===e.status?n.red:"inherit"}},v,"error"!==e.status&&React.createElement(React.Fragment,null,E?p:u,e.dimensions&&React.createElement(React.Fragment,null,", ",e.dimensions," dimensions"))))),status:React.createElement(oa,{embedding:e,envName:R,isDifferentModel:E}),updated:o,created:c,actions:React.createElement("div",null,React.createElement(h.M,{className:"primary",rounded:!0,icon:"pencil",disabled:Ee,onClick:()=>k({type:"edit",data:e})}),React.createElement(h.M,{className:"primary",rounded:!0,icon:"replay",disabled:Ee||!y,onClick:()=>ke(e.id)}),React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",disabled:Ee,onClick:()=>Ie([e.id])}))}})):[]}),[p,se,Ee]),ke=async e=>{u("syncEmbedding");try{await xe(e)}catch(e){console.error(e),alert((null==e?void 0:e.message)??e)}u(!1)},Ae=(e,t=!1)=>{a.invalidateQueries({queryKey:["vectors"]})},xe=async(e=null,t=null,a=void 0)=>{const n=await(async({vectorId:e,postId:t,envId:a},n=null)=>await be(`${w}/vectors/sync`,{nonce:P(),method:"POST",json:{vectorId:e,postId:t,envId:a},signal:n}))({vectorId:e,postId:t,envId:W},a);return n.success&&Ae(n.vector),n},Pe=async()=>{u("bulkPullAll");const e={page:1,limit:1e4,filters:{envId:W}};let t=[],n=[],l=!1;for(;!l;)try{const a=await Te(e);a.vectors.length<e.limit&&(l=!0),t=t.concat(a.vectors),e.page++}catch(e){return console.error(e),alert((null==e?void 0:e.message)??e),void u(!1)}for(console.log("Remote vectors retrieved.",{remoteVectors:t}),l=!1,e.limit=20,e.page=0;!l;){const t=await Ne(e);t.vectors.length<e.limit&&(l=!0),n=n.concat(t.vectors),e.page++}n=n.map((e=>e.dbId)),console.log("Local vectors retrieved.",{vectors:n});const r=t.filter((e=>!n.includes(e)));if(console.log("Vectors to pull from Vector DB to AI Engine.",{vectorsToPull:r}),!r.length)return u(!1),void H({type:"pull",stats:{total:0,added:0,errors:0,errorDetails:[],remoteTotal:t.length,alreadySynced:n.length}});const o={total:r.length,added:0,errors:0,errorDetails:[],remoteTotal:t.length,alreadySynced:n.length},i=r.map((e=>async t=>{try{return await(async(e,t)=>await be(`${w}/vectors/add_from_remote`,{nonce:P(),method:"POST",json:e,signal:t}))({envId:W,dbId:e},t),await a.invalidateQueries({queryKey:["vectors"]}),o.added++,{success:!0}}catch(t){return o.errors++,o.errorDetails.push({dbId:e,error:t.message}),{success:!1,error:t}}}));await pe.start(i),u(!1),H({type:"pull",stats:o}),pe.reset()},De=async(e=!1)=>{u("bulkPushAll");let t=[];const a={total:0,added:0,updated:0,upToDate:0,skipped:0,errors:0,errorDetails:[]};if(e||0===I.length){const e=await(async(e,t="publish")=>{const a=await be(`${w}/helpers/posts_ids?postType=${e}&postStatus=${t}`,{nonce:P()});return null!=a&&a.postIds?a.postIds:[]})(i,j.syncPostStatus);a.total=e.length,t=e.map((e=>async t=>{try{const n=await xe(null,e,t);if(n.success)switch(n.action){case"added":a.added++;break;case"updated":a.updated++;break;case"up-to-date":a.upToDate++;break;case"skipped":a.skipped++;break;default:n.message&&n.message.includes("no content")?a.skipped++:n.vector&&a.upToDate++}else a.errors++,n.message&&a.errorDetails.push({postId:e,error:n.message});return{success:!0}}catch(t){return a.errors++,a.errorDetails.push({postId:e,error:t.message}),{success:!1,error:t}}}))}else{const e=se.vectors.filter((e=>I.includes(e.id)));a.total=e.length,t=e.map((e=>async t=>{try{let n;if(e.refId?n=await xe(e.id,null,t):(await Oe(e,t),n={success:!0}),n.success)switch(n.action){case"added":a.added++;break;case"updated":a.updated++;break;case"up-to-date":default:a.upToDate++;break;case"skipped":a.skipped++}else a.errors++,n.message&&a.errorDetails.push({title:e.title,error:n.message});return{success:!0}}catch(t){return a.errors++,a.errorDetails.push({title:e.title,error:t.message}),{success:!1,error:t}}}))}await pe.start(t),u(!1),H({type:"push",stats:a,selectedType:e?`All ${i}s`:"Selected items"}),pe.reset()},Le=ta((()=>React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex"}},React.createElement(ae.u,{scrolldown:!0,name:"environment",style:{flex:1,marginBottom:5},disabled:Ee,value:(null==V?void 0:V.id)??null,onChange:e=>{q(e)}},z.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))),!(null!=z&&z.length)&&React.createElement(ae.j,{value:null,label:"None"}))))),[V,z,Ee]),Fe=ta((()=>null!=de&&de.message?React.createElement(ce.X,{variant:"danger",style:{margin:"5px 5px"}},React.createElement("b",null,de.message),React.createElement("br",null),React.createElement("small",null,"Check your Console Logs and PHP Error Logs for more information.")):"search"===p?ge.HELP.NO_EMBEDDINGS_RESULTS:ge.HELP.NO_EMBEDDINGS_ROWS),[p,de]);return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{fullWidth:!0,minimal:!0,style:{margin:10}},React.createElement("div",{style:{display:"flex"}},React.createElement(Qe.V,{style:{flex:1,marginRight:15}},React.createElement(Je.S,{style:{marginRight:10},disabled:Ee,onLabel:ge.EMBEDDINGS.AI_SEARCH,offLabel:ge.EMBEDDINGS.EDIT,width:110,onValue:"search",offValue:"edit",checked:"search"===p,onChange:v,onBackgroundColor:n.purple,offBackgroundColor:n.green}),"edit"===p&&React.createElement(React.Fragment,null,React.createElement(h.M,{className:"primary",disabled:!V||Ee,onClick:()=>k({type:"add",data:we})},"Add"))),React.createElement(Qe.V,{style:{flex:"auto"}},"edit"===p&&React.createElement(React.Fragment,null,I.length>0&&React.createElement(React.Fragment,null,React.createElement(h.M,{className:"primary",disabled:Ee,isBusy:"bulkPushAll"===d,onClick:()=>De(!1)},"Sync Selected"),React.createElement(h.M,{className:"danger",disabled:Ee,onClick:async()=>{confirm("Are you sure you want to delete the selected embeddings?")&&(u("deleteEmbeddings"),await Ie(I),M([]),u(!1))}},ge.COMMON.DELETE_SELECTED)),I.length>0&&React.createElement("div",{style:{display:"flex",alignItems:"center",marginLeft:10,marginRight:10}},I.length," selected"),React.createElement(at.j,{busy:pe.busy,style:{flex:"auto"},value:pe.value,max:pe.max,onStopClick:pe.stop})),"search"===p&&React.createElement("div",{style:{flex:"auto",display:"flex"}},React.createElement(ne.A,{style:{flex:"auto",marginRight:5},placeholder:"Search",disabled:!V||Ee,value:_,onChange:C,onEnter:fe,onReset:async()=>{b(""),C(""),re((e=>({...e,filters:{...e.filters,search:""}})))}}),React.createElement(h.M,{className:"primary",onClick:fe,disabled:!V||Ee||!_,isBusy:"searchVectors"===d},"Search"))))),React.createElement(E.Y,{minimal:!0,style:{flex:3}},React.createElement(R.z,{className:"primary",title:"Embeddings",action:React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",alignItems:"center"}},React.createElement(ae.u,{scrolldown:!0,name:"debugMode",style:{width:180},disabled:Ee,value:A||null,onChange:x},React.createElement(ae.j,{value:null,label:"Current Environment"}),React.createElement(ae.j,{value:"includeOrphans",label:"With Orphans"}),React.createElement(ae.j,{value:"includeAll",label:"All Envs & Orphans"})),React.createElement(h.M,{className:"secondary",style:{marginLeft:5},disabled:!V||me,onClick:()=>{a.invalidateQueries({queryKey:["vectors"]})}},ge.COMMON.REFRESH)))},React.createElement(Xe.o,{busy:Ee,sort:te.sort,onSortChange:(e,t)=>{re((a=>({...a,sort:{accessor:e,by:t}})))},emptyMessage:Fe,data:Se,columns:ue,onSelectRow:e=>{1===I.length&&I[0]===e&&M([]),M([e])},onSelect:e=>{M([...I,...e])},onUnselect:e=>{M([...I.filter((t=>!e.includes(t)))])},selectedItems:I}),React.createElement(le.g,null),"search"!==p&&React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(tt.Q,{currentPage:te.page,limit:te.limit,onCurrentPageChanged:e=>re((t=>({...t,page:e}))),total:Me,onClick:e=>{re((t=>({...t,page:e})))}}),React.createElement(h.M,{className:"primary",style:{marginLeft:5},disabled:!V,onClick:()=>{k({type:"export",data:{envId:W}})}},ge.COMMON.EXPORT)))),React.createElement(E.Y,{minimal:!0},React.createElement("div",{style:{margin:8}},React.createElement(c.s,{h2:!0,style:{color:"white",marginBottom:10}},"Settings"),React.createElement(g._,{inversed:!0},React.createElement(g.V,{title:"Environment"},React.createElement("div",{style:{padding:"10px 0"}},Le,React.createElement("div",{style:{display:"flex",marginTop:10}},React.createElement("div",{style:{flex:1,marginRight:5}},React.createElement("label",null,"Minimum Score:"),React.createElement("br",null),React.createElement("span",{style:{color:"var(--neko-green)"}},Y,"%")),React.createElement("div",{style:{flex:1,marginLeft:5}},React.createElement("label",null,"Max Embedding(s):"),React.createElement("br",null),React.createElement("span",{style:{color:"var(--neko-green)"}},K))),React.createElement("p",null,"The best ",K," embedding(s) with a score of ",Y," or more will provide additional context."))),React.createElement(g.V,{title:"Settings"},React.createElement("div",{style:{padding:"10px 0"}},React.createElement("div",{style:{marginBottom:10}},React.createElement("label",null,"Min Score (%)"),React.createElement(ne.A,{type:"number",value:void 0!==(null==V?void 0:V.min_score)?V.min_score:35,min:0,max:100,disabled:!V||Ee||D,onFinalChange:async e=>{if(V){L(!0);try{const a=z.map((t=>t.id===W?{...t,min_score:parseInt(e)||0}:t));await t(a,"embeddings_envs")}finally{L(!1)}}}})),React.createElement("div",null,React.createElement("label",null,"Max Results"),React.createElement(ne.A,{type:"number",value:void 0!==(null==V?void 0:V.max_select)?V.max_select:10,min:1,max:100,disabled:!V||Ee||D,onFinalChange:async e=>{if(V){L(!0);try{const a=z.map((t=>t.id===W?{...t,max_select:parseInt(e)||1}:t));await t(a,"embeddings_envs")}finally{L(!1)}}}})))))),"search"!==p&&React.createElement("div",{style:{margin:"20px 8px 8px 8px"}},React.createElement(c.s,{h2:!0,style:{color:"white",marginBottom:10}},ge.EMBEDDINGS.SYNC_POSTS),React.createElement(g._,{inversed:!0},React.createElement(g.V,{title:"Push",inversed:!0},React.createElement(le.g,{line:!0}),React.createElement("div",{style:{display:"flex",alignItems:"center"}},React.createElement(ae.u,{id:"postType",scrolldown:!0,disabled:Ee,name:"postType",style:{width:100},onChange:s,value:i},null==J?void 0:J.map((e=>React.createElement(ae.j,{key:e.type,value:e.type,label:e.name})))),React.createElement(h.M,{fullWidth:!0,className:"primary",style:{marginLeft:10},disabled:!V||Ee,isBusy:"bulkPushAll"===d,onClick:()=>De(!0)},ge.EMBEDDINGS.SYNC_ALL," ",!Z&&React.createElement(React.Fragment,null,"(",`${ee}`,")"))),React.createElement(le.g,{tiny:!0}),React.createElement(h.M,{fullWidth:!0,className:"primary",disabled:!V||Ee,isBusy:"singleRun"===d,onClick:async()=>{const e=prompt("Enter the Post ID to synchronize with:");if(e){u("singleRun");try{await xe(null,e)}catch(e){console.error(e),alert((null==e?void 0:e.message)??e)}u(!1)}}},ge.EMBEDDINGS.SYNC_ONE)),React.createElement(g.V,{title:"Pull",inversed:!0},React.createElement(h.M,{fullWidth:!0,className:"primary",disabled:!V||Ee,isBusy:"bulkPullAll"===d,onClick:()=>Pe()},ge.EMBEDDINGS.SYNC_ALL)),React.createElement(g.V,{title:"Settings",inversed:!0},React.createElement(m.R,{label:ge.EMBEDDINGS.REWRITE_CONTENT,disabled:d,checked:j.rewriteContent,onChange:e=>{he({...j,rewriteContent:e})},description:ge.EMBEDDINGS.REWRITE_CONTENT_DESCRIPTION}),j.rewriteContent&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement(Ke.m,{value:j.rewritePrompt,rows:5,disabled:d,onBlur:e=>{he({...j,rewritePrompt:e})},description:ge.EMBEDDINGS.REWRITE_PROMPT_DESCRIPTION}),React.createElement(le.g,null)),React.createElement(m.R,{label:ge.EMBEDDINGS.FORCE_RECREATE,checked:j.forceRecreate,disabled:d,onChange:e=>{he({...j,forceRecreate:e})},description:ge.EMBEDDINGS.FORCE_RECREATE_DESCRIPTION}),React.createElement(le.g,null),React.createElement(h.M,{className:"danger",fullWidth:!0,icon:"trash",disabled:!V||d,isBusy:"deleteAllEmbeddings"===d,onClick:async()=>{if(V&&confirm(ge.EMBEDDINGS.DELETE_ALL_EMBEDDINGS_CONFIRM+`\n\n${V.name}`)){u("deleteAllEmbeddings");try{await(0,y.IU)(`${w}/vectors/delete_all`,{nonce:N,method:"POST",json:{envId:W}}),a.invalidateQueries({queryKey:["vectors"]})}catch(e){alert((null==e?void 0:e.message)??e)}u(!1)}}},"deleteAllEmbeddings"===d?"Deleting...":ge.EMBEDDINGS.DELETE_ALL_EMBEDDINGS)))),"search"!==p&&React.createElement("div",{style:{margin:"20px 8px 8px 8px"}},React.createElement(c.s,{h2:!0,style:{color:"white",marginBottom:10}},ge.EMBEDDINGS.AUTO_SYNC_POSTS),React.createElement(g._,{inversed:!0},React.createElement(g.V,{title:"Status",inversed:!0},ve),React.createElement(g.V,{title:"Settings",inversed:!0},ve,V&&Re&&React.createElement(React.Fragment,null,React.createElement(le.g,{tiny:!0}),React.createElement(ce.X,{variant:"danger",style:{padding:"10px 20px",marginBottom:5}},"The currently selected environment is not used for Auto-Sync. Do you want to use this one?"),React.createElement(h.M,{fullWidth:!0,className:"primary",disabled:Ee,onClick:()=>he({...j,syncPostsEnvId:W}),style:{flex:1}},"Use Current Environment"),React.createElement(le.g,{tiny:!0})),React.createElement(le.g,{tiny:!0}),React.createElement(m.R,{label:ge.EMBEDDINGS.AUTO_SYNC_POSTS,checked:j.syncPosts,disabled:d,onChange:e=>{he({...j,syncPosts:e})},description:ge.EMBEDDINGS.AUTO_SYNC_POSTS_DESCRIPTION}),j.syncPosts&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement(ne.A,{name:"syncPostTypes",value:j.syncPostTypes,isCommaSeparatedArray:!0,description:ge.HELP.POST_TYPES,onBlur:e=>{he({...j,syncPostTypes:e})}}),React.createElement(le.g,null),React.createElement(ne.A,{name:"syncPostStatus",value:j.syncPostStatus||"publish",isCommaSeparatedArray:!0,description:ge.HELP.POST_STATUS,onBlur:e=>{he({...j,syncPostStatus:e})}}),React.createElement(le.g,null),React.createElement(ne.A,{name:"syncPostCategories",value:j.syncPostCategories||"publish",isCommaSeparatedArray:!0,description:ge.HELP.POST_CATEGORIES,onBlur:e=>{he({...j,syncPostCategories:e})}}))))),"search"!==p&&React.createElement("div",{style:{margin:"20px 8px 8px 8px"}},React.createElement(c.s,{h2:!0,style:{color:"white",marginBottom:10}},"Import Data"),React.createElement(le.g,null),React.createElement(R.z,{className:"primary",style:{margin:"-20px -10px -10px -10px"}},React.createElement(Ze.Z,{ref:G,onSelectFiles:async e=>{for(let t=0;t<e.length;t++){const a=e[t],n=new FileReader,l=a.name.endsWith(".json"),r=a.name.endsWith(".jsonl"),o=a.name.endsWith(".csv");l||r||o?(n.onerror=()=>{B({title:"File Read Error",message:`Failed to read the file: ${a.name}`,details:"Please check if the file is accessible and not corrupted."})},n.onload=async e=>{try{const t=e.target.result;let n=[],i=[];if(l)try{if(n=JSON.parse(t),!Array.isArray(n))throw new Error("JSON file must contain an array of objects")}catch(e){return void B({title:"Invalid JSON Format",message:`Failed to parse JSON file: ${a.name}`,details:e.message,help:'Ensure your JSON file contains an array of objects with \'title\' and \'content\' fields.\n\nExample:\n[\n  {"title": "Example Title", "content": "Example content"},\n  {"title": "Another Title", "content": "More content"}\n]'})}else if(r){const l=t.split("\n").filter((e=>e.trim()));for(let t=0;t<l.length;t++){const a=l[t].trim();if(a)try{const e=JSON.parse(a);e&&n.push(e)}catch(e){i.push(`Line ${t+1}: ${e.message}`)}}if(i.length>0&&(B({title:"JSONL Parse Errors",message:`Failed to parse some lines in JSONL file: ${a.name}`,details:i.slice(0,5).join("\n")+(i.length>5?`\n...and ${i.length-5} more errors`:""),help:'Each line in a JSONL file must be a valid JSON object with \'title\' and \'content\' fields.\n\nExample line:\n{"title": "Example Title", "content": "Example content"}'}),0===n.length))return}else if(o){const e=Ve().parse(t,{header:!0,skipEmptyLines:!0});if(e.errors.length>0){const t=e.errors.slice(0,5).map((e=>`Row ${e.row||"unknown"}: ${e.message}`)).join("\n");if(B({title:"CSV Parse Errors",message:`Failed to parse CSV file: ${a.name}`,details:t+(e.errors.length>5?`\n...and ${e.errors.length-5} more errors`:""),help:'Ensure your CSV file has headers including \'title\' and \'content\' columns.\n\nExample CSV format:\ntitle,content\n"Example Title","Example content"\n"Another Title","More content"'}),0===e.data.length)return}if(n=e.data,n.length>0){const e=Object.keys(n[0]);if(!e.includes("title")||!e.includes("content"))return void B({title:"Missing Required Columns",message:"CSV file must have 'title' and 'content' columns",details:`Found columns: ${e.join(", ")}`,help:"The first row of your CSV must contain column headers, including 'title' and 'content'.\n\nOptional columns: 'type', 'refId', 'refUrl'"})}}if(!Array.isArray(n)||0===n.length)return void B({title:"No Data Found",message:"The file appears to be empty or contains no valid data",details:`File: ${a.name}`,help:"Please ensure your file contains at least one record with 'title' and 'content' fields."});const c=[],s=[];if(n.forEach(((e,t)=>{var a,n;if(!e||"object"!=typeof e)return void s.push(`Row ${t+1}: Invalid data structure`);const l=null===(a=e.title)||void 0===a?void 0:a.toString().trim(),r=null===(n=e.content)||void 0===n?void 0:n.toString().trim();l||r?l?r?c.push({title:l,content:r,type:e.type||null,refId:e.refId||null,refUrl:e.refUrl||null}):s.push(`Row ${t+1}: Missing content`):s.push(`Row ${t+1}: Missing title`):s.push(`Row ${t+1}: Both title and content are empty`)})),0===c.length)return void B({title:"No Valid Entries",message:"No entries with both title and content were found",details:s.slice(0,5).join("\n")+(s.length>5?`\n...and ${s.length-5} more issues`:""),help:"Each entry must have both a 'title' and 'content' field with non-empty values."});s.length>0&&console.warn("Import validation issues:",s),k({type:"import",data:{importVectors:c,envId:W,totalEntries:n.length,validEntries:c.length,invalidEntries:s.length}})}catch(e){console.error("Import error:",e),B({title:"Import Failed",message:"An unexpected error occurred while processing the file",details:e.message,help:"Please check the file format and try again. If the problem persists, check the browser console for more details."})}},n.readAsText(a)):B({title:"Unsupported File Type",message:`Only JSON, JSONL, and CSV files are supported. You provided: ${a.name}`,details:"Please ensure your file has one of these extensions: .json, .jsonl, or .csv"})}},accept:""},React.createElement(h.M,{fullWidth:!0,className:"secondary",disabled:!V||Ee,onClick:()=>G.current.click()},"From CSV or JSON")),React.createElement(le.g,{tiny:!0}),React.createElement(h.M,{fullWidth:!0,className:"secondary",disabled:!V||Ee,onClick:()=>k({type:"pdf-import"})},"From PDF"))))),React.createElement(Pt,{modal:S,setModal:k,busy:d,onAddEmbedding:_e,onModifyEmbedding:Oe}),React.createElement(Ft,{modal:S,setModal:k,busy:d}),React.createElement(Ut,{modal:S,setModal:k,busy:d,onAddEmbedding:_e,onModifyEmbedding:Oe}),React.createElement(Zt,{modal:S,setModal:k,onAddEmbedding:_e,environment:V}),pe.TasksErrorModal,React.createElement(ie.n,{isOpen:!!F,title:(null==F?void 0:F.title)||"Import Error",onRequestClose:()=>B(null),okButton:{label:"Close",onClick:()=>B(null)},content:React.createElement("div",null,React.createElement("p",{style:{marginBottom:10}},null==F?void 0:F.message),(null==F?void 0:F.details)&&React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:10,borderRadius:4,marginBottom:10,fontFamily:"monospace",fontSize:"12px",whiteSpace:"pre-wrap",maxHeight:"150px",overflowY:"auto"}},F.details),(null==F?void 0:F.help)&&React.createElement("div",{style:{backgroundColor:"#e8f4f8",padding:10,borderRadius:4,fontSize:"13px",whiteSpace:"pre-wrap"}},React.createElement("strong",null,"Help:"),React.createElement("br",null),F.help))}),React.createElement(ie.n,{isOpen:!!U,title:"push"===(null==U?void 0:U.type)?"Sync Complete":"Pull Complete",onRequestClose:()=>H(null),okButton:{label:"Close",onClick:()=>H(null)},content:U&&React.createElement("div",null,React.createElement("div",{style:{backgroundColor:U.stats.errors>0?"#fff8e6":"#e8f5e9",padding:15,borderRadius:8,marginBottom:20,textAlign:"center"}},React.createElement(c.s,{h3:!0,style:{marginBottom:10,color:U.stats.errors>0?n.orange:n.green}},U.stats.errors>0?"⚠️ Sync Completed with Warnings":"✅ All Done"),React.createElement("p",{style:{fontSize:"14px",marginBottom:0}},"push"===U.type?`${U.stats.updated} updated, ${U.stats.added} added, ${U.stats.upToDate} up-to-date`:`Successfully pulled ${U.stats.added} embeddings from the vector database`)),React.createElement("div",{style:{display:"grid",gridTemplateColumns:"pull"===U.type?"1fr 1fr":"1fr 1fr 1fr 1fr",gap:10,marginBottom:20}},"push"===U.type?React.createElement(React.Fragment,null,React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:15,borderRadius:6,textAlign:"center"}},React.createElement("div",{style:{fontSize:"24px",fontWeight:"bold",color:n.green}},U.stats.updated),React.createElement("div",{style:{fontSize:"12px",color:"#666",marginTop:5}},"Updated")),React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:15,borderRadius:6,textAlign:"center"}},React.createElement("div",{style:{fontSize:"24px",fontWeight:"bold",color:n.blue}},U.stats.added),React.createElement("div",{style:{fontSize:"12px",color:"#666",marginTop:5}},"Added")),React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:15,borderRadius:6,textAlign:"center"}},React.createElement("div",{style:{fontSize:"24px",fontWeight:"bold",color:n.lightGray}},U.stats.upToDate),React.createElement("div",{style:{fontSize:"12px",color:"#666",marginTop:5}},"Up to Date")),React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:15,borderRadius:6,textAlign:"center"}},React.createElement("div",{style:{fontSize:"24px",fontWeight:"bold",color:U.stats.errors>0?n.red:n.lightGray}},U.stats.errors),React.createElement("div",{style:{fontSize:"12px",color:"#666",marginTop:5}},"Errors"))):React.createElement(React.Fragment,null,React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:15,borderRadius:6,textAlign:"center"}},React.createElement("div",{style:{fontSize:"24px",fontWeight:"bold",color:n.green}},U.stats.added),React.createElement("div",{style:{fontSize:"12px",color:"#666",marginTop:5}},"Pulled")),React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:15,borderRadius:6,textAlign:"center"}},React.createElement("div",{style:{fontSize:"24px",fontWeight:"bold",color:n.lightGray}},U.stats.alreadySynced),React.createElement("div",{style:{fontSize:"12px",color:"#666",marginTop:5}},"Already Synced")))),U.stats.errors>0&&React.createElement("div",{style:{backgroundColor:"#ffebee",padding:15,borderRadius:6,marginBottom:15}},React.createElement("div",{style:{display:"flex",alignItems:"center",marginBottom:10}},React.createElement(Ye.z,{icon:"alert",color:n.red,width:20}),React.createElement("span",{style:{marginLeft:8,fontWeight:"bold",color:n.red}},U.stats.errors," Error",U.stats.errors>1?"s":"")),U.stats.errorDetails.length>0&&React.createElement("div",{style:{maxHeight:"120px",overflowY:"auto",fontSize:"12px",backgroundColor:"#fff",padding:10,borderRadius:4,border:"1px solid #ffcdd2"}},U.stats.errorDetails.slice(0,5).map(((e,t)=>React.createElement("div",{key:t,style:{marginBottom:5}},React.createElement("strong",null,e.postId?`Post #${e.postId}`:e.title||`Item ${t+1}`,":")," ",e.error))),U.stats.errorDetails.length>5&&React.createElement("div",{style:{marginTop:10,color:"#666"}},"...and ",U.stats.errorDetails.length-5," more errors"))),"pull"===U.type&&React.createElement("div",{style:{fontSize:"13px",color:"#666",marginTop:15,padding:10,backgroundColor:"#f9f9f9",borderRadius:4}},React.createElement(Ye.z,{icon:"info",width:16,style:{marginRight:5,verticalAlign:"middle"}}),`${U.stats.remoteTotal} total embeddings found in the vector database.`))}))};var ca=a(2262),sa=a(4731);const{useState:da,useMemo:ma,Fragment:ua}=wp.element;ca.t1.register(ca.PP,ca.kc,ca.E8,ca.m_,ca.s$);const pa=({month:e,usageData:t,groupBy:a,metric:n})=>0===t[e].length?React.createElement("div",{style:{width:"calc(100% - 36px)",margin:"5px 18px 0px 18px",fontStyle:"italic"}},"No data available."):"queries"===n?React.createElement("table",{style:{width:"calc(100% - 36px)",margin:"5px 18px 0px 18px",borderCollapse:"collapse"}},React.createElement("tbody",null,t[e].map(((e,t)=>{const n=e.queries?e.queries.toLocaleString():"0";if("family"===a&&e.models&&e.models.length>0)return React.createElement(ua,{key:t},React.createElement("tr",{style:{fontWeight:"bold"}},React.createElement("td",{style:{paddingRight:10}},e.name),React.createElement("td",{style:{textAlign:"right",paddingRight:10}},n),React.createElement("td",{style:{textAlign:"right"}},"Queries")),e.models.map(((e,a)=>React.createElement("tr",{key:`${t}-${a}`,style:{fontSize:"0.9em",opacity:.8}},React.createElement("td",{style:{paddingRight:10,paddingLeft:20}},"↳ ",e.modelId||e.rawName),React.createElement("td",{style:{textAlign:"right",paddingRight:10}},e.queries?e.queries.toLocaleString():"0"),React.createElement("td",{style:{textAlign:"right"}},"Queries")))));const l="Unknown Model"===e.name?`⚠️ ${e.rawName}`:"model"===a&&e.modelId?e.modelId:e.name;return React.createElement("tr",{key:t},React.createElement("td",{style:{paddingRight:10}},l),React.createElement("td",{style:{textAlign:"right",paddingRight:10}},n),React.createElement("td",{style:{textAlign:"right"}},"queries"))})))):React.createElement("table",{style:{width:"calc(100% - 36px)",margin:"5px 18px 0px 18px",borderCollapse:"collapse"}},React.createElement("tbody",null,t[e].map(((e,t)=>{const n=e.isImage?"images":e.isAudio?"seconds":"tokens",l=e.units.toLocaleString();if("family"===a&&e.models&&e.models.length>0)return React.createElement(ua,{key:t},React.createElement("tr",{style:{fontWeight:"bold"}},React.createElement("td",{style:{paddingRight:10}},e.name),React.createElement("td",{style:{textAlign:"right",paddingRight:10}},l),React.createElement("td",{style:{paddingRight:10}},n),React.createElement("td",{style:{textAlign:"right"}},e.price>0?`${e.price.toFixed(4)}$`:"-")),e.models.map(((e,a)=>React.createElement("tr",{key:`${t}-${a}`,style:{fontSize:"0.9em",opacity:.8}},React.createElement("td",{style:{paddingRight:10,paddingLeft:20}},"↳ ",e.modelId||e.rawName),React.createElement("td",{style:{textAlign:"right",paddingRight:10}},e.units.toLocaleString()),React.createElement("td",{style:{paddingRight:10}},e.isImage?"images":e.isAudio?"seconds":"tokens"),React.createElement("td",{style:{textAlign:"right"}},e.price>0?`${e.price.toFixed(4)}$`:"-")))));const r="Unknown Model"===e.name?`⚠️ ${e.rawName}`:"model"===a&&e.modelId?e.modelId:e.name;return React.createElement("tr",{key:t},React.createElement("td",{style:{paddingRight:10}},r),React.createElement("td",{style:{textAlign:"right",paddingRight:10}},l),React.createElement("td",{style:{paddingRight:10}},n),React.createElement("td",{style:{textAlign:"right"}},e.price>0?`${e.price.toFixed(4)}$`:"-"))})))),Ea=({options:e})=>{const{models:t,getModel:a,calculatePrice:n}=Ce(e,null,!0),l=null==e?void 0:e.ai_models_usage,o=null==e?void 0:e.ai_models_usage_daily,{colors:i}=(0,r.z)(),[c,s]=da("family"),[d,m]=da("price"),[u,p]=da("daily"),E=ma((()=>{const e={},t="daily"===u?o||{}:l||{};return Object.keys(t).forEach((l=>{const r=t[l];e[l]||(e[l]=[]);const o={};Object.keys(r).forEach((e=>{const t=r[e],l=a(e);let i=null,s=null,d=!1,m=!1;l?"image"===l.type?(s=(null==t?void 0:t.images)||0,m=!0):"second"===l.type?(s=(null==t?void 0:t.seconds)||0,d=!0):(i=(null==t?void 0:t.prompt_tokens)||0,s=(null==t?void 0:t.completion_tokens)||0):(i=(null==t?void 0:t.prompt_tokens)||0,s=(null==t?void 0:t.completion_tokens)||0);const u=l?n(e,i,s):0,p=m?s:i+s,E=(null==t?void 0:t.queries)||0,g="family"===c&&null!=l&&l.family?l.family:e,h="family"===c&&null!=l&&l.family?l.family:l?l.rawName:"Unknown Model";o[g]||(o[g]={name:h,rawName:e,modelId:e,units:0,price:0,queries:0,isImage:m,isAudio:d,family:l?l.family:null,models:[]}),o[g].units+=p,o[g].price+=u,o[g].queries+=E,"family"===c&&null!=l&&l.family&&o[g].models.push({name:l.rawName,rawName:e,modelId:e,units:p,price:u,queries:E,isImage:m,isAudio:d})})),e[l]=Object.values(o),e[l].sort(((e,t)=>t.price-e.price))})),e}),[l,o,t,u,c]),g=ma((()=>{const e=new Date,t={};if("daily"===u)for(let a=29;a>=0;a--){const n=new Date(e);n.setDate(n.getDate()-a);const l=`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`;t[l]=E[l]||[]}else{const a=Object.keys(E).sort();let n=e;if(a.length>0){const[e,t]=a[0].split("-");n=new Date(e,t-1,1)}const l=new Date(e.getFullYear(),e.getMonth()-11,1),r=new Date(n<l?n:l);for(;r.getFullYear()<e.getFullYear()||r.getFullYear()===e.getFullYear()&&r.getMonth()<=e.getMonth();){const e=`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,"0")}`;t[e]=E[e]||[],r.setMonth(r.getMonth()+1)}}return t}),[E,u]),h=ma((()=>{const e=Object.keys(g).sort(),a=[],n=[i.blue,i.green,i.yellow,i.orange,i.red,i.purple];if("model"===c){t.forEach(((t,l)=>{const r=t.model,o=t.rawName,i=e.map((e=>{var t;const a=null===(t=g[e])||void 0===t?void 0:t.find((e=>e.modelId===r||e.rawName===r));return"tokens"===d?a?Math.max(a.units,1):0:"queries"===d?a&&a.queries||0:a?Math.max(a.price,.01):0}));i.some((e=>e>0))&&a.push({label:o,data:i,backgroundColor:n[l%n.length]})}));const l=e.map((e=>{var t;const a=null===(t=g[e])||void 0===t?void 0:t.filter((e=>"Unknown Model"===e.name));return"tokens"===d?a.reduce(((e,t)=>e+Math.max(t.units,1)),0):"queries"===d?a.reduce(((e,t)=>e+(t.queries||0)),0):a.reduce(((e,t)=>e+Math.max(t.price,.01)),0)}));l.some((e=>e>0))&&a.push({label:"Unknown Model",data:l,backgroundColor:"rgba(128, 128, 128, 0.5)"})}else if("family"===c){const t={};e.forEach((a=>{(g[a]||[]).forEach((n=>{const l=n.name;if(l){let r;t[l]||(t[l]=Array(e.length).fill(0)),r="tokens"===d?Math.max(n.units,1):"queries"===d?n.queries||0:Math.max(n.price,.01);const o=e.indexOf(a);t[l][o]+=r}}))})),Object.keys(t).forEach(((e,l)=>{a.push({label:e,data:t[e],backgroundColor:n[l%n.length]})}))}return{labels:e,datasets:a}}),[g,t,c,d,i]),R=ma((()=>{const e={};h.datasets.forEach((t=>{const a=t.label;e[a]||(e[a]=0),t.data.forEach((t=>{e[a]+=t}))}));const t=Object.entries(e).sort((([,e],[,t])=>t-e)).slice(0,8).map((([e])=>e));return h.datasets.filter((e=>t.includes(e.label)))}),[h]),y={plugins:{legend:{position:"bottom",labels:{filter:e=>R.some((t=>t.label===e.text))}}},responsive:!0,scales:{x:{stacked:!0},y:{stacked:!0}}};return React.createElement(React.Fragment,null,l&&0===Object.keys(l).length&&React.createElement("div",{style:{fontStyle:"italic"}},"No data available."),l&&Object.keys(l).length>0&&React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flexWrap:"wrap"}},React.createElement("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap"}},React.createElement(oe.o,{name:"metric",value:d,onChange:m},React.createElement(oe.K,{title:"Price",value:"price"}),React.createElement(oe.K,{title:"Units",value:"tokens"}),React.createElement(oe.K,{title:"Queries",value:"queries"})),React.createElement(oe.o,{name:"groupBy",value:c,onChange:s},React.createElement(oe.K,{title:"Family",value:"family"}),React.createElement(oe.K,{title:"Model",value:"model"}))),React.createElement(oe.o,{name:"viewMode",value:u,onChange:p},React.createElement(oe.K,{title:"Daily",value:"daily"}),React.createElement(oe.K,{title:"Monthly",value:"monthly"}))),React.createElement(le.g,{size:"medium"}),React.createElement(sa.yP,{options:y,data:h}),React.createElement(le.g,{size:"medium"}),React.createElement(et.Zc,{keepState:"monthlyUsageCategories"},Object.keys(g).sort().reverse().filter((e=>{const t=new Date,a=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`,n=t.toISOString().split("T")[0];return"monthly"===u&&e===a||("daily"===u&&e===n||g[e].length>0)})).map(((e,t)=>{const a=g[e]||[],n="daily"===u,l=n?"📅":"🗓️";let r;if("queries"===d){r=`${a.reduce(((e,t)=>e+(t.queries||0)),0).toLocaleString()} Queries`}else{r=`${a.reduce(((e,t)=>e+t.price),0).toFixed(2)}$`}let o=e;if(n){o=new Date(e+"T00:00:00").toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}return React.createElement(et.y2,{key:t,title:`${l} ${o} (${r})`},React.createElement(pa,{month:e,usageData:g,groupBy:c,metric:d}))}))),React.createElement(le.g,{size:"medium"}),React.createElement("div",{style:{fontSize:"var(--neko-small-font-size)",color:"var(--neko-gray-60)"}},ge.COMMON.USAGE_ESTIMATES_NOTE)))};var ga=a(6841);const{useState:ha}=wp.element;function Ra(e,t){const a=new Blob([e],{type:"text/plain;charset=utf-8;"}),n=document.createElement("a");n.href=URL.createObjectURL(a),n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}const ya=({modal:e,setModal:t})=>{const[a,n]=ha(!1),[l,r]=ha(0),[o,i]=ha(0),c=async()=>{let e=!1;const t={page:1,limit:20,filters:{}};let a=[];for(;!e;){const n=await Oe(t);n.chats.length<2&&(e=!0),r((()=>n.total)),n.chats.forEach((e=>{e.messages=JSON.parse(e.messages),e.extra=JSON.parse(e.extra)})),a=a.concat(n.chats),i((()=>a.length)),t.page++}return a};return React.createElement(React.Fragment,null,React.createElement(ie.n,{isOpen:"export"===(null==e?void 0:e.type),title:"Export Discussions",onRequestClose:()=>t(null),okButton:{label:"Close",disabled:a,onClick:()=>t(null)},customButtons:React.createElement(React.Fragment,null,React.createElement(h.M,{onClick:async()=>{try{n(!0);const e=await c(),t=(0,y.F1)(e,2),a=new Date,l=a.getFullYear(),o=a.getMonth()+1;Ra(t,`discussions-${l}-${o}-${a.getDate()}.json`),setTimeout((()=>{r(0)}),1e3)}catch(e){console.error(e),alert("An error occurred while exporting discussions. Check your console.")}finally{n(!1)}},disabled:a},"Export JSON")),content:React.createElement(React.Fragment,null,React.createElement(at.j,{busy:a,style:{flex:"auto"},value:o,max:l}))}))},{useMemo:va,useState:fa,useEffect:ba,useCallback:wa}=wp.element,_a=L.Ay.div`
  font-size: 12px;
  border-bottom: 1px solid black;
`,Ca=L.Ay.span`
  font-weight: bold;
  text-transform: uppercase;
`,Ta=L.Ay.div`
  font-size: 12px;
  color: #bdb8b8;
  background: #eeeeee;
  padding: 2px 8px;
`,Oa=L.Ay.div`
  font-size: 14px;
  padding: 10px;
  border: 1px solid #eaeaea;
  background: #f5f5f5;
  color: #333333;
  word-break: break-word;
  overflow-wrap: break-word;
  word-wrap: break-word;
  hyphens: auto;

  img {
    max-width: 100%;
    height: auto;
  }

  a {
    color: #333333;
    text-decoration: underline;
  }

  a:hover {
    color: #333333;
    text-decoration: none;
  }

  blockquote {
    border-left: 4px solid #dddddd;
    padding-left: 10px;
    margin-left: 0;
    font-style: italic;
  }

  pre {
    background: #eeeeee;
    padding: 10px;
    border-radius: 5px;
    overflow-x: auto;
    text-wrap: pretty;
  }

  code {
    background: #eeeeee;
    padding: 2px 5px;
    border-radius: 5px;
  }

  table {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 10px;
  }
  
  table td, table th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 5px;
  }

  table tr:nth-child(even) {
    background-color: #dddddd;
  }

  .mwai-dead-image {
    color: #ab5252;
    background: #ffd2d2;
    padding: 8px 8px;
    text-align: center;
  }
`,Na={overrides:{object:{component:({children:e,...t})=>`<object ${Object.keys(t).map((e=>`${e}="${t[e]}"`)).join(" ")}>${e}</object>`},script:{component:({children:e,...t})=>`<script ${Object.keys(t).map((e=>`${e}="${t[e]}"`)).join(" ")}>${e}<\/script>`},iframe:{component:({children:e,...t})=>`<iframe ${Object.keys(t).map((e=>`${e}="${t[e]}"`)).join(" ")}>${e}</iframe>`}}},Ia=({content:e})=>{const[t,a]=fa(e||""),n=e=>new Promise((t=>{const a=new Image;a.onload=()=>t(!0),a.onerror=()=>t(!1),a.src=e}));ba((()=>{e&&(async e=>{const t=/!\[.*?\]\((.*?)\)/g;let l,r=e;for(;null!==(l=t.exec(e));){const e=l[1];if(!await n(e)){const e='<div class="mwai-dead-image">Image not available</div>';r=r.replace(l[0],e)}}a(r)})(e)}),[e]);const l=va((()=>{let e="";try{e=(0,ga.cx)(t,Na)}catch(a){console.error("Crash in markdown-to-jsx! Reverting to plain text.",{e:a,processedContent:t}),e=t}return e}),[t]);return React.createElement(Oa,null,l)},Ma=({message:e})=>{var t,a,n,l;const r=null!=e&&null!==(t=e.extra)&&void 0!==t&&t.embeddings?null==e||null===(a=e.extra)||void 0===a?void 0:a.embeddings:null!=e&&null!==(n=e.extra)&&void 0!==n&&n.embedding?[null==e||null===(l=e.extra)||void 0===l?void 0:l.embedding]:[];return React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement(_a,null,React.createElement(Ca,null,e.role||e.type)),(null==r?void 0:r.length)>0&&React.createElement(Ta,null,r.map((e=>React.createElement("div",{key:r.id},React.createElement("span",null,e.title)," (",React.createElement("span",null,(100*e.score.toFixed(4)).toFixed(2)),")")))),React.createElement(Ia,{content:e.content||e.text}))},Sa=async(e=[])=>await be(`${w}/discussions/delete`,{nonce:P(),method:"POST",json:{chatIds:e}}),ka=()=>{var e,t,a,n,r,i,c,s,d,u,p;const g=(0,l.jE)(),[y,v]=fa({type:null,data:null}),[f,b]=fa(!1),[w,_]=fa(!1),{data:C}=(0,o.I)({queryKey:["chatbots"],queryFn:st,initialData:A}),T=va((()=>[{accessor:"updated",title:"Time",width:"95px",sortable:!0},{accessor:"user",title:"User",width:"100px",filters:{type:"text",description:ge.HELP.USER_FILTER}},{accessor:"botId",title:"Chatbot",width:"100px",filters:{type:"select",options:C.map((e=>({value:e.botId,label:e.name})))}},{accessor:"preview",title:ge.COMMON.PREVIEW,width:"100%",filters:{type:"text"}},{accessor:"messages",title:"#",width:"45px"}]),[C]),[O,N]=fa((()=>T.filter((e=>e.filters)).map((e=>({accessor:e.accessor,value:null}))))),[I,M]=fa([]),[S,k]=fa({filters:O,sort:{accessor:"updated",by:"desc"},page:1,limit:10}),x=wa((async()=>!document.hidden?await Oe(S):new Promise((()=>{}))),[S]),{isFetching:P,data:D,error:L}=(0,o.I)({queryKey:["chats",JSON.stringify(S)],queryFn:x,refetchInterval:w?5e3:null});ba((()=>{k({...S,filters:O})}),[O]);const F=va((()=>(null==D?void 0:D.total)||0),[D]),B=va((()=>null!=D&&D.chats?D.chats.sort(((e,t)=>new Date(t.updated)-new Date(e.updated))).map((e=>{const t=JSON.parse(e.messages),a=JSON.parse(e.extra),n=Ie(e.created),l=Ie(e.updated),r=Me(e.userId??(null==a?void 0:a.userId),e.ip??(null==a?void 0:a.ip)),o=null==t?void 0:t.filter((e=>"user"===e.role||"user"===e.type)),i=null!=o&&o.length?o[0].content||o[0].text:"",c=null!=o&&o.length?o[o.length-1].content||o[o.length-1].text:"",s=C.find((t=>t.botId===e.botId)),d=null==a?void 0:a.parentBotId,m=d?C.find((e=>e.botId===d)):null;let u,p=null;s?u=s.name:m?(u=m.name,p=React.createElement(Ye.z,{icon:"tools",height:"14",style:{position:"relative",top:2,marginRight:2},tooltip:"Overriden Bot"})):u=React.createElement(React.Fragment,null,React.createElement(Ye.z,{icon:"cog",height:"14",style:{position:"relative",top:2,marginRight:2},tooltip:"Custom Bot"}),"Custom");const E=e.title?React.createElement(React.Fragment,null,React.createElement("div",null,e.title),React.createElement("small",null,React.createElement("i",null,i))):React.createElement(React.Fragment,null,React.createElement("div",null,i),React.createElement("small",null,c));return{id:e.id,botId:React.createElement(React.Fragment,null,React.createElement("div",null,p,u),React.createElement("div",null,React.createElement("small",null,e.botId))),user:r,messages:(null==t?void 0:t.length)??0,preview:E,extra:a.model,created:React.createElement("div",{style:{textAlign:"right"}},n),updated:React.createElement("div",{style:{textAlign:"right"}},l)}})):[]),[D,C]),U=va((()=>{if(1!==(null==I?void 0:I.length))return null;const e=null==D?void 0:D.chats.find((e=>e.id===I[0]));if(!e)return null;let t=[],a={};try{t=JSON.parse(e.messages),a=JSON.parse(e.extra)}catch(t){console.error("Could not parse discussion messages or extra.",{e:t,currentDiscussion:e})}return{id:e.id,chatId:e.chatId,botId:e.botId,messages:t,extra:a,created:e.created,updated:e.updated}}),[I,D]),H=async()=>{if(b(!0),I.length){const e=null==D?void 0:D.chats.filter((e=>I.includes(e.id))),t=e.map((e=>e.chatId));await Sa(t),M([])}else{if(!window.confirm(ge.ALERTS.ARE_YOU_SURE))return void b(!1);await Sa()}await g.invalidateQueries({queryKey:["chats"]}),g.refetchQueries({queryKey:["chats"]}),b(!1)},j=va((()=>React.createElement("div",null,React.createElement("div",{style:{display:"flex",flexDirection:"row"}},React.createElement(tt.Q,{currentPage:S.page,limit:S.limit,onCurrentPageChanged:e=>k({...S,page:e}),total:F,onClick:e=>{k({...S,page:e})}}),React.createElement(h.M,{className:"primary",style:{marginLeft:5},onClick:()=>{v({type:"export",data:{}})}},ge.COMMON.EXPORT)))),[S,F]),G=va((()=>null!=L&&L.message?React.createElement(ce.X,{variant:"danger",style:{margin:"5px 5px"}},React.createElement("b",null,L.message),React.createElement("br",null),React.createElement("small",null,"Check your Console Logs and PHP Error Logs for more information.")):null),[L]),$=Ie(null==U?void 0:U.created),z=Ie(null==U?void 0:U.updated);return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,style:{flex:2}},React.createElement(R.z,{className:"primary",title:ge.COMMON.DISCUSSIONS,action:React.createElement(React.Fragment,null,React.createElement("div",null,!w&&React.createElement(h.M,{className:"secondary",style:{marginLeft:5},disabled:P,onClick:async()=>{await g.invalidateQueries({queryKey:["chats"]})}},ge.COMMON.REFRESH),I.length>0&&React.createElement(React.Fragment,null,React.createElement(h.M,{className:"danger",disabled:!1,onClick:H},ge.COMMON.DELETE))))},React.createElement(Xe.o,{busy:!w&&P||f,sort:S.sort,onSortChange:(e,t)=>{k({...S,sort:{accessor:e,by:t}})},emptyMessage:G,filters:O,onFilterChange:(e,t)=>{const a=[...O.filter((t=>t.accessor!==e)),{accessor:e,value:t}];N(a)},data:L?[]:B,columns:T,selectedItems:I,onSelectRow:e=>{1!==I.length||I[0]!==e?M([e]):M([])},onSelect:e=>{M([...I,...e])},onUnselect:e=>{M([...I.filter((t=>!e.includes(t)))])}}),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginTop:10}},React.createElement(h.M,{className:"danger",disabled:I.length,style:{marginRight:10},onClick:H},ge.COMMON.DELETE_ALL),React.createElement(m.R,{name:"auto-refresh",label:"Auto Refresh",value:"1",checked:w,style:{width:180},onChange:()=>_(!w)}),React.createElement("div",{style:{flex:"auto"}}),j))),React.createElement(E.Y,{minimal:!0,style:{flex:1}},React.createElement(R.z,{className:"primary",title:"Selected Discussion",action:React.createElement(React.Fragment,null)},!U&&React.createElement("div",{style:{textAlign:"center",padding:10}},"No discussion selected."),null==U||null===(e=U.messages)||void 0===e?void 0:e.map(((e,t)=>React.createElement(Ma,{key:t,message:e})))),!!U&&React.createElement(R.z,{className:"primary",title:"Information"},React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Model"),React.createElement("div",null,null==U||null===(t=U.extra)||void 0===t?void 0:t.model)),React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Bot ID (or Custom ID)"),React.createElement("div",null,null==U?void 0:U.botId)),(null==U||null===(a=U.extra)||void 0===a?void 0:a.parentBotId)&&React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Parent Bot ID"),React.createElement("div",null,null==U||null===(n=U.extra)||void 0===n?void 0:n.parentBotId)),(null==U||null===(r=U.extra)||void 0===r?void 0:r.context)&&React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Context"),React.createElement("div",null,null==U||null===(i=U.extra)||void 0===i?void 0:i.context)),(null==U||null===(c=U.extra)||void 0===c?void 0:c.assistantId)&&React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Assistant ID"),React.createElement("div",null,null==U||null===(s=U.extra)||void 0===s?void 0:s.assistantId)),(null==U||null===(d=U.extra)||void 0===d?void 0:d.threadId)&&React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Thread ID"),React.createElement("div",null,null==U||null===(u=U.extra)||void 0===u?void 0:u.threadId)),React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Chat ID"),React.createElement("div",null,null==U?void 0:U.chatId)),React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Session"),React.createElement("div",null,null==U||null===(p=U.extra)||void 0===p?void 0:p.session)),React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Created"),React.createElement("div",null,$)),React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Updated"),React.createElement("div",null,z))))),React.createElement(ya,{modal:y,setModal:v,busy:f}))},Aa=L.Ay.div`
  background: white;
  padding: 15px;
  border-radius: 5px;

  h2 {
    margin-bottom: 8px;
  }
  
  h2:first-child, h3:first-child {
    margin-top: 0;
  }

  label {
    display: block;
    margin-bottom: 5px;
  }

  label {
    margin-top: 10px;
  }

  ul {
    margin: 20px 0 0 0;
  }

  li {
    margin-bottom: 5px;
    border: 1px solid #e5e5e5;
    padding: 8px;
    background: #f5f5f5;
    border-radius: 5px;
    cursor: pointer;
    position: relative;

    &:last-child {
      margin-bottom: 0;
    }

    &:hover {
      background: #e5e5e5;
    }

    &.active {
      background: #007cba;
      color: white;
      border-color: #007cba;

      &.modified {
        background: #ff8c00;
        border-color: #ff8c00;
      }
    }
  }

  .information {
    color: #a3a3a3;
    margin-top: 5px;
    font-size: 12px;
    line-height: 100%;
  }
`,xa=(0,L.Ay)(ne.A)`
  flex: auto !important;

  input {
    height: 50px !important;
    font-size: 13px !important;
    font-family: monospace !important;
    padding: 20px !important;
    border-color: #333d4e !important;
    background: #333d4e !important;
    color: white !important;
  }
`,Pa=(L.Ay.div`
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  padding: 20px;
  margin-bottom: 20px;
  height: auto;
  
  p {
    margin: 10px 0;
    color: #666;
    font-size: 14px;
    line-height: 1.5;
  }
  
  label {
    font-weight: 600;
    color: #333;
  }
`,L.Ay.div`
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  padding: 20px;
  height: auto;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  
  .content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .content-body {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
`,L.Ay.div`
  display: flex;
  flex-direction: column;

  label {
    margin-bottom: 3px;
  }

  .mwai-builder-row {
    margin-top: 10px;
    display: flex;
    flex-direction: row;

    .neko-color-picker {
      margin-left: 5px;
    }
  }

  .mwai-builder-col {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-right: 5px;
  }

  .mwai-builder-col:last-child {
    margin-right: 0;
  }

  pre {
    white-space: pre-wrap;
    background: #d4f0ff;
    color: #037cba;
    padding: 10px;
    font-size: 13px;
    font-weight: bold;
    margin: 10px 0 10px 0;
  }

  .neko-spacer {
    margin-bottom: 0 !important;
  }

  .neko-input {
  }

  .nui-select-option {
  }


`),{useMemo:Da}=wp.element,La=({model:e,maxTokens:t,onRecommendedClick:a,...n})=>{const l=null==e?void 0:e.maxContextualTokens,r=null==e?void 0:e.maxCompletionTokens,o=null==e?void 0:e.maxTokens,i=!!a;t=Math.floor(parseInt(t),0);const c=Da((()=>e?r||(l?Math.floor(l/2):o?Math.floor(o/2):null):null),[r,l,o]),s=Da((()=>e?c===t?"var(--neko-green)":t>r?"var(--neko-red)":"var(--neko-yellow)":null),[r,t,c]);return React.createElement("span",n,(!(null==e||!e.maxContextualTokens)||!(null==e||!e.maxCompletionTokens))&&React.createElement(React.Fragment,null,!(null==e||!e.maxContextualTokens)&&React.createElement(React.Fragment,null,"Contextual: ",null==e?void 0:e.maxContextualTokens),!(null==e||!e.maxContextualTokens)&&!(null==e||!e.maxCompletionTokens)&&React.createElement(React.Fragment,null," - "),!(null==e||!e.maxCompletionTokens)&&React.createElement(React.Fragment,null,"Completion: ",null==e?void 0:e.maxCompletionTokens),React.createElement("br",null)),!(null!=e&&e.maxCompletionTokens)&&!(null==e||!e.maxTokens)&&React.createElement(React.Fragment,null,"Total Max Tokens: ",null==e?void 0:e.maxTokens,React.createElement("br",null)),!!c&&c!==t&&React.createElement(React.Fragment,null,"Recommended: ",React.createElement("b",{onClick:i?()=>a(c):null,style:{color:s,cursor:i?"pointer":"inherit"}},c,t>r&&React.createElement(React.Fragment,null,"❗️")),React.createElement("br",null)))},{useState:Fa,useMemo:Ba}=wp.element,Ua=L.Ay.div`
  pre {
    display: flex;
    align-items: center;
    background: #f8fcff;
    color: #779bb8;
    margin: 0px;
    padding: 3px 8px;
    font-size: 13px;
    border: 2px solid rgb(210 228 243);
    border-radius: 5px;
    font-family: system-ui;
    cursor: pointer;
    font-weight: 500;
  }

  .mwai-name {
    font-style: italic;
  }

  .mwai-value {
    color: var(--neko-green);
  }

  .skipped-params {
    margin-top: 10px;
    color: #ff4d4f;
  }
`,Ha=e=>"string"!=typeof e?e:e.replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/\n/g,"\\n").replace(/\[/g,"&#91;").replace(/\]/g,"&#93;"),ja=({currentChatbot:e,isCustom:t=!1,defaultChatbot:a,...n})=>{const[l,r]=Fa(null),o=Ba((()=>{if(!e)return{shortcodeHtml:null,shortcodeText:null,skipped:[]};let n;const l=[],r=[];if(t){for(const t in e){const n=e[t];if(null==n||"botId"===t||"name"===t||""===n||a&&a[t]===n||"object"==typeof n||Array.isArray(n)&&0===n.length){"object"==typeof n&&Array.isArray(n)&&0!==n.length&&r.push(t);continue}const o=Ha(n),i=t.replace(/([A-Z])/g,(e=>`_${e.toLowerCase()}`));l.push(`${i}="${o}"`)}n="[mwai_chatbot"+(l.length?` ${l.join(" ")}`:"")+"]"}else{const t=e.botId??"default";l.push(`id="${t}"`),n=`[mwai_chatbot id="${t}"]`}return{shortcodeHtml:React.createElement("span",null,"[mwai_chatbot"," ",l.map(((e,t)=>{const[a,n]=e.split("=");return React.createElement("span",{key:t},React.createElement("span",{className:"mwai-name"},a),"=",React.createElement("span",{className:"mwai-value"},n),t<l.length-1?" ":"")})),"]"),shortcodeText:n,skipped:r}}),[e,t,a]),i=(null==o?void 0:o.skipped)??[];return e?React.createElement(Ua,n,React.createElement("pre",{onClick:async()=>{navigator.clipboard?(await navigator.clipboard.writeText(o.shortcodeText),r("Copied!"),setTimeout((()=>{r(null)}),2e3)):alert("Clipboard is not enabled (only works with https).")}},!l&&o.shortcodeHtml,l&&React.createElement("span",null,l)),i.length>0&&React.createElement("div",{className:"skipped-params"},"Skipped parameters: ",i.join(", "))):null};var Ga=a(7678);function $a(){return $a=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},$a.apply(this,arguments)}const{useMemo:za,useState:Wa,useEffect:qa,useRef:Va}=wp.element,Ya="drop-shadow(0 0 5px rgba(0,0,0,0.1))",Ka=["alloy","ash","ballad","coral","echo","sage","shimmer","verse"],Xa=["chat-openai.svg","chat-robot-1.svg","chat-robot-2.svg","chat-nyao-1.svg","chat-nyao-2.svg","chat-nyao-3.svg","chat-color-blue.svg","chat-color-green.svg","chat-color-red.svg","chat-traditional-1.svg","chat-traditional-2.svg","avatar-user.svg","avatar-woman-blond.svg","avatar-woman-indian.svg","avatar-woman-asian.svg","avatar-woman-doctor.svg","avatar-man-blond.svg","avatar-man-black.svg","avatar-man-sunglasses.svg","avatar-man-pirate.svg"],Qa=({label:e,valueName:t,updateShortcodeParams:a,icon:n})=>{const l=n||"chat-color-green.svg",r=(0,Ga.Ve)(l),o=r||(null==l?void 0:l.startsWith("https://"))||(null==l?void 0:l.startsWith("http://")),i=o?l:`${_}/images/${l}`;return React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-builder-row"},React.createElement("label",null,e,":")),React.createElement("div",{style:{marginTop:0,border:"1.5px solid #d2e4f3",borderRadius:5,padding:"10px 10px 10px 10px",background:"#f5fcff"}},React.createElement("div",{className:"mwai-builder-row",style:{marginTop:0}},React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center"}},Xa.map((e=>React.createElement("div",{key:e,style:{cursor:"pointer"},onMouseDown:e=>e.stopPropagation(),onClick:n=>{n.stopPropagation(),a(e,t)}},React.createElement("img",{style:{marginRight:2,marginBottom:2,filter:Ya},width:24,height:24,src:`${_}/images/${e}`})))),React.createElement("div",{style:{width:24,height:24,border:"1px solid #d2e4f3",background:"#f5fcff",borderRadius:5,cursor:"pointer",display:"flex",justifyContent:"center",alignItems:"center"},onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),a(`${_}/images/chat-traditional-1.svg`,t)}},"..."))),React.createElement("div",{className:"mwai-builder-col",style:{width:48,display:"flex",alignItems:"end"}},r?React.createElement("div",{style:{fontSize:48,lineHeight:"48px",marginRight:0,paddingTop:0}},l):React.createElement("img",{style:{marginRight:0,paddingTop:0,filter:Ya},width:48,height:48,src:`${i}`}))),o&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.CUSTOM_ICON,":"),React.createElement(ne.A,{name:"icon",value:l,onBlur:e=>a(e,t),onEnter:e=>a(e,t)})))))},Ja=e=>{var t,a,n,l,r,o,i,c,s,d,u,p,g,R,v,f,b,_;const{themes:C,shortcodeParams:T,updateShortcodeParams:N,defaultChatbot:I,blockMode:M,deleteCurrentChatbot:S,resetCurrentChatbot:k,duplicateCurrentChatbot:A,options:x,...P}=e,{completionModels:D,imageModels:L,realtimeModels:F,getModel:B}=Ce(x,T.envId||null),U="chat"===T.mode??"chat",H="assistant"===T.mode??!1,j="images"===T.mode??!1,G="realtime"===T.mode??!1,$=T.contentAware,z=za((()=>(null==x?void 0:x.ai_envs)||[]),[x.ai_envs]),W=null==x?void 0:x.module_embeddings,q=null==x?void 0:x.module_orchestration,V=(null==x?void 0:x.functions)||[],Y=T.functions||[],[K,X]=Wa(!1),Q=(null==x?void 0:x.mcp_envs)||[],J=T.mcpServers||[],Z=Va(T.envId);qa((()=>{Z.current=T.envId}),[T.envId]);const ee=za((()=>T.instructions&&T.instructions.includes("{CONTENT}")),[T.instructions]),te=za((()=>z.find((e=>e.id===T.envId))||null),[z,T.envId]),le=za((()=>(null==te?void 0:te.assistants)||[]),[te]),re=za((()=>le.find((e=>e.id===T.assistantId))||null),[le,T.assistantId]),oe=re?re.model:T.model||(T.envId?null:null==x?void 0:x.ai_default_model),ie=B(oe),se=x.embeddings_envs||[],de=za((()=>{var e;return null==ie||null===(e=ie.tags)||void 0===e?void 0:e.includes("functions")}),[ie]),me=za((()=>{var e;return null==ie||null===(e=ie.tags)||void 0===e?void 0:e.includes("vision")}),[ie]),ue=za((()=>{var e;return null==ie||null===(e=ie.tags)||void 0===e?void 0:e.includes("files")}),[ie]),pe=za((()=>{var e;return null==ie||null===(e=ie.tags)||void 0===e?void 0:e.includes("image")}),[ie]),Ee=za((()=>{var e;return(null==ie||null===(e=ie.tags)||void 0===e?void 0:e.includes("mcp"))||!1}),[ie]),he=za((()=>{var e;return(null==ie||null===(e=ie.tools)||void 0===e?void 0:e.length)>0}),[ie]),Re=za((()=>{var e;return null==ie||null===(e=ie.tags)||void 0===e?void 0:e.includes("responses")}),[ie]),ye=za((()=>{if(!T.embeddingsEnvId||!ie)return!1;const e=se.find((e=>e.id===T.embeddingsEnvId));if(!e||"openai-vector-store"!==e.type)return!1;const t=e.openai_env_id,a=T.envId||(null==x?void 0:x.ai_default_env),n=z.find((e=>e.id===a)),l=!n||"openai"===n.type,r=Re,o=!1!==(null==x?void 0:x.ai_responses_api);return l&&r&&o&&t===a&&e.store_id}),[T.embeddingsEnvId,T.envId,ie,se,Re,z,x]),ve=za((()=>j?L:(G?F:D)??[]),[j,G,D,L,F]);qa((()=>{const e=Y.filter((e=>V.some((t=>t.id===e.id)))),t=J.filter((e=>Q.some((t=>t.id===e.id))));if(e.length!==Y.length)console.warn("Update Params: Functions has been updated."),N(e,"functions");else if(t.length!==J.length)console.warn("Update Params: MCP Servers has been updated."),N(t,"mcpServers");else if(pe&&!T.resolution){if(console.warn("Update Params: Resolution has been set."),null!=ie&&ie.resolutions){const e=ie.resolutions.map((e=>e.name)),t=e.includes("1024x1024")?"1024x1024":e[0];N(t,"resolution")}}else!pe&&T.resolution?(console.warn("Update Params: Resolution has been removed."),N(null,"resolution")):pe&&U||H&&T.model?(console.warn("Update Params: Model has been removed."),N(null,"model")):!H&&T.assistantId?(console.warn("Update Params: Assistant has been removed."),N(null,"assistantId")):!T.imageUpload||me||j?T.fileSearch&&!H?(console.warn("Update Params: File search has been removed."),N(null,"fileSearch")):T.model&&!T.envId?(console.warn("Update Params: Model has been removed."),N("","model")):T.envId&&!te?(console.warn("Update Params: Environment has been removed."),N(null,"envId")):T.model&&T.envId&&!ie?(console.warn("Update Params: Model has been removed because it doesn't exist in the current environment."),N("","model")):!T.model&&T.envId&&ve.length>0&&Z.current!==T.envId?(console.log("Update Params: Auto-selecting first available model for the environment."),N(ve[0].model,"model")):!W&&T.embeddingsEnvId?(console.warn("Update Params: Embeddings environment has been removed."),N(null,"embeddingsEnvId")):!H||!T.fileSearch||null!=re&&re.has_file_search?T.aiAvatar||T.aiName?T.userAvatar||T.userName?T.guestAvatar||T.guestName||(console.warn("Update Params: Guest avatar has been set to true."),N(!0,"guestAvatar")):(console.warn("Update Params: User avatar has been set to true."),N(!0,"userAvatar")):(console.warn("Update Params: AI avatar has been set to true."),N(!0,"aiAvatar")):(console.warn("Update Params: File search has been removed."),N(null,"fileSearch")):(console.warn("Update Params: Vision has been removed."),N(null,"imageUpload"))}),[T,J,Q,ie,ve]);const fe=za((()=>pe&&ie?ie.resolutions?null==ie?void 0:ie.resolutions:(console.error("This image model does not have resolutions.",ie),[]):[]),[ie,pe]),be=za((()=>{const e=[U?"Chat":H?"Assistant":j?"Images":G?"Realtime":null,(null==T?void 0:T.botId)||(null==I?void 0:I.id)||"default"].filter(Boolean).join(", ");return React.createElement("div",null,ge.COMMON.CHATBOT,React.createElement("small",{style:{opacity:.5}}," ",e))}),[U,H,null==T?void 0:T.botId,null==I?void 0:I.id]),we=za((()=>{const e=(e,t)=>{const a=z.find((t=>t.id===e));if(!a)return null;const n=B(t);return[a.name,null==n?void 0:n.rawName].filter(Boolean).join(", ")};if(T.envId){const t=e(T.envId,T.model);if(t)return React.createElement("div",null,ge.COMMON.AI_MODEL,React.createElement("small",{style:{opacity:.5}}," ",t))}else{const t=e(null==x?void 0:x.ai_default_env,null==x?void 0:x.ai_default_model);if(t)return React.createElement("div",null,ge.COMMON.AI_MODEL,React.createElement("small",{style:{opacity:.5}}," ",t))}return ge.COMMON.AI_MODEL}),[T.envId,T.model,z,B,null==x?void 0:x.ai_default_env,null==x?void 0:x.ai_default_model]),_e=za((()=>{if(T.embeddingsEnvId){const e=se.find((e=>e.id===T.embeddingsEnvId));if(e){const t=[e.name,$?"Content Aware":null].filter(Boolean).join(", ");return React.createElement("div",null,ge.COMMON.CONTEXT,React.createElement("small",{style:{opacity:.5}}," ",t))}}return ge.COMMON.CONTEXT}),[T.embeddingsEnvId,se,$]),Te=za((()=>{const e=ge.COMMON.FUNCTIONS,t=Y.length>0,a=t?`Enabled: ${Y.length}, Total: ${V.length}`:"";return React.createElement("div",{style:{display:"flex",alignItems:"center",gap:"8px"}},React.createElement("span",null,e),a&&React.createElement("small",{style:{opacity:.5}},a),!de&&t&&React.createElement("small",{style:{color:"#ff6b6b",fontWeight:"bold"}},"(Not Supported)"))}),[Y,V,de]),Oe=za((()=>{const e=ge.COMMON.MCP_SERVERS,t=J.length>0,a=t?`Enabled: ${J.length}, Total: ${Q.length}`:"";return React.createElement("div",{style:{display:"flex",alignItems:"center",gap:"8px"}},React.createElement("span",null,e),a&&React.createElement("small",{style:{opacity:.5}},a),!Ee&&t&&React.createElement("small",{style:{color:"#ff6b6b",fontWeight:"bold"}},"(Not Supported)"))}),[J,Q,Ee]),Ne=za((()=>{const e=T.tools||[],t=(null==ie?void 0:ie.tools)||[],a=ge.COMMON.TOOLS||"Tools",n=e.length>0,l=e.filter((e=>t.includes(e))).length,r=e.length-l,o=n?`Enabled: ${e.length}`:"";return React.createElement("div",{style:{display:"flex",alignItems:"center",gap:"8px"}},React.createElement("span",null,a),o&&React.createElement("small",{style:{opacity:.5}},o),r>0&&React.createElement("small",{style:{color:"#ff6b6b",fontWeight:"bold"}},"(Not Supported: ",r,")"))}),[T.tools,ie]),Ie=za((()=>{const e=T.contextMaxLength||(null==x?void 0:x.context_max_length),t=[T.maxMessages?`Messages: ${T.maxMessages}`:null,e?`Context: ${e}`:null].filter(Boolean).join(", ");return React.createElement("div",null,ge.COMMON.THRESHOLDS,React.createElement("small",{style:{opacity:.5}}," ",t))}),[T.contextMaxLength,T.maxMessages,null==x?void 0:x.context_max_length]),Me=za((()=>{const e=null==C?void 0:C.find((e=>e.themeId===T.themeId)),t=[(null==e?void 0:e.name)||T.themeId,T.window?"Popup":null].filter(Boolean).join(", ");return React.createElement("div",null,ge.COMMON.APPEARANCE,React.createElement("small",{style:{opacity:.5}}," ",t))}),[T.themeId,T.window,C]);return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,$a({minimal:!0},P),React.createElement(Pa,null,React.createElement(et.Zc,{keepState:"chatbotParams"},React.createElement(et.y2,{title:be},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.NAME,":"),React.createElement(ne.A,{name:"name","data-form-type":"other",disabled:"default"===T.botId,value:T.name,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("div",null,React.createElement("label",{style:{display:"block"}},ge.COMMON.ID,":"),React.createElement(ne.A,{name:"botId",type:"text",placeholder:"Optional",disabled:"default"===T.botId,value:T.botId,onBlur:N,onEnter:N}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("div",null,React.createElement("label",{style:{display:"block"}},ge.COMMON.SCOPE,":"),React.createElement(ne.A,{name:"scope",type:"text",placeholder:"Scope",value:T.scope,onBlur:N,onEnter:N}))),!G&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.LOCAL_MEMORY,":"),React.createElement(m.R,{name:"localMemory",label:"Yes",checked:T.localMemory,value:"1",onChange:N}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{height:"chat"===T.mode?76:"inherit"}},React.createElement("label",null,ge.COMMON.MODE,":"),React.createElement(ae.u,{scrolldown:!0,id:"mode",name:"mode",value:T.mode,onChange:N},React.createElement(ae.j,{value:"chat",label:"Chat"}),React.createElement(ae.j,{value:"images",label:"Images"}),React.createElement(ae.j,{value:"assistant",label:"Assistant",isPro:!0,requirePro:!O}),React.createElement(ae.j,{value:"realtime",label:"Realtime",isPro:!0,requirePro:!O}))),(U||H||G)&&React.createElement("div",{className:"mwai-builder-col",style:{flex:5}},React.createElement("label",null,ge.COMMON.INSTRUCTIONS,":"),React.createElement(Ke.m,{name:"instructions",rows:10,textAreaStyle:{resize:"none"},value:T.instructions,onBlur:N,onEnter:N})))),React.createElement(et.y2,{title:we},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.ENVIRONMENT,":"),React.createElement(ae.u,{scrolldown:!0,name:"envId",value:T.envId??"",onChange:N,description:T.envId&&""!==T.envId?null:(()=>{const e=z.find((e=>e.id===(null==x?void 0:x.ai_default_env)));return e?`→ ${e.name}`:null})()},z.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(ae.j,{value:"",label:"Default"}))),(U||j||G)&&React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,ge.COMMON.MODEL,":"),React.createElement(ae.u,{scrolldown:!0,textFiltering:ve.length>16,name:"model",disabled:!T.envId,value:T.model||"",onChange:N,description:T.model&&""!==T.model||T.envId?null:`→ ${null==x?void 0:x.ai_default_model}`},React.createElement(ae.j,{value:"",label:T.envId?"None":"Default"}),ve.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),H&&React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,ge.COMMON.ASSISTANT,":"),React.createElement(ae.u,{scrolldown:!0,name:"assistantId",value:T.assistantId,onChange:N},React.createElement(ae.j,{value:"",label:"None"}),le.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))))),pe&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.RESOLUTION,":"),React.createElement(ae.u,{scrolldown:!0,name:"resolution",value:T.resolution,onChange:N},fe.map((e=>React.createElement(ae.j,{key:e.name,value:e.name,label:e.label}))))),(me||j)&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,j?ge.COMMON.IMAGE_UPLOAD||"Image Upload":ge.COMMON.VISION,":"),React.createElement(m.R,{name:"imageUpload",label:ge.COMMON.ENABLE,checked:T.imageUpload,value:"1",onChange:N})),ue&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.FILES,":"),React.createElement(m.R,{name:"fileUpload",label:ge.COMMON.ENABLE,checked:T.fileUpload,value:"1",onChange:N}))),(U||G)&&React.createElement("div",{className:"mwai-builder-row"},G&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.VOICE,":"),React.createElement(ae.u,{scrolldown:!0,name:"voice",value:T.voice,onChange:N},React.createElement(ae.j,{value:"",label:"Default"}),Ka.map((e=>React.createElement(ae.j,{key:e,value:e,label:e}))))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.TEMPERATURE,":"),React.createElement(ne.A,{name:"temperature",type:"number",step:"0.1",min:"0",max:"1",value:T.temperature,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.MAX_TOKENS,":"),React.createElement(ne.A,{name:"maxTokens",type:"number",description:React.createElement(La,{model:ie,maxTokens:T.maxTokens,onRecommendedClick:e=>{N(e,"maxTokens")},style:{fontSize:11,lineHeight:"8px"}}),value:T.maxTokens,onBlur:N,onEnter:N})))),H&&React.createElement(et.y2,{title:ge.COMMON.ASSISTANT},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.FILE_SEARCH,":"),React.createElement(ae.u,{scrolldown:!0,name:"fileSearch",disabled:!(null!=re&&re.has_file_search),description:(0,y.FE)(null!=re&&re.has_file_search?ge.SETTINGS.ASSISTANT_FILE_SEARCH:ge.SETTINGS.ASSISTANT_NO_FILE_SEARCH),value:T.fileSearch,onChange:N},React.createElement(ae.j,{value:"",label:"None"}),React.createElement(ae.j,{value:"discussion",label:"For Discussion"}))))),(U||H)&&React.createElement(et.y2,{title:_e},React.createElement("div",{style:{marginTop:15,fontWeight:"bold"}},ge.COMMON.EMBEDDINGS),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.EMBEDDINGS_ENV,":"),React.createElement(ae.u,{scrolldown:!0,name:"embeddingsEnvId",requirePro:!0,isPro:O,disabled:!W||!(null!=se&&se.length),value:T.embeddingsEnvId,onChange:N},se.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(ae.j,{value:"",label:"None"})))),T.embeddingsEnvId&&(()=>{const e=se.find((e=>e.id===T.embeddingsEnvId));if("openai-vector-store"===(null==e?void 0:e.type)){if(ye)return React.createElement(ce.X,{variant:"success",style:{marginTop:10,marginBottom:10}},"Since the model and vector store use the same OpenAI environment, we'll use direct integration via Responses API for smart and fast context retrieval.");{const t=T.envId||(null==x?void 0:x.ai_default_env),a=e.openai_env_id;return e.store_id?a!==t?React.createElement(ce.X,{variant:"warning",style:{marginTop:10,marginBottom:10}},"The model and vector store environments don't match - it will work but queries will be processed like a regular vector server instead of using direct OpenAI integration."):React.createElement(ce.X,{variant:"info",style:{marginTop:10,marginBottom:10}},"Direct OpenAI integration is not available. This may be because the model doesn't support Responses API or it's not enabled in settings."):React.createElement(ce.X,{variant:"danger",style:{marginTop:10,marginBottom:10}},"The OpenAI Vector Store ID is not configured. Please set the Vector Store ID in the embeddings environment settings to use this environment.")}}return null})(),React.createElement("div",{style:{marginTop:15,fontWeight:"bold"}},ge.COMMON.OTHERS),U&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.CONTENT_AWARE,":"),React.createElement(m.R,{name:"contentAware",label:"Yes",requirePro:!0,isPro:O,checked:T.contentAware,value:"1",onChange:N}))),$&&!ee&&React.createElement(ce.X,{variant:"danger",style:{marginTop:15,padding:"10px 15px"}},React.createElement("p",null,(0,y.FE)(ge.SETTINGS.ALERT_CONTENTAWARE_BUT_NO_CONTENT)))),(de||Y.length>0)&&V.length>0&&React.createElement(et.y2,{title:Te},React.createElement("p",null,React.createElement(ke,{style:{marginRight:3}}),React.createElement(Ae,{style:{marginRight:3}}),React.createElement(xe,{style:{marginRight:5}}),(0,y.FE)(ge.HELP.FUNCTIONS)),!(null!=V&&V.length)&&React.createElement(ce.X,{variant:"danger"},(0,y.FE)(ge.HELP.FUNCTIONS_UNAVAILABLE)),!(null==V||!V.length)&&React.createElement("div",{style:{maxHeight:200,overflowY:"auto",border:"1px solid #d1e3f2",marginTop:10,padding:"5px 6px",borderRadius:5}},null==V?void 0:V.map((e=>React.createElement(m.R,{key:e.id,name:"functions",label:React.createElement(React.Fragment,null,"js"===e.target&&React.createElement(Pe,{style:{marginRight:5}}),"js"!==e.target&&React.createElement(De,{style:{marginRight:5}}),React.createElement("span",null,e.name)),description:e.desc,checked:Y.some((t=>t.id===e.id)),value:e.id,onChange:t=>{const a=Y.filter((t=>t.id!==e.id));t&&a.push({type:e.type,id:e.id}),N(a,"functions")}})))),Y.length>1&&ye&&Re&&React.createElement(ce.X,{variant:"warning",style:{marginTop:10}},'When using Responses API with an OpenAI Vector Store connected as Context, calling multiple functions in one query (e.g., "What\'s X and Y?") may fail with "No tool output found" error. To avoid this, disable Responses API in Settings.'),H&&React.createElement(React.Fragment,null,React.createElement("p",null,"Assistant needs to be updated with the set of functions every time you modify them (including their names, arguments, descriptions, etc)."),React.createElement(h.M,{className:"primary",fullWidth:!0,onClick:async()=>{X(!0);try{await(async(e,t,a)=>{const n=await lt(`${w}/openai/assistants/set_functions`,{method:"POST",json:{envId:e,assistantId:t,functions:a}});if(!n.success)throw new Error(n.message);return n})(T.envId,T.assistantId,Y),alert("Functions have been set on the assistant.")}catch(e){alert(e.message)}X(!1)},isBusy:K},"Set Functions on Assistant"))),(Ee||J.length>0)&&q&&Q.length>0&&React.createElement(et.y2,{title:Oe},React.createElement("p",null,React.createElement(Ae,{style:{marginRight:5}}),(0,y.FE)(ge.HELP.MCP_SERVERS||"MCP (Model Context Protocol) servers enable AI models to interact with external tools and systems.")),!(null!=Q&&Q.length)&&React.createElement(ce.X,{variant:"danger"},(0,y.FE)(ge.HELP.MCP_SERVERS_UNAVAILABLE||"No MCP servers are available. Configure them in the MCP Servers section under Orchestration.")),!(null==Q||!Q.length)&&React.createElement("div",{style:{maxHeight:200,overflowY:"auto",border:"1px solid #d1e3f2",marginTop:10,padding:"5px 6px",borderRadius:5}},null==Q?void 0:Q.map((e=>React.createElement(m.R,{key:e.id,name:"mcpServers",label:React.createElement(React.Fragment,null,React.createElement(Ae,{style:{marginRight:5}}),React.createElement("span",null,e.name)),description:e.url||"MCP Server",checked:J.some((t=>t.id===e.id)),value:e.id,onChange:t=>{const a=J.filter((t=>t.id!==e.id));t&&a.push({id:e.id}),N(a,"mcpServers")}}))))),(he||(null===(t=T.tools)||void 0===t?void 0:t.length)>0)&&((null==ie||null===(a=ie.tools)||void 0===a?void 0:a.length)>0||(null===(n=T.tools)||void 0===n?void 0:n.length)>0)&&React.createElement(et.y2,{title:Ne},React.createElement("p",null,React.createElement(ke,{style:{marginRight:3}}),React.createElement(xe,{style:{marginRight:5}}),(0,y.FE)(ge.HELP.TOOLS||"Enable AI tools like web search and image generation to enhance your chatbot capabilities.")),React.createElement("div",{style:{marginTop:10}},((null==ie||null===(l=ie.tools)||void 0===l?void 0:l.includes("web_search"))||(null===(r=T.tools)||void 0===r?void 0:r.includes("web_search")))&&React.createElement(m.R,{name:"tools_web_search",label:ge.COMMON.WEB_SEARCH||"Web Search",description:ge.HELP.WEB_SEARCH||"Allow the AI to search the web for current information",checked:null===(o=T.tools)||void 0===o?void 0:o.includes("web_search"),value:"web_search",variant:null!=ie&&null!==(i=ie.tools)&&void 0!==i&&i.includes("web_search")||null===(c=T.tools)||void 0===c||!c.includes("web_search")?void 0:"danger",onChange:e=>{const t=T.tools||[],a=e?[...t.filter((e=>"web_search"!==e)),"web_search"]:t.filter((e=>"web_search"!==e));N(a,"tools")}}),((null==ie||null===(s=ie.tools)||void 0===s?void 0:s.includes("image_generation"))||(null===(d=T.tools)||void 0===d?void 0:d.includes("image_generation")))&&React.createElement(m.R,{name:"tools_image_generation",label:ge.COMMON.IMAGE_GENERATION||"Image Generation",description:ge.HELP.IMAGE_GENERATION||"Allow the AI to generate images based on text descriptions",checked:null===(u=T.tools)||void 0===u?void 0:u.includes("image_generation"),value:"image_generation",variant:null!=ie&&null!==(p=ie.tools)&&void 0!==p&&p.includes("image_generation")||null===(g=T.tools)||void 0===g||!g.includes("image_generation")?void 0:"danger",onChange:e=>{const t=T.tools||[],a=e?[...t.filter((e=>"image_generation"!==e)),"image_generation"]:t.filter((e=>"image_generation"!==e));N(a,"tools")}}),((null==ie||null===(R=ie.tools)||void 0===R?void 0:R.includes("thinking"))||(null===(v=T.tools)||void 0===v?void 0:v.includes("thinking")))&&React.createElement(m.R,{name:"tools_thinking",label:ge.COMMON.THINKING||"Thinking",description:ge.HELP.THINKING||"Enable enhanced reasoning mode for complex tasks requiring step-by-step analysis and planning",checked:null===(f=T.tools)||void 0===f?void 0:f.includes("thinking"),value:"thinking",variant:null!=ie&&null!==(b=ie.tools)&&void 0!==b&&b.includes("thinking")||null===(_=T.tools)||void 0===_||!_.includes("thinking")?void 0:"danger",onChange:e=>{const t=T.tools||[],a=e?[...t.filter((e=>"thinking"!==e)),"thinking"]:t.filter((e=>"thinking"!==e));N(a,"tools")}}))),React.createElement(et.y2,{title:Ie},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.INPUT_MAX_LENGTH,":"),React.createElement(ne.A,{name:"textInputMaxLength",type:"number",description:ge.HELP.INPUT_MAX_LENGTH,step:"1",min:"8",value:T.textInputMaxLength,onBlur:N,onEnter:N})),!G&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.MAX_MESSAGES,":"),React.createElement(ne.A,{name:"maxMessages",type:"number",description:ge.HELP.MAX_MESSAGES,step:"1",min:"1",max:"1024",value:T.maxMessages,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.CONTEXT_MAX_LENGTH,":"),React.createElement(ne.A,{name:"contextMaxLength",type:"number",step:"1",description:ge.HELP.CONTEXT_MAX_LENGTH,value:T.contextMaxLength||(null==x?void 0:x.context_max_length),onBlur:N,onEnter:N})))),React.createElement(et.y2,{title:Me},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,ge.COMMON.THEME,":"),React.createElement(ae.u,{scrolldown:!0,name:"themeId",value:T.themeId,description:"",onChange:N},React.createElement(ae.j,{value:"none",label:"None"}),React.createElement(ae.j,{value:"chatgpt",label:"ChatGPT"}),React.createElement(ae.j,{value:"timeless",label:"Timeless"}),React.createElement(ae.j,{value:"messages",label:"Messages"}),null==C?void 0:C.filter((e=>"css"===e.type)).map((e=>React.createElement(ae.j,{key:e.themeId,value:e.themeId,label:e.name}))))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.POPUP,":"),React.createElement(m.R,{name:"window",label:"Yes",checked:T.window,value:"1",onChange:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.FULL_SCREEN,":"),React.createElement(m.R,{name:"fullscreen",label:"Yes",checked:T.fullscreen,value:"1",onChange:N,disabled:T.window})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.COPY_BUTTON,":"),React.createElement(m.R,{name:"copyButton",label:"Yes",checked:T.copyButton,value:"1",onChange:N}))),"timeless"===T.themeId&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.HEADER_SUBTITLE,":"),React.createElement(ne.A,{name:"headerSubtitle","data-form-type":"other",value:T.headerSubtitle,onBlur:N,onEnter:N}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.AVATAR,":"),React.createElement(m.R,{name:"aiAvatar",label:"Yes",checked:T.aiAvatar,value:"1",onChange:N,disabled:!T.aiName})),React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,ge.COMMON.AI_NAME,":"),React.createElement(ne.A,{name:"aiName","data-form-type":"other",value:T.aiName,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:7}},React.createElement("label",null,ge.COMMON.START_SENTENCE,":"),React.createElement(Ke.m,{name:"startSentence",rows:1,value:T.startSentence,onBlur:N,onEnter:N}))),T.aiAvatar&&React.createElement(Qa,{label:ge.COMMON.AI_AVATAR,updateShortcodeParams:N,valueName:"aiAvatarUrl",icon:T.aiAvatarUrl}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.AVATAR,":"),React.createElement(m.R,{name:"userAvatar",label:"Yes",checked:T.userAvatar,value:"1",onChange:N,disabled:!T.userName})),React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,ge.COMMON.USER_NAME,":"),React.createElement(ne.A,{name:"userName","data-form-type":"other",value:T.userName,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,ge.COMMON.PLACEHOLDER,":"),React.createElement(ne.A,{name:"textInputPlaceholder",value:T.textInputPlaceholder,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,ge.COMMON.SEND,":"),React.createElement(ne.A,{name:"textSend",value:T.textSend,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,ge.COMMON.CLEAR,":"),React.createElement(ne.A,{name:"textClear",value:T.textClear,onBlur:N,onEnter:N}))),T.userAvatar&&React.createElement("p",null,React.createElement("i",null,"The ",React.createElement("a",{href:"https://gravatar.com/",target:"_blank",rel:"noreferrer"},"gravatar")," of this user will be used as the avatar.")),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.AVATAR,":"),React.createElement(m.R,{name:"guestAvatar",label:"Yes",checked:T.guestAvatar,value:"1",onChange:N,disabled:!T.guestName})),React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,ge.COMMON.GUEST_NAME,":"),React.createElement(ne.A,{name:"guestName",value:T.guestName,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:7}},React.createElement("label",null,ge.COMMON.COMPLIANCE_TEXT,":"),React.createElement(ne.A,{name:"textCompliance",value:T.textCompliance,onBlur:N,onEnter:N}))),T.guestAvatar&&React.createElement(Qa,{label:ge.COMMON.GUEST_AVATAR,updateShortcodeParams:N,valueName:"guestAvatarUrl",icon:T.guestAvatarUrl})),React.createElement(et.y2,{title:ge.COMMON.POPUP,hide:!T.window},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:4}},React.createElement("label",null,ge.COMMON.POSITION,":"),React.createElement(ae.u,{scrolldown:!0,name:"iconPosition",value:T.iconPosition,onChange:N},React.createElement(ae.j,{value:"bottom-right",label:"Bottom Right"}),React.createElement(ae.j,{value:"bottom-left",label:"Bottom Left"}),React.createElement(ae.j,{value:"top-right",label:"Top Right"}),React.createElement(ae.j,{value:"top-left",label:"Top Left"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.BUBBLE,":"),React.createElement(m.R,{name:"iconBubble",label:"Yes",checked:T.iconBubble,value:"1",onChange:N}))),React.createElement(Qa,{label:ge.COMMON.ICON,updateShortcodeParams:N,valueName:"icon",icon:T.icon}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:4}},React.createElement("label",null,ge.COMMON.ICON_TEXT,":"),React.createElement(ne.A,{name:"iconText",description:ge.HELP.ICON_TEXT,value:T.iconText,onBlur:N,onEnter:N})),React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,ge.COMMON.ICON_TEXT_DELAY,":"),React.createElement(ne.A,{name:"iconTextDelay",type:"number",description:ge.HELP.ICON_TEXT_DELAY??1,value:T.iconTextDelay,onBlur:N,onEnter:N})))),Re&&!H&&!j&&React.createElement(et.y2,{title:ge.COMMON.ADVANCED||"Advanced"},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.HISTORY_STRATEGY,":"),React.createElement(ae.u,{scrolldown:!0,name:"historyStrategy",description:ge.HELP.HISTORY_STRATEGY,value:T.historyStrategy||"",onChange:N},React.createElement(ae.j,{value:"",label:ge.COMMON.AUTOMATIC||"Automatic"}),React.createElement(ae.j,{value:"internal",label:ge.COMMON.FULL_HISTORY||"Full History"}),React.createElement(ae.j,{value:"response_id",label:ge.COMMON.INCREMENTAL||"Incremental"}))))),!M&&React.createElement(et.y2,{title:ge.COMMON.SHORTCODES},React.createElement(ja,{currentChatbot:T,style:{marginTop:10}}),"default"!==T.botId&&React.createElement(React.Fragment,null,React.createElement("p",null,ge.HELP.CUSTOM_SHORTCODE),React.createElement(ja,{currentChatbot:T,isCustom:!0,defaultChatbot:I,style:{marginTop:10}}))),!M&&React.createElement(et.y2,{title:ge.COMMON.ACTIONS},React.createElement("div",{style:{display:"flex",marginTop:10}},React.createElement(h.M,{className:"primary",onClick:A},ge.COMMON.DUPLICATE),React.createElement(h.M,{className:"secondary",onClick:k},ge.COMMON.RESET),React.createElement("div",{style:{flex:"auto"}}),React.createElement(h.M,{className:"danger",disabled:"Default"===T.name,onClick:S},ge.COMMON.DELETE))))))))};var Za=a(7612);const{useState:en,useEffect:tn,useRef:an,useCallback:nn}=wp.element,ln=L.Ay.div`
  position: relative;

  .swatch {
    width: 24px;
    height: 24px;
    border: 3px solid #fff;
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), inset 0 0 0 1px rgba(0, 0, 0, 0.1);
    cursor: pointer;
  }
  
  .popover {
    position: absolute;
    top: -210px;
    left: -80px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
    z-index: 9999;
    border-radius: 8px;
  }
`,rn=({name:e,value:t,onChange:a})=>{const n=an(),[l,r]=en(!1),[o,i]=en(t);tn((()=>{i(t)}),[t]);const c=nn((()=>{o!==t&&a(o,e),r(!1)}),[o,t]);var s,d;return tn((()=>{let e=!1,t=!1;const a=a=>{!e&&t&&s.current&&!s.current.contains(a.target)&&d(a)},n=a=>{t=s.current,e=s.current&&s.current.contains(a.target)};return document.addEventListener("mousedown",n),document.addEventListener("touchstart",n),document.addEventListener("click",a),()=>{document.removeEventListener("mousedown",n),document.removeEventListener("touchstart",n),document.removeEventListener("click",a)}}),[s=n,d=c]),React.createElement(ln,{className:"neko-color-picker"},React.createElement("div",{className:"swatch",style:{backgroundColor:o},onClick:()=>r(!0)}),l&&React.createElement("div",{className:"popover",ref:n,style:{background:"white"}},React.createElement(Za.jI,{color:o,onChange:i}),React.createElement("div",{style:{display:"flex",padding:5}},React.createElement(h.M,{style:{flex:1},onClick:()=>a(o,e)},"Apply"))))},on=e=>{const{settings:t,onUpdateSettings:a}=e;return React.createElement(React.Fragment,null,React.createElement(Pa,null,React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.SPACING,":"),React.createElement(ne.A,{id:"spacing",name:"spacing",value:(null==t?void 0:t.spacing)??"15px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.BORDER_RADIUS,":"),React.createElement(ne.A,{id:"borderRadius",name:"borderRadius",value:(null==t?void 0:t.borderRadius)??"10px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.FONT_SIZE,":"),React.createElement(ne.A,{id:"fontSize",name:"fontSize",value:(null==t?void 0:t.fontSize)??"15px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_PRIMARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundPrimaryColor)??"#454654",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",value:(null==t?void 0:t.backgroundPrimaryColor)??"#454654",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_SECONDARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundSecondaryColor",name:"backgroundSecondaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundSecondaryColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundSecondaryColor",name:"backgroundSecondaryColor",value:(null==t?void 0:t.backgroundSecondaryColor)??"#343541",onChange:a,onEnter:a})))),React.createElement(le.g,null),React.createElement(et.y2,{title:ge.COMMON.POPUP,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.75}},React.createElement("label",null,ge.COMMON.WIDTH,":"),React.createElement(ne.A,{id:"width",name:"width",value:(null==t?void 0:t.width)??"460px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.75}},React.createElement("label",null,ge.COMMON.MAX_HEIGHT,":"),React.createElement(ne.A,{id:"maxHeight",name:"maxHeight",value:(null==t?void 0:t.maxHeight)??"40vh",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.AVATAR_MESSAGE_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(rn,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#343541",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.AVATAR_MESSAGE_FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onChange:a,onEnter:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BUBBLE_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"bubbleColor",name:"bubbleColor",style:{flex:1},value:(null==t?void 0:t.bubbleColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(rn,{id:"bubbleColor",name:"bubbleColor",value:(null==t?void 0:t.bubbleColor)??"#343541",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.HEADER_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",style:{flex:1},value:(null==t?void 0:t.backgroundHeaderColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",value:(null==t?void 0:t.backgroundHeaderColor)??"#343541",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.HEADER_BUTTONS_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"headerButtonsColor",name:"headerButtonsColor",style:{flex:1},value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"headerButtonsColor",name:"headerButtonsColor",value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onChange:a,onEnter:a}))))))},{useMemo:cn,useState:sn,useEffect:dn}=wp.element,mn='/* AI Engine Pro - Custom Theme CSS\n   This is a comprehensive starting template for creating your own chatbot theme.\n   Modify the CSS variables and styles below to customize your chatbot\'s appearance. */\n\n/* ==========================================\n   CSS VARIABLES - Customize these first!\n   ========================================== */\n.mwai-THEME_ID-theme {\n  /* Core Spacing & Sizing */\n  --mwai-spacing: 15px;\n  --mwai-fontSize: 14px;\n  --mwai-lineHeight: 1.6;\n  --mwai-borderRadius: 10px;\n  --mwai-width: 350px;\n  --mwai-maxHeight: 600px;\n  \n  /* Colors - Primary Palette */\n  --mwai-fontColor: #1a1a1a;\n  --mwai-bgPrimary: #ffffff;\n  --mwai-bgSecondary: #f8f9fa;\n  --mwai-primaryColor: #0066cc;\n  --mwai-primaryHover: #0052a3;\n  \n  /* Message Colors */\n  --mwai-userBgColor: #0066cc;\n  --mwai-userTextColor: #ffffff;\n  --mwai-aiBgColor: #f1f3f5;\n  --mwai-aiTextColor: #1a1a1a;\n  \n  /* UI Element Colors */\n  --mwai-borderColor: #e1e4e8;\n  --mwai-shadowColor: rgba(0, 0, 0, 0.1);\n  --mwai-headerBg: #f8f9fa;\n  --mwai-inputBg: #ffffff;\n  --mwai-buttonBg: #0066cc;\n  --mwai-buttonHover: #0052a3;\n  \n  /* Typography */\n  font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif;\n}\n\n/* ==========================================\n   MAIN CONTAINER & LAYOUT\n   ========================================== */\n.mwai-THEME_ID-theme.mwai-chatbot {\n  font-size: var(--mwai-fontSize);\n  line-height: var(--mwai-lineHeight);\n  color: var(--mwai-fontColor);\n  background: var(--mwai-bgPrimary);\n}\n\n.mwai-THEME_ID-theme .mwai-content {\n  background: var(--mwai-bgPrimary);\n  border-radius: var(--mwai-borderRadius);\n  box-shadow: 0 2px 10px var(--mwai-shadowColor);\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  overflow: hidden;\n}\n\n/* ==========================================\n   HEADER SECTION\n   ========================================== */\n.mwai-THEME_ID-theme .mwai-header {\n  display: none;\n}\n\n.mwai-THEME_ID-theme .mwai-header .mwai-name-text {\n  font-weight: 600;\n  flex: 1;\n}\n\n.mwai-THEME_ID-theme .mwai-header .mwai-buttons {\n  display: flex;\n  gap: 8px;\n}\n\n.mwai-THEME_ID-theme .mwai-header .mwai-close-button,\n.mwai-THEME_ID-theme .mwai-header .mwai-resize-button {\n  background: none;\n  border: none;\n  cursor: pointer;\n  padding: 4px;\n  color: var(--mwai-fontColor);\n  opacity: 0.6;\n  transition: opacity 0.2s;\n}\n\n.mwai-THEME_ID-theme .mwai-header .mwai-close-button:hover,\n.mwai-THEME_ID-theme .mwai-header .mwai-resize-button:hover {\n  opacity: 1;\n}\n\n/* ==========================================\n   CONVERSATION AREA\n   ========================================== */\n.mwai-THEME_ID-theme .mwai-body {\n  flex: 1;\n  overflow: hidden;\n  display: flex;\n  flex-direction: column;\n}\n\n.mwai-THEME_ID-theme .mwai-conversation {\n  flex: 1;\n  overflow-y: auto;\n  padding: var(--mwai-spacing);\n  display: flex;\n  flex-direction: column;\n  gap: 10px;\n}\n\n/* Scrollbar Styling */\n.mwai-THEME_ID-theme .mwai-conversation::-webkit-scrollbar {\n  width: 6px;\n}\n\n.mwai-THEME_ID-theme .mwai-conversation::-webkit-scrollbar-track {\n  background: transparent;\n}\n\n.mwai-THEME_ID-theme .mwai-conversation::-webkit-scrollbar-thumb {\n  background: var(--mwai-borderColor);\n  border-radius: 3px;\n}\n\n/* ==========================================\n   MESSAGES / REPLIES\n   ========================================== */\n.mwai-THEME_ID-theme .mwai-reply {\n  display: flex;\n  gap: 10px;\n  animation: mwai-fade-in 0.3s ease-in;\n}\n\n/* User Messages */\n.mwai-THEME_ID-theme .mwai-reply.mwai-user {\n  background: var(--mwai-userBgColor);\n  color: var(--mwai-userTextColor);\n  border-radius: var(--mwai-borderRadius);\n  padding: 10px 15px;\n}\n\n.mwai-THEME_ID-theme .mwai-reply.mwai-user .mwai-text {\n  max-width: 100%;\n  word-wrap: break-word;\n}\n\n/* AI Messages */\n.mwai-THEME_ID-theme .mwai-reply.mwai-ai {\n  background: var(--mwai-aiBgColor);\n  color: var(--mwai-aiTextColor);\n  border-radius: var(--mwai-borderRadius);\n  padding: 10px 15px;\n}\n\n.mwai-THEME_ID-theme .mwai-reply.mwai-ai .mwai-text {\n  max-width: 100%;\n  word-wrap: break-word;\n}\n\n/* System Messages */\n.mwai-THEME_ID-theme .mwai-reply.mwai-system .mwai-text {\n  background: var(--mwai-bgSecondary);\n  color: var(--mwai-fontColor);\n  opacity: 0.8;\n  border-radius: var(--mwai-borderRadius);\n  padding: 8px 12px;\n  text-align: center;\n  font-size: 0.9em;\n  margin: 0 auto;\n}\n\n/* Avatar */\n.mwai-THEME_ID-theme .mwai-reply .mwai-avatar {\n  width: 32px;\n  height: 32px;\n  border-radius: 50%;\n  background: var(--mwai-bgSecondary);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-shrink: 0;\n}\n\n.mwai-THEME_ID-theme .mwai-reply .mwai-avatar img {\n  width: 100%;\n  height: 100%;\n  border-radius: 50%;\n  object-fit: cover;\n}\n\n/* Copy Button */\n.mwai-THEME_ID-theme .mwai-reply-actions {\n  display: flex;\n  gap: 4px;\n  margin-top: 4px;\n}\n\n.mwai-THEME_ID-theme .mwai-copy-button {\n  background: var(--mwai-bgSecondary);\n  border: 1px solid var(--mwai-borderColor);\n  border-radius: 4px;\n  padding: 4px 8px;\n  cursor: pointer;\n  font-size: 12px;\n  color: var(--mwai-fontColor);\n  transition: all 0.2s;\n}\n\n.mwai-THEME_ID-theme .mwai-copy-button:hover {\n  background: var(--mwai-primaryColor);\n  color: white;\n  border-color: var(--mwai-primaryColor);\n}\n\n/* ==========================================\n   INPUT AREA\n   ========================================== */\n.mwai-THEME_ID-theme .mwai-input {\n  padding: var(--mwai-spacing);\n  border-top: 1px solid var(--mwai-borderColor);\n  background: var(--mwai-inputBg);\n  display: flex;\n  gap: 10px;\n  align-items: center;\n}\n\n.mwai-THEME_ID-theme .mwai-input-text {\n  flex: 1;\n  display: flex;\n  align-items: center;\n  background: var(--mwai-bgSecondary);\n  border: 1px solid var(--mwai-borderColor);\n  border-radius: calc(var(--mwai-borderRadius) / 2);\n  padding: 8px 12px;\n}\n\n.mwai-THEME_ID-theme .mwai-input-text textarea {\n  flex: 1;\n  border: none;\n  background: transparent;\n  resize: none;\n  outline: none;\n  font-family: inherit;\n  font-size: inherit;\n  line-height: 1.4;\n  max-height: 100px;\n  color: var(--mwai-fontColor);\n}\n\n/* Prevent focus outlines and selection */\n.mwai-THEME_ID-theme .mwai-input-text:focus,\n.mwai-THEME_ID-theme .mwai-input-text *:focus {\n  outline: none;\n  box-shadow: none;\n}\n\n.mwai-THEME_ID-theme .mwai-input:focus-within {\n  outline: none;\n}\n\n.mwai-THEME_ID-theme .mwai-input-text textarea::placeholder {\n  color: var(--mwai-fontColor);\n  opacity: 0.5;\n}\n\n/* Input Buttons */\n.mwai-THEME_ID-theme .mwai-microphone {\n  background: none;\n  border: none;\n  cursor: pointer;\n  padding: 4px;\n  color: var(--mwai-fontColor);\n  opacity: 0.6;\n  transition: opacity 0.2s;\n}\n\n.mwai-THEME_ID-theme .mwai-microphone:hover {\n  opacity: 1;\n}\n\n/* File Upload - Minimalist */\n.mwai-THEME_ID-theme .mwai-file-upload {\n  position: relative;\n  display: flex;\n  align-items: center;\n}\n\n.mwai-THEME_ID-theme .mwai-file-upload-icon {\n  width: 24px;\n  height: 24px;\n  cursor: pointer;\n  background: none;\n  border: none;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  position: relative;\n  color: var(--mwai-fontColor);\n  opacity: 0.6;\n}\n\n/* Default state - plus icon */\n.mwai-THEME_ID-theme .mwai-file-upload-icon::before {\n  content: "+";\n  font-size: 20px;\n  font-weight: 300;\n}\n\n/* File uploaded states - checkmark */\n.mwai-THEME_ID-theme .mwai-file-upload-icon.mwai-image-ok::before,\n.mwai-THEME_ID-theme .mwai-file-upload-icon.mwai-document-ok::before {\n  content: "✓";\n  font-size: 16px;\n}\n\n/* Hover on uploaded files - show remove option */\n.mwai-THEME_ID-theme .mwai-file-upload-icon.mwai-image-ok:hover::before,\n.mwai-THEME_ID-theme .mwai-file-upload-icon.mwai-document-ok:hover::before,\n.mwai-THEME_ID-theme .mwai-file-upload-icon.mwai-image-del::before,\n.mwai-THEME_ID-theme .mwai-file-upload-icon.mwai-document-del::before {\n  content: "×";\n  font-size: 20px;\n  font-weight: 300;\n}\n\n/* Uploading states - minimal indicator */\n.mwai-THEME_ID-theme .mwai-file-upload-icon.mwai-image-up::before,\n.mwai-THEME_ID-theme .mwai-file-upload-icon.mwai-document-up::before {\n  content: "•";\n  font-size: 24px;\n}\n\n/* Progress indicator - hidden for minimalism */\n.mwai-THEME_ID-theme .mwai-file-upload-progress {\n  display: none;\n}\n\n.mwai-THEME_ID-theme .mwai-input-submit {\n  background: var(--mwai-buttonBg);\n  color: white;\n  border: none;\n  border-radius: calc(var(--mwai-borderRadius) / 2);\n  padding: 10px 20px;\n  cursor: pointer;\n  font-weight: 500;\n  transition: background 0.2s;\n}\n\n.mwai-THEME_ID-theme .mwai-input-submit:hover:not(:disabled) {\n  background: var(--mwai-buttonHover);\n}\n\n.mwai-THEME_ID-theme .mwai-input-submit:disabled {\n  opacity: 0.5;\n  cursor: not-allowed;\n}\n\n/* ==========================================\n   WINDOW MODE SPECIFIC\n   ========================================== */\n.mwai-THEME_ID-theme.mwai-window {\n  position: fixed;\n  right: 30px;\n  bottom: 30px;\n  width: var(--mwai-width);\n  z-index: 9999;\n}\n\n.mwai-THEME_ID-theme.mwai-window .mwai-content {\n  display: none;\n  opacity: 0;\n  max-height: var(--mwai-maxHeight);\n  transition: opacity 0.3s ease-in-out;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-open .mwai-content {\n  display: flex;\n  opacity: 1;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-open .mwai-trigger {\n  display: none;\n}\n\n/* Window Positions */\n.mwai-THEME_ID-theme.mwai-window.mwai-bottom-left {\n  right: auto;\n  left: 30px;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-top-right {\n  top: 30px;\n  bottom: auto;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-top-left {\n  top: 30px;\n  bottom: auto;\n  right: auto;\n  left: 30px;\n}\n\n/* ==========================================\n   TRIGGER BUTTON\n   ========================================== */\n.mwai-THEME_ID-theme .mwai-trigger {\n  position: fixed;\n  right: 30px;\n  bottom: 30px;\n  z-index: 9999;\n}\n\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-container {\n  background: var(--mwai-primaryColor);\n  color: white;\n  width: 60px;\n  height: 60px;\n  border-radius: 50%;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  cursor: pointer;\n  box-shadow: 0 4px 12px var(--mwai-shadowColor);\n  transition: transform 0.2s, box-shadow 0.2s;\n}\n\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-container:hover {\n  transform: scale(1.1);\n  box-shadow: 0 6px 16px var(--mwai-shadowColor);\n}\n\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-text {\n  background: var(--mwai-bgPrimary);\n  color: var(--mwai-fontColor);\n  border: 1px solid var(--mwai-borderColor);\n  box-shadow: 0 2px 8px var(--mwai-shadowColor);\n  max-width: 200px;\n  font-size: 13px;\n  margin-bottom: 10px;\n  padding: 10px 15px;\n  border-radius: var(--mwai-borderRadius);\n}\n\n/* ==========================================\n   LOADING & ANIMATIONS\n   ========================================== */\n@keyframes mwai-fade-in {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n.mwai-THEME_ID-theme .mwai-bouncing-dots {\n  display: flex;\n  gap: 4px;\n  padding: 10px;\n}\n\n.mwai-THEME_ID-theme .mwai-dot {\n  width: 8px;\n  height: 8px;\n  background: var(--mwai-primaryColor);\n  border-radius: 50%;\n  animation: mwai-bounce 1.4s infinite ease-in-out both;\n}\n\n.mwai-THEME_ID-theme .mwai-dot1 { animation-delay: -0.32s; }\n.mwai-THEME_ID-theme .mwai-dot2 { animation-delay: -0.16s; }\n.mwai-THEME_ID-theme .mwai-dot3 { animation-delay: 0; }\n\n@keyframes mwai-bounce {\n  0%, 80%, 100% {\n    transform: scale(0);\n    opacity: 0.5;\n  }\n  40% {\n    transform: scale(1);\n    opacity: 1;\n  }\n}\n\n/* ==========================================\n   ERROR & SYSTEM MESSAGES\n   ========================================== */\n.mwai-THEME_ID-theme .mwai-error {\n  background: #fee;\n  color: #c33;\n  padding: 10px;\n  border-radius: var(--mwai-borderRadius);\n  margin: 10px;\n  text-align: center;\n  font-size: 0.9em;\n}\n\n/* ==========================================\n   SHORTCUTS & BLOCKS\n   ========================================== */\n.mwai-THEME_ID-theme .mwai-shortcuts {\n  padding: 10px;\n  display: flex;\n  gap: 8px;\n  flex-wrap: wrap;\n}\n\n.mwai-THEME_ID-theme .mwai-shortcut {\n  background: var(--mwai-bgSecondary);\n  border: 1px solid var(--mwai-borderColor);\n  border-radius: calc(var(--mwai-borderRadius) / 2);\n  padding: 6px 12px;\n  cursor: pointer;\n  font-size: 0.9em;\n  transition: all 0.2s;\n}\n\n.mwai-THEME_ID-theme .mwai-shortcut:hover {\n  background: var(--mwai-primaryColor);\n  color: white;\n  border-color: var(--mwai-primaryColor);\n}\n\n/* ==========================================\n   RESPONSIVE & MOBILE\n   ========================================== */\n@media (max-width: 768px) {\n  .mwai-THEME_ID-theme.mwai-window {\n    width: 100%;\n    height: 100%;\n    max-width: 100%;\n    max-height: 100%;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n  }\n  \n  .mwai-THEME_ID-theme.mwai-window .mwai-content {\n    max-height: 100%;\n    border-radius: 0;\n  }\n  \n  .mwai-THEME_ID-theme .mwai-trigger {\n    right: 20px;\n    bottom: 20px;\n  }\n}',un=e=>{const{theme:t,onUpdateTheme:a}=e,[n,l]=sn("");dn((()=>{l(t.style)}),[t]);const r=cn((()=>n!==t.style),[n,t]);return React.createElement(Pa,null,React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.NAME,":"),React.createElement(ne.A,{name:"name","data-form-type":"other",value:t.name,onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("div",null,React.createElement("label",{style:{display:"block"}},ge.COMMON.ID,":"),React.createElement(ne.A,{name:"themeId",type:"text",placeholder:"Optional",value:t.themeId,onBlur:a,onEnter:a})))),React.createElement(le.g,null),React.createElement("label",null,"Custom CSS:"),React.createElement(Ke.m,{name:"css",value:n,onChange:l,rows:16,tabToSpaces:2}),React.createElement("div",{style:{display:"flex"}},React.createElement(h.M,{fullWidth:!0,onClick:()=>{const e=mn.replace(/THEME_ID/g,t.themeId);l(e)}},"Default CSS"),React.createElement(h.M,{fullWidth:!0,onClick:()=>{a(n,"style")},disabled:!r},"Apply CSS")))},pn=e=>{const{settings:t,onUpdateSettings:a}=e;return React.createElement(React.Fragment,null,React.createElement(Pa,null,React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.SPACING,":"),React.createElement(ne.A,{id:"spacing",name:"spacing",value:(null==t?void 0:t.spacing)??"15px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.BORDER_RADIUS,":"),React.createElement(ne.A,{id:"borderRadius",name:"borderRadius",value:(null==t?void 0:t.borderRadius)??"10px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.FONT_SIZE,":"),React.createElement(ne.A,{id:"fontSize",name:"fontSize",value:(null==t?void 0:t.fontSize)??"15px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_PRIMARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundPrimaryColor)??"#fafafa",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",value:(null==t?void 0:t.backgroundPrimaryColor)??"#fafafa",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_USER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundUserColor",name:"backgroundUserColor",style:{flex:1},value:(null==t?void 0:t.backgroundSecondaryColor)??"#0084ff",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundUserColor",name:"backgroundUserColor",value:(null==t?void 0:t.backgroundSecondaryColor)??"#0084ff",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_AI_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundAiColor",name:"backgroundAiColor",style:{flex:1},value:(null==t?void 0:t.backgroundSecondaryColor)??"#eee",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundAiColor",name:"backgroundAiColor",value:(null==t?void 0:t.backgroundSecondaryColor)??"#eee",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_AI_SECONDARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundAiSecondaryColor",name:"backgroundAiSecondaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundSecondaryColor)??"#ddd",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundAiSecondaryColor",name:"backgroundAiSecondaryColor",value:(null==t?void 0:t.backgroundSecondaryColor)??"#ddd",onChange:a,onEnter:a})))),React.createElement(le.g,null),React.createElement(et.y2,{title:ge.COMMON.POPUP,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.75}},React.createElement("label",null,ge.COMMON.WIDTH,":"),React.createElement(ne.A,{id:"width",name:"width",value:(null==t?void 0:t.width)??"460px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.75}},React.createElement("label",null,ge.COMMON.MAX_HEIGHT,":"),React.createElement(ne.A,{id:"maxHeight",name:"maxHeight",value:(null==t?void 0:t.maxHeight)??"40vh",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.AVATAR_MESSAGE_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#0084ff",onBlur:a,onEnter:a}),React.createElement(rn,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#0084ff",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.AVATAR_MESSAGE_FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onChange:a,onEnter:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BUBBLE_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"bubbleColor",name:"bubbleColor",style:{flex:1},value:(null==t?void 0:t.bubbleColor)??"#0084ff",onBlur:a,onEnter:a}),React.createElement(rn,{id:"bubbleColor",name:"bubbleColor",value:(null==t?void 0:t.bubbleColor)??"#0084ff",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.HEADER_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",style:{flex:1},value:(null==t?void 0:t.backgroundHeaderColor)??"#0084ff",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",value:(null==t?void 0:t.backgroundHeaderColor)??"#0084ff",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.HEADER_BUTTONS_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"headerButtonsColor",name:"headerButtonsColor",style:{flex:1},value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"headerButtonsColor",name:"headerButtonsColor",value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onChange:a,onEnter:a}))))))},En=e=>{const{settings:t,onUpdateSettings:a}=e;return React.createElement(React.Fragment,null,React.createElement(ce.X,{variant:"danger"},"This theme is ",React.createElement("b",null,"still in development"),". The related settings will be available soon."),React.createElement(Pa,null,React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.SPACING,":"),React.createElement(ne.A,{id:"spacing",name:"spacing",value:(null==t?void 0:t.spacing)??"15px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.BORDER_RADIUS,":"),React.createElement(ne.A,{id:"borderRadius",name:"borderRadius",value:(null==t?void 0:t.borderRadius)??"10px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.66}},React.createElement("label",null,ge.COMMON.FONT_SIZE,":"),React.createElement(ne.A,{id:"fontSize",name:"fontSize",value:(null==t?void 0:t.fontSize)??"13px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ge.COMMON.FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_PRIMARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundPrimaryColor)??"#fafafa",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",value:(null==t?void 0:t.backgroundPrimaryColor)??"#fafafa",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_USER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundUserColor",name:"backgroundUserColor",style:{flex:1},value:(null==t?void 0:t.backgroundSecondaryColor)??"#434cc5",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundUserColor",name:"backgroundUserColor",value:(null==t?void 0:t.backgroundSecondaryColor)??"#434cc5",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_AI_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundAiColor",name:"backgroundAiColor",style:{flex:1},value:(null==t?void 0:t.backgroundSecondaryColor)??"#F1F3F7",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundAiColor",name:"backgroundAiColor",value:(null==t?void 0:t.backgroundSecondaryColor)??"#eee",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BACK_AI_SECONDARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundAiSecondaryColor",name:"backgroundAiSecondaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundSecondaryColor)??"#ddd",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundAiSecondaryColor",name:"backgroundAiSecondaryColor",value:(null==t?void 0:t.backgroundSecondaryColor)??"#ddd",onChange:a,onEnter:a})))),React.createElement(le.g,null),React.createElement(et.y2,{title:ge.COMMON.POPUP,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.75}},React.createElement("label",null,ge.COMMON.WIDTH,":"),React.createElement(ne.A,{id:"width",name:"width",value:(null==t?void 0:t.width)??"360px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.75}},React.createElement("label",null,ge.COMMON.MAX_HEIGHT,":"),React.createElement(ne.A,{id:"maxHeight",name:"maxHeight",value:(null==t?void 0:t.maxHeight)??"40vh",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.AVATAR_MESSAGE_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(rn,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#343541",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.AVATAR_MESSAGE_FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onChange:a,onEnter:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.BUBBLE_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"bubbleColor",name:"bubbleColor",style:{flex:1},value:(null==t?void 0:t.bubbleColor)??"#434cc5",onBlur:a,onEnter:a}),React.createElement(rn,{id:"bubbleColor",name:"bubbleColor",value:(null==t?void 0:t.bubbleColor)??"#434cc5",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.HEADER_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",style:{flex:1},value:(null==t?void 0:t.backgroundHeaderColor)??"#434cc5",onBlur:a,onEnter:a}),React.createElement(rn,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",value:(null==t?void 0:t.backgroundHeaderColor)??"#434cc5",onChange:a,onEnter:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.HEADER_BUTTONS_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(ne.A,{id:"headerButtonsColor",name:"headerButtonsColor",style:{flex:1},value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(rn,{id:"headerButtonsColor",name:"headerButtonsColor",value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onChange:a,onEnter:a}))))))},gn=e=>{const{theme:t,updateTheme:a,resetTheme:n,deleteTheme:l}=e,r=(e,n)=>{const l={...t.settings,[n]:e};a(l,"settings")};return React.createElement(React.Fragment,null,"internal"===t.type&&"chatgpt"===t.themeId&&React.createElement(on,{settings:t.settings??[],onUpdateSettings:r}),"internal"===t.type&&"messages"===t.themeId&&React.createElement(pn,{settings:t.settings??[],onUpdateSettings:r}),"internal"===t.type&&"timeless"===t.themeId&&React.createElement(En,{settings:t.settings??[],onUpdateSettings:r}),"internal"!==t.type&&React.createElement(un,{theme:t,onUpdateTheme:a}),React.createElement(le.g,null),React.createElement(et.y2,{title:ge.COMMON.ACTIONS}),React.createElement("div",{style:{display:"flex",marginTop:10}},React.createElement(h.M,{className:"secondary",onClick:()=>{n()}},ge.COMMON.RESET),React.createElement("div",{style:{flex:"auto"}}),React.createElement(h.M,{className:"danger",disabled:"internal"===t.type,onClick:l},ge.COMMON.DELETE)))},{useState:hn}=wp.element,Rn=e=>{const t=(0,l.jE)(),{onSwitchTheme:a=(()=>{})}=e,[n,r]=hn(!1),{data:i}=(0,o.I)({queryKey:["themes"],queryFn:it,initialData:S}),c=e.currentTheme,s=async(e,a)=>{try{r(!0);const n={...c,[a]:e};let l=[...i];const o=l.findIndex((e=>e.themeId===c.themeId));l[o]=n,l=await ct(l),t.setQueryData(["themes"],l)}catch(e){console.error(e)}r(!1)},d=async()=>{r(!0);const e=[...i.filter((e=>e.themeId!==c.themeId))];a(e[0].themeId),await ct(e),await t.setQueryData(["themes"],e),r(!1)},m=async()=>{r(!0);const e=[...i],a=e.findIndex((e=>e.themeId===c.themeId));e[a]={type:e[a].type,name:e[a].name,themeId:e[a].themeId,settings:[],style:""},await ct(e),await t.setQueryData(["themes"],e),r(!1)};return React.createElement(React.Fragment,null,React.createElement(g._,{inversed:!0,onChange:(e,t)=>{const n=i.find((e=>e.themeId===t.key));n&&a(n.themeId)},currentTab:null==c?void 0:c.themeId,action:React.createElement(React.Fragment,null,React.createElement(h.M,{rounded:!0,className:"secondary",icon:"plus",onClick:async()=>{r(!0);try{const e=await ct([...i,{type:"css",name:"New Theme",themeId:"theme-"+Se(),settings:[],style:""}]);t.setQueryData(["themes"],e)}catch(e){console.error(e)}r(!1)}}))},null==i?void 0:i.map((e=>React.createElement(g.V,{key:e.themeId,title:e.name,busy:n},React.createElement(gn,{theme:e,updateTheme:s,resetTheme:m,deleteTheme:d}))))))};var yn=a(1469),vn=a(6966);const fn=()=>{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 bn(){return bn=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},bn.apply(this,arguments)}const{useState:wn,useEffect:_n,useRef:Cn,useCallback:Tn}=wp.element,On=({enabled:e,content:t,children:a,className:n,...l})=>{const r=(0,vn.gR)(),[o,i]=wn("idle"),[c,s]=wn(!0),d=Cn(null),m=Cn(!1),u=Tn((()=>{m.current||(m.current=!0,d.current=setTimeout((()=>{s(!1)}),500))}),[]),p=Tn((()=>{d.current&&clearTimeout(d.current),s(!0),m.current=!1}),[]);_n((()=>()=>{d.current&&clearTimeout(d.current)}),[]);const E="success"===o?'<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" />':"error"===o?'<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" />':'<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" />';return React.createElement("div",bn({},l,{onMouseLeave:p,onMouseEnter:u,onMouseOver:u}),React.createElement("span",{className:n},a),React.createElement("div",{className:r("mwai-reply-actions",{"mwai-hidden":c})},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:E}}))))},{useState:Nn}=wp.element,In=({enabled:e,content:t,children:a,className:n,message:l,...r})=>{const o=(0,vn.gR)(),{actions:i,state:c}=(0,yn.o)(),{setMessages:s,saveMessages:d,retryLastQuery:m}=i,{messages:u}=c,[p,E]=Nn("idle"),g=u.length>0&&u[u.length-1].id===l.id,h="success"===p?'<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" />':"error"===p?'<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" />':'<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" />';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),E("success")}catch(e){E("error"),console.warn("Not allowed to copy to clipboard. Make sure your website uses HTTPS.",{content:t})}finally{setTimeout((()=>{E("idle")}),2e3)}},title:"Copy"},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:h}})),React.createElement("div",{className:"mwai-action-button",onClick:()=>{s((e=>{const t=e.findIndex((e=>e.id===l.id));let a;return a=t>0?e.filter(((e,a)=>a!==t&&a!==t-1)):e.filter((e=>e.id!==l.id)),d(a),a}))},title:"Delete"},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:'<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>'}})),l.failedQuery&&g&&React.createElement("div",{className:"mwai-action-button",onClick:()=>{l.failedQuery&&m&&(s((e=>{const t=e.findIndex((e=>e.id===l.id));let a;return a=t>0?e.filter(((e,a)=>a!==t&&a!==t-1)):e.filter((e=>e.id!==l.id)),d(a),a})),m())},title:"Retry"},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:'<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"/>'}}))))},{useMemo:Mn}=wp.element;const Sn=({role:e="user"})=>{const{state:t}=(0,yn.o)(),{pluginUrl:a,iconUrl:n,userData:l,userName:r,aiName:o,guestName:i,userAvatar:c,aiAvatar:s,guestAvatar:d,userAvatarUrl:m,aiAvatarUrl:u,guestAvatarUrl:p}=t,E=Mn((()=>{const t="assistant"===e,E=!l&&!t,g=e=>React.createElement("div",{className:"mwai-name-text"},e),h=(e,t,n,l,r=!1)=>{if(!e)return null;if((0,Ga.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,vn.mv)(e)?e:e&&!(0,Ga.Ve)(e)?t?e:`${a}/images/${e}`:(t||(0,Ga.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,l):null};if(t){const e=h(s,u,n,"AI Avatar");return e?(null===u&&n&&console.warn("Using iconUrl as a temporary fallback for AI avatar. Please set aiAvatarUrl."),e):g(o)}if(!E){const e=h(c,m,null==l?void 0:l.AVATAR_URL,"User Avatar",!0);return e||g(function(e,t,a){if(!a||0===Object.keys(a).length)return t||e||"Guest";return Object.entries(a).reduce(((e,[t,a])=>{const n=`{${t}}`;return e.includes(n)?e.replace(n,a):e}),e)}(r,i,l))}if(E){const e=h(d,p,null,"Guest Avatar");return e||g(i||"Guest")}}),[e,o,r,i,l,n,s,c,d,u,m,p,a]);return React.createElement("span",{className:"mwai-name"},E)},{useMemo:kn}=wp.element,An=({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)},xn=({message:e})=>{let t=e.content??"";(t.match(/```/g)||[]).length%2!=0&&(t+="\n```");const a=kn((()=>({overrides:{BlinkingCursor:{component:Ga.rn},a:{component:An},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=kn((()=>{let e="";try{e=(0,ga.cx)(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(Ga.rn,null)):n},{useState:Pn,useMemo:Dn,useEffect:Ln,useRef:Fn}=wp.element,Bn=({message:e,onRendered:t=(()=>{})})=>{const{state:a}=(0,yn.o)(),{copyButton:n,debugMode:l}=a,[r]=Pn(e.isQuerying||e.isStreaming),o=e.isQuerying,i=e.isStreaming;if(Ln((()=>{r&&(!r||o||i)||t()}),[r,o,i]),o)return React.createElement(fn,null);const c=e.isError||"error"===e.role?In:On;return React.createElement(React.Fragment,null,React.createElement(Sn,{role:e.role}),React.createElement(c,{content:e.content,enabled:n,className:"mwai-text",message:e},React.createElement(xn,{message:e})))},Un=({message:e,onRendered:t=(()=>{})})=>{const[a,n]=Pn(null==e?void 0:e.images);Ln((()=>{t()}));return e.isQuerying?React.createElement(fn,null):React.createElement(React.Fragment,null,React.createElement(Sn,{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)})))))))},Hn=({message:e,conversationRef:t})=>{var a;const{state:n,actions:l}=(0,yn.o)(),{typewriter:r}=n,{setMessages:o,retryLastQuery:i}=l,c=(0,vn.gR)(),s=Fn(),d=c("mwai-reply",{"mwai-ai":"assistant"===e.role,"mwai-user":"user"===e.role,"mwai-system":"system"===e.role,"mwai-error":"error"===e.role||e.isError}),m=(null==e||null===(a=e.images)||void 0===a?void 0:a.length)>0,u="error"===e.role||e.isError,p=()=>{if(s.current&&!e.isQuerying&&!s.current.classList.contains("mwai-rendered")&&"undefined"!=typeof hljs){s.current.classList.add("mwai-rendered");s.current.querySelectorAll("pre code").forEach((e=>{hljs.highlightElement(e)}))}};return Dn((()=>{if("user"===e.role)return React.createElement("div",{ref:s,className:d},React.createElement(Bn,{message:e}));if("assistant"===e.role)return m?React.createElement("div",{ref:s,className:d},React.createElement(Un,{message:e,conversationRef:t,onRendered:p})):React.createElement("div",{ref:s,className:d},React.createElement(Bn,{message:e,conversationRef:t,onRendered:p}));if("system"===e.role&&!u)return React.createElement("div",{ref:s,className:d},React.createElement(Bn,{message:e,conversationRef:t,onRendered:p}));if(u){const a={...e,role:"assistant"};return React.createElement("div",{ref:s,className:d},React.createElement(Bn,{message:a,conversationRef:t,onRendered:p}))}return React.createElement("div",null,React.createElement("i",null,"Unhandled role."))}),[e,t,m,r])},{useMemo:jn}=wp.element;function Gn(e,t,a,n){if((0,Ga.Ve)(n||a))return l=n||a,React.createElement("div",{className:"mwai-avatar mwai-emoji",style:{fontSize:"48px",lineHeight:"48px"}},l);var l;const r=(o=n,((0,vn.mv)(o)?o:o?`${t}/images/${o}`:null)||a||`${t}/images/chat-openai.svg`);var o,i,c;return r?(i=r,c="AI Engine",React.createElement("div",{className:"mwai-avatar"},React.createElement("img",{alt:c,src:i}))):React.createElement("div",{className:"mwai-name-text"},e)}const $n=()=>{const{state:e,actions:t}=(0,yn.o)(),{theme:a,isWindow:n,fullscreen:l,aiName:r,pluginUrl:o,open:i,iconUrl:c,aiAvatarUrl:s,windowed:d,headerSubtitle:m}=e,{setOpen:u,setWindowed:p}=t,E=jn((()=>{if(!n)return null;const e="timeless"===(null==a?void 0:a.themeId),t=e?Gn(r,o,c,s):null,E=null==m?"Discuss with":m;return React.createElement(React.Fragment,null,e&&React.createElement(React.Fragment,null,t,React.createElement("div",{className:"mwai-name"},E&&React.createElement("small",{className:"mwai-subtitle"},E),React.createElement("div",null,r)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-buttons"},l&&React.createElement("div",{className:"mwai-resize-button",onClick:()=>p(!d)}),React.createElement("div",{className:"mwai-close-button",onClick:()=>u(!i)})))}),[n,null==a?void 0:a.themeId,r,o,c,s,l,p,d,u,i,m]);return React.createElement("div",{className:"mwai-header"},E)},{useMemo:zn,useEffect:Wn}=wp.element,qn=()=>{const{state:e,actions:t}=(0,yn.o)(),{isWindow:a,iconText:n,showIconMessage:l,iconAlt:r,iconUrl:o,open:i}=e,{setShowIconMessage:c,setOpen:s}=t;Wn((()=>{i&&l&&c(!1)}),[i,c,l]);const d=zn((()=>{if(!a)return null;return React.createElement("div",{className:"mwai-trigger mwai-open-button"},React.createElement(vn.bE,{className:"mwai-icon-text-container",if:n&&l},React.createElement("div",{className:"mwai-icon-text-close",onClick:()=>c(!1)},"✕"),React.createElement("div",{className:"mwai-icon-text",onClick:()=>s(!0)},n)),React.createElement("div",{className:"mwai-icon-container",onClick:()=>s(!0)},(0,Ga.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})))}),[a,n,l,r,o,c,s]);return React.createElement(React.Fragment,null,d)};var Vn=a(2192);const{useState:Yn,useMemo:Kn,useRef:Xn}=wp.element,Qn=()=>{const e=(0,vn.gR)(),{state:t,actions:a}=(0,yn.o)(),{uploadedFile:n,busy:l,imageUpload:r,fileUpload:o,fileSearch:i,draggingType:c}=t,{onUploadFile:s}=a,[d,m]=Yn(!1),u=Xn(),p=null==n?void 0:n.uploadedId,E=r||i||o,g=n,h=Kn((()=>null!=g&&g.localFile?g.localFile.type.startsWith("image/")?"image":"document":c),[g,c]),R=Kn((()=>{let e="idle";null!=g&&g.uploadProgress?e="up":c?e="add":d&&p?e="del":p?e="ok":d&&!p&&(e="add");return`mwai-file-upload-icon mwai-${h?h.toLowerCase():"idle"}-${e}`}),[h,g,c,d,p]),y=Kn((()=>null!=g&&g.uploadProgress?g.uploadProgress>99?99:Math.round(g.uploadProgress):""),[g]);return E?React.createElement("div",{disabled:l,onClick:()=>{null!=n&&n.localFile?s(null):l||u.current.click()},onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!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:l?"default":"pointer"}},React.createElement("div",{className:R},React.createElement("span",{className:"mwai-file-upload-progress"},y)),React.createElement("input",{type:"file",ref:u,onChange:e=>{const t=e.target.files[0];t&&s(t)},style:{display:"none"}})):null},{useRef:Jn,useState:Zn,useEffect:el,useImperativeHandle:tl}=wp.element,al=()=>{const e=(0,vn.gR)(),{state:t,actions:a}=(0,yn.o)(),{inputText:n,textInputMaxLength:l,textInputPlaceholder:r,error:o,speechRecognitionAvailable:i,isMobile:c,conversationRef:s,open:d,uploadIconPosition:m,locked:u,isListening:p,busy:E,speechRecognition:g,chatbotInputRef:h}=t,{onSubmitAction:R,setIsListening:y,resetError:v,setInputText:f}=a,[b,w]=Zn(!1),_=Jn();tl(h,(()=>({focusInput:()=>{var e;null===(e=_.current)||void 0===e||e.focus()},currentElement:()=>_.current}))),el((()=>{!c&&d&&_.current.focus(),s.current&&(s.current.scrollTop=s.current.scrollHeight)}),[d,c,s]);const C=e("mwai-input-text",{});return React.createElement("div",{ref:h,className:C},"mwai-input"===m&&React.createElement(Qn,null),React.createElement(Vn.A,{ref:_,disabled:E||u,placeholder:r,value:n,maxLength:l,onCompositionStart:()=>w(!0),onCompositionEnd:()=>w(!1),onKeyDown:e=>{b||"Enter"!==e.code||e.shiftKey||(e.preventDefault(),R())},onChange:e=>{return t=e.target.value,p&&y(!1),o&&v(),void f(t);var t}}),g&&React.createElement(vn.tm,{active:p,disabled:!i||E,className:"mwai-microphone",onClick:()=>y(!p)}))};var nl=a(7775),ll=a(1585);const{useMemo:rl,useCallback:ol}=wp.element,il=()=>{const{state:e,actions:t}=(0,yn.o)(),{onClear:a,onSubmitAction:n,setIsListening:l}=t,{textClear:r,textSend:o,uploadedFile:i,inputText:c,messages:s,isListening:d,timeElapsed:m,busy:u,submitButtonConf:p,locked:E}=e,g=!(null==i||!i.uploadProgress),h=!!(null==i||!i.uploadedId)&&c.length<1&&(null==s?void 0:s.length)>1,R=rl((()=>u?m?React.createElement("div",{className:"mwai-timer"},m):null:null!=p&&p.imageSend&&null!=p&&p.imageClear?React.createElement("img",{src:h?p.imageClear:p.imageSend,alt:h?r:o}):h||o?h&&!r?React.createElement(ll.A,{size:"20"}):React.createElement("span",null,h?r:o):React.createElement(nl.A,{size:"20",style:{marginLeft:10}})),[u,m,h,r,o,p]),y=rl((()=>"mwai-input-submit "+(u?"mwai-busy":"")),[u]),v=ol((()=>{d&&l(!1),h?a():n()}),[h,d,a,n,l]),f=ol((()=>{u||v()}),[u,v]);return React.createElement("button",{className:y,disabled:u||g||E,onClick:f},R)};var cl=a(5731),sl=a(9798),dl=a(8834),ml=a(7611),ul=a(3893),pl=a(718),El=a(215);const{useState:gl,useRef:hl,useEffect:Rl}=wp.element;function yl(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 vl({assistantStream:e=null,userStream:t=null,assistantColor:a=null,userColor:n=null,userUI:l={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:c=50,pulseMaxSize:s=30}){const[d,m]=gl(0),[u,p]=gl(0),E=hl(0),g=hl(0),h=hl(null),R=hl(null),y=hl(null),v=hl(null),f=hl(null);Rl((()=>{if(!e&&!t)return;h.current||(h.current=new AudioContext);const a=h.current;let n,l,r;e&&(n=a.createMediaStreamSource(e),R.current=a.createAnalyser(),R.current.fftSize=1024,y.current=new Uint8Array(R.current.frequencyBinCount),n.connect(R.current)),t&&(l=a.createMediaStreamSource(t),v.current=a.createAnalyser(),v.current.fftSize=1024,f.current=new Uint8Array(v.current.frequencyBinCount),l.connect(v.current));const c=()=>{let e=0;R.current&&y.current&&(e=yl(R.current,y.current));let t=0;v.current&&f.current&&(t=yl(v.current,f.current)),e>E.current?E.current=E.current*(1-o)+e*o:E.current=E.current*(1-i)+e*i,t>g.current?g.current=g.current*(1-o)+t*o:g.current=g.current*(1-i)+t*i,m(E.current),p(g.current),r=requestAnimationFrame(c)};return c(),()=>{n&&n.disconnect(),R.current&&R.current.disconnect(),l&&l.disconnect(),v.current&&v.current.disconnect(),r&&cancelAnimationFrame(r)}}),[e,t,o,i]);const b=c+Math.min(d/20,1)*s,w=c+Math.min(u/20,1)*s,_=c+s,C={width:w,height:w,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",opacity:.5};n&&(C.backgroundColor=n);const T={width:b,height:b,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",opacity:.5};a&&(T.backgroundColor=a);const O={width:c,height:c,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"flex",justifyContent:"center",alignItems:"center",overflow:"hidden",color:"#fff"};n&&(O.backgroundColor=n);const N={width:c,height:c,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"flex",justifyContent:"center",alignItems:"center",overflow:"hidden",color:"#fff"};a&&(N.backgroundColor=a);let I="mwai-visualizer";u>d?I+=" mwai-user-talking":d>u&&(I+=" mwai-assistant-talking");const M=e=>{if(!e)return null;const{emoji:t,text:a,image:n,use:l}=e;switch(l){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:_,height:_,overflow:"visible"}},React.createElement("div",{className:"mwai-animation",style:C}),React.createElement("div",{style:O},M(l))),React.createElement("hr",{className:"mwai-visualizer-line"}),React.createElement("div",{className:"mwai-visualizer-assistant",style:{position:"relative",width:_,height:_,overflow:"visible"}},React.createElement("div",{className:"mwai-animation",style:T}),React.createElement("div",{style:N},M(r))))}const fl="tool_call",bl="tool_result",wl="status",_l="error",Cl="transcript";const Tl=class{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(wl,"Starting realtime session...")}sessionConnected(){const e=this.sessionStartTime?(new Date).getTime()-this.sessionStartTime:0;this.emit(wl,`Realtime session connected in ${e}ms.`)}sessionEnding(){this.emit(wl,"Ending realtime session...")}sessionError(e){this.emit(_l,`Realtime session error: ${e}`)}userStartedSpeaking(){this.emit(wl,"User speaking...",{visibility:"collapsed"})}userStoppedSpeaking(){this.emit(wl,"User finished speaking.",{visibility:"collapsed"})}assistantStartedSpeaking(){this.emit(wl,"Assistant speaking...",{visibility:"collapsed"})}assistantStoppedSpeaking(){this.emit(wl,"Assistant finished speaking.",{visibility:"collapsed"})}functionCalling(e,t){this.emit(fl,`Calling ${e}...`,{metadata:{tool_name:e,arguments:t}})}functionResult(e,t){this.emit(bl,`Got result from ${e}.`,{metadata:{tool_name:e,result:t}})}functionError(e,t){this.emit(_l,`Function ${e} failed: ${t}`,{metadata:{tool_name:e}})}userTranscribed(e){this.emit(wl,`User: "${e}"`,{visibility:"collapsed"})}assistantTranscribed(e){this.emit(wl,`Assistant: "${e}"`,{visibility:"collapsed"})}usageUpdated(e){const{text_input_tokens:t,audio_input_tokens:a,text_output_tokens:n,audio_output_tokens:l}=e,r=t+a+n+l;this.emit(wl,`Tokens used: ${r} (Text: ${t}/${n}, Audio: ${a}/${l})`,{visibility:"collapsed",metadata:{usage:e}})}},{useState:Ol,useRef:Nl,useCallback:Il,useMemo:Ml,useEffect:Sl}=wp.element,kl=1,Al=3,xl=kl;function Pl(e,...t){xl>=e&&console.log(...t)}function Dl(e,t="user"){const{pluginUrl:a,iconUrl:n,userData:l,userName:r,aiName:o,guestName:i,userAvatar:c,aiAvatar:s,guestAvatar:d,userAvatarUrl:m,aiAvatarUrl:u,guestAvatarUrl:p}=e,E=(e,t,n,l,r=!1)=>{if(t){const e=((e,t=!1)=>(0,vn.mv)(e)?e:e&&!(0,Ga.Ve)(e)?t?e:`${a}/images/${e}`:null)(n,r)||l;if(e)return{emoji:null,text:null,image:e,use:"image"}}return(0,Ga.Ve)(e)?{emoji:e,text:null,image:null,use:"emoji"}:{emoji:null,text:e,image:null,use:"text"}};if("assistant"===t)return E(o,s,u,n);if(l){const e=function(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"}(r,i,l);return E(e,c,m,null==l?void 0:l.AVATAR_URL,!0)}return l||"user"!==t?{emoji:null,text:"Unknown",image:null,use:"text"}:E(i||"Guest",d,p,null)}const Ll=({onMessagesUpdate:e,onStreamEvent:t})=>{const{state:a,actions:n}=(0,yn.o)(),{busy:l,locked:r,open:o,popup:i,system:c}=a,{onStartRealtimeSession:s,onRealtimeFunctionCallback:d,onCommitStats:m,onCommitDiscussions:u,setError:p}=n,E=(null==c||c.debugMode,(null==c?void 0:c.eventLogs)||!1),[g,h]=Ol(!1),[R,y]=Ol(!1),[v,f]=Ol(!1),[b,w]=Ol(null),[_,C]=Ol(null),[T,O]=Ol({text_input_tokens:0,audio_input_tokens:0,text_output_tokens:0,audio_output_tokens:0,text_cached_tokens:0,audio_cached_tokens:0}),[N,I]=Ol([]),M=Nl(new Set),S=Il(((e,a)=>{a&&a.subtype&&t&&t({...a,timestamp:a.timestamp||(new Date).getTime(),messageId:"realtime-session"})}),[t]),k=Nl(null);Sl((()=>{k.current=new Tl(S,E)}),[S,E]);const A=Nl(null),x=Nl(null),P=Nl(null),D=Nl(null),[L,F]=Ol(!0),[B,U]=Ol(!0),[H,j]=Ol(!1),[G,$]=Ol(!1),[z,W]=Ol(null),q=Nl([]),V=Ml((()=>Dl(a,"user")),[a]),Y=Ml((()=>Dl(a,"assistant")),[a]);Sl((()=>{!o&&R&&i&&Z()}),[o,i,R]),Sl((()=>{e&&e(N)}),[N,e]);const K=Il((async e=>{const t=await m(e);t.overLimit&&(E&&k.current&&k.current.emit(_l,t.limitMessage||"Usage limit exceeded",{visibility:"visible",error:!0}),console.warn("Usage limit exceeded, stopping realtime connection:",t.limitMessage),D.current&&D.current())}),[m,E]),X=Il((()=>{x.current&&"open"===x.current.readyState?(x.current.send(JSON.stringify({type:"session.update",session:{input_audio_transcription:{model:"whisper-1"}}})),Pl(kl,"Sent session.update to enable Whisper.")):console.error("Data channel is not open yet; cannot enable transcription.")}),[]),Q=Il((async(e,t,a)=>{let n={};try{n=JSON.parse(a||"{}")}catch(e){console.error("Could not parse function arguments.",a)}const l=q.current.find((e=>e.name===t));if(l)try{var r;const a=await d(l.id,l.type,l.name,l.target,n);if(null==a||!a.success)return void console.error("Callback failed.",null==a?void 0:a.message);const o=a.data;if(E&&k.current){const a="string"==typeof o?o:JSON.stringify(o),n=a.length>100?a.substring(0,100)+"...":a;k.current.emit(bl,`Got result from ${t}.`,{metadata:{tool_name:t,result:n,call_id:e}})}"open"===(null===(r=x.current)||void 0===r?void 0:r.readyState)&&(Pl(kl,"Send callback value:",o),x.current.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(o)}})),x.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}'.`)}),[d,E]),J=Il((async(e,t)=>{h(!0),E&&k.current&&k.current.emit(wl,"Starting realtime session...",{visibility:"visible"});const a=new RTCPeerConnection;let n;A.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}),P.current=n,n.getTracks().forEach((e=>a.addTrack(e,n)))}catch(e){return console.error("Error accessing microphone.",e),E&&k.current&&k.current.emit(wl,"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 h(!1)}a.ontrack=e=>{const t=document.getElementById("mwai-audio");t&&(t.srcObject=e.streams[0]),W(e.streams[0])};const l=a.createDataChannel("oai-events");x.current=l,l.addEventListener("open",(()=>{Pl(kl,"Data channel open."),E&&k.current&&k.current.emit(wl,"Realtime session connected",{visibility:"visible"}),X()})),l.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(xl>=Al)console.log("Incoming message from Realtime API.",t);else if(xl===kl){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(E&&t.type&&k.current){let e="",a=wl,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=Cl,n=!0;break;case"response.audio_transcript.done":e="Got transcript from assistant.",a=Cl,n=!0;break;case"response.function_call_arguments.done":e=`Calling ${t.name}...`,a=fl,n=!0}n&&k.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;Pl(kl,"Function call requested.",e,a),Q(e,a,n);break}case"response.done":{const e=t.response;if(null!=e&&e.usage){const t=function(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:l=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:l}}(e.usage);t&&O((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 K(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 h(!1);const c=await i.text();await a.setRemoteDescription({type:"answer",sdp:c}),Pl(kl,"Realtime connection established."),h(!1),y(!0),f(!1),C("user")}),[X,Q,K,p]),Z=Il((()=>{E&&k.current&&k.current.emit(wl,"Ending realtime session...",{visibility:"visible"});try{A.current&&(A.current.close(),A.current=null),P.current&&(P.current.getTracks().forEach((e=>e.stop())),P.current=null),x.current=null,h(!1),y(!1),f(!1),C(null),u(N),I([]),O({text_input_tokens:0,audio_input_tokens:0,text_output_tokens:0,audio_output_tokens:0,text_cached_tokens:0,audio_cached_tokens:0}),Pl(kl,"Stopped Realtime connection.")}catch(e){console.error("Error stopping connection.",e)}}),[N,T,u]);Sl((()=>{D.current=Z}),[Z]);const ee=Il((()=>{if(!P.current)return;const e=P.current.getAudioTracks();e.length&&(v?(e.forEach((e=>{e.enabled=!0})),Pl(kl,"Resumed microphone."),f(!1)):(e.forEach((e=>{e.enabled=!1})),Pl(kl,"Paused microphone."),f(!0)))}),[v]),te=Il((async()=>{h(!0);try{const e=await s();if(null==e||!e.success){console.error("Could not start realtime session.",e),h(!1);const t=(null==e?void 0:e.message)||"Could not start realtime session.";return void p(t)}q.current=e.function_callbacks||[],w(e.session_id),await J(e.client_secret,e.model)}catch(e){console.error("Error in handlePlay.",e),h(!1);const t=e.message||"An error occurred while starting the realtime session.";p(t)}}),[s,J,p]),ae=Il((()=>Z()),[Z]),ne=Il((()=>U((e=>!e))),[]),le=Il((()=>$((e=>!e))),[]),re=Il((()=>j((e=>!e))),[]),oe=Ml((()=>v?"mwai-pause mwai-active":"mwai-pause"),[v]),ie=Ml((()=>{const e=[...N].reverse().find((e=>"assistant"===e.role));return e?e.content.length>256?`${e.content.slice(0,256)}...`:e.content:"..."}),[N]),ce=Ml((()=>B?"mwai-option mwai-option-users mwai-active":"mwai-option mwai-option-users"),[B]),se=Ml((()=>H?"mwai-option mwai-option-captions mwai-active":"mwai-option mwai-option-captions"),[H]),de=Ml((()=>G?"mwai-option mwai-option-statistics mwai-active":"mwai-option mwai-option-statistics"),[G]);return React.createElement("div",null,React.createElement("audio",{id:"mwai-audio",autoPlay:!0}),B&&React.createElement("div",{style:{display:"flex",justifyContent:"center"}},React.createElement(vl,{assistantStream:z,userUI:V,assistantUI:Y,userStream:P.current})),React.createElement("div",{className:"mwai-controls"},!R&&!g&&React.createElement("button",{onClick:te,className:"mwai-play",disabled:l||r,"aria-label":"Play"},React.createElement(cl.A,{size:16})),g&&React.createElement("button",{className:"mwai-play",disabled:!0},React.createElement(sl.A,{size:16,style:{animation:"spin 0.8s linear infinite"}})),R&&!g&&React.createElement(React.Fragment,null,React.createElement("button",{onClick:ae,className:"mwai-stop",disabled:l||r,"aria-label":"Stop"},React.createElement(dl.A,{size:16})),React.createElement("button",{onClick:ee,className:oe,disabled:l||r,"aria-label":"Pause"},React.createElement(ml.A,{size:16})))),H&&ie&&ie.length>0&&React.createElement("div",{className:"mwai-last-transcript"},ie),G&&React.createElement("div",{className:"mwai-statistics"},React.createElement("div",null,React.createElement("label",null,"Text In"),React.createElement("span",null,T.text_input_tokens)),React.createElement("div",null,React.createElement("label",null,"Text Out"),React.createElement("span",null,T.text_output_tokens)),React.createElement("div",null,React.createElement("label",null,"Text Cached"),React.createElement("span",null,T.text_cached_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio In"),React.createElement("span",null,T.audio_input_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio Out"),React.createElement("span",null,T.audio_output_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio Cached"),React.createElement("span",null,T.audio_cached_tokens))),L&&React.createElement("div",{className:"mwai-options"},React.createElement(ul.A,{size:13,title:"Show Users",className:ce,onClick:ne}),React.createElement(pl.A,{size:18,title:"Show Captions",className:se,onClick:re}),React.createElement(El.A,{size:14,title:"Show Statistics",className:de,onClick:le})))};var Fl=a(6816),Bl=a(6844),Ul=a(9454),Hl=a(8445),jl=a(7946),Gl=a(8697),$l=a(942),zl=a(3324),Wl=a(5107),ql=a(7677);const{useState:Vl,useMemo:Yl,useEffect:Kl}=wp.element,Xl=({allStreamData:e,debugMode:t,onClear:a,hasData:n,isWindow:l})=>{const[r,o]=Vl({}),[i,c]=Vl(!1),[s,d]=Vl(!l),m=Yl((()=>{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 s?t.slice(0,20):t.slice(0,1)}),[e,s]),u=(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&&m.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"}},E=Yl((()=>{if(0===m.length)return null;for(const e of m){const t=u(e.subtype,e.metadata);if("debug"!==e.subtype&&"heartbeat"!==e.subtype){if(e.data.includes("Stream completed")){const t=m.findIndex((e=>e.data.includes("Request completed")));if(t>=0&&t<m.indexOf(e)){const e=m[t];return{data:e.data,category:u(e.subtype,e.metadata),color:p(u(e.subtype,e.metadata),e.data)}}}return{data:e.data,category:t,color:p(t,e.data)}}}return null}),[m]);return React.createElement("div",{className:"mwai-chunks "+(i?"":"mwai-chunks-collapsed")},React.createElement("div",{className:"mwai-chunks-header"},React.createElement(Bl.A,{size:12}),React.createElement("span",{className:"mwai-chunks-title"},"Events",E&&React.createElement("span",{className:"mwai-chunks-status",style:{color:E.color}},": ",E.data)),i&&React.createElement(React.Fragment,null,m.length>0&&a&&React.createElement("div",{className:"mwai-chunks-toggle",onClick:a,title:"Clear stream events"},React.createElement(Gl.A,{size:12})),!l&&React.createElement("div",{className:"mwai-chunks-toggle",onClick:()=>d(!s),title:s?"Show minimal (last event only)":"Show detailed (all events)"},s?React.createElement($l.A,{size:12}):React.createElement(zl.A,{size:12}))),React.createElement("div",{className:"mwai-chunks-toggle",onClick:()=>c(!i),title:i?"Hide events":"Show events"},i?React.createElement(Wl.A,{size:12}):React.createElement(ql.A,{size:12}))),i&&(0===m.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(Bl.A,{size:14}),"waiting"),React.createElement("span",{className:"mwai-chunk-data"},"No events yet."))):m.map((e=>{const t=r[e.id],a=u(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(Fl.A,{size:14});case"mcp":case"output":default:return React.createElement(Bl.A,{size:14});case"thinking":return React.createElement(Ul.A,{size:14});case"search":return React.createElement(Hl.A,{size:14});case"error":case"warning":return React.createElement(jl.A,{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(ql.A,{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(0,ga.cx)(t)}catch(e){return React.createElement("pre",null,t)}})()):React.createElement("pre",null,JSON.stringify(e.metadata,null,2))))}))))},{useState:Ql,useEffect:Jl,useRef:Zl,useMemo:er}=wp.element,tr=({conversationRef:e,onScroll:t,messageList:a,jsxShortcuts:n,jsxBlocks:l,inputClassNames:r,handleDrop:o,handleDrag:i,needsFooter:c,needTools:s,uploadIconPosition:d})=>{const{state:m,actions:u}=(0,yn.o)(),{debugMode:p,eventLogs:E,messages:g,isRealtime:h,textCompliance:R,chatbotInputRef:y,isWindow:v}=m,[f,b]=Ql([]),[w,_]=Ql(new Set),C=Zl([]),[T,O]=(Zl(0),Ql([]));Jl((()=>{(0===g.length||1===g.length&&"assistant"===g[0].role)&&_(new Set)}),[g]),Jl((()=>{const e=[];[...g,...T].forEach((t=>{t.streamEvents&&p&&!w.has(t.id)&&t.streamEvents.forEach((a=>{e.push({...a,messageId:t.id})}))})),h||(C.current=e,b(e))}),[g,T,p,h,w]);return React.createElement("div",{className:"mwai-body"},!h&&React.createElement(React.Fragment,null,React.createElement("div",{ref:e,className:"mwai-conversation",onScroll:t},a,n),l,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(al,null),React.createElement(il,null))),h&&React.createElement("div",{className:"mwai-realtime"},React.createElement(Ll,{onMessagesUpdate:O,onStreamEvent:e=>{b((t=>[...t,e]))}})),c&&React.createElement("div",{className:"mwai-footer"},s&&React.createElement("div",{className:"mwai-tools"},"mwai-tools"===d&&React.createElement(Qn,null)),R&&React.createElement("div",{className:"mwai-compliance",dangerouslySetInnerHTML:{__html:R}})),E&&React.createElement(Xl,{allStreamData:f,debugMode:p,onClear:()=>{b([]),C.current=[];const e=new Set;[...g,...T].forEach((t=>{t.streamEvents&&e.add(t.id)})),_(e)},hasData:f.length>0,isWindow:v}))},{useState:ar,useMemo:nr,useLayoutEffect:lr,useCallback:rr,useEffect:or,useRef:ir}=wp.element,cr=e=>{const t=(0,vn.gR)(),{style:a}=e,[n,l]=ar(!0),{state:r,actions:o}=(0,yn.o)(),{theme:i,botId:c,customId:s,messages:d,textCompliance:m,isWindow:u,fullscreen:p,iconPosition:E,iconBubble:g,shortcuts:h,blocks:R,imageUpload:y,fileSearch:v,fileUpload:f,draggingType:b,isBlocked:w,virtualKeyboardFix:_,windowed:C,cssVariables:T,conversationRef:O,open:N,busy:I,uploadIconPosition:M}=r,{onSubmit:S,setIsBlocked:k,setDraggingType:A,onUploadFile:x}=o,P=nr((()=>"css"===(null==i?void 0:i.type)?null==i?void 0:i.style:null),[i]),D=y||v||f,L=D||m,F=ir(null),{viewportHeight:B,isIOS:U,isAndroid:H}=(0,vn.kW)();or((()=>{if(!_)return;if(!U&&!H)return;if(!u)return;const e=document.querySelector(".mwai-window");if(e)if(N){if(e.style.height=`${B}px`,U){(()=>{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)}})()}}else e.style.height=""}),[p,H,U,u,C,N,B,_]);const j=t("mwai-chatbot",{[`mwai-${null==i?void 0:i.themeId}-theme`]:!0,"mwai-window":u,"mwai-bubble":g,"mwai-open":N,"mwai-fullscreen":!C||!u&&p,"mwai-bottom-left":"bottom-left"===E,"mwai-top-right":"top-right"===E,"mwai-top-left":"top-left"===E});lr((()=>{n&&O.current&&(O.current.scrollTop=O.current.scrollHeight)}),[d,n,O,I]);const G=ir(new Set);or((()=>{R&&R.length>0&&R.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(!G.current.has(t)){const a=document.createElement("script");a.type="text/javascript",a.textContent=e,document.body.appendChild(a),G.current.add(t)}})(a.script)}))}),[R]);const $=nr((()=>null==d?void 0:d.map((e=>React.createElement(Hn,{key:e.id,message:e})))),[d]),z=nr((()=>h&&0!==h.length?React.createElement("div",{className:"mwai-shortcuts"},h.map(((e,a)=>{const{type:n,data:l}=e,{label:r,variant:o,icon:i,className:s}=l??{};let d=t("mwai-shortcut",{"mwai-success":"success"===o,"mwai-danger":"danger"===o,"mwai-warning":"warning"===o,"mwai-info":"info"===o});s&&(d+=` ${s}`);const m=i&&i.startsWith("http"),u=i&&!m&&i.length>=1&&i.length<=2;switch(n){case"message":{const{message:e}=l,t=()=>{S(e)};return React.createElement("button",{className:d,key:a,onClick:t},(m||u)&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},m&&React.createElement("img",{src:i,alt:r||"AI Shortcut"}),u&&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}=l,t=()=>{if("function"==typeof e)e();else if("string"==typeof e){const t=e.replace(/{CHATBOT_ID}/g,c),a=new Function(`return (${t});`)();l.onClick=a,a()}else console.warn("No valid callback function provided in data.onClick.")};return React.createElement("button",{className:d,key:a,onClick:t},(m||u)&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},m&&React.createElement("img",{src:i,alt:r||"AI Shortcut"}),u&&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,S,h]),W=nr((()=>R&&0!==R.length?React.createElement("div",{className:"mwai-blocks"},R.map(((e,a)=>{const{type:n,data:l}=e;if("content"!==n)return console.warn(`Block type ${n} is not supported.`),null;const{html:r,variant:o}=l,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,R]),q=rr(((e,t)=>{e.preventDefault(),e.stopPropagation();const a=e.dataTransfer.items[0];t?(F.current&&(clearTimeout(F.current),F.current=null),y&&(e=>e.type.startsWith("image/"))(a)?(A("image"),k(!1)):(v||f)&&(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))(a)?(A("document"),k(!1)):(A(!1),k(!0))):F.current||(F.current=setTimeout((()=>{A(!1),k(!1),F.current=null}),100))}),[y,v,f]),V=rr((e=>{if(e.preventDefault(),q(e,!1),I)return;const t=e.dataTransfer.files[0];t&&("image"===b&&y||"document"===b&&(v||f)?x(t):(k(!0),setTimeout((()=>k(!1)),2e3)))}),[I,b,y,f,v,x]),Y=t("mwai-input",{"mwai-dragging":b,"mwai-blocked":w});return React.createElement(vn.bE,{dir:"auto",id:`mwai-chatbot-${s||c}`,className:j,style:{...T,...a},if:!0,disableTransition:!u},P&&React.createElement("style",null,P),React.createElement(qn,null),React.createElement($n,null),React.createElement(tr,{conversationRef:O,onScroll:()=>{if(O.current){const{scrollTop:e,scrollHeight:t,clientHeight:a}=O.current;l(t-e<=a+1)}},messageList:$,jsxShortcuts:z,jsxBlocks:W,inputClassNames:Y,handleDrop:V,handleDrag:q,needsFooter:L,needTools:D,uploadIconPosition:M}))},sr=e=>React.createElement(yn.G,e,React.createElement(cr,e)),{useMemo:dr,useState:mr,useEffect:ur}=wp.element,pr=e=>{e?localStorage.setItem("mwai-admin-chatbotKey",e):localStorage.removeItem("mwai-admin-chatbotKey")},Er=e=>{const t=(0,l.jE)(),{options:a,updateOption:n,busy:i}=e,[c,s]=mr("chatbots"),[d,m]=mr(!1),[u,p]=mr((()=>localStorage.getItem("mwai-admin-chatbotKey")||"chatbot-key-0")),R=null==a?void 0:a.chatbot_defaults,{colors:y}=(0,r.z)(),{data:v}=(0,o.I)({queryKey:["chatbots"],queryFn:st,initialData:A}),{data:f}=(0,o.I)({queryKey:["themes"],queryFn:it,initialData:S}),w=(null==a?void 0:a.botId)??"none",T=(null==a?void 0:a.chatbot_select)??"tabs",O=i||d,[I,x]=mr({});ur((()=>{if(v){const e={};if(v.forEach(((t,a)=>{e[`chatbot-key-${a}`]=t.botId})),x(e),!u||!(u in e)){const t=Object.keys(e)[0];p(t),pr(t)}}}),[v,u]);const P=dr((()=>{if(v){return v.find((e=>"default"===e.botId))}}),[v]),D=dr((()=>{if(v&&u&&I[u]){const e=I[u];return v.find((t=>t.botId===e))}return null}),[v,u,I]),L=dr((()=>{if(f&&D){return f.find((e=>e.themeId===(null==D?void 0:D.themeId)))}return f.find((e=>"chatgpt"===e.themeId))}),[D,f]),F=async(e,a)=>{if("botId"===a&&"default"===e)return void alert("You cannot name a chatbot 'default'. Please choose another name.");if("botId"===a&&""===e)return void alert("Your chatbot must have an ID.");if("botId"===a&&v.find((t=>t.botId===e)))return void alert("This chatbot ID is already in use. Please choose another ID.");m(!0);const n={...D,[a]:e};let l=[...v];if(D){const r=l.findIndex((e=>e.botId===D.botId));-1!==r&&(l[r]=n,l=await dt(l),t.setQueryData(["chatbots"],l),"botId"===a&&x((t=>({...t,[u]:e}))))}m(!1)},B=async(e=R)=>{m(!0);const a="chatbot-"+Se(),n={...e,botId:a,name:"New Chatbot"};delete n.functions;const l=await dt([...v,n]);t.setQueryData(["chatbots"],l);const r=`chatbot-key-${Object.keys(I).length}`;x((e=>({...e,[r]:a}))),p(r),pr(r),m(!1)},U=async()=>{m(!0);const e=I[u],a=Object.keys(I),n=a.indexOf(u);let l;l=n>0?a[n-1]:a.length>1?a[n+1]:null,p(l),pr(l);let r=v.filter((t=>t.botId!==e));r=await dt(r),t.setQueryData(["chatbots"],r);const o={...I};delete o[u],x(o),m(!1)},H=async()=>{m(!0);let e=[...v];const a=e.findIndex((e=>e.botId===D.botId));e[a]={...R,botId:D.botId,name:D.name},e=await dt(e),t.setQueryData(["chatbots"],e),m(!1)},j=async()=>{B(D)};return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,fullWidth:!0,style:{margin:10}},React.createElement(Qe.V,null,React.createElement(ja,{currentChatbot:D}),React.createElement("label",{style:{marginLeft:5}},ge.COMMON.CHATBOTS),React.createElement(Je.S,{style:{marginLeft:5},disabled:O,onLabel:"",offLabel:"",width:42,offValue:"chatbots",onValue:"themes",offBackgroundColor:y.blue,onBackgroundColor:y.purple,checked:"themes"===c,onChange:s}),React.createElement("label",{style:{marginLeft:5}},ge.COMMON.THEMES),React.createElement("div",{style:{flex:"auto"}}),React.createElement("label",null,ge.COMMON.SITE_WIDE_CHATBOT,":"),React.createElement(ae.u,{scrolldown:!0,name:"botId",disabled:O,style:{minWidth:160},value:w,onChange:n},React.createElement(ae.j,{value:"none",label:"None"}),null==v?void 0:v.map((e=>React.createElement(ae.j,{key:e.botId,value:e.botId,label:e.name})))))),React.createElement(E.Y,{minimal:!0,style:{margin:10,maxWidth:"50%"}},"chatbots"===c&&React.createElement(React.Fragment,null,"dropdown"===T&&React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",alignItems:"center",marginBottom:10}},React.createElement(ae.u,{scrolldown:!0,textFiltering:!0,name:"botId",disabled:O,style:{flex:"auto",marginRight:10},value:u,onChange:p},null==v?void 0:v.map(((e,t)=>React.createElement(ae.j,{key:e.botId,value:`chatbot-key-${t}`,label:e.name})))),React.createElement(h.M,{rounded:!0,className:"secondary",icon:"plus",disabled:O,onClick:()=>B()})),D&&React.createElement(re.L,{style:{borderRadius:10}},React.createElement(Ja,{style:{margin:"-10px -10px"},options:a,themes:f,defaultChatbot:P,deleteCurrentChatbot:U,resetCurrentChatbot:H,duplicateCurrentChatbot:j,shortcodeParams:D,updateShortcodeParams:F}))),"tabs"===T&&React.createElement(React.Fragment,null,React.createElement(g._,{inversed:!0,onChange:(e,t)=>{p(t.key),pr(t.key)},currentTab:u,action:React.createElement(h.M,{rounded:!0,className:"secondary",icon:"plus",disabled:O,onClick:()=>B()})},Object.entries(I).map((([e,t])=>{const n=v.find((e=>e.botId===t));return React.createElement(g.V,{key:e,title:n.name,busy:d},React.createElement(Ja,{options:a,themes:f,defaultChatbot:P,deleteCurrentChatbot:U,resetCurrentChatbot:H,duplicateCurrentChatbot:j,shortcodeParams:n,updateShortcodeParams:F}))}))))),"themes"===c&&React.createElement(Rn,{themes:f,options:a,updateOption:n,currentTheme:L,onSwitchTheme:e=>{F(e,"themeId")}})),React.createElement(E.Y,{minimal:!0,style:{maxWidth:"50%"}},React.createElement("small",{style:{marginLeft:15,marginBottom:-20}},"Chatbot: ",React.createElement("b",null,null==D?void 0:D.name)," - Theme: ",React.createElement("b",null,null==L?void 0:L.name)),React.createElement("div",{style:{position:"relative",margin:"5px 10px 10px 10px",minHeight:480,borderRadius:5,padding:10,border:"2px dashed rgb(0 0 0 / 20%)",background:"rgb(0 0 0 / 5%)"}},!!D&&React.createElement(sr,{system:{botId:D.botId,userData:C,sessionId:M,restNonce:N,pluginUrl:_,restUrl:b,stream:k,debugMode:null==a?void 0:a.debug_mode,eventLogs:null==a?void 0:a.event_logs,typewriter:null==a?void 0:a.chatbot_typewriter,speech_recognition:null==a?void 0:a.shortcode_chat_speech_recognition,speech_synthesis:null==a?void 0:a.shortcode_chat_speech_synthesis},params:D,theme:L,style:D.window||D.fullscreen?{position:"absolute"}:{}})),React.createElement("div",{style:{marginLeft:10,fontSize:11,lineHeight:"140%",opacity:.5}},"This is the actual chatbot, but there might be some differences when run on your front-end, depending on your theme and the other plugins you use."))))};var gr=a(421);const{useMemo:hr,useState:Rr,useEffect:yr}=wp.element,vr=[{accessor:"id",visible:!1},{accessor:"time",title:"Time",width:"95px",sortable:!0},{accessor:"user",title:"User",width:"100px",filters:{type:"text",description:"Type a User ID, or an IP."}},{accessor:"scope",title:"Scope",width:"100px",filters:{type:"checkbox",options:[{value:"chatbot",label:"Chatbot"},{value:"form",label:"Form"},{value:"playground",label:"Playground"}]}},{accessor:"model",title:"Model",width:"100%"},{accessor:"units",title:"Units",width:"75px",align:"right",sortable:!0},{accessor:"price",title:"Price",width:"95px",align:"right",sortable:!0},{accessor:"accuracy",title:"",width:"20px",align:"center"}],fr=async(e=[])=>await(0,y.IU)(`${w}/system/logs/delete`,{nonce:N,method:"POST",json:{logIds:e}}),br=({selectedLogIds:e,setSelectedLogIds:t,onDataFetched:a})=>{const n=(0,l.jE)(),[r,i]=Rr(!1),{getModelName:c}=Ce(I,null,!0),[s,d]=Rr((()=>vr.filter((e=>e.filters)).map((e=>({accessor:e.accessor,value:[]}))))),[m,u]=Rr({filters:s,sort:{accessor:"time",by:"desc"},page:1,limit:20}),{isFetching:p,data:E,error:g}=(0,o.I)({queryKey:["logs",JSON.stringify(m)],queryFn:()=>(async e=>{const t={...e,offset:(e.page-1)*e.limit},a=await(0,y.IU)(`${w}/system/logs/list`,{nonce:N,method:"POST",json:t});if(a&&!1===a.success)throw new Error(a.message||"Failed to retrieve logs");return a?{total:a.total,logs:a.logs}:{total:0,logs:[]}})(m)});yr((()=>{u({...m,filters:s})}),[s]),yr((()=>{null!=E&&E.logs&&a&&a(E.logs)}),[null==E?void 0:E.logs,a]);const v=hr((()=>(null==E?void 0:E.total)||0),[E]),f=hr((()=>null!=E&&E.logs?E.logs.sort(((e,t)=>t.created_at-e.created_at)).map((e=>{var t;const a=Ie(e.time),n=Me(e.userId,e.ip),l=Math.round(1e3*e.price)/1e3;let r=React.createElement("span",null,"$",l.toFixed(4));e.price>=.001&&(r=React.createElement("b",null,"$",l.toFixed(4))),e.price>=.01&&(r=React.createElement("b",null,"$",l.toFixed(2))),e.price>=.1&&(r=React.createElement("b",{style:{fontWeight:"bold"}},"$",l.toFixed(2)));const o=Math.round(1e6*e.price)/1e6,i=React.createElement("small",{style:{color:"var(--neko-gray)"}},"$",o.toFixed(6)),s=(null==I||null===(t=I.ai_envs)||void 0===t||null===(t=t.find((t=>t.id===e.envId)))||void 0===t?void 0:t.name)||e.envId,d=React.createElement("div",null,React.createElement("span",{title:e.model},c(e.model,!0),"assistant"===e.mode&&React.createElement("i",null," (Assistant)")),React.createElement("br",null),React.createElement("small",null,s)),m=e.accuracy||"none",u=React.createElement("div",{style:{textAlign:"center"},title:{none:"Accuracy unknown (historical data)",estimated:"Both values are estimated",tokens:"Token count is accurate (from API), price is estimated",price:"Price is accurate (from API), token count is estimated",full:"Both token count and price are accurate (from API)"}[m]},React.createElement("div",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:{none:"var(--neko-gray-60)",estimated:"var(--neko-orange)",tokens:"var(--neko-yellow)",price:"var(--neko-yellow)",full:"var(--neko-green)"}[m]||"var(--neko-gray-60)",margin:"0 auto"}}));return{id:e.id,scope:React.createElement("div",null,e.scope,React.createElement("br",null),React.createElement("small",{style:{color:"var(--neko-gray)"}},e.session)),user:n,model:d,units:React.createElement("div",{style:{textAlign:"right"}},e.units,React.createElement("br",null),React.createElement("small",null,e.type)),price:React.createElement(React.Fragment,null,r,i),time:React.createElement("div",{style:{textAlign:"right"}},a),accuracy:u}})):[]),[E]),b=async()=>{if(i(!0),e.length)await fr(e),t([]);else{if(!window.confirm(ge.ALERTS.ARE_YOU_SURE))return void i(!1);await fr()}await n.invalidateQueries({queryKey:["logs"]}),i(!1)},_=hr((()=>null!=g&&g.message?React.createElement(ce.X,{variant:"danger",style:{margin:"5px 5px"}},React.createElement("b",null,g.message),React.createElement("br",null),React.createElement("small",null,"Check your Console Logs and PHP Error Logs for more information.")):null),[g]);return React.createElement(React.Fragment,null,React.createElement(R.z,{className:"primary",title:ge.COMMON.QUERY_LOGS,action:React.createElement("div",null,React.createElement(h.M,{className:"secondary",style:{marginLeft:5},disabled:p,onClick:async()=>{try{await n.invalidateQueries({queryKey:["logs"]})}catch(e){}}},ge.COMMON.REFRESH),e.length>0&&React.createElement(h.M,{className:"danger",onClick:b},ge.COMMON.DELETE))},React.createElement(Xe.o,{busy:p||r,onSelectRow:a=>{1===e.length&&e[0]===a?t([]):t([a])},onSelect:a=>{t([...e,...a])},onUnselect:a=>{t(e.filter((e=>!a.includes(e))))},selectedItems:e,sort:m.sort,onSortChange:(e,t)=>{u({...m,sort:{accessor:e,by:t}})},emptyMessage:_,filters:s,onFilterChange:(e,t)=>{const a=[...s.filter((t=>t.accessor!==e)),{accessor:e,value:t}];d(a)},data:g?[]:f,columns:vr}),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginTop:10,marginBottom:-5}},React.createElement(h.M,{className:"danger",disabled:e.length>0,onClick:b},ge.COMMON.DELETE_ALL),React.createElement("div",{style:{flex:"auto"}}),React.createElement(tt.Q,{currentPage:m.page,limit:m.limit,onCurrentPageChanged:e=>u({...m,page:e}),total:v,onClick:e=>u({...m,page:e})}))),React.createElement(R.z,{className:"primary",title:"Information"},React.createElement("p",null,React.createElement("b",null,"Prices and tokens counts aren't accurate in many cases.")),React.createElement("p",null,"For more information, check this:"," ",React.createElement("a",{href:"https://ai.thehiddendocs.com/cost-calculation/",target:"_blank",rel:"noreferrer"},"Cost & Usage Calculation"),". You are also always welcome to discuss about it in the"," ",React.createElement("a",{href:"https://discord.gg/bHDGh38",target:"_blank",rel:"noreferrer"},"Discord Server"),".")))},{useMemo:wr,useState:_r}=wp.element;ca.t1.register(ca.PP,ca.kc,ca.E8,ca.m_,ca.s$);const Cr=({options:e,updateOption:t,busy:a})=>{var n;const[l,i]=_r([]),[c,s]=_r([]),[d,u]=_r("users"),p=null==e?void 0:e.limits,v=null==e?void 0:e.default_limits,f=wr((()=>1===c.length?c[0]:null),[c]),b=wr((()=>{const e=l.find((e=>e.id===f));if(e&&e.stats&&"string"==typeof e.stats)try{e.stats=JSON.parse(e.stats)}catch(t){e.stats={}}return e}),[l,f]),{isFetching:_,data:C}=(0,o.I)({queryKey:["logsMeta",f],queryFn:()=>(async e=>e?(await(0,y.IU)(`${w}/system/logs/meta`,{nonce:N,method:"POST",json:{logId:e,metaKeys:["query","reply","fields"]}})).data:null)(f),enabled:!!f,staleTime:864e5}),{colors:T}=(0,r.z)(),{models:O,getModel:I}=Ce(e,null,!0),{data:M}=(0,o.I)({queryKey:["logsActivityDailyByModel"],queryFn:()=>(async(e=31,t=!1)=>{const a=await be(`${w}/system/logs/activity_daily`,{nonce:P(),method:"POST",json:{days:e,byModel:t}});return null!=a&&a.data?a.data:[]})(31,!0),staleTime:36e5}),S=wr((()=>{if(!M||0===M.length)return null;const e=M.map(((e,t)=>{const a=new Date;return a.setDate(a.getDate()-(M.length-1-t)),a.toLocaleDateString("en-US",{month:"short",day:"numeric"})}));if(!O||0===O.length){return{labels:e,datasets:[{label:"Queries",data:M.map((e=>Object.values(e).reduce(((e,t)=>e+t),0))),backgroundColor:T.blue}]}}const t={},a=new Set;M.forEach((e=>{Object.keys(e).forEach((e=>{if(!t[e]){const n=I(e),l=(null==n?void 0:n.family)||"Unknown";t[e]=l,a.add(l)}}))}));const n=[T.blue,T.green,T.yellow,T.orange,T.red,T.purple],l={},r=Array.from(a).sort();r.forEach(((e,t)=>{l[e]=n[t%n.length]}));return{labels:e,datasets:r.map((e=>{const a=M.map((a=>{let n=0;return Object.entries(a).forEach((([a,l])=>{t[a]===e&&(n+=l)})),n}));return{label:e,data:a,backgroundColor:l[e]}}))}}),[M,T,O,I]),k=wr((()=>null!=p&&p[d]?p[d]:{credits:1,creditType:"price",timeFrame:"month",isAbsolute:!1,overLimitMessage:"You have reached the limit.",ignoredUsers:""}),[p,d]),A=async(e,a)=>{"credits"===a&&(e=Math.max(0,e));const n={...k,[a]:e},l={...p,[d]:n};await t(l,"limits")},x=wr((()=>Array.isArray(C)?null:C),[C]);return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,style:{flex:2.5}},React.createElement(br,{selectedLogIds:c,setSelectedLogIds:s,onDataFetched:i})),React.createElement(E.Y,{minimal:!0},f&&React.createElement(React.Fragment,null,React.createElement(le.g,{large:!0}),React.createElement(g._,{inversed:!0,style:{marginRight:10,marginLeft:10}},React.createElement(g.V,{title:ge.COMMON.QUERY},React.createElement("div",{style:{height:380,overflow:"auto",maxHeight:380}},_&&React.createElement("i",{style:{color:"gray"}},"Loading..."),!_&&!x&&React.createElement("i",{style:{color:"gray"}},ge.COMMON.DATA_NOT_AVAILABLE),!_&&x&&React.createElement(gr.p2,{value:x.query,rootName:"query",indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}))),React.createElement(g.V,{title:ge.COMMON.REPLY},React.createElement("div",{style:{height:380,overflow:"auto",maxHeight:380}},_&&React.createElement("i",{style:{color:"gray"}},"Loading..."),!_&&!x&&React.createElement("i",{style:{color:"gray"}},ge.COMMON.DATA_NOT_AVAILABLE),!_&&x&&React.createElement(gr.p2,{value:x.reply,rootName:"reply",indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}))),x&&x.fields&&React.createElement(g.V,{title:"Fields"},React.createElement("div",{style:{height:380,overflow:"auto",maxHeight:380}},_&&React.createElement("i",{style:{color:"gray"}},"Loading..."),!_&&!x&&React.createElement("i",{style:{color:"gray"}},ge.COMMON.DATA_NOT_AVAILABLE),!_&&x&&React.createElement(gr.p2,{value:x.fields,rootName:"fields",indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}))),(null==b?void 0:b.stats)&&React.createElement(g.V,{title:"Stats"},React.createElement("div",{style:{height:380,overflow:"auto",maxHeight:380}},React.createElement(gr.p2,{value:b.stats,rootName:"stats",indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}))))),S&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement(R.z,{className:"primary",title:ge.COMMON.ACTIVITY,style:{flex:1}},React.createElement("div",null,React.createElement(sa.yP,{options:{responsive:!0,plugins:{legend:{display:!1}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:S})))),React.createElement(Pa,{style:{marginTop:-25}},React.createElement(R.z,{className:"primary",busy:a,title:ge.COMMON.LIMITS,style:{flex:1}},React.createElement(m.R,{name:"enabled",label:ge.STATISTICS.ENABLE_LIMITS,checked:null==p?void 0:p.enabled,value:"1",onChange:async(e,a)=>{const n={...p,[a]:e};await t(n,"limits")}}),(null==p?void 0:p.enabled)&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement(oe.o,{value:d,busy:a,onChange:e=>u(e)},React.createElement(oe.K,{title:ge.COMMON.USERS,value:"users",disabled:!(null!=p&&p.enabled)}),React.createElement(oe.K,{title:ge.COMMON.GUESTS,value:"guests"}),React.createElement(oe.K,{title:ge.COMMON.SYSTEM,value:"system"})),"userId"===(null==p?void 0:p.target)&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,"Message for Guests:"),React.createElement(ne.A,{id:"guestMessage",name:"guestMessage",disabled:!(null!=p&&p.enabled),value:null==p?void 0:p.guestMessage,onEnter:A,onBlur:A}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.CREDITS,":"),React.createElement(ne.A,{id:"credits",name:"credits",type:"number",min:"0",max:"1000000",disabled:!(null!=p&&p.enabled),value:k.credits,onEnter:A,onBlur:A})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.TYPE,":"),React.createElement(ae.u,{scrolldown:!0,id:"creditType",name:"creditType",disabled:!(null!=p&&p.enabled),value:k.creditType,onChange:A},React.createElement(ae.j,{key:"queries",id:"queries",value:"queries",label:"Queries"}),React.createElement(ae.j,{key:"units",id:"units",value:"units",label:"Tokens"}),React.createElement(ae.j,{key:"price",id:"price",value:"price",label:"Dollars"})))),0!==k.credits&&React.createElement("p",null,"If you want to apply variable amount of credits,"," ",React.createElement("a",{href:"https://meowapps.com/ai-engine/faq/#limits",target:"_blank",rel:"noreferrer"},"click here"),"."),0!==k.credits&&"price"===k.creditType&&React.createElement("p",null,"The dollars represent the budget you spent through OpenAI."),0===k.credits&&React.createElement("p",null,"Since there are no credits, the Message for No Credits Message will be displayed."),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.TIMEFRAME,":"),React.createElement(ae.u,{scrolldown:!0,id:"timeFrame",name:"timeFrame",disabled:!(null!=p&&p.enabled),value:k.timeFrame,onChange:A},React.createElement(ae.j,{key:"second",id:"second",value:"second",label:"Second"}),React.createElement(ae.j,{key:"minute",id:"minute",value:"minute",label:"Minute"}),React.createElement(ae.j,{key:"hour",id:"hour",value:"hour",label:"Hour"}),React.createElement(ae.j,{key:"day",id:"day",value:"day",label:"Day"}),React.createElement(ae.j,{key:"week",id:"week",value:"week",label:"Week"}),React.createElement(ae.j,{key:"month",id:"month",value:"month",label:"Month"}),React.createElement(ae.j,{key:"year",id:"year",value:"year",label:"Year"}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.COMMON.ABSOLUTE,":"),React.createElement(m.R,{name:"isAbsolute",label:"Yes",disabled:!(null!=p&&p.enabled),checked:k.isAbsolute,value:"1",onChange:A}))),k.isAbsolute&&React.createElement("p",null,(0,y.FE)(ge.STATISTICS.ABSOLUTE_HELP)),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.STATISTICS.NO_CREDITS_MESSAGE,":"),React.createElement(ne.A,{id:"overLimitMessage",name:"overLimitMessage",disabled:!(null!=p&&p.enabled),value:k.overLimitMessage,onEnter:A,onBlur:A}))),"users"===d&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,ge.STATISTICS.FULL_ACCESS_USERS,":"),React.createElement(ae.u,{scrolldown:!0,id:"ignoredUsers",name:"ignoredUsers",disabled:!(null!=p&&p.enabled),value:null==p||null===(n=p.users)||void 0===n?void 0:n.ignoredUsers,description:"",onChange:A},React.createElement(ae.j,{key:"none",id:"none",value:"",label:ge.COMMON.NONE}),React.createElement(ae.j,{key:"editor",id:"editor",value:"administrator,editor",label:ge.COMMON.EDITORS_ADMINS}),React.createElement(ae.j,{key:"admin",id:"admin",value:"administrator",label:ge.COMMON.ADMINS_ONLY})))),React.createElement(le.g,null),React.createElement(h.M,{fullWidth:!0,className:"danger",onClick:async()=>{confirm(ge.ALERTS.ARE_YOU_SURE)&&await t(v,"limits")}},ge.COMMON.RESET_LIMITS)))))))};var Tr=a(7392);const Or=({options:e,updateOption:t,setOptions:a,busy:n})=>{const l=null==e?void 0:e.debug_mode,r=null==e?void 0:e.module_mcp,o=null==e?void 0:e.server_debug_mode,i=null==e?void 0:e.mcp_debug_mode,c=null==e?void 0:e.queries_debug_mode,d=null==e?void 0:e.dev_mode,u=React.createElement(s.d,{title:ge.COMMON.DEV_MODE},React.createElement(m.R,{name:"dev_mode",label:ge.COMMON.ENABLE,value:"1",checked:d,description:ge.COMMON.DEV_MODE_HELP,onChange:t})),p=React.createElement(s.d,{title:ge.COMMON.CLIENT_DEBUG},React.createElement(m.R,{name:"debug_mode",label:ge.COMMON.ENABLE,value:"1",checked:l,description:ge.COMMON.CLIENT_DEBUG_HELP,onChange:t})),g=React.createElement(s.d,{title:ge.COMMON.SERVER_DEBUG},React.createElement(m.R,{name:"server_debug_mode",label:ge.COMMON.ENABLE,value:"1",checked:o,description:ge.COMMON.SERVER_DEBUG_HELP,onChange:t})),v=r?React.createElement(s.d,{title:ge.COMMON.MCP_DEBUG},React.createElement(m.R,{name:"mcp_debug_mode",label:ge.COMMON.ENABLE,value:"1",checked:i,description:ge.COMMON.MCP_DEBUG_HELP,onChange:t})):null,f=React.createElement(s.d,{title:ge.COMMON.QUERIES_DEBUG},React.createElement(m.R,{name:"queries_debug_mode",label:ge.COMMON.ENABLE,value:"1",checked:c,description:ge.COMMON.QUERIES_DEBUG_HELP,onChange:t}));return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{title:"Debugging",className:"primary",busy:n},React.createElement(h.M,{onClick:async()=>{const e=prompt("Enter the Post ID you want to retrieve the content from.");if(!e)return;const t=await(async(e,t=0,a=0,n="publish")=>await be(`${w}/helpers/post_content?postType=${e}&postStatus=${n}&offset=${t}&postId=${a}`,{nonce:P()}))(null,null,e);if(console.log(`Data for Post ID ${e}`,t),null!=t&&t.content){const e=t.content.trim().replace(/<[^>]*>?/gm,""),a=e.split(" ")[0],n=e.split(" ").pop();console.log(`Content First Word: ${a}`),console.log(`Content Last Word: ${n}`)}}},"Get Content"),React.createElement("p",null,"This button will display the content of the post, as seen by AI Engine, in your Developer Tools Console. That allows you to check what AI Engine uses when using Content Aware, Embeddings Sync, etc."),React.createElement(h.M,{onClick:async()=>{await(async()=>await be(`${w}/helpers/run_tasks`,{nonce:P(),method:"POST"}))()}},"Run Tasks"),React.createElement("p",null,"This button will force the AI Engine to run the tasks. Normally, the AI Engine runs the tasks every 10 minutes. This button will force the AI Engine to run the tasks immediately.")),React.createElement(R.z,{title:"Settings",className:"primary",busy:n},u,React.createElement("h3",{style:{marginTop:20,marginBottom:10}},"Logs Console"),p,g,React.createElement("h3",{style:{marginTop:20,marginBottom:10}},"PHP Error Logs"),v,f),React.createElement(R.z,{title:"Optimization",className:"primary",busy:n},React.createElement(h.M,{onClick:async()=>{if(confirm("This will:\n\n1. Add database indexes to optimize query performance\n2. Remove logs older than 3 months\n3. Remove chat discussions older than 3 months\n\nThis action cannot be undone. Continue?"))try{const e=await(async()=>{const e=await lt(`${w}/helpers/optimize_database`,{method:"POST"});if(!e.success)throw new Error(e.message);return e})();alert(`Database optimization completed!\n\n${e.message||"Indexes added and old data cleaned up successfully."}`)}catch(e){alert(`Optimization failed: ${e.message}`)}}},"Optimize Database"),React.createElement("p",null,(0,y.FE)("This will add indexes to the AI Engine database tables to improve query performance, and clean up old data (logs and discussions older than 3 months). <b>Use this if you notice the plugin becoming slower over time.</b>")))),React.createElement(E.Y,{minimal:!0},o&&React.createElement(Tr.k,{refreshQuery:ut,clearQuery:pt,i18n:ge}))))},{useMemo:Nr,useState:Ir}=wp.element,Mr=({env:e,updateEnvironment:t,deleteEnvironment:a,ai_envs:n,options:l})=>{const{embeddingsModels:r}=Ce(l,null==e?void 0:e.ai_embeddings_env),[o,i]=Ir(!1),[c,d]=Ir(null),u=Nr((()=>n&&null!=l&&l.ai_engines?n.filter((e=>{const t=l.ai_engines.find((t=>t.type===e.type));if(!t||!t.models)return!1;return t.models.some((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("embedding")}))})):[]),[n,l]),p=Nr((()=>r.find((t=>t.model===e.ai_embeddings_model))),[r,e.ai_embeddings_model]),E=Nr((()=>{var e;if(!p)return[];if(!p.dimensions)return console.error("This embeddings model does not have dimensions:",p),[];if((null==p||null===(e=p.tags)||void 0===e?void 0:e.includes("matryoshka"))&&p.dimensions.length>0){const e=p.dimensions[0];return[3072,2048,1536,1024,768,512].filter((t=>t<=e))}return p.dimensions}),[p]),g=Nr((()=>!!e.ai_embeddings_dimensions&&("pinecone"===e.type&&e.pinecone_dimensions?parseInt(e.pinecone_dimensions)!==parseInt(e.ai_embeddings_dimensions):!("qdrant"!==e.type||!e.qdrant_dimensions)&&parseInt(e.qdrant_dimensions)!==parseInt(e.ai_embeddings_dimensions))),[e.pinecone_dimensions,e.qdrant_dimensions,e.ai_embeddings_dimensions,e.type]);return React.createElement(React.Fragment,null,React.createElement(s.d,{title:ge.COMMON.NAME},React.createElement(ne.A,{name:"name",value:e.name,onFinalChange:a=>t(e.id,{name:a})})),React.createElement(s.d,{title:ge.COMMON.TYPE},React.createElement(ae.u,{scrolldown:!0,name:"type",value:e.type,description:"qdrant"===e.type?(0,y.FE)(ge.HELP.QDRANT):null,onChange:a=>t(e.id,{type:a})},React.createElement(ae.j,{value:"pinecone",label:"Pinecone"}),React.createElement(ae.j,{value:"qdrant",label:"Qdrant"}),React.createElement(ae.j,{value:"openai-vector-store",label:"OpenAI Vector Store"}))),"openai-vector-store"!==e.type&&React.createElement(s.d,{title:ge.COMMON.API_KEY},React.createElement(ne.A,{name:"apikey",value:e.apikey,description:(0,y.FE)("pinecone"===e.type?ge.COMMON.PINECONE_APIKEY_HELP:ge.COMMON.QDRANT_APIKEY_HELP),onFinalChange:a=>t(e.id,{apikey:a})})),"openai-vector-store"!==e.type&&React.createElement(s.d,{title:ge.COMMON.SERVER},React.createElement(ne.A,{name:"server",value:e.server,description:(0,y.FE)("qdrant"===e.type?ge.COMMON.QDRANT_SERVER_HELP:ge.COMMON.PINECONE_SERVER_HELP),onFinalChange:a=>t(e.id,{server:a})})),"pinecone"===e.type&&React.createElement(React.Fragment,null,React.createElement(s.d,{title:ge.COMMON.NAMESPACE},React.createElement(ne.A,{name:"namespace",value:e.namespace,description:(0,y.FE)(ge.COMMON.PINECONE_NAMESPACE_HELP),onFinalChange:a=>t(e.id,{namespace:a})})),React.createElement(s.d,{title:ge.COMMON.DIMENSIONS},React.createElement(ne.A,{name:"pinecone_dimensions",value:e.pinecone_dimensions||"",readOnly:!0,placeholder:"Run Quick Test",description:(0,y.FE)("The vector dimensions of your Pinecone index. This is detected automatically when you run Quick Test and should match your embedding model's output dimensions.")}))),"qdrant"===e.type&&React.createElement(React.Fragment,null,React.createElement(s.d,{title:ge.COMMON.QDRANT_COLLECTION},React.createElement(ne.A,{name:"collection",value:e.collection,description:(0,y.FE)(ge.COMMON.QDRANT_COLLECTION_HELP),onFinalChange:a=>t(e.id,{collection:a})})),React.createElement(s.d,{title:ge.COMMON.DIMENSIONS},React.createElement(ne.A,{name:"qdrant_dimensions",value:e.qdrant_dimensions||"",readOnly:!0,placeholder:"Detected from collection",description:(0,y.FE)("The vector dimensions of your Qdrant collection. This should match your embedding model's output dimensions.")}))),"openai-vector-store"===e.type&&React.createElement(React.Fragment,null,React.createElement(s.d,{title:"OpenAI Environment"},React.createElement(ae.u,{scrolldown:!0,name:"openai_env_id",value:e.openai_env_id||null,description:(0,y.FE)("Select the OpenAI environment to use for accessing the vector store."),onChange:a=>t(e.id,{openai_env_id:a})},React.createElement(ae.j,{key:null,value:null,label:"Select an environment"}),n.filter((e=>"openai"===e.type)).map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))))),React.createElement(s.d,{title:"Vector Store ID"},React.createElement(ne.A,{name:"store_id",value:e.store_id||"",placeholder:"vs_abc123...",description:(0,y.FE)("The ID of your OpenAI vector store. You can find this in the OpenAI dashboard."),onFinalChange:a=>t(e.id,{store_id:a})}))),React.createElement(s.d,{title:"Env ID"},React.createElement(ne.A,{name:"env_id",value:e.id,readOnly:!0,description:"The unique identifier for this environment"})),React.createElement(et.Zc,{keepState:"embeddingsEnvs"},"openai-vector-store"!==e.type&&React.createElement(et.y2,{title:"Score"},React.createElement("div",{style:{marginTop:10}},React.createElement(s.d,{title:ge.COMMON.MIN_SCORE},React.createElement(ne.A,{name:"min_score",value:e.min_score||35,type:"number",min:"0",max:"100",step:"1",description:(0,y.FE)(ge.HELP.MIN_SCORE),onFinalChange:a=>t(e.id,{min_score:a})})),React.createElement(s.d,{title:ge.COMMON.MAX_SELECT},React.createElement(ne.A,{name:"max_select",value:e.max_select||10,type:"number",min:"1",max:"100",step:"1",description:(0,y.FE)(ge.HELP.MAX_SELECT),onFinalChange:a=>t(e.id,{max_select:a})})))),"openai-vector-store"!==e.type&&React.createElement(et.y2,{title:React.createElement("div",{style:{display:"flex",alignItems:"center",gap:"8px"}},React.createElement("span",null,ge.COMMON.AI_ENVIRONMENT),g&&(null==e?void 0:e.ai_embeddings_override)&&React.createElement("small",{style:{color:"var(--neko-red)",fontWeight:"bold"}},"(Dimension Mismatch)"))},React.createElement("div",{style:{marginTop:10}},React.createElement(s.d,{title:ge.COMMON.OVERRIDE_DEFAULTS},React.createElement(m.R,{label:ge.COMMON.ENABLE,value:"1",checked:null==e?void 0:e.ai_embeddings_override,onChange:a=>t(e.id,{ai_embeddings_override:a})})),(null==e?void 0:e.ai_embeddings_override)&&React.createElement(React.Fragment,null,React.createElement(s.d,{title:ge.COMMON.ENVIRONMENT},React.createElement(ae.u,{scrolldown:!0,name:"ai_embeddings_env",value:null==e?void 0:e.ai_embeddings_env,onChange:a=>t(e.id,{ai_embeddings_env:a})},React.createElement(ae.j,{key:null,value:null,label:"None"}),u.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))))),React.createElement(s.d,{title:ge.COMMON.MODEL},React.createElement(ae.u,{scrolldown:!0,name:"ai_embeddings_model",value:e.ai_embeddings_model,onChange:a=>t(e.id,{ai_embeddings_model:a})},r.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),React.createElement(s.d,{title:ge.COMMON.DIMENSIONS},React.createElement(ae.u,{scrolldown:!0,name:"ai_embeddings_dimensions",value:e.ai_embeddings_dimensions||null,onChange:a=>t(e.id,{ai_embeddings_dimensions:a})},E.map(((e,t)=>React.createElement(ae.j,{key:e,value:e,label:0===t?`${e} (Native)`:e}))),React.createElement(ae.j,{key:null,value:null,label:"Not Set"}))),g&&React.createElement(ce.X,{variant:"warning",style:{marginTop:10,marginBottom:10}},React.createElement("strong",null,"Dimension Mismatch:")," Your ","pinecone"===e.type?"Pinecone index":"Qdrant collection"," has ","pinecone"===e.type?e.pinecone_dimensions:e.qdrant_dimensions," dimensions, but the selected embedding model is configured for ",e.ai_embeddings_dimensions," dimensions. This will cause errors when trying to store embeddings. Please select a matching dimension size or use a different embedding model.")))),React.createElement(et.y2,{title:ge.COMMON.ACTIONS},React.createElement("div",{style:{display:"flex",marginTop:10,justifyContent:"flex-end"}},"pinecone"===e.type&&React.createElement(h.M,{className:"primary",onClick:async()=>{i(!0);try{const a=await(0,y.IU)(`${w}/embeddings/test_pinecone`,{method:"POST",nonce:N,json:{env_id:e.id}});d(a),a.success&&a.dimension&&t(e.id,{pinecone_dimensions:a.dimension})}catch(e){d({success:!1,error:e.message||"Failed to test Pinecone connection"})}finally{i(!1)}},isBusy:o},"Quick Test"),React.createElement(h.M,{className:"danger",onClick:()=>a(e.id)},ge.COMMON.DELETE)))),c&&React.createElement(ie.n,{title:"Pinecone Connection Test",isOpen:!!c,onRequestClose:()=>d(null),okButton:{label:"Close",onClick:()=>d(null)},content:React.createElement("div",null,c.success?React.createElement(React.Fragment,null,React.createElement(ce.X,{variant:"success",style:{marginBottom:15}},"Connection successful!"),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Status:")," ",c.ready?React.createElement("span",{style:{color:"green"}},"Ready"):React.createElement("span",{style:{color:"orange"}},"Not Ready")),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Name:")," ",c.index_name),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Metric:")," ",c.metric,"cosine"===c.metric?React.createElement("span",{style:{color:"green"}}," ✓"):React.createElement("span",{style:{color:"orange"}}," (expected: cosine)")),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Dimensions:")," ",c.dimension,c.dimension_match?React.createElement("span",{style:{color:"green"}}," ✓ (matches configuration)"):React.createElement("span",{style:{color:"red"}}," ✗ (expected: ",c.expected_dimension,")")),c.host&&React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Host:")," ",c.host)):React.createElement(React.Fragment,null,React.createElement(ce.X,{variant:"danger",style:{marginBottom:15}},"Connection failed"),React.createElement("div",null,React.createElement("strong",null,"Error:")," ",c.error)))}))};const Sr=function({environments:e,updateEnvironment:t,updateOption:a,options:n,busy:l}){const r=t=>{if(1===e.length)return void alert("You can't delete the last environment.");const n=e.filter((e=>e.id!==t));a(n,"embeddings_envs")};return React.createElement("div",{style:{padding:"0px 10px 20px 10px",marginTop:13}},React.createElement(c.s,{h2:!0,style:{color:"white"}},"Environments for Embeddings"),React.createElement(g._,{inversed:!0,style:{marginTop:-5},action:React.createElement(h.M,{rounded:!0,className:"secondary",icon:"plus",onClick:()=>{const t=[...e,{name:"New Environment",type:"pinecone",apikey:"",server:"",indexes:[],namespaces:[]}];a(t,"embeddings_envs")}})},e.map((e=>React.createElement(g.V,{key:e.id,title:e.name,busy:l},React.createElement(Mr,{env:e,updateEnvironment:t,deleteEnvironment:r,ai_envs:(null==n?void 0:n.ai_envs)||[],options:n}))))))},{useCallback:kr,useMemo:Ar,useState:xr}=wp.element,Pr=({updateEnvironment:e,environmentId:t,deployments:a,options:n})=>{const l=(n,l,r)=>{const o=JSON.parse((0,y.F1)(a));o[n][l]=r,e(t,{deployments:o})},r=Ar((()=>{var e;const t=null==n||null===(e=n.ai_engines)||void 0===e?void 0:e.find((e=>"openai"===e.type));return(null==t?void 0:t.models)??[]}),[n]);return React.createElement(s.d,{title:ge.COMMON.OPENAI_AZURE_DEPLOYMENTS,style:{marginTop:10}},a.map(((n,o)=>React.createElement("div",{key:o,style:{display:"flex",marginBottom:10}},React.createElement(ne.A,{style:{flex:1},value:n.name,placeholder:ge.COMMON.OPENAI_AZURE_DEPLOYMENT_NAME,onBlur:e=>l(o,"name",e),onEnter:e=>l(o,"name",e)}),React.createElement(ae.u,{style:{flex:1,marginLeft:10},scrolldown:!0,id:"model",name:"model",value:n.model,onChange:e=>l(o,"model",e)},r.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name})))),React.createElement(h.M,{rounded:!0,isSmall:!0,style:{marginLeft:10,height:30},icon:"trash",onClick:()=>(n=>{const l=[...a];l.splice(n,1),e(t,{deployments:l})})(o)})))),React.createElement(h.M,{fullWidth:!0,icon:"plus",onClick:()=>{const n=[...a,{name:"",model:""}];e(t,{deployments:n})}}))},Dr=({updateEnvironment:e,environmentId:t,customModels:a})=>{const n=(n,l,r)=>{const o=JSON.parse((0,y.F1)(a));o[n][l]=r,e(t,{customModels:o})};return React.createElement(s.d,{title:ge.COMMON.HUGGINGFACE_MODELS,style:{marginTop:10}},a.map(((l,r)=>{var o,i;return React.createElement("div",{key:r,style:{display:"flex",flexDirection:"column",marginBottom:10}},React.createElement("div",{key:r,style:{display:"flex",marginBottom:2}},React.createElement(ne.A,{style:{flex:1},value:l.name,placeholder:ge.COMMON.HUGGINGFACE_MODEL_NAME,onBlur:e=>n(r,"name",e),onEnter:e=>n(r,"name",e)}),React.createElement(ne.A,{style:{flex:2,marginLeft:5},value:l.apiUrl,placeholder:ge.COMMON.HUGGINGFACE_MODEL_URL,onBlur:e=>n(r,"apiUrl",e),onEnter:e=>n(r,"apiUrl",e)}),React.createElement(h.M,{rounded:!0,isSmall:!0,style:{marginLeft:5,height:30},icon:"trash",onClick:()=>(n=>{const l=[...a];l.splice(n,1),e(t,{customModels:l})})(r)})),React.createElement("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center"}},React.createElement("span",{style:{marginRight:5}},"Image Model"),React.createElement(m.R,{style:{marginTop:r?0:5,marginRight:10},disabled:!0,checked:null===(o=l.tags)||void 0===o?void 0:o.includes("image"),onChange:n=>{const l=JSON.parse((0,y.F1)(a));l[r].tags||(l[r].tags=["core","chat"]),n?l[r].tags.push("image"):l[r].tags=l[r].tags.filter((e=>"image"!==e)),e(t,{customModels:l})}}),React.createElement("span",{style:{marginRight:5}},"Vision Model"),React.createElement(m.R,{style:{marginTop:r?0:5,marginRight:33},disabled:!0,checked:null===(i=l.tags)||void 0===i?void 0:i.includes("vision"),onChange:n=>{const l=JSON.parse((0,y.F1)(a));l[r].tags||(l[r].tags=["core","chat"]),n?l[r].tags.push("vision"):l[r].tags=l[r].tags.filter((e=>"vision"!==e)),e(t,{customModels:l})}})))})),React.createElement(h.M,{fullWidth:!0,icon:"plus",onClick:()=>{const n=[...a,{name:"",apiUrl:"",tags:["core","chat"]}];e(t,{customModels:n})}}))};const Lr=function({options:e,environments:t,updateEnvironment:a,updateOption:n,busy:l}){const[r,o]=xr(!1),[i,d]=xr(!1),[m,u]=xr(null),p=(null==e?void 0:e.ai_engines)??[],E=kr((e=>{switch(e.type){case"openai":return(0,y.FE)(ge.HELP.OPENAI_API_KEY);case"azure":return(0,y.FE)(ge.HELP.AZURE_API_KEY);case"openrouter":return(0,y.FE)(ge.HELP.OPENROUTER_API_KEY);case"anthropic":return(0,y.FE)(ge.HELP.ANTHROPIC_API_KEY);default:return""}}),[]),R=kr((async(t,a)=>{try{o(!0);const l=await(0,y.IU)(`${w}/ai/models`,{method:"POST",nonce:N,json:{envId:t}});o(!1);let r=null==l?void 0:l.models;if(!r)throw new Error("Could not fetch models.");r=r.map((e=>({...e,envId:t,type:a})));let i=(null==e?void 0:e.ai_models)??[];i=i.filter((e=>!(e.type===a&&(!e.envId||e.envId===t)))),i.push(...r),n(i,"ai_models")}catch(e){alert(e.message),console.log(e),o(!1)}}),[n]),v=kr((async e=>{d(!0);try{const t=await(0,y.IU)(`${w}/ai/test_connection`,{method:"POST",nonce:N,json:{env_id:e.id}});u(t)}catch(t){u({success:!1,error:t.message||"Failed to test connection",provider:e.type})}finally{d(!1)}}),[]);return React.createElement("div",{style:{padding:"0px 10px 5px 10px",marginTop:13,marginBottom:5}},React.createElement(c.s,{h2:!0,style:{color:"white",marginBottom:15}},ge.COMMON.ENVIRONMENTS_FOR_AI),React.createElement(g._,{inversed:!0,style:{marginTop:-5},action:React.createElement(h.M,{rounded:!0,className:"secondary",icon:"plus",onClick:()=>{const e=[...t,{name:"New Environment",type:"openai",apikey:""}];n(e,"ai_envs")}})},t.map((o=>{var c;let d=0;const m=p.find((e=>e.type===o.type))||{},u=null===(c=m.inputs)||void 0===c?void 0:c.includes("dynamicModels");return Array.isArray(m.models)&&(d=m.models.length),React.createElement(g.V,{key:o.id,title:o.name,busy:l},React.createElement(s.d,{title:ge.COMMON.NAME},React.createElement(ne.A,{name:"name",value:o.name,onFinalChange:e=>a(o.id,{name:e})})),React.createElement(s.d,{title:ge.COMMON.TYPE},React.createElement(ae.u,{scrolldown:!0,name:"type",value:o.type,onChange:e=>a(o.id,{type:e})},p.map((e=>React.createElement(ae.j,{key:e.type,value:e.type,label:e.name}))))),(e=>{const t=(p.find((t=>t.type===e.type))||{}).inputs||[];return React.createElement(React.Fragment,null,t.includes("apikey")&&React.createElement(s.d,{title:ge.COMMON.API_KEY},React.createElement(ne.A,{name:"apikey",value:e.apikey,description:E(e),onFinalChange:t=>a(e.id,{apikey:t})})),t.includes("organizationId")&&React.createElement(s.d,{title:ge.COMMON.OPENAI_ORGANIZATION_ID},React.createElement(ne.A,{name:"organizationId",value:e.organizationId,description:(0,y.FE)(ge.HELP.OPENAI_ORGANIZATION_ID),onFinalChange:t=>a(e.id,{organizationId:t})})),t.includes("endpoint")&&React.createElement(s.d,{title:ge.COMMON.ENDPOINT},React.createElement(ne.A,{name:"endpoint",value:e.endpoint,onFinalChange:t=>a(e.id,{endpoint:t})})),t.includes("region")&&React.createElement(s.d,{title:ge.COMMON.REGION},React.createElement(ne.A,{name:"region",value:e.region,onFinalChange:t=>a(e.id,{region:t})})),t.includes("projectId")&&React.createElement(s.d,{title:ge.COMMON.PROJECT_ID},React.createElement(ne.A,{name:"projectId",value:e.projectId,onFinalChange:t=>a(e.id,{projectId:t})})))})(o),"google"===o.type&&React.createElement(React.Fragment,null,(""===o.apikey||!o.apikey)&&React.createElement(ce.X,{variant:"info",style:{marginBottom:10}},"Click ",React.createElement("a",{href:"https://aistudio.google.com/app/apikey",target:"_blank",rel:"noreferrer"},"here")," to access AI Studio and create your API Key."),React.createElement(ce.X,{variant:"danger"},"Streaming is only supported in the Pro Version of AI Engine. As of 2025, Gemini is still unstable. If you encounter issues, let's discuss them on ",React.createElement("a",{href:"https://discord.gg/bHDGh38",target:"_blank",rel:"noreferrer"},"Discord"),"."),React.createElement(le.g,null)),"huggingface"===o.type&&React.createElement(React.Fragment,null,React.createElement(ce.X,{variant:"danger"},"Support for Hugging Face is experimental and may not work as expected. Also, AI Engine is ready for Image and Vision but Hugging Face is not (hence the disabled checkboxes). Let's discuss about Hugging Face on ",React.createElement("a",{href:"https://discord.gg/bHDGh38",target:"_blank",rel:"noreferrer"},"Discord"),"."),React.createElement(le.g,null)),"perplexity"===o.type&&(""===o.apikey||!o.apikey)&&React.createElement(React.Fragment,null,React.createElement(ce.X,{variant:"warning"},"Perplexity.ai is a paid service. Click ",React.createElement("a",{href:"https://perplexity.ai/pro?referral_code=A1R94DGZ",target:"_blank",rel:"noreferrer"},"here")," to create an account with 10$ free credit."),React.createElement(le.g,null)),React.createElement(et.Zc,{keepState:"environmentCategories"},u&&React.createElement(et.y2,{title:ge.COMMON.MODELS},"openrouter"===o.type&&React.createElement("p",null,"There are currently ",React.createElement("b",null,d)," models available. OpenRouter models need to be refresh regularly. This button will fetch the latest models and their prices."),"google"===o.type&&React.createElement("p",null,"There are currently ",React.createElement("b",null,d)," models available. Google models need to be refresh regularly. This button will fetch the latest models and their prices."),"openrouter"!==o.type&&"google"!==o.type&&React.createElement("p",null,"There are currently ",React.createElement("b",null,d)," models available. This button will fetch the latest models."),React.createElement(h.M,{fullWidth:!0,className:"primary",isBusy:r,onClick:()=>R(o.id,o.type)},ge.COMMON.REFRESH_MODELS)),"azure"===o.type&&React.createElement(React.Fragment,null,React.createElement("p",null,ge.HELP.AZURE_DEPLOYMENTS),React.createElement(et.y2,{title:ge.COMMON.OPENAI_AZURE_DEPLOYMENTS},React.createElement(Pr,{deployments:o.deployments??[],environmentId:o.id,updateEnvironment:a,options:e}))),"huggingface"===o.type&&React.createElement(et.y2,{title:ge.COMMON.HUGGINGFACE_MODELS},React.createElement("p",null,"Browse the ",React.createElement("a",{href:"https://huggingface.co/models",target:"_blank",rel:"noreferrer"},"Models on Hugging Face"),". Use the Deploy button (Inference API Serverless) in order to get the API URL. Paste it below with the name of your choice and you're done!"),React.createElement(Dr,{customModels:o.customModels??[],environmentId:o.id,updateEnvironment:a,options:e})),React.createElement(et.y2,{title:ge.COMMON.ENVIRONMENT_ID},React.createElement("p",null,'The EnvID is "',React.createElement("b",null,o.id),'".')),React.createElement(et.y2,{title:ge.COMMON.ACTIONS},React.createElement("div",{style:{display:"flex",marginTop:10}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(h.M,{className:"primary",isBusy:i,onClick:()=>v(o)},ge.COMMON.QUICK_TEST||"Quick Test"),React.createElement(h.M,{className:"danger",onClick:()=>(e=>{if(1===t.length)return void alert("You can't delete the last environment.");const a=t.filter((t=>t.id!==e));n(a,"ai_envs")})(o.id)},ge.COMMON.DELETE)))))}))),React.createElement(ie.n,{isOpen:!!m,onRequestClose:()=>u(null),title:"Connection Test Results",okButton:{label:"Close",onClick:()=>u(null)},content:m&&React.createElement("div",null,m.success?React.createElement(React.Fragment,null,React.createElement(ce.X,{variant:"success"},"Connection successful!"),React.createElement(le.g,null),React.createElement("div",null,React.createElement("strong",null,"Provider:")," ",m.provider,React.createElement("br",null),React.createElement("strong",null,"Environment:")," ",m.name,React.createElement("br",null),m.data&&React.createElement(React.Fragment,null,"openai"===m.provider&&m.data.models&&React.createElement(React.Fragment,null,React.createElement("strong",null,"Available Models:")," ",m.data.models.length,React.createElement("br",null),React.createElement("strong",null,"Sample Models:")," ",m.data.models.slice(0,3).join(", "),m.data.models.length>3&&"..."),"anthropic"===m.provider&&m.data.models&&React.createElement(React.Fragment,null,React.createElement("strong",null,"Available Models:")," ",m.data.models.length,React.createElement("br",null),React.createElement("strong",null,"Models:")," ",m.data.models.join(", ")),"google"===m.provider&&m.data.models&&React.createElement(React.Fragment,null,React.createElement("strong",null,"Available Models:")," ",m.data.models.length,React.createElement("br",null),React.createElement("strong",null,"Sample Models:")," ",m.data.models.slice(0,3).join(", "),m.data.models.length>3&&"..."),"openrouter"===m.provider&&m.data.models&&React.createElement(React.Fragment,null,React.createElement("strong",null,"Available Models:")," ",m.data.models.length,React.createElement("br",null),React.createElement("strong",null,"Sample Models:")," ",m.data.models.slice(0,3).join(", "),m.data.models.length>3&&"..."),"azure"===m.provider&&m.data.deployments&&React.createElement(React.Fragment,null,React.createElement("strong",null,"Deployments:")," ",m.data.deployments.length,React.createElement("br",null),React.createElement("strong",null,"Available:")," ",m.data.deployments.join(", "))))):React.createElement(ce.X,{variant:"danger"},React.createElement("strong",null,"Connection failed!"),React.createElement("br",null),m.error))}))},{useCallback:Fr,useState:Br}=wp.element;const Ur=function({options:e,mcpServers:t,updateMCPServer:a,updateOption:n,busy:l}){const[r,o]=Br({}),i=Fr(((e,n)=>{var l,r;(l=n,r=e,t.some((e=>e.name===l&&e.id!==r)))?o((t=>({...t,[e]:"Name must be unique"}))):(o((t=>{const a={...t};return delete a[e],a})),a(e,{name:n}))}),[t,a]),d=Fr(((e,t)=>{a(e,{url:t})}),[a]),m=Fr(((e,t)=>{a(e,{token:t})}),[a]);return React.createElement("div",{style:{padding:"0px 10px 5px 10px",marginTop:13,marginBottom:5}},React.createElement(c.s,{h2:!0,style:{color:"white",marginBottom:15}},ge.COMMON.MCP_SERVERS),React.createElement(g._,{inversed:!0,style:{marginTop:-5},action:React.createElement(h.M,{rounded:!0,className:"secondary",icon:"plus",onClick:()=>{const e="New MCP Server";let a=1,l=e;for(;t.some((e=>e.name===l));)l=`${e} ${a}`,a++;const r={name:l,type:"url",url:"",token:""},o=[...t,r];n(o,"mcp_envs")}})},t.map((e=>React.createElement(g.V,{key:e.id,title:e.name,busy:l},React.createElement(s.d,{title:ge.COMMON.NAME},React.createElement(ne.A,{name:"name",value:e.name,error:r[e.id],description:"The name must be unique across all MCP servers",onFinalChange:t=>i(e.id,t)})),React.createElement(s.d,{title:ge.COMMON.URL},React.createElement(ne.A,{name:"url",value:e.url,placeholder:"https://example.com/mcp-server",description:(0,y.FE)(ge.HELP.MCP_SERVER_URL),onFinalChange:t=>d(e.id,t)})),React.createElement(s.d,{title:ge.COMMON.TOKEN},React.createElement(ne.A,{name:"token",value:e.token,placeholder:"Bearer token for authentication",description:(0,y.FE)(ge.HELP.MCP_SERVER_TOKEN),onFinalChange:t=>m(e.id,t)})),React.createElement(et.Zc,{keepState:"mcpServerCategories"},React.createElement(et.y2,{title:ge.COMMON.SERVER_ID},React.createElement("p",null,'The Server ID is "',React.createElement("b",null,e.id),'".')),React.createElement(et.y2,{title:ge.COMMON.ACTIONS},React.createElement("div",{style:{display:"flex",marginTop:10}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(h.M,{className:"danger",onClick:()=>(e=>{if(1===t.length)return void alert("You can't delete the last MCP server.");const a=t.filter((t=>t.id!==e));n(a,"mcp_envs")})(e.id)},ge.COMMON.DELETE)))))))))},{useState:Hr}=wp.element;const jr=function({options:e}){const[t,a]=Hr({}),{data:n,isLoading:l,refetch:r,isRefetching:i}=(0,o.I)({queryKey:["mcp-functions",null==e?void 0:e.module_mcp,null==e?void 0:e.mcp_core,null==e?void 0:e.mcp_plugins,null==e?void 0:e.mcp_themes,null==e?void 0:e.mcp_dynamic_rest],queryFn:async()=>{const e=await fetch(`${window.wpApiSettings.root}mwai/v1/mcp/functions`,{headers:{"Content-Type":"application/json","X-WP-Nonce":window.wpApiSettings.nonce}});if(!e.ok)throw new Error("Failed to fetch MCP functions");return e.json()},enabled:!0===(null==e?void 0:e.module_mcp),refetchInterval:!1}),s=null!=e&&e.module_mcp&&null!=n&&n.success&&n.count>0?React.createElement(h.M,{className:"secondary",onClick:()=>r(),disabled:i},i?"Refreshing...":"Refresh"):null;return React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement(R.z,{className:"primary",title:ge.COMMON.MCP_FUNCTIONS||"MCP Functions",action:s},null!=e&&e.module_mcp?l?React.createElement("p",null,"Loading MCP functions..."):null!=n&&n.success?React.createElement(React.Fragment,null,0!==n.count||null!=e&&e.mcp_core||null!=e&&e.mcp_themes||null!=e&&e.mcp_plugins||null!=e&&e.mcp_dynamic_rest?React.createElement("p",null,React.createElement("strong",null,n.count)," functions are currently registered via MCP."):React.createElement("p",null,ge.COMMON.MCP_NO_OPTIONS),(null==n?void 0:n.functions)&&(()=>{const e=n.functions.reduce(((e,t)=>{const a=t.category||"Others";return e[a]||(e[a]=[]),e[a].push(t),e}),{}),l=Object.keys(e).sort(((e,t)=>"Others"===e?1:"Others"===t?-1:e.localeCompare(t)));return React.createElement("div",{style:{marginTop:10}},l.map((n=>React.createElement("div",{key:n,style:{marginBottom:15}},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:"1px solid #e0e0e0",paddingBottom:5,marginBottom:10}},React.createElement(c.s,{h4:!0,style:{margin:0,color:"#333"}},n," (",e[n].length,")"),React.createElement(h.M,{size:"small",className:"secondary",onClick:()=>a((e=>({...e,[n]:!e[n]})))},t[n]?"Hide Details":"Show Details")),t[n]&&React.createElement(et.Zc,{keepState:`mcpFunctionDetails-${n}`},e[n].map(((e,t)=>React.createElement(et.y2,{key:`${n}-${t}`,title:e.name},React.createElement("div",{style:{padding:"10px 0",color:"#333"}},React.createElement("p",{style:{marginBottom:10,color:"#333"}},React.createElement("strong",null,"Description:")," ",e.description||"No description available"),e.inputSchema&&React.createElement("div",{style:{marginBottom:10,color:"#333"}},React.createElement("strong",null,"Arguments:"),React.createElement("pre",{style:{backgroundColor:"#f5f5f5",padding:10,borderRadius:4,fontSize:12,overflow:"auto",marginTop:5,color:"#333",border:"1px solid #ddd"}},JSON.stringify(e.inputSchema,null,2))),e.outputSchema&&React.createElement("div",{style:{color:"#333"}},React.createElement("strong",null,"Output:"),React.createElement("pre",{style:{backgroundColor:"#f5f5f5",padding:10,borderRadius:4,fontSize:12,overflow:"auto",marginTop:5,color:"#333",border:"1px solid #ddd"}},JSON.stringify(e.outputSchema,null,2))))))))))))})()):React.createElement("p",null,"Failed to load MCP functions."):React.createElement("p",null,"Enable MCP module to see available functions.")))},{useState:Gr}=wp.element,$r=L.Ay.div`
  pre {
    display: flex;
    align-items: center;
    background: #f8fcff;
    color: #779bb8;
    margin: 10px 0 0 0;
    padding: 3px 8px;
    font-size: 13px;
    border: 2px solid rgb(210 228 243);
    border-radius: 5px;
    font-family: system-ui;
    cursor: pointer;
    font-weight: 500;
  }

  .highlight {
    color: var(--neko-green);
    background: transparent;
  }
`,zr=({children:e,value:t,...a})=>{const[n,l]=Gr(null);return React.createElement($r,a,React.createElement("pre",{onClick:async()=>{navigator.clipboard?(await navigator.clipboard.writeText(t),l("Copied!"),setTimeout((()=>{l(null)}),2e3)):alert("Clipboard is not enabled (only works with https).")}},!n&&e,n&&React.createElement("span",null,n)))},{useState:Wr,useEffect:qr}=wp.element,Vr=()=>{const[e,t]=Wr(""),[a,n]=Wr(""),[l,r]=Wr(""),[o,i]=Wr(!1),[c,s]=Wr("imageToText"),[d,m]=Wr(null);qr((()=>{t(""),n(""),r("")}),[c]);const u=async(t="imageToText")=>{let a="";if("textToJSON"===t)a=`${w}/ai/json`;else if("imageToText"===t)a=`${w}/ai/transcribe_image`;else{if("audioToText"!==t)return void alert(`Unknown transcription type: ${t}`);a=`${w}/ai/transcribe_audio`}i(t),m(Date.now());try{var r;let t=(await(0,y.IU)(a,{method:"POST",nonce:N,json:{url:e,message:l}})).data;null!=t&&null!==(r=t.error)&&void 0!==r&&r.message?alert(t.error.message):n(t)}catch(e){alert(e.message)}finally{i(!1),m(null)}};return React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{title:"Features",className:"raw"},React.createElement(g._,{inversed:!0,onChange:(e,t)=>{s(t.key)}},React.createElement(g.V,{title:ge.COMMON.IMAGE_TO_TEXT,key:"imageToText"},React.createElement("label",null,"Image URL:"),React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{name:"url",rows:2,value:e,onChange:t}),React.createElement(le.g,null),React.createElement("label",null,"Prompt:"),React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{rows:2,value:l,onChange:r}),React.createElement(le.g,null),React.createElement(h.M,{fullWidth:!0,style:{height:40},disabled:o,isBusy:"imageToText"===o,startTime:d,onClick:()=>{u("imageToText")}},"Transcribe Image"),React.createElement(le.g,{tiny:!0}),React.createElement("p",null,"If you are looking for beautiful images to play with this, here are some URLs: ",React.createElement("a",{target:"_blank",href:"https://offbeatjapan.org"},"Offbeat Japan"),", ",React.createElement("a",{target:"_blank",href:"https://unsplash.com"},"Unsplash"),", ",React.createElement("a",{target:"_blank",href:"https://www.pexels.com"},"Pexels"),".")),React.createElement(g.V,{title:ge.COMMON.AUDIO_TO_TEXT,key:"audioToText"},React.createElement("label",null,"Audio URL:"),React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{name:"url",rows:2,value:e,onChange:t}),React.createElement(le.g,null),React.createElement("label",null,"Prompt:"),React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{rows:2,value:l,onChange:r}),React.createElement(le.g,null),React.createElement(h.M,{fullWidth:!0,style:{height:40},disabled:o,isBusy:"audioToText"===o,startTime:d,onClick:()=>{u("audioToText")}},"Transcribe Audio")),React.createElement(g.V,{title:ge.COMMON.PROMPT_TO_JSON,key:"textToJSON"},React.createElement("label",null,"Prompt:"),React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{rows:2,value:l,onChange:r}),React.createElement(le.g,null),React.createElement(h.M,{fullWidth:!0,style:{height:40},disabled:o,isBusy:"textToJSON"===o,startTime:d,onClick:()=>{u("textToJSON")}},"Query AI"),React.createElement(le.g,null),React.createElement("label",null,"Examples:"),React.createElement("ul",null,React.createElement("li",null,"👽 List the best science fiction books. Include the title, author, publication year, and a short synopsis."),React.createElement("li",null,"🎋 Identify the most beautiful gardens in Japan. Provide the garden name, location (gps: [lng, lat]), best visiting season, and features."),React.createElement("li",null,"💰 Identify the current top 10 richest individuals globally. For each person, include their name, estimated net worth, source of wealth, country of residence, and key tags (such as 'technology', 'retail', 'investor', etc.). Additionally, provide a brief description of their most notable business ventures or achievements."),React.createElement("li",null,"🦁 Compile a list of significant archaeological discoveries in the last decade. Include the discovery, location, date, and significance.")),React.createElement(le.g,null))))),React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{title:"Transcription",className:"primary"},React.createElement(le.g,{tiny:!0}),"textToJSON"===c&&React.createElement(gr.p2,{value:a,indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}),"textToJSON"!==c&&React.createElement(Ke.m,{name:"context",rows:21,value:a,disabled:!a}))))},{useState:Yr,useMemo:Kr,useEffect:Xr}=wp.element,Qr=({options:e,updateOption:t,busy:a})=>{const[n,l]=Yr(""),[r,o]=Yr(null),[i,c]=Yr(null),[s,d]=Yr(!1),m=null==e?void 0:e.module_embeddings,u=(null==e?void 0:e.embeddings_envs)||[],p=async t=>{d(!0),o(null),c(null);try{const a={search:n,method:t,..."embeddings"===t&&(null==e?void 0:e.search_frontend_env_id)&&{envId:e.search_frontend_env_id},..."keywords"===t&&(null==e?void 0:e.search_website_context)&&{websiteContext:e.search_website_context}},l=await(0,y.IU)(`${b}/mwai-ui/v1/search`,{method:"POST",nonce:N,json:a});o(l)}catch(e){console.error("Search error:",e),o({success:!1,message:e.message||"An error occurred during search"})}finally{d(!1)}},v=Kr((()=>null!=r&&r.results?r.results.map((e=>({id:e.id,title:e.title||"Untitled",excerpt:e.excerpt||"No excerpt available",score:e.score?`${(100*e.score).toFixed(0)}%`:null,foundWith:e.found_with||null}))):[]),[r]),f=Kr((()=>{const e=[{accessor:"title",title:"Title",width:"200px"},{accessor:"excerpt",title:"Excerpt",width:"100%"}];return"embeddings"===(null==r?void 0:r.method)?(e[1].width="100%",e.push({accessor:"score",title:"Score",width:"80px"})):"keywords"===(null==r?void 0:r.method)&&(e[1].width="50%",e.push({accessor:"score",title:"Score",width:"80px"}),e.push({accessor:"foundWith",title:"Found with",width:"50%"})),e}),[null==r?void 0:r.method]),w=Kr((()=>{return null!=r&&r.debug?"embeddings"===(null==r?void 0:r.method)?React.createElement("div",{style:{marginTop:10,padding:10,background:"#f0f0f0",borderRadius:4,fontSize:12}},React.createElement("strong",null,"Debug Info:"),React.createElement("div",null,"Total vectors found: ",r.debug.total_vectors),React.createElement("div",null,"Filtered posts: ",r.debug.filtered_posts),React.createElement("div",null,"Min score threshold: ",r.debug.min_score),r.debug.sample_vectors&&React.createElement("details",{style:{marginTop:5}},React.createElement("summary",null,"Sample vectors (first 5)"),React.createElement("pre",{style:{fontSize:11,marginTop:5}},JSON.stringify(r.debug.sample_vectors,null,2)))):React.createElement("div",{style:{marginTop:10,padding:10,background:"#f0f0f0",borderRadius:4,fontSize:12}},r.debug.keyword_tiers&&React.createElement(React.Fragment,null,React.createElement("strong",null,"Keyword Tiers Generated:"),React.createElement("div",{style:{marginLeft:10,marginTop:5}},React.createElement("div",null,React.createElement("strong",null,"Exact:")," ",null===(e=r.debug.keyword_tiers.exact)||void 0===e?void 0:e.join(", ")),React.createElement("div",null,React.createElement("strong",null,"Contextual:")," ",null===(t=r.debug.keyword_tiers.contextual)||void 0===t?void 0:t.join(", ")),React.createElement("div",null,React.createElement("strong",null,"General:")," ",null===(a=r.debug.keyword_tiers.general)||void 0===a?void 0:a.join(", "))),React.createElement("div",{style:{marginTop:10}},React.createElement("strong",null,"Progressive Search (",r.debug.total_searches," attempts):"))),r.debug.searches&&React.createElement("details",{style:{marginTop:5}},React.createElement("summary",null,"View search attempts"),React.createElement("div",{style:{marginTop:5,fontSize:11}},r.debug.searches.map(((e,t)=>React.createElement("div",{key:t,style:{marginBottom:3}},e.attempt,'. "',e.keywords,'" (score: ',e.score,"%) → ",e.found," posts"))))),r.debug.total_searches&&React.createElement("div",{style:{marginTop:5,color:"#666"}},r.results.length>=3?`Stopped after finding ${r.results.length} results`:`Completed ${r.debug.total_searches} searches`)):null;var e,t,a}),[r]);return React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,style:{flex:2}},React.createElement(R.z,{title:"Search Test",className:"primary"},React.createElement("div",{style:{marginBottom:15}},React.createElement(ne.A,{name:"query",value:n,onChange:l,onEnter:()=>p((null==e?void 0:e.search_frontend_method)||"wordpress"),placeholder:"Enter your search query...",disabled:s,fullWidth:!0})),React.createElement("div",{style:{display:"flex",gap:8,marginBottom:10}},React.createElement(h.M,{className:"primary",onClick:()=>p((null==e?void 0:e.search_frontend_method)||"wordpress"),disabled:!n||s,isBusy:s,style:{flex:1}},"Search")),React.createElement("div",{style:{display:"flex",gap:8}},React.createElement(h.M,{className:"secondary",onClick:()=>p("wordpress"),disabled:!n||s,style:{flex:1}},"WordPress"),React.createElement(h.M,{className:"secondary",onClick:()=>p("keywords"),disabled:!n||s,style:{flex:1}},"AI Keywords"),React.createElement(h.M,{className:"secondary",onClick:()=>p("embeddings"),disabled:!n||s||!m||0===u.length,style:{flex:1}},"Embeddings"),React.createElement(h.M,{className:"secondary",onClick:async()=>{d(!0),o(null),c(null);const t=["wordpress","keywords","embeddings"],a={};try{for(const l of t)try{const t={search:n,method:l,..."embeddings"===l&&(null==e?void 0:e.search_frontend_env_id)&&{envId:e.search_frontend_env_id},..."keywords"===l&&(null==e?void 0:e.search_website_context)&&{websiteContext:e.search_website_context}},r=await(0,y.IU)(`${b}/mwai-ui/v1/search`,{method:"POST",nonce:N,json:t});a[l]=r}catch(e){console.error(`${l} search error:`,e),a[l]={success:!1,message:e.message||`An error occurred during ${l} search`}}c(a)}finally{d(!1)}},disabled:!n||s,style:{flex:1}},"Multi-Method"))),r&&React.createElement(R.z,{title:"Results",className:"primary"},!1===r.success&&React.createElement(ce.X,{variant:"danger"},r.message,r.debug&&React.createElement("div",{style:{marginTop:5,fontSize:12}},"Debug: ",r.debug)),r.success&&React.createElement(React.Fragment,null,v.length>0?React.createElement(Xe.o,{data:v,columns:f,onSelectRow:e=>{const t=`${window.location.origin}/?p=${e}`;window.open(t,"_blank")}}):React.createElement("div",{style:{textAlign:"center",padding:20,color:"#666"}},"No results found for your search query."))),r&&r.success&&w&&"wordpress"!==r.method&&React.createElement(R.z,{title:"Search Debugging",className:"primary"},w),i&&!r&&React.createElement(g._,{inversed:!0,title:"Search Results",style:{padding:8}},Object.entries(i).map((([e,t])=>{const a=((e,t)=>null!=e&&e.results?e.results.map((e=>({id:e.id,title:e.title||"Untitled",excerpt:e.excerpt||"No excerpt available",score:e.score?`${(100*e.score).toFixed(0)}%`:null,foundWith:e.found_with||null}))):[])(t),n=(e=>{const t=[{accessor:"title",title:"Title",width:"200px"},{accessor:"excerpt",title:"Excerpt",width:"100%"}];return"embeddings"===e?(t[1].width="100%",t.push({accessor:"score",title:"Score",width:"80px"})):"keywords"===e&&(t[1].width="50%",t.push({accessor:"score",title:"Score",width:"80px"}),t.push({accessor:"foundWith",title:"Found with",width:"50%"})),t})(e),l=((e,t)=>{return null!=e&&e.debug?"embeddings"===t?React.createElement("div",{style:{marginTop:10,padding:10,background:"rgba(255,255,255,0.1)",borderRadius:4,fontSize:12}},React.createElement("strong",null,"Debug Info:"),React.createElement("div",null,"Total vectors found: ",e.debug.total_vectors),React.createElement("div",null,"Filtered posts: ",e.debug.filtered_posts),React.createElement("div",null,"Min score threshold: ",e.debug.min_score),e.debug.sample_vectors&&React.createElement("details",{style:{marginTop:5}},React.createElement("summary",null,"Sample vectors (first 5)"),React.createElement("pre",{style:{fontSize:11,marginTop:5}},JSON.stringify(e.debug.sample_vectors,null,2)))):"keywords"===t?React.createElement("div",{style:{marginTop:10,padding:10,background:"rgba(255,255,255,0.1)",borderRadius:4,fontSize:12}},e.debug.keyword_tiers&&React.createElement(React.Fragment,null,React.createElement("strong",null,"Keyword Tiers Generated:"),React.createElement("div",{style:{marginLeft:10,marginTop:5}},React.createElement("div",null,React.createElement("strong",null,"Exact:")," ",null===(a=e.debug.keyword_tiers.exact)||void 0===a?void 0:a.join(", ")),React.createElement("div",null,React.createElement("strong",null,"Contextual:")," ",null===(n=e.debug.keyword_tiers.contextual)||void 0===n?void 0:n.join(", ")),React.createElement("div",null,React.createElement("strong",null,"General:")," ",null===(l=e.debug.keyword_tiers.general)||void 0===l?void 0:l.join(", "))),React.createElement("div",{style:{marginTop:10}},React.createElement("strong",null,"Progressive Search (",e.debug.total_searches," attempts):"))),e.debug.searches&&React.createElement("details",{style:{marginTop:5}},React.createElement("summary",null,"View search attempts"),React.createElement("div",{style:{marginTop:5,fontSize:11}},e.debug.searches.map(((e,t)=>React.createElement("div",{key:t,style:{marginBottom:3}},e.attempt,'. "',e.keywords,'" (score: ',e.score,"%) → ",e.found," posts"))))),e.debug.total_searches&&React.createElement("div",{style:{marginTop:5}},e.results.length>=3?`Stopped after finding ${e.results.length} results`:`Completed ${e.debug.total_searches} searches`)):null:null;var a,n,l})(t,e),r="wordpress"===e?"WordPress":"keywords"===e?"AI Keywords":"Embeddings";return React.createElement(g.V,{key:e,title:r,inversed:!0},!1===t.success&&React.createElement(ce.X,{variant:"danger"},t.message,t.debug&&React.createElement("div",{style:{marginTop:5,fontSize:12}},"Debug: ",t.debug)),t.success&&React.createElement(React.Fragment,null,a.length>0?React.createElement(Xe.o,{data:a,columns:n,onSelectRow:e=>{const t=`${window.location.origin}/?p=${e}`;window.open(t,"_blank")}}):React.createElement("div",{style:{textAlign:"center",padding:20}},"No results found for your search query."),l&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement("div",null,React.createElement("strong",null,"Search Debugging:"),l))))})))),React.createElement(E.Y,{minimal:!0,style:{flex:1}},React.createElement(R.z,{title:"Search Method",className:"primary",busy:a},React.createElement("div",{style:{marginBottom:15}},React.createElement("label",{style:{display:"block",marginBottom:5,fontWeight:"bold"}},"Frontend Search Method"),React.createElement(ae.u,{name:"search_frontend_method",value:(null==e?void 0:e.search_frontend_method)||"wordpress",onChange:t,fullWidth:!0},React.createElement(ae.j,{value:"wordpress",label:"WordPress"}),React.createElement(ae.j,{value:"keywords",label:"AI Keywords"}),React.createElement(ae.j,{value:"embeddings",label:"Embeddings"}))),React.createElement("div",{style:{padding:10,background:"#f9f9f9",borderRadius:4,fontSize:13}},React.createElement("strong",null,"Frontend Search:"),React.createElement("p",{style:{margin:"5px 0"}},"This controls how search widgets and blocks work on your website frontend. The method selected above will be used for all frontend searches."),React.createElement("p",{style:{margin:"5px 0"}},"Use the buttons above to test different methods before applying them to the frontend."))),React.createElement(g._,{inversed:!0,title:"Settings",style:{marginTop:10,padding:8},busy:a},React.createElement(g.V,{title:"WordPress",inversed:!0},React.createElement("div",{style:{padding:10,background:"rgba(255,255,255,0.1)",borderRadius:4,fontSize:13}},React.createElement("strong",null,"WordPress Method:"),React.createElement("p",{style:{margin:"5px 0"}},"Uses the standard WordPress search functionality without any AI enhancements. This searches for exact matches of your query in post titles and content."),React.createElement("p",{style:{margin:"5px 0"}},"Results are ordered by relevance as determined by WordPress's built-in search algorithm."))),React.createElement(g.V,{title:"AI Keywords",inversed:!0},React.createElement("div",{style:{marginBottom:15}},React.createElement("label",{style:{display:"block",marginBottom:5,fontWeight:"bold"}},"Website Context"),React.createElement(Ke.m,{name:"search_website_context",value:(null==e?void 0:e.search_website_context)||"This is a website with useful information and content.",onBlur:t,rows:3,fullWidth:!0,description:"Describe what your website is about to help AI generate better search keywords."})),React.createElement("div",{style:{padding:10,background:"rgba(255,255,255,0.1)",borderRadius:4,fontSize:13}},React.createElement("strong",null,"AI Keywords Method:"),React.createElement("p",{style:{margin:"5px 0"}},"Uses a smart progressive search algorithm optimized for WordPress search. Searches progressively from high to low precision using simple words that authors actually write in posts."))),React.createElement(g.V,{title:"Embeddings",inversed:!0},React.createElement("div",{style:{marginBottom:15}},React.createElement("label",{style:{display:"block",marginBottom:5,fontWeight:"bold"}},"Embeddings Environment"),m?u.length>0?React.createElement(ae.u,{name:"search_frontend_env_id",value:(null==e?void 0:e.search_frontend_env_id)||"",onChange:t,fullWidth:!0,placeholder:"Select environment..."},u.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))):React.createElement(ce.X,{variant:"info",style:{fontSize:13}},"No embeddings environments configured. Please configure one in the Knowledge tab."):React.createElement(ce.X,{variant:"warning",style:{fontSize:13}},"The Embeddings module is not enabled. Please enable it in the Settings under Modules.")),React.createElement("div",{style:{padding:10,background:"rgba(255,255,255,0.1)",borderRadius:4,fontSize:13}},React.createElement("strong",null,"Embeddings Method:"),React.createElement("p",{style:{margin:"5px 0"}},"Your search query will be converted into embeddings and compared against your indexed content for semantic similarity. This provides more intelligent results based on meaning rather than exact keyword matches."),React.createElement("p",{style:{margin:"5px 0"}},"Make sure you have content indexed in your selected embeddings environment."))))))},{useState:Jr,useMemo:Zr,useEffect:eo}=wp.element,to=[{accessor:"name",title:"Name",width:"30%",verticalAlign:"top"},{accessor:"instructions",title:"Instructions",width:"40%",verticalAlign:"top"},{accessor:"parameters",title:"Parameters",width:"20%",verticalAlign:"top"},{accessor:"createdOn",title:"Created On",width:"10%",verticalAlign:"top"}],ao=[{accessor:"file",title:"File",width:"30%",verticalAlign:"top"},{accessor:"metadata",title:"Metadata",width:"30%",verticalAlign:"top"},{accessor:"userId",title:"User ID",width:"80px",verticalAlign:"top"},{accessor:"purpose",title:"Purpose",width:"20%",verticalAlign:"top"},{accessor:"created",title:"Created On",width:"20%",verticalAlign:"top"},{accessor:"actions",title:"Actions",width:"60px",verticalAlign:"top"}],no=({options:e,refreshOptions:t})=>{var a;const n=(0,l.jE)(),[i,s]=Jr(null),[d,m]=Jr(!1),[u,p]=Jr(null==e||null===(a=e.ai_envs)||void 0===a||null===(a=a[0])||void 0===a?void 0:a.id),[v,f]=Jr("assistants"),[_,C]=Jr([]),{colors:T}=(0,r.z)(),O=Zr((()=>{var t;return(null==e||null===(t=e.ai_envs)||void 0===t?void 0:t.filter((e=>"openai"===e.type||"azure"===e.type)))||[]}),[e]),N=Zr((()=>O.find((e=>e.id===u))),[u,O]),I=Zr((()=>(null==N?void 0:N.assistants)||[]),[N]),[M,S]=Jr({userId:null,purpose:["assistant-in","assistant-out"],metadata:null,envId:u,page:1,limit:10}),k=(0,y.F1)(M);eo((()=>{const e=(()=>{const e=localStorage.getItem("mwai-admin-assistants");try{return JSON.parse(e)}catch(e){return{}}})(),t=(null==e?void 0:e.envId)??null;t&&p(t)}),[]),eo((()=>{(({envId:e})=>{const t={envId:e||null};localStorage.setItem("mwai-admin-assistants",(0,y.F1)(t))})({envId:u})}),[u]),eo((()=>{S({...M,envId:u})}),[u]);const{isFetching:A,data:x}=(0,o.I)({queryKey:["assistants-files",k],enabled:"files"===v,staleTime:3e5,queryFn:()=>(async({userId:e=null,purpose:t=null,metadata:a=null,envId:n=null,limit:l=10,page:r=0})=>{const o=await lt(`${b}/mwai-ui/v1/files/list`,{method:"POST",json:{userId:e,purpose:t,metadata:a,envId:n,limit:l,page:r}});if(!o.success)throw new Error(o.message);return null==o?void 0:o.data})(M)}),P=e=>e?React.createElement("small",null,React.createElement("ul",{style:{margin:0,padding:0}},Object.keys(e).map((t=>React.createElement("li",{key:t,style:{margin:0}},React.createElement("i",null,t),": ",e[t]," ","assistant_id"===t?`(${(e=>{const t=I.find((t=>t.id===e));return(null==t?void 0:t.name)||"N/A"})(e[t])})`:""))))):null,D=(e,t)=>React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("span",null,(e=>{if(!e)return null;const t=e.split("/").pop();return React.createElement("a",{href:e,target:"_blank",rel:"noreferrer"},t)})(e)),React.createElement("small",null,t)),L=async e=>{m(!0);try{await(async e=>{const t=await lt(`${b}/mwai-ui/v1/files/delete`,{method:"POST",json:{files:e}});if(!t.success)throw new Error(t.message);return t})(e),await n.invalidateQueries("assistants-files"),C([])}catch(e){s(e)}m(!1)},F=Zr((()=>null==x?void 0:x.files.map((e=>{return{...e,file:D(e.url,e.refId),purpose:(t=e.purpose,"assistant-out"===t?"Generated":"assistant-in"===t?"Uploaded":t),metadata:P(e.metadata),created:new Date(e.created).toLocaleDateString(),actions:React.createElement(React.Fragment,null,React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",disabled:d,onClick:()=>L([e.id])}))};var t}))),[x]),B=Zr((()=>(null==x?void 0:x.total)||0),[x]),U=Zr((()=>I.map((e=>{var t;return{...e,name:React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("span",null,e.name),React.createElement("small",null,e.id)),instructions:(null===(t=e.instructions)||void 0===t?void 0:t.length)>100?`${e.instructions.slice(0,100)}...`:e.instructions,parameters:React.createElement(React.Fragment,null,React.createElement("ul",{style:{margin:0,padding:0}},React.createElement("li",{style:{margin:0,display:"flex"}},React.createElement(Ye.z,{icon:"check",width:16,color:T.green}),React.createElement("span",{style:{marginLeft:3}},e.model??"Unknown")),!e.model&&React.createElement("li",{style:{margin:0,display:"flex",lineHeight:"12px"}},React.createElement("small",null,"The model could not be found in your AI environment. Please make sure it exists as a deployment, and Refresh the list of Assistants.")),React.createElement("li",{style:{margin:0,display:"flex"}},React.createElement(Ye.z,{icon:e.has_file_search?"check":"close",width:16,color:e.has_file_search?T.green:T.gray}),React.createElement("a",{style:{marginLeft:3},href:"https://platform.openai.com/docs/assistants/tools/file-search",target:"_blank",rel:"noreferrer"},"File Search")),React.createElement("li",{style:{margin:0,display:"flex"}},React.createElement(Ye.z,{icon:e.has_code_interpreter?"check":"close",width:16,color:e.has_code_interpreter?T.green:T.gray}),React.createElement("a",{style:{marginLeft:3},href:"https://platform.openai.com/docs/assistants/tools/code-interpreter",target:"_blank",rel:"noreferrer"},"Code Interpreter")))),createdOn:new Date(e.createdOn).toLocaleDateString()}}))),[I,T.gray,T.green]),H=d,j=Zr((()=>React.createElement(ae.u,{scrolldown:!0,value:u,onChange:p,style:{marginLeft:5}},O.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))))),[u,O]),G=Zr((()=>React.createElement("div",null,React.createElement("div",{style:{display:"flex",flexDirection:"row"}},React.createElement(tt.Q,{currentPage:M.page,limit:M.limit,total:B,onClick:e=>{S({...M,page:e})}})))),[M,B]);return React.createElement(E.N,null,React.createElement(E.Y,{fullWidth:!0,minimal:!0,style:{margin:8}},React.createElement(g._,{inversed:!0,currentTab:v,onChange:(e,t)=>{f(t.key)},action:React.createElement(React.Fragment,null,React.createElement("div",{style:{flex:"auto"}}),_.length>0&&"files"===v&&React.createElement(React.Fragment,null,React.createElement(h.M,{className:"danger",disabled:!1,onClick:()=>L(_)},ge.COMMON.DELETE)),"files"===v&&React.createElement(h.M,{disabled:H||!N,busy:H,onClick:async()=>{await n.invalidateQueries("assistants-files")},className:"secondary"},ge.COMMON.REFRESH),"assistants"===v&&React.createElement(h.M,{disabled:H||!N,busy:H,onClick:async()=>{m(!0);try{await(async e=>{const t=await lt(`${w}/openai/assistants/list?envId=${e}`);if(!t.success)throw new Error(t.message);return null==t?void 0:t.assistants})(u),await t()}catch(e){s(e)}m(!1)},className:"secondary"},ge.COMMON.REFRESH),j)},React.createElement(g.V,{title:ge.COMMON.ASSISTANTS,key:"assistants"},React.createElement(Xe.o,{busy:H,data:U,columns:to,emptyMessage:ge.NO_ASSISTANTS_YET})),React.createElement(g.V,{title:ge.COMMON.FILES,key:"files"},React.createElement(Xe.o,{busy:A||H,data:F,columns:ao,selectedItems:_,onSelect:e=>{C([..._,...e])},onUnselect:e=>{C([..._.filter((t=>!e.includes(t)))])},emptyMessage:ge.NO_FILES_YET}),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginTop:10}},React.createElement("div",{style:{flex:"auto"}}),G)))),React.createElement(E.Y,{fullWidth:!0,minimal:!0},React.createElement(R.z,{className:"primary"},React.createElement(c.s,{p:!0},(0,y.FE)(ge.HELP.ASSISTANTS_INTRO)),React.createElement(ce.X,{variant:"danger"},(0,y.FE)(ge.HELP.ASSISTANTS_WARNINGS))),React.createElement(le.g,{tiny:!0}),i&&React.createElement(ie.n,{isOpen:!!i,title:"Error",onRequestClose:()=>s(null),okButton:{label:"Ok",onClick:()=>s(null)},content:React.createElement("p",null,null==i?void 0:i.message)})))};var lo=a(9491);const{useState:ro,useMemo:oo}=wp.element,io=L.Ay.div`
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 20px;
`,co=({addons:e})=>{const t=e.some((e=>e.enabled))?"enabled":"all",[a,n]=ro(t),l=oo((()=>"enabled"===a?e.filter((e=>e.enabled)):"disabled"===a?e.filter((e=>!e.enabled)):e),[e,a]);return React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,fullWidth:!0,style:{padding:10}},React.createElement(Qe.V,null,React.createElement(oe.o,{name:"filter",value:a,onChange:e=>n(e)},React.createElement(oe.K,{title:"All",value:"all"}),React.createElement(oe.K,{title:"Enabled",value:"enabled"}),React.createElement(oe.K,{title:"Disabled",value:"disabled"}))),React.createElement(le.g,null),React.createElement(io,null,l.map((e=>React.createElement(re.L,{key:e.id,style:{marginBottom:0},footer:React.createElement("div",{style:{display:"flex",width:"100%",alignItems:"center",marginLeft:10,minHeight:30}},React.createElement("span",{style:{fontSize:"11px",marginRight:15,color:e.enabled?"#4CAF50":"#666",textTransform:"uppercase",fontWeight:"bold"}},e.enabled?React.createElement("label",null,"Enabled"):React.createElement("label",null,"Disabled")),React.createElement("div",{style:{flex:"auto"}}),e.enabled&&e.settings_url&&React.createElement(h.M,{className:"primary",onClick:()=>window.open(e.settings_url,"_self")},"Settings"),!e.enabled&&React.createElement(h.M,{className:"primary",onClick:()=>window.open(e.install_url,"_blank")},"Install"))},React.createElement("div",{style:{display:"flex",justifyContent:"flex-start",alignItems:"center",marginBottom:10}},React.createElement("div",{style:{width:32,marginTop:-5}},React.createElement(lo.r,null)),React.createElement(c.s,{h3:!0,style:{margin:0,marginLeft:8,fontWeight:"bold"}},e.name),React.createElement("div",{style:{marginLeft:5,marginTop:3,fontSize:10,color:"#fec74c"}},Array.from({length:e.stars},((e,t)=>React.createElement("span",{key:t},"★"))))),React.createElement("div",{className:"addon-description"},e.description)))))))},{useMemo:so,useState:mo,useEffect:uo,useCallback:po}=wp.element,Eo=[{envKey:"ai_fast_default_env",modelKey:"ai_fast_default_model",defaultModel:"gpt-4.1-nano"},{envKey:"ai_embeddings_default_env",modelKey:"ai_embeddings_default_model",defaultModel:"text-embedding-ada-002"},{envKey:"ai_vision_default_env",modelKey:"ai_vision_default_model",defaultModel:"gpt-4o-mini"},{envKey:"ai_images_default_env",modelKey:"ai_images_default_model",defaultModel:"dall-e-3-hd"},{envKey:"ai_audio_default_env",modelKey:"ai_audio_default_model",defaultModel:"whisper-1"},{envKey:"ai_json_default_env",modelKey:"ai_json_default_model",defaultModel:"gpt-4o-mini"}],go=["module_forms","module_statistics","module_embeddings","module_assistants","module_orchestration"],ho=()=>{var e,t,a,n,l,r,o,i,p,_,C;const[M,S]=mo(I),k=b.replace("/wp-json",""),[A,x]=mo((()=>{const e=localStorage.getItem("mwai_settings_section");return e||"ai"})),[P,D]=mo(null),[L,F]=mo(!1),[B,U]=mo(!1),H=null==M?void 0:M.module_suggestions,j=null==M?void 0:M.module_advisor,G=null==M?void 0:M.module_forms,$=null==M?void 0:M.module_finetunes,z=null==M?void 0:M.module_statistics,W=null==M?void 0:M.module_playground,q=null==M?void 0:M.module_generator_content,V=null==M?void 0:M.module_generator_images,Y=null==M?void 0:M.module_moderation,K=null==M?void 0:M.module_embeddings,X=null==M?void 0:M.module_assistants,Q=null==M?void 0:M.module_transcription,J=null==M?void 0:M.module_addons,Z=null==M?void 0:M.module_devtools,ee=null==M?void 0:M.module_chatbots,te=null==M?void 0:M.module_search,ce=null==M?void 0:M.module_orchestration,se=so((()=>null!=M&&M.ai_envs?null==M?void 0:M.ai_envs:[]),[M]),de=so((()=>null!=M&&M.mcp_envs?null==M?void 0:M.mcp_envs:[]),[M]),me=null==M?void 0:M.ai_fast_default_env,pe=null==M?void 0:M.ai_fast_default_model,Ee=null==M?void 0:M.ai_default_env,he=null==M?void 0:M.ai_default_model,Re=null==M?void 0:M.ai_vision_default_env,ye=null==M?void 0:M.ai_vision_default_model,ve=null==M?void 0:M.ai_embeddings_default_env,fe=null==M?void 0:M.ai_embeddings_default_model,be=null==M?void 0:M.ai_images_default_env,we=null==M?void 0:M.ai_images_default_model,Te=null==M?void 0:M.ai_audio_default_env,Oe=null==M?void 0:M.ai_audio_default_model,Ne=null==M?void 0:M.ai_json_default_env,Ie=null==M?void 0:M.ai_json_default_model,Me=null==M?void 0:M.ai_streaming,Se=null==M?void 0:M.ai_responses_api,Ae=null==M?void 0:M.privacy_first,xe=null!=M&&M.embeddings_envs?null==M?void 0:M.embeddings_envs:[],Pe=null==M?void 0:M.embeddings_default_env,De=null==M?void 0:M.syntax_highlight,Le=null==M?void 0:M.event_logs,Fe=null==M?void 0:M.chatbot_discussions,Be=null==M?void 0:M.virtual_keyboard_fix,Ue=null==M?void 0:M.chatbot_gdpr_consent,He=null==M?void 0:M.chatbot_gdpr_text,je=null==M?void 0:M.chatbot_gdpr_button,Ge=null==M?void 0:M.speech_recognition,ze=null==M?void 0:M.speech_synthesis,We=null==M?void 0:M.public_api,qe=null==M?void 0:M.statistics_data,Ve=null==M?void 0:M.statistics_forms_data,Ye=null==M?void 0:M.intro_message,Ke=null==M?void 0:M.module_addons,Xe=null==M?void 0:M.context_max_length,Qe=null==M?void 0:M.banned_ips,Je=null==M?void 0:M.banned_words,Ze=null==M?void 0:M.ignore_word_boundaries,et=(null==M?void 0:M.custom_languages)||[],tt=(null==M?void 0:M.admin_bar)??["settings"],at=null==M?void 0:M.resolve_shortcodes,nt=null==M?void 0:M.clean_uninstall,{completionModels:lt}=Ce(M),{visionModels:rt}=Ce(M,null==M?void 0:M.ai_vision_default_env),{audioModels:ot}=Ce(M,null==M?void 0:M.ai_audio_default_env),{jsonModels:ut}=Ce(M,null==M?void 0:M.ai_json_default_env),{imageModels:pt}=Ce(M,null==M?void 0:M.ai_images_default_env),{embeddingsModels:Et}=Ce(M,null==M?void 0:M.ai_embeddings_default_env),gt=so((()=>se&&null!=M&&M.ai_engines?se.filter((e=>{const t=M.ai_engines.find((t=>t.type===e.type));if(!t||!t.models)return!1;return t.models.some((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("embedding")}))})):[]),[se,M]),ht=so((()=>Et.find((e=>e.model===fe))),[Et,fe]),Rt=so((()=>{var e,t;if(!ht)return[];if((null==ht||null===(e=ht.tags)||void 0===e?void 0:e.includes("matryoshka"))&&(null==ht||null===(t=ht.dimensions)||void 0===t?void 0:t.length)>0){const e=ht.dimensions[0];return[3072,2048,1536,1024,768,512].filter((t=>t<=e))}return(null==ht?void 0:ht.dimensions)||[]}),[ht]),yt=L,vt=po((async e=>{try{if((0,y.F1)(e)===(0,y.F1)(M))return;F(!0);const t=await(0,y.IU)(`${w}/settings/update`,{method:"POST",nonce:N,json:{options:e}});S(t.options)}catch(t){console.error(ge.ERROR.UPDATING_OPTIONS,null!=t&&t.message?{message:t.message,options:M,newOptions:e}:{err:t,options:M,newOptions:e}),t.message&&D(React.createElement(React.Fragment,null,React.createElement("div",null,ge.ERROR.UPDATING_OPTIONS),React.createElement("small",null,(0,y.FE)(ge.ERROR.CHECK_YOUR_CONSOLE))))}finally{F(!1)}}),[M]);uo((()=>{(async()=>{let e=!1;const t={...M};Eo.forEach((({envKey:a,modelKey:n,defaultModel:l})=>{let r=!1;if(M[a]&&(r=!!se.find((e=>e.id===M[a]))),!r){const r=se.find((e=>"openai"===(null==e?void 0:e.type)));r?t[a]===r.id&&t[n]===l||(console.warn(`Updating ${a} and ${n} to ${r.id} and ${l}`),e=!0,t[a]=r.id,t[n]=l):null===t[a]&&null===t[n]||(console.warn(`Updating ${a} and ${n} to null`),e=!0,t[a]=null,t[n]=null)}if("ai_embeddings_default_model"===n&&t[n]){const a=(null==t?void 0:t.ai_embeddings_default_dimensions)||null;if(null!==a){const l=Et.find((e=>e.model===t[n]));if(l){var o,i;const n=null==l||null===(o=l.tags)||void 0===o?void 0:o.includes("matryoshka");let r=(null==l?void 0:l.dimensions)||[];if(n&&(null==l||null===(i=l.dimensions)||void 0===i?void 0:i.length)>0){const e=l.dimensions[0];r=[3072,2048,1536,1024,768,512].filter((t=>t<=e))}if(!r.includes(parseInt(a))){const a=r[0]||null;null!==a&&(t.ai_embeddings_default_dimensions=a,console.warn(`Updating embeddings default dimensions to ${a}`),e=!0)}}}}})),e&&await vt(t)})()}),[se,M,vt,Et]);const ft=async()=>{F(!0);try{const e=await mt();S(e)}catch(e){console.error(ge.ERROR.GETTING_OPTIONS,null!=e&&e.message?{message:e.message}:{err:e}),e.message&&D(React.createElement(React.Fragment,null,React.createElement("div",null,ge.ERROR.GETTING_OPTIONS),React.createElement("small",null,(0,y.FE)(ge.ERROR.CHECK_YOUR_CONSOLE))))}finally{F(!1)}},bt=async(e,t)=>{const a={...M,[t]:e};await vt(a)},wt=async e=>{U(!0);try{await bt(e,"embeddings_settings")}finally{U(!1)}},_t=async(e,t)=>{const a=xe.map((a=>a.id===e?{...a,...t}:a));bt(a,"embeddings_envs")};uo((()=>{if(!O){const e={...M};let t=!1;go.forEach((a=>{e[a]&&(e[a]=!1,console.warn(`Resetting ${a}`),t=!0)})),t&&(0,y.F1)(e)!==(0,y.F1)(M)&&vt(e)}}),[]),uo((()=>{localStorage.setItem("mwai_settings_section",A)}),[A]),uo((()=>{!Me&&Le&&bt(!1,"event_logs")}),[Me,Le,bt]),uo((()=>{"ai"===A||"files"===A||"remote"===A||"others"===A||"chatbot"===A&&ee||"knowledge"===A&&K||"orchestration"===A&&ce||x("ai")}),[A,ee,K,ce]);const Ct=React.createElement(s.d,{title:ge.COMMON.UTILITIES},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_suggestions",label:ge.COMMON.POSTS_SUGGESTIONS,value:"1",checked:H,description:ge.COMMON.POSTS_SUGGESTIONS_HELP,onChange:bt}))),Tt=React.createElement(s.d,{title:ge.COMMON.ADVISOR},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_advisor",label:ge.COMMON.ENABLE,value:"1",checked:j,description:ge.HELP.ADVISOR,onChange:bt}))),Ot=React.createElement(s.d,{title:ge.COMMON.GENERATORS},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_generator_content",label:ge.COMMON.CONTENT_GENERATOR,value:"1",checked:q,description:ge.COMMON.CONTENT_GENERATOR_HELP,onChange:bt}),React.createElement(m.R,{name:"module_generator_images",label:ge.COMMON.IMAGES_GENERATOR,value:"1",checked:V,description:ge.COMMON.IMAGES_GENERATOR_HELP,onChange:bt}))),Nt=React.createElement(s.d,{title:ge.COMMON.PLAYGROUND},React.createElement(m.R,{name:"module_playground",label:ge.COMMON.ENABLE,value:"1",checked:W,description:ge.COMMON.PLAYGROUND_HELP,onChange:bt})),Mt=React.createElement(s.d,{title:ge.COMMON.FORMS},React.createElement(m.R,{name:"module_forms",label:ge.COMMON.ENABLE,value:"1",checked:G,requirePro:!0,isPro:O,description:ge.COMMON.FORMS_HELP,onChange:bt})),kt=React.createElement(s.d,{title:ge.COMMON.SEARCH},React.createElement(m.R,{name:"module_search",label:ge.COMMON.ENABLE,value:"1",checked:te,description:ge.COMMON.SEARCH_HELP,onChange:bt})),At=React.createElement(s.d,{title:ge.COMMON.FINETUNES},React.createElement(m.R,{name:"module_finetunes",label:ge.COMMON.ENABLE,value:"1",checked:$,description:React.createElement(React.Fragment,null,React.createElement(ke,{disabled:!$,style:{marginRight:3}}),ge.HELP.FINETUNES),onChange:bt})),xt=React.createElement(s.d,{title:React.createElement(React.Fragment,null,ge.COMMON.INSIGHTS)},React.createElement(m.R,{name:"module_statistics",label:ge.COMMON.ENABLE,value:"1",checked:z,requirePro:!0,isPro:O,description:ge.COMMON.INSIGHTS_HELP,onChange:bt})),Pt=React.createElement(s.d,{title:React.createElement(React.Fragment,null,ge.COMMON.MODERATION)},React.createElement(m.R,{name:"module_moderation",label:ge.COMMON.ENABLE,value:"1",checked:Y,description:React.createElement(React.Fragment,null,React.createElement(ke,{disabled:!Y,style:{marginRight:3}}),ge.COMMON.MODERATION_HELP),onChange:bt})),Dt=React.createElement(s.d,{title:React.createElement(React.Fragment,null,ge.COMMON.TRANSCRIPTION)},React.createElement(m.R,{name:"module_transcription",label:ge.COMMON.ENABLE,value:"1",checked:Q,description:ge.COMMON.TRANSCRIPTION_HELP,onChange:bt})),Lt=React.createElement(s.d,{title:React.createElement(React.Fragment,null,ge.COMMON.KNOWLEDGE)},React.createElement(m.R,{name:"module_embeddings",label:ge.COMMON.ENABLE,value:"1",checked:K,requirePro:!0,isPro:O,description:(0,y.FE)(ge.COMMON.KNOWLEDGE_HELP),onChange:bt})),Ft=React.createElement(s.d,{title:React.createElement(React.Fragment,null,ge.COMMON.ASSISTANTS,React.createElement("small",{style:{position:"relative",top:-3,fontSize:8}}," BETA"))},React.createElement(m.R,{name:"module_assistants",label:ge.COMMON.ENABLE,value:"1",checked:X,requirePro:!0,isPro:O,description:React.createElement(React.Fragment,null,React.createElement(ke,{disabled:!X,style:{marginRight:3}}),ge.HELP.ASSISTANTS),onChange:bt})),Bt=React.createElement(s.d,{title:ge.COMMON.ORCHESTRATION},React.createElement(m.R,{name:"module_orchestration",label:ge.COMMON.ENABLE,value:"1",checked:ce,requirePro:!0,isPro:O,description:ge.COMMON.ORCHESTRATION_HELP,onChange:bt})),Ut=React.createElement(s.d,{title:ge.COMMON.CHATBOT},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_chatbots",label:ge.COMMON.ENABLE,value:"1",checked:ee,description:ge.COMMON.CHATBOT_HELP,onChange:bt}))),Ht=React.createElement(s.d,{title:ge.COMMON.QUERIES_DATA},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"statistics_data",label:ge.COMMON.ENABLE,value:"1",checked:qe,description:ge.HELP.QUERIES_DATA,onChange:bt}))),jt=React.createElement(s.d,{title:ge.COMMON.QUERIES_FORMS_DATA},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"statistics_forms_data",label:ge.COMMON.ENABLE,value:"1",checked:Ve,description:ge.HELP.QUERIES_FORMS_DATA,onChange:bt}))),Gt=React.createElement(s.d,{title:ge.COMMON.INTRO_MESSAGE},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"intro_message",label:ge.COMMON.ENABLE,value:"1",checked:Ye,description:ge.HELP.INTRO_MESSAGE,onChange:bt}))),$t=React.createElement(s.d,{title:ge.COMMON.ADDONS},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_addons",label:ge.COMMON.ENABLE,value:"1",checked:Ke,description:ge.HELP.ADDONS,onChange:bt}))),zt=React.createElement(s.d,{title:ge.COMMON.CHATBOT_SELECT},React.createElement(ae.u,{scrolldown:!0,name:"chatbot_select",value:null==M?void 0:M.chatbot_select,onChange:bt,description:ge.HELP.CHATBOT_SELECT},React.createElement(ae.j,{key:"tabs",value:"tabs",label:ge.COMMON.TABS}),React.createElement(ae.j,{key:"dropdown",value:"dropdown",label:ge.COMMON.DROPDOWN}))),Wt=React.createElement(s.d,{title:ge.COMMON.WEBSPEECH_API},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"speech_recognition",label:ge.COMMON.SPEECH_RECOGNITION,value:"1",checked:Ge,description:ge.HELP.SPEECH_RECOGNITION,onChange:bt})),React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"speech_synthesis",label:ge.COMMON.SPEECH_SYNTHESIS+" (SOON)",value:"1",disabled:!0,checked:ze,description:ge.HELP.SPEECH_SYNTHESIS,onChange:bt}))),qt=React.createElement(s.d,{title:ge.COMMON.VIRTUAL_KEYBOARD},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"virtual_keyboard_fix",label:ge.COMMON.FIX,value:"1",checked:Be,description:ge.HELP.VIRTUAL_KEYBOARD,onChange:bt}))),Vt=React.createElement(s.d,{title:ge.COMMON.GDPR_CONSENT},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"chatbot_gdpr_consent",label:ge.COMMON.ENABLE,value:"1",checked:Ue,description:ge.HELP.GDPR_CONSENT,onChange:bt}))),Yt=React.createElement(s.d,{title:ge.COMMON.GDPR_TEXT},React.createElement(ne.A,{name:"chatbot_gdpr_text",value:He,onBlur:bt})),Kt=React.createElement(s.d,{title:ge.COMMON.GDPR_BUTTON},React.createElement(ne.A,{name:"chatbot_gdpr_button",value:je,onBlur:bt})),Xt=React.createElement(s.d,{title:ge.COMMON.STREAMING},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"ai_streaming",label:ge.COMMON.ENABLE,value:"1",checked:Me,description:ge.HELP.STREAMING,onChange:bt}))),Qt=React.createElement(s.d,{title:"Responses API"},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"ai_responses_api",label:ge.COMMON.ENABLE,value:"1",checked:Se,description:"Use OpenAI's new Responses API for improved performance and features. This is recommended, but can be disabled if you experience issues.",onChange:bt}))),Jt=React.createElement(s.d,{title:ge.COMMON.PRIVACY_FIRST},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"privacy_first",label:ge.COMMON.ENABLE,value:"1",checked:Ae,description:ge.HELP.PRIVACY_FIRST,onChange:bt}))),Zt=React.createElement(s.d,{title:ge.COMMON.DISCUSSIONS},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"chatbot_discussions",label:ge.COMMON.ENABLE,value:"1",checked:Fe,description:ge.HELP.DISCUSSIONS,onChange:bt}))),ea=React.createElement(s.d,{title:ge.COMMON.SUMMARIZE},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"chatbot_discussions_titling",label:ge.COMMON.ENABLE,value:"1",checked:null==M?void 0:M.chatbot_discussions_titling,description:ge.HELP.DISCUSSION_SUMMARY,onChange:bt}))),ta=React.createElement(s.d,{title:ge.COMMON.PAGING||"Paging"},React.createElement(ae.u,{scrolldown:!0,name:"chatbot_discussions_paging",value:(null==M?void 0:M.chatbot_discussions_paging)||10,onChange:bt,description:ge.HELP.DISCUSSIONS_PAGING||"Number of discussions to display per page"},React.createElement(ae.j,{value:"None",label:"None"}),React.createElement(ae.j,{value:5,label:"5 per Page"}),React.createElement(ae.j,{value:10,label:"10 per Page"}),React.createElement(ae.j,{value:15,label:"15 per Page"}),React.createElement(ae.j,{value:20,label:"20 per Page"}),React.createElement(ae.j,{value:30,label:"30 per Page"}),React.createElement(ae.j,{value:50,label:"50 per Page"}))),aa=React.createElement(s.d,{title:ge.COMMON.REFRESH_INTERVAL||"Refresh Interval"},React.createElement(ae.u,{scrolldown:!0,name:"chatbot_discussions_refresh_interval",value:(null==M?void 0:M.chatbot_discussions_refresh_interval)||5,onChange:bt,description:ge.HELP.DISCUSSIONS_REFRESH_INTERVAL||"How often to refresh the discussions list (in seconds)"},React.createElement(ae.j,{value:1,label:"1 second"}),React.createElement(ae.j,{value:2,label:"2 seconds"}),React.createElement(ae.j,{value:5,label:"5 seconds"}),React.createElement(ae.j,{value:10,label:"10 seconds"}),React.createElement(ae.j,{value:30,label:"30 seconds"}),React.createElement(ae.j,{value:60,label:"60 seconds"}),React.createElement(ae.j,{value:120,label:"120 seconds"}),React.createElement(ae.j,{value:"Manual",label:"Manually"}),React.createElement(ae.j,{value:"Never",label:"Never"}))),na=React.createElement(s.d,{title:"Metadata Bar"},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"chatbot_discussions_metadata_enabled",label:ge.COMMON.ENABLE,value:"1",checked:null==M?void 0:M.chatbot_discussions_metadata_enabled,description:"Display a metadata bar under discussion titles.",onChange:bt}))),la=null!=M&&M.chatbot_discussions_metadata_enabled?React.createElement(s.d,{title:"Metadata Display"},React.createElement(d.E,{max:"3"},React.createElement(m.R,{name:"chatbot_discussions_metadata_start_date",label:"Start Date",value:"1",checked:null==M?void 0:M.chatbot_discussions_metadata_start_date,description:"Show when the discussion was created.",onChange:bt}),React.createElement(m.R,{name:"chatbot_discussions_metadata_last_update",label:"Last Update",value:"1",checked:null==M?void 0:M.chatbot_discussions_metadata_last_update,description:"Show when the discussion was last modified.",onChange:bt}),React.createElement(m.R,{name:"chatbot_discussions_metadata_message_count",label:"Message Count",value:"1",checked:null==M?void 0:M.chatbot_discussions_metadata_message_count,description:"Show the number of messages in the discussion.",onChange:bt}))):null,ra=React.createElement(s.d,{title:ge.COMMON.SYNTAX_HIGHLIGHT},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"syntax_highlight",label:ge.COMMON.ENABLE,value:"1",checked:De,description:ge.HELP.SYNTAX_HIGHLIGHT,onChange:bt}))),oa=React.createElement(s.d,{title:ge.COMMON.EVENT_LOGS},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"event_logs",label:ge.COMMON.ENABLE,value:"1",checked:Le,disabled:!Me,description:ge.HELP.EVENT_LOGS,onChange:bt}))),ca=React.createElement(s.d,{title:ge.COMMON.PUBLIC_API},React.createElement(m.R,{name:"public_api",label:ge.COMMON.ENABLE,value:"1",checked:We,description:ge.HELP.PUBLIC_API,onChange:bt}),We&&React.createElement(zr,{value:`${b}/mwai/v1/`},React.createElement("span",null,k,React.createElement("span",{className:"highlight"},"/wp-json/mwai/v1/")))),sa=React.createElement(s.d,{title:ge.COMMON.BEARER_TOKEN},React.createElement(ne.A,{name:"public_api_bearer_token",value:null==M?void 0:M.public_api_bearer_token,description:(0,y.FE)(ge.HELP.BEARER_TOKEN),onBlur:bt})),da=React.createElement(s.d,{title:"SSE Endpoint"},React.createElement(m.R,{name:"module_mcp",label:ge.COMMON.ENABLE,value:"1",checked:null==M?void 0:M.module_mcp,description:"Enable the /wp-json/mcp/v1/sse endpoint. Check the labs/mcp.md for more information.",onChange:bt}),(null==M?void 0:M.module_mcp)&&React.createElement(React.Fragment,null,React.createElement(zr,{value:`${b}/mcp/v1/sse`},React.createElement("span",null,k,React.createElement("span",{className:"highlight"},"/wp-json/mcp/v1/sse"))))),ma=React.createElement(s.d,{title:ge.COMMON.BEARER_TOKEN},React.createElement(ne.A,{name:"mcp_bearer_token",value:null==M?void 0:M.mcp_bearer_token,description:(0,y.FE)(ge.HELP.MCP_BEARER_TOKEN),onBlur:bt})),ua=React.createElement(s.d,{title:"No-Auth URL"},React.createElement(m.R,{name:"mcp_noauth_url",label:ge.COMMON.ENABLE,value:"1",checked:null==M?void 0:M.mcp_noauth_url,disabled:!(null!=M&&M.module_mcp&&null!=M&&M.mcp_bearer_token),description:"Enable a special URL that includes authentication in the path. Only works when SSE Endpoint is enabled and Bearer Token is set.",onChange:bt}),(null==M?void 0:M.mcp_noauth_url)&&(null==M?void 0:M.module_mcp)&&(null==M?void 0:M.mcp_bearer_token)&&React.createElement(zr,{value:`${b}/mcp/v1/${M.mcp_bearer_token}/sse`},React.createElement("span",null,k,"/wp-json/mcp/v1/",React.createElement("span",{className:"highlight"},M.mcp_bearer_token),"/sse"))),pa=React.createElement(s.d,{title:"Tuned Core"},React.createElement(m.R,{name:"mcp_core",label:"Enable (Recommended)",value:"1",checked:null==M?void 0:M.mcp_core,description:"A highly-optimized MCP integration providing a streamlined, AI-focused layer tailored specifically for ease-of-use, performance, and clarity.",onChange:bt})),ga=React.createElement(s.d,{title:"Tuned Plugins"},React.createElement(m.R,{name:"mcp_plugins",label:ge.COMMON.ENABLE,value:"1",checked:null==M?void 0:M.mcp_plugins,requirePro:!0,isPro:O,description:"Create, fork, edit, and manage plugins directly through MCP.",onChange:bt})),ha=React.createElement(s.d,{title:"Tuned Themes"},React.createElement(m.R,{name:"mcp_themes",label:ge.COMMON.ENABLE,value:"1",checked:null==M?void 0:M.mcp_themes,requirePro:!0,isPro:O,description:"Enables theme management, editing, and the ability to fork existing themes into new ones to effortlessly integrate additional features.",onChange:bt})),Ra=React.createElement(s.d,{title:"Dynamic REST"},React.createElement(m.R,{name:"mcp_dynamic_rest",label:ge.COMMON.ENABLE,value:"1",checked:null==M?void 0:M.mcp_dynamic_rest,description:"The Automattic way. Dynamically provide comprehensive access to WordPress's REST API endpoints through MCP. Might be more obscure for the AI to work with.",onChange:bt})),ya=React.createElement(s.d,{title:"Local Upload"},React.createElement(ae.u,{scrolldown:!0,name:"image_local_upload",value:null==M?void 0:M.image_local_upload,onChange:bt,description:"Files can be stored either in the filesystem or the Media Library."},React.createElement(ae.j,{key:"uploads",value:"uploads",label:"Filesystem"}),React.createElement(ae.j,{key:"library",value:"library",label:"Media Library"}))),va=React.createElement(s.d,{title:"Remote Upload"},React.createElement(ae.u,{scrolldown:!0,name:"image_remote_upload",value:null==M?void 0:M.image_remote_upload,onChange:bt,description:"Select Upload Data for private sites; Share URLs requires your WordPress to be online and reachable."},React.createElement(ae.j,{key:"data",value:"data",label:"Upload Data"}),React.createElement(ae.j,{key:"url",value:"url",label:"Share URLs"}))),fa=React.createElement(s.d,{title:"Expiration"},React.createElement(ae.u,{scrolldown:!0,name:"image_expires",value:(null==M?void 0:M.image_expires)??"never",onChange:bt,description:"Uploaded files will be deleted after a certain amount of time. This also affects files uploaded to OpenAI via the Assistants."},React.createElement(ae.j,{key:300,value:300,label:"5 minutes"}),React.createElement(ae.j,{key:3600,value:3600,label:"1 hour"}),React.createElement(ae.j,{key:21600,value:21600,label:"6 hours"}),React.createElement(ae.j,{key:86400,value:86400,label:"1 day"}),React.createElement(ae.j,{key:604800,value:604800,label:"1 week"}),React.createElement(ae.j,{key:2592e3,value:2592e3,label:"1 month"}),React.createElement(ae.j,{key:"Never",value:"never",label:"Never"}))),ba=React.createElement(s.d,{title:"Local Download"},React.createElement(ae.u,{scrolldown:!0,name:"image_local_download",value:(null==M?void 0:M.image_local_download)??null,onChange:bt,description:"Files can be stored either in the filesystem or the Media Library."},React.createElement(ae.j,{key:null,value:null,label:"None"}),React.createElement(ae.j,{key:"uploads",value:"uploads",label:"Filesystem"}),React.createElement(ae.j,{key:"library",value:"library",label:"Media Library"}))),wa=React.createElement(s.d,{title:"Expiration"},React.createElement(ae.u,{scrolldown:!0,name:"image_expires_download",value:(null==M?void 0:M.image_expires_download)??"never",onChange:bt,description:"Downloaded files will be deleted after a certain amount of time."},React.createElement(ae.j,{key:300,value:300,label:"5 minutes"}),React.createElement(ae.j,{key:3600,value:3600,label:"1 hour"}),React.createElement(ae.j,{key:21600,value:21600,label:"6 hours"}),React.createElement(ae.j,{key:86400,value:86400,label:"1 day"}),React.createElement(ae.j,{key:604800,value:604800,label:"1 week"}),React.createElement(ae.j,{key:2592e3,value:2592e3,label:"1 month"}),React.createElement(ae.j,{key:"Never",value:"never",label:"Never"}))),_a=React.createElement(s.d,{title:ge.COMMON.DEV_TOOLS},React.createElement(m.R,{name:"module_devtools",label:ge.COMMON.ENABLE,value:"1",checked:Z,description:ge.HELP.DEV_TOOLS,onChange:bt})),Ca=React.createElement(s.d,{title:ge.COMMON.SHORTCODES},React.createElement(m.R,{name:"resolve_shortcodes",label:ge.COMMON.RESOLVE,value:"1",checked:at,description:ge.HELP.RESOLVE_SHORTCODE,onChange:bt})),Ta=React.createElement(s.d,{title:ge.COMMON.CONTEXT_MAX_LENGTH},React.createElement(ne.A,{name:"context_max_length",value:Xe,type:"number",step:"1",description:ge.HELP.CONTEXT_MAX_LENGTH,onBlur:bt})),Oa=React.createElement(s.d,{title:ge.COMMON.BANNED_WORDS},React.createElement(ne.A,{id:"banned_words",name:"banned_words",value:Je,isCommaSeparatedArray:!0,description:ge.HELP.BANNED_WORDS,onBlur:bt})),Na=React.createElement(s.d,{title:ge.COMMON.WORD_BOUNDARIES},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"ignore_word_boundaries",label:ge.COMMON.IGNORE,value:"1",checked:Ze,description:ge.HELP.WORD_BOUNDARIES,onChange:bt}))),Ia=React.createElement(s.d,{title:ge.COMMON.MODEL},React.createElement(ae.u,{scrolldown:!0,name:"ai_default_model",value:he,onChange:bt},lt.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),Ma=React.createElement(s.d,{title:ge.COMMON.MODEL},React.createElement(ae.u,{scrolldown:!0,name:"ai_fast_default_model",value:pe,onChange:bt},lt.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),Sa=React.createElement(s.d,{title:ge.COMMON.MODEL},React.createElement(ae.u,{scrolldown:!0,name:"ai_embeddings_default_model",value:fe,onChange:bt},Et.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),Aa=React.createElement(s.d,{title:ge.COMMON.DIMENSIONS},React.createElement(ae.u,{scrolldown:!0,name:"ai_embeddings_default_dimensions",value:null!=M&&M.ai_embeddings_default_dimensions?parseInt(M.ai_embeddings_default_dimensions):null,onChange:bt},Rt.map(((e,t)=>React.createElement(ae.j,{key:e,value:e,label:0===t?`${e} (Native)`:e}))),React.createElement(ae.j,{key:null,value:null,label:"Not Set"}))),xa=React.createElement(s.d,{title:ge.COMMON.MODEL},React.createElement(ae.u,{scrolldown:!0,name:"ai_vision_default_model",value:ye,onChange:bt},rt.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),Pa=React.createElement(s.d,{title:ge.COMMON.MODEL},React.createElement(ae.u,{scrolldown:!0,name:"ai_audio_default_model",value:Oe,onChange:bt},ot.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),Da=React.createElement(s.d,{title:ge.COMMON.MODEL},React.createElement(ae.u,{scrolldown:!0,name:"ai_json_default_model",value:Ie,onChange:bt},ut.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),La=React.createElement(s.d,{title:ge.COMMON.MODEL},React.createElement(ae.u,{scrolldown:!0,name:"ai_images_default_model",value:we,onChange:bt},pt.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name}))))),Fa=React.createElement(s.d,{title:ge.COMMON.BANNED_IPS},React.createElement(ne.A,{id:"banned_ips",name:"banned_ips",value:Qe,isCommaSeparatedArray:!0,description:ge.HELP.BANNED_IPS,onBlur:bt})),Ba=React.createElement(s.d,{title:"Available Languages"},React.createElement(ne.A,{id:"custom_languages",name:"custom_languages",value:et,isCommaSeparatedArray:!0,description:"The complete list of languages available in AI Engine. You can add, remove, or modify languages. Use format: 'Language Name (code)' or just 'Language Name'. The language code (e.g., 'en', 'fr') helps with internationalization but is optional.",placeholder:"English (en), French (fr), Spanish (es), German (de)",onBlur:bt})),Ua=React.createElement(s.d,{title:ge.COMMON.PLAYGROUND},React.createElement(m.R,{label:ge.COMMON.ENABLE,value:"1",checked:null==tt?void 0:tt.playground,onChange:e=>{const t={...tt,playground:e};bt(t,"admin_bar")}})),Ha=React.createElement(s.d,{title:ge.COMMON.GENERATE_CONTENT},React.createElement(m.R,{label:ge.COMMON.ENABLE,value:"1",checked:null==tt?void 0:tt.content_generator,onChange:e=>{const t={...tt,content_generator:e};bt(t,"admin_bar")}})),ja=React.createElement(s.d,{title:ge.COMMON.GENERATE_IMAGES},React.createElement(m.R,{label:ge.COMMON.ENABLE,value:"1",checked:null==tt?void 0:tt.images_generator,onChange:e=>{const t={...tt,images_generator:e};bt(t,"admin_bar")}})),Ga=React.createElement(s.d,{title:"AI Engine"},React.createElement(m.R,{label:ge.COMMON.ENABLE,value:"1",checked:null==tt?void 0:tt.settings,onChange:e=>{const t={...tt,settings:e};bt(t,"admin_bar")}})),$a=React.createElement("div",null,React.createElement(Ea,{options:M})),za=React.createElement(React.Fragment,null,React.createElement(le.g,{height:5}),React.createElement(s.d,{title:ge.COMMON.ENVIRONMENT},React.createElement(ae.u,{scrolldown:!0,name:"ai_default_env",value:Ee,onChange:bt},se.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))))),Wa=React.createElement(React.Fragment,null,React.createElement(le.g,{height:5}),React.createElement(s.d,{title:ge.COMMON.ENVIRONMENT},React.createElement(ae.u,{scrolldown:!0,name:"ai_fast_default_env",value:me,onChange:bt},se.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))))),qa=React.createElement(React.Fragment,null,React.createElement(le.g,{height:5}),React.createElement(s.d,{title:ge.COMMON.ENVIRONMENT},React.createElement(ae.u,{scrolldown:!0,name:"ai_embeddings_default_env",value:ve,onChange:bt},gt.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))))),Va=React.createElement(React.Fragment,null,React.createElement(le.g,{height:5}),React.createElement(s.d,{title:ge.COMMON.ENVIRONMENT},React.createElement(ae.u,{scrolldown:!0,name:"ai_vision_default_env",value:Re,onChange:bt},se.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))))),Ya=React.createElement(React.Fragment,null,React.createElement(le.g,{height:5}),React.createElement(s.d,{title:ge.COMMON.ENVIRONMENT},React.createElement(ae.u,{scrolldown:!0,name:"ai_audio_default_env",value:Te,onChange:bt},se.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))))),Ka=React.createElement(React.Fragment,null,React.createElement(le.g,{height:5}),React.createElement(s.d,{title:ge.COMMON.ENVIRONMENT},React.createElement(ae.u,{scrolldown:!0,name:"ai_json_default_env",value:Ne,onChange:bt},se.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))))),Xa=React.createElement(React.Fragment,null,React.createElement(le.g,{height:5}),React.createElement(s.d,{title:ge.COMMON.ENVIRONMENT},React.createElement(ae.u,{scrolldown:!0,name:"ai_images_default_env",value:be,onChange:bt},se.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))))),Qa=React.createElement(ae.u,{scrolldown:!0,name:"embeddings_default_env",value:Pe,onChange:bt},xe.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))),Ja=React.createElement(s.d,{title:ge.COMMON.PLUGIN_DATA},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"clean_uninstall",label:ge.COMMON.DELETE_ALL,description:ge.COMMON.PLUGIN_DATA_DESCRIPTION,value:"1",checked:nt,onChange:bt})));return React.createElement(u.z,null,React.createElement($e,{options:M}),React.createElement(E.N,null,React.createElement(E.Y,{fullWidth:!0},React.createElement(_e,{options:M}),Ye&&React.createElement(re.L,null,(0,y.FE)(ge.SETTINGS.INTRO)),React.createElement(g._,{keepTabOnReload:!0},React.createElement(g.V,{key:"dashboard",title:ge.COMMON.DASHBOARD},React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{busy:yt,title:ge.COMMON.CLIENT_MODULES,className:"primary"},Ut,Mt,kt),React.createElement(R.z,{busy:yt,title:ge.COMMON.SERVER_MODULES,className:"primary"},xt,Lt,Bt,At,Pt,Ft),React.createElement(R.z,{busy:yt,title:ge.COMMON.BACKEND_MODULES,className:"primary"},Tt,Ot,Nt,Ct,Dt)),React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{busy:yt,title:ge.COMMON.USAGE,className:"primary"},$a)))),ee&&React.createElement(g.V,{key:"chatbots",title:ge.COMMON.CHATBOTS},React.createElement(Er,{options:M,updateOption:bt,busy:yt})),te&&React.createElement(g.V,{key:"search",title:ge.COMMON.SEARCH},React.createElement(Qr,{options:M,updateOption:bt,busy:yt})),ee&&Fe&&React.createElement(g.V,{key:"discussions",title:ge.COMMON.DISCUSSIONS},React.createElement(ka,null)),z&&React.createElement(g.V,{key:"insights",title:ge.COMMON.INSIGHTS},React.createElement(Cr,{options:M,updateOption:bt,busy:yt})),K&&React.createElement(g.V,{key:"knowledge",title:ge.COMMON.KNOWLEDGE},React.createElement(ia,{options:M,updateEnvironment:_t,updateOption:bt})),X&&React.createElement(g.V,{key:"assistants",title:ge.COMMON.ASSISTANTS},React.createElement(no,{options:M,updateOption:bt,refreshOptions:ft})),$&&React.createElement(g.V,{key:"finetunes",title:ge.COMMON.FINETUNES},React.createElement(It,{options:M,updateOption:bt,refreshOptions:ft})),Y&&React.createElement(g.V,{key:"moderation",title:ge.COMMON.MODERATION},React.createElement(St,{options:M,updateOption:bt,busy:yt})),Q&&React.createElement(g.V,{key:"transcription",title:ge.COMMON.TRANSCRIPTION},React.createElement(Vr,{options:M,updateOption:bt})),J&&React.createElement(g.V,{key:"addons",title:ge.COMMON.ADDONS},React.createElement(co,{addons:null==M?void 0:M.addons,updateOption:bt})),React.createElement(g.V,{key:"settings",title:ge.COMMON.SETTINGS},React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,fullWidth:!0,style:{paddingLeft:10,paddingTop:10}},React.createElement(oe.o,{inversed:!0,name:"quicklinks",value:A,onChange:x},React.createElement(oe.K,{title:"AI",value:"ai"}),ee&&React.createElement(oe.K,{title:"Chatbot",value:"chatbot"}),K&&React.createElement(oe.K,{title:"Knowledge",value:"knowledge"}),ce&&React.createElement(oe.K,{title:"Orchestration",value:"orchestration"}),React.createElement(oe.K,{title:"Files & Media",value:"files"}),React.createElement(oe.K,{title:ge.COMMON.REMOTE_ACCESS,value:"remote"}),React.createElement(oe.K,{title:ge.COMMON.OTHERS,value:"others"}))),React.createElement(E.Y,{minimal:!0,fullWidth:!0},React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},"ai"===A&&React.createElement(React.Fragment,null,React.createElement(Lr,{busy:yt,options:M,environments:se,updateEnvironment:async(e,t)=>{const a=se.map((a=>a.id===e?{...a,...t}:a));bt(a,"ai_envs")},updateOption:bt}),React.createElement("div",{style:{padding:"0px 10px 15px 10px",marginTop:13,marginBottom:5}},React.createElement(c.s,{h2:!0,style:{color:"white",marginBottom:15}},ge.COMMON.AI_ENVIRONMENT_DEFAULTS),React.createElement(g._,{inversed:!0},React.createElement(g.V,{key:"ai",title:ge.COMMON.DEFAULT,busy:yt},za,Ia),React.createElement(g.V,{key:"fast",title:ge.COMMON.DEFAULT_FAST,busy:yt},Wa,Ma),React.createElement(g.V,{key:"vision",title:ge.COMMON.VISION,busy:yt},Va,xa),React.createElement(g.V,{key:"images",title:ge.COMMON.IMAGES,busy:yt},Xa,La),React.createElement(g.V,{key:"embeddings",title:ge.COMMON.EMBEDDINGS,busy:yt},qa,Sa,Aa),React.createElement(g.V,{key:"audio",title:ge.COMMON.AUDIO,busy:yt},Ya,Pa),React.createElement(g.V,{key:"json",title:ge.COMMON.JSON,busy:yt},Ka,Da)))),"knowledge"===A&&K&&React.createElement(React.Fragment,null,React.createElement(Sr,{busy:yt,options:M,environments:xe,updateEnvironment:_t,updateOption:bt}),React.createElement(R.z,{busy:yt,title:ge.COMMON.EMBEDDINGS_ENVIRONMENT_DEFAULT,className:"primary"},Qa)),"chatbot"===A&&React.createElement(React.Fragment,null,React.createElement(R.z,{busy:yt,title:ge.COMMON.CHATBOT,className:"primary"},Zt,ra,Wt,qt,Vt,Ue&&React.createElement(React.Fragment,null,Yt,Kt))),"orchestration"===A&&React.createElement(React.Fragment,null,React.createElement(Ur,{busy:yt,options:M,mcpServers:de,updateMCPServer:async(e,t)=>{const a=de.map((a=>a.id===e?{...a,...t}:a));bt(a,"mcp_envs")},updateOption:bt})),"files"===A&&React.createElement(R.z,{busy:yt,title:"Uploaded by Users",className:"primary"},ya,va,fa),"others"===A&&React.createElement(R.z,{busy:yt,title:ge.COMMON.USER_INTERFACE,className:"primary"},Gt,$t),"others"===A&&z&&React.createElement(R.z,{busy:yt,title:ge.COMMON.INSIGHTS,className:"primary"},React.createElement("p",null,ge.HELP.STATISTICS),Ht,jt),"others"===A&&React.createElement(R.z,{busy:yt,title:ge.COMMON.ADMIN_BAR,className:"primary"},Ga,Ua,Ha,ja),"others"===A&&React.createElement(R.z,{busy:yt,title:ge.COMMON.MAINTENANCE,className:"primary"},React.createElement("p",{style:{marginBottom:"15px"}},"It is important to keep regular backups of your settings. Use Export Settings to save your configuration. Import Settings allows you to restore a previous configuration. Reset Settings will restore all settings to their defaults. Reset Usage will clear all usage statistics and start fresh."),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"10px",marginBottom:"10px"}},React.createElement(h.M,{className:"blue",onClick:async()=>{F("exportSettings");try{const e=await st(),t=await it(),a={chatbots:e,themes:t,options:await mt()},n=new Blob([(0,y.F1)(a)],{type:"application/json"}),l=URL.createObjectURL(n),r=document.createElement("a");r.href=l;const o=new Date,i=`ai-engine-${o.getFullYear()}-${o.getMonth()+1}-${o.getDate()}.json`;r.setAttribute("download",i),r.click()}catch(e){alert("Error while exporting settings. Please check your console."),console.log(e)}finally{F(!1)}},style:{flex:2}},"Export Settings"),React.createElement(h.M,{className:"danger",onClick:async()=>{F("importSettings");try{const e=document.createElement("input");e.type="file",e.accept="application/json",e.onchange=async e=>{const t=e.target.files[0];if(!t)return;const a=new FileReader;a.onload=async e=>{const t=JSON.parse(e.target.result),{chatbots:a,themes:n,options:l}=t;await dt(a),await ct(n),await vt(l),alert("Settings imported. The page will now reload to reflect the changes."),window.location.reload()},a.readAsText(t)},e.click()}catch(e){alert("Error while importing settings. Please check your console."),console.log(e)}finally{F(!1)}},style:{flex:1}},"Import Settings"),React.createElement(h.M,{className:"danger",onClick:async()=>{if(window.confirm(ge.ALERTS.ARE_YOU_SURE)){F(!0);try{await(0,y.IU)(`${w}/settings/reset`,{method:"POST",nonce:N}),alert("Settings reset. The page will now reload to reflect the changes."),window.location.reload()}catch(e){alert("Error while resetting settings. Please check your console."),console.log(e)}finally{F(!1)}}},style:{flex:1}},"Reset Settings")),React.createElement(h.M,{className:"danger",onClick:async()=>{if(window.confirm(ge.COMMON.RESET_USAGE_SURE)){F(!0);try{await bt([],"ai_usage"),await bt([],"ai_usage_daily");const e=await(0,y.IU)(`${w}/settings/options`,{method:"GET",headers:{"X-WP-Nonce":N}});e.success&&e.options&&(vt(e.options),showSnackbar("Usage data has been reset successfully.","success"))}catch(e){console.error("Error resetting usage:",e),showSnackbar("Failed to reset usage data. Please try again.","error")}finally{F(!1)}}},disabled:yt,fullWidth:!0},ge.COMMON.RESET," ",ge.COMMON.USAGE)),"remote"===A&&React.createElement(React.Fragment,null,React.createElement(R.z,{busy:yt,title:"Model Context Protocol (MCP)",className:"primary"},React.createElement("p",null,(0,y.FE)(ge.HELP.MCP_INTRO)),React.createElement(le.g,null),da,ma,ua,(null==M?void 0:M.module_mcp)&&React.createElement(React.Fragment,null,pa,ga,ha,Ra)),(null==M?void 0:M.module_mcp)&&React.createElement(jr,{options:M}))),React.createElement(E.Y,{minimal:!0},"ai"===A&&React.createElement(React.Fragment,null,React.createElement(R.z,{busy:yt,title:ge.COMMON.GENERAL,className:"primary"},Xt,oa,Qt)),"knowledge"===A&&K&&React.createElement(React.Fragment,null,React.createElement(R.z,{className:"primary",title:ge.COMMON.DEFAULTS},React.createElement("p",null,React.createElement("strong",null,ge.COMMON.AI_ENVIRONMENT,":")," ",null!=M&&M.ai_embeddings_default_env?null==M||null===(e=M.ai_envs)||void 0===e||null===(e=e.find((e=>e.id===M.ai_embeddings_default_env)))||void 0===e?void 0:e.name:(null==M||null===(t=M.ai_envs)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.name)||"OpenAI",React.createElement("br",null),React.createElement("strong",null,ge.COMMON.EMBEDDINGS_MODEL,":")," ",(null==M?void 0:M.ai_embeddings_default_model)||"text-embedding-3-small",React.createElement("br",null),React.createElement("strong",null,ge.COMMON.DIMENSIONS,":")," ",(null==M?void 0:M.ai_embeddings_default_dimensions)||1536),React.createElement("p",{style:{marginTop:10,fontSize:"0.9em",fontStyle:"italic"}},'If a particular embeddings environment needs different settings, use the "Override Defaults" option in the AI Environment section of each embeddings environment.')),React.createElement(R.z,{className:"primary",title:"Embeddings Search",style:{marginTop:10},busy:B},React.createElement(s.d,{title:"Method"},React.createElement(ae.u,{scrolldown:!0,value:(null==M||null===(a=M.embeddings_settings)||void 0===a?void 0:a.search_method)||"simple",onChange:e=>wt({...M.embeddings_settings,search_method:e}),description:"Choose how to build search queries from conversations."},React.createElement(ae.j,{value:"simple",label:"Simple"}),React.createElement(ae.j,{value:"context_aware",label:"Context-Aware"}),React.createElement(ae.j,{value:"smart_search",label:"Smart Search"}))),("context_aware"===(null==M||null===(n=M.embeddings_settings)||void 0===n?void 0:n.search_method)||"smart_search"===(null==M||null===(l=M.embeddings_settings)||void 0===l?void 0:l.search_method)||"user_messages"===(null==M||null===(r=M.embeddings_settings)||void 0===r?void 0:r.search_method)||"ai_optimized"===(null==M||null===(o=M.embeddings_settings)||void 0===o?void 0:o.search_method))&&React.createElement(s.d,{title:"Messages"},React.createElement(ne.A,{type:"number",value:(null==M||null===(i=M.embeddings_settings)||void 0===i?void 0:i.context_messages)||10,min:1,max:20,onFinalChange:e=>wt({...M.embeddings_settings,context_messages:parseInt(e)||10}),description:"Number of recent messages to consider for context."})),("smart_search"===(null==M||null===(p=M.embeddings_settings)||void 0===p?void 0:p.search_method)||"ai_optimized"===(null==M||null===(_=M.embeddings_settings)||void 0===_?void 0:_.search_method))&&React.createElement(s.d,{title:"Instructions"},React.createElement(m.R,{name:"include_instructions",label:"Enable",value:"1",checked:(null==M||null===(C=M.embeddings_settings)||void 0===C?void 0:C.include_instructions)||!1,onChange:()=>{var e;return wt({...M.embeddings_settings,include_instructions:!(null!=M&&null!==(e=M.embeddings_settings)&&void 0!==e&&e.include_instructions)})},description:"Include chatbot instructions in search queries."}))),React.createElement(R.z,{className:"primary",title:"Information",style:{marginTop:10}},React.createElement("div",{style:{marginBottom:20}},React.createElement("p",null,"Embeddings are textual data converted into vectors that enable similarity search. They allow AI to find relevant context from your knowledge base, synchronized with vector databases like Pinecone or Qdrant for efficient storage and retrieval. When enabled in chatbots or forms, AI Engine searches your knowledge base for relevant context to enrich responses. Both chatbots and AI Forms can use embeddings to provide more contextual answers."),React.createElement("p",{style:{marginTop:15}},React.createElement("strong",null,"Working with Embeddings")),React.createElement("p",{style:{marginTop:5}},"Access the ",React.createElement("b",null,"Knowledge")," tab to manage your embeddings, where you can:"),React.createElement("ul",{style:{marginTop:5,marginLeft:20}},React.createElement("li",null,"Create, edit, and search embeddings (",React.createElement("strong",null,"EDIT"),")."),React.createElement("li",null,"Query your knowledge base directly (",React.createElement("strong",null,"AI SEARCH"),")."),React.createElement("li",null,"Use Sync to process posts and create/update embeddings.")),React.createElement("p",{style:{marginTop:15}},React.createElement("strong",null,"Embeddings Search")),React.createElement("p",{style:{marginTop:5}},"Configure how AI Engine searches your knowledge base when processing conversations. The search method determines what context is used to find relevant embeddings:"),React.createElement("ul",{style:{marginTop:5,marginLeft:20}},React.createElement("li",null,React.createElement("strong",null,"Last Message Only:")," Uses only the last message for context (default, fastest)."),React.createElement("li",null,React.createElement("strong",null,"Recent User Messages:")," Includes more conversation history for better context."),React.createElement("li",null,React.createElement("strong",null,"AI-Optimized Query:")," Uses AI to create smarter searches based on full context (uses Default Fast model, additional costs apply).")),React.createElement("p",{style:{marginTop:15}},"Learn more in the ",React.createElement("a",{href:"https://ai.thehiddendocs.com/embeddings/",target:"_blank"},"documentation")," or join the ",React.createElement("a",{href:"https://discord.gg/bHDGh38",target:"_blank"},"Discord Server")," to discuss embeddings with other users.")))),"chatbot"===A&&React.createElement(React.Fragment,null,Fe&&React.createElement(R.z,{busy:yt,title:ge.COMMON.DISCUSSIONS,className:"primary"},ea,ta,aa,na,la),React.createElement(R.z,{busy:yt,title:ge.COMMON.USER_INTERFACE,className:"primary"},zt)),"orchestration"===A&&React.createElement(R.z,{className:"primary",title:"Information"},React.createElement("p",null,(0,y.FE)(ge.SETTINGS.ORCHESTRATION_INFO))),"remote"===A&&React.createElement(R.z,{busy:yt,title:ge.COMMON.REST_API,className:"primary"},React.createElement("p",null,(0,y.FE)(ge.HELP.REST_API_INTRO)),React.createElement(le.g,null),ca,sa),"remote"===A&&React.createElement(R.z,{className:"primary",title:"Information"},React.createElement("p",null,(0,y.FE)(ge.SETTINGS.REMOTE_ACCESS_INFO))),"files"===A&&React.createElement(R.z,{busy:yt,title:"Generated by AI",className:"primary"},ba,null!==(null==M?void 0:M.image_local_download)&&wa),"others"===A&&React.createElement(R.z,{busy:yt,title:ge.COMMON.ADVANCED,className:"primary"},Ca,Ta,_a,Ja),"others"===A&&React.createElement(R.z,{busy:yt,title:"Languages",className:"primary"},Ba),"others"===A&&React.createElement(R.z,{busy:yt,title:ge.COMMON.SECURITY,className:"primary"},Jt,Oa,(null==Je?void 0:Je.length)>0&&Na,Fa)))))),Z&&React.createElement(g.V,{key:"devtools",title:ge.COMMON.DEV_TOOLS},React.createElement(Or,{options:M,setOptions:S,updateOption:bt,busy:yt})),React.createElement(g.V,{key:"license",title:ge.COMMON.LICENSE_TAB},React.createElement(ue,{domain:f,prefix:v,isPro:T,isRegistered:O}))))),React.createElement(ie.n,{isOpen:P,title:ge.COMMON.ERROR,content:P,onRequestClose:()=>D(!1),okButton:{label:"Close",onClick:()=>D(!1)}}))};var Ro=a(6087);const yo=[{value:"informative",label:"Informative"},{value:"descriptive",label:"Descriptive"},{value:"creative",label:"Creative"},{value:"narrative",label:"Narrative"},{value:"persuasive",label:"Persuasive"},{value:"reflective",label:"Reflective"},{value:"argumentative",label:"Argumentative"},{value:"analytical",label:"Analytical"},{value:"evaluative",label:"Evaluative"},{value:"journalistic",label:"Journalistic"},{value:"technical",label:"Technical"}],vo=[{value:"neutral",label:"Neutral"},{value:"formal",label:"Formal"},{value:"assertive",label:"Assertive"},{value:"cheerful",label:"Cheerful"},{value:"humorous",label:"Humorous"},{value:"informal",label:"Informal"},{value:"inspirational",label:"Inspirational"},{value:"professional",label:"Professional"},{value:"confluent",label:"Confluent"},{value:"emotional",label:"Emotional"},{value:"persuasive",label:"Persuasive"},{value:"supportive",label:"Supportive"},{value:"sarcastic",label:"Sarcastic"},{value:"condescending",label:"Condescending"},{value:"skeptical",label:"Skeptical"},{value:"narrative",label:"Narrative"},{value:"journalistic",label:"Journalistic"}],fo="",bo="Write a title for an article in {LANGUAGE}. Must be between 40 and 60 characters. Write naturally as a human would. Output only the title, no formatting, no Markdown, no special characters.\n\n### TOPIC:\n{TOPIC}\n\n### CONTEXT:\n{CONTEXT}\n\nGenerate a title based on the topic above, taking into account the provided context.",wo='Write {SECTIONS_COUNT} consecutive headings for an article about "{TITLE}", in {LANGUAGE}. Each heading is between 40 and 60 characters. Format each heading with Markdown (## ). Write naturally as a human would. Output only the headings, nothing else.\n\n### TOPIC:\n{TOPIC}\n\n### CONTEXT:\n{CONTEXT}\n\nCreate headings that align with both the topic and context provided above.',_o='Write an article about "{TITLE}" in {LANGUAGE}. Write {PARAGRAPHS_PER_SECTION} paragraphs per heading. Use Markdown for formatting. Add an introduction prefixed by "===INTRO: ", and a conclusion prefixed by "===OUTRO: ". Write naturally as a human would.\n\n### ARTICLE STRUCTURE:\n{SECTIONS}\n\n### TOPIC DETAILS:\n{TOPIC}\n\n### WRITING CONTEXT:\n{CONTEXT}\n\nWrite the article following the structure above, incorporating the topic details while adhering to the context guidelines.',Co='Write an excerpt for an article in {LANGUAGE}. Must be between 40 and 60 characters. Write naturally as a human would. Output only the excerpt, no formatting.\n\n### ARTICLE TITLE:\n"{TITLE}"\n\n### TOPIC:\n{TOPIC}\n\n### CONTEXT:\n{CONTEXT}\n\nCreate a compelling excerpt that captures the essence of the article while considering the context.',To=[{id:"default",name:"Default Template",mode:"query",model:fo,envId:"",temperature:.8,stopSequence:"",maxTokens:2048,prompt:""},{id:"article_translator",name:"Text Translator",mode:"query",model:fo,envId:"",temperature:.3,stopSequence:"",maxTokens:2048,prompt:"Translate this article into French:\n\nUchiko is located in Ehime prefecture, in the west of the island. The town was prosperous at the end of the 19th century thanks to its production of very good quality white wax. This economic boom allowed wealthy local merchants to build beautiful properties, whose heritage is still visible throughout the town.\n"},{id:"restaurant_review",name:"Restaurant Review Writer",mode:"query",model:fo,envId:"",temperature:.8,stopSequence:"",maxTokens:2048,prompt:"Write a review for a French restaurant located in Kagurazaka, Tokyo. Looks like an old restaurant, food is traditional, chef is talkative, it is always full. Not expensive, but not fancy.\n"},{id:"article_corrector",name:"Text Corrector",mode:"query",model:fo,envId:"",temperature:.2,stopSequence:"",maxTokens:2048,prompt:"Fix the grammar and spelling mistakes in this text:\n\nI wake up at eleben yesderday, I will go bed eary tonigt.\n"},{id:"seo_assistant",name:"SEO Optimizer",mode:"query",model:fo,envId:"",temperature:.6,stopSequence:"",maxTokens:1024,prompt:"For the following article, write a SEO-friendly and short title, keywords for Google, and a short excerpt to introduce it. Use this format:\n\nTitle: \nKeywords: \nExcerpt:\n\nArticle:\nUchiko is located in Ehime prefecture, in the west of the island. The town was prosperous at the end of the 19th century thanks to its production of very good quality white wax. This economic boom allowed wealthy local merchants to build beautiful properties, whose heritage is still visible throughout the town."}],Oo=[{id:"default",name:"Default Template",model:"",envId:"",resolution:"",maxResults:1,prompt:""},{id:"japan",name:"Ghibli Scene",model:"",envId:"",resolution:"",maxResults:1,prompt:"Create an image in the style of a Ghibli-inspired anime oil painting, depicting a quaint, old house in the Japanese countryside. This house, reminiscent of a traditional izakaya, is surrounded by lush trees and overlooks vibrant rice fields. The scene is bathed in the warm, soft glow of a setting sun, casting gentle shadows and creating a tranquil, nostalgic atmosphere. The composition should be rich in texture, capturing the serene beauty of rural Japan in a whimsical, Ghibli-like manner."},{id:"steampunk",name:"Steampunk Architecture",model:"",envId:"",resolution:"",maxResults:1,prompt:"Create an image showcasing steampunk architecture, focusing on the exterior view of a grand theater. The style should reflect award-winning architectural photography from a science fiction magazine. The theater, a masterpiece of steampunk design, combines Victorian influences with futuristic, mechanical elements. Its intricate facade features exposed gears, brass pipes, and steam vents, all integrated into the ornate, classical structure. The building should be set against a dramatic sky, highlighting its unique features and the interplay of light and shadow, capturing the essence of a high-quality, professional architectural photograph."},{id:"nyao-illustration",name:"Nyao Illustration",model:"",envId:"",resolution:"",maxResults:1,prompt:"The character is an anthropomorphic cat with a whimsical and endearing design, featuring a blend of white and blue fur. The right side of the cat's face has a patch of blue fur that also covers the outer part of the ear, while the left side remains predominantly white, except that the eye is surrounded by a green patch of fur. The tail mirrors this pattern with white fur leading to a blue tip. The character's facial expression is joyous, with a wide, open-mouthed smile showcasing a single front tooth and a small, black nose.  The cat's paws are also white, with defined fingers that suggest human-like dexterity. An orange collar encircles the neck, contrasting with the green and blue tones of the body. This collar is adorned with a blue and white emblem in the center, reminiscent of the WordPress logo. The drawing style of this image can be defined as a digital illustration with a cartoonish and whimsical aesthetic. It features bold outlines, flat colors, and simplified shapes which are typical of contemporary character design aimed at a broad, family-friendly audience. The style is reminiscent of modern vector art, which is often used for web graphics, animation, and media aimed at engaging a casual viewer with its clear, approachable, and vibrant visuals."}],No=[{id:"default",name:"Default Template",mode:"single",topic:"",topics:"",context:"",topicsAreTitles:!1,title:"",sections:"",model:fo,envId:"",temperature:.8,maxTokens:2048,sectionsCount:2,paragraphsCount:3,language:"en",customLanguage:"",writingStyle:"creative",writingTone:"cheerful",titlePromptFormat:bo,sectionsPromptFormat:wo,contentPromptFormat:_o,excerptPromptFormat:Co},{id:"explore_tokyo_offbeat",name:"Explore Tokyo Offbeat",mode:"single",topic:"5 hidden Tokyo neighborhoods only locals know: retro Showa-era streets, authentic Edo atmosphere, family-run restaurant alleys, old shopping arcades, quiet residential gems. Write in first person as a Tokyo local sharing secret spots.",topics:"",context:"",topicsAreTitles:!1,title:"",sections:"",model:fo,envId:"",temperature:.8,maxTokens:2048,sectionsCount:5,paragraphsCount:2,language:"en",customLanguage:"",writingStyle:"informative",writingTone:"informal",titlePromptFormat:bo,sectionsPromptFormat:wo,contentPromptFormat:_o,excerptPromptFormat:Co},{id:"cat_blog_bulk",name:"Cat Blog Bulk Generator",mode:"bulk",topic:"",topics:"Why Cats Make Perfect Companions\nUnderstanding Cat Body Language\nThe Science Behind Purring\nIndoor vs Outdoor Cats Debate\nBest Cat Breeds for Families\nCat Nutrition Guide\nTraining Your Cat: Tips and Tricks\nCommon Cat Health Issues",context:"Context: This is for a cat enthusiast blog targeting pet owners and cat lovers. The tone should be friendly, informative, and occasionally playful. Include practical tips, scientific facts, and real-world advice. Each article should be engaging and helpful for cat parents at all experience levels.",topicsAreTitles:!1,title:"",sections:"",model:fo,envId:"",temperature:.7,maxTokens:2048,sectionsCount:4,paragraphsCount:3,language:"en",customLanguage:"",writingStyle:"informative",writingTone:"cheerful",titlePromptFormat:bo,sectionsPromptFormat:wo,contentPromptFormat:_o,excerptPromptFormat:Co}],{useState:Io,useEffect:Mo,useMemo:So}=wp.element;function ko(){return(new Date).getTime().toString(36)+Math.random().toString(36).substr(2,9)}const Ao="mwai_last_template_",xo=e=>{const t=[...e];return t.sort(((e,t)=>e.name.localeCompare(t.name))),t},Po=(e="playground")=>{const[t,a]=Io(),[n,l]=Io(!1),[r,i]=Io([]),{isLoading:c,data:s}=(0,o.I)({queryKey:[`templates-${e}`],queryFn:()=>(async e=>{try{const t=await(0,y.IU)(`${w}/system/templates?category=${e}`,{nonce:N});let a=[];"imagesGenerator"===e?a=Oo:"playground"===e?a=To:"contentGenerator"===e&&(a=No);const n=a.find((e=>"default"===e.id));return null!=t&&t.templates&&t.templates.length>0&&(a=xo(t.templates)),n?a.forEach((e=>{Object.keys(n).forEach((t=>{void 0===e[t]&&(e[t]=n[t])}))})):console.warn("Default template not found for category: "+e),a}catch(e){console.error(e),alert(e.message)}})(e)});Mo((()=>{for(let t=0;t<r.length;t++){const a=r[t];let n=!1;if(a&&(null===a.envId||void 0===a.envId||null===a.model||void 0===a.model)){const t=(null==I?void 0:I.ai_default_env)||null;let l=(null==I?void 0:I.ai_default_model)||null;"imagesGenerator"===e&&(l="dall-e-3-hd"),t&&l&&(a.envId=t,a.model=l,n=!0)}n&&i([...r])}}),[r]),Mo((()=>{if(s){i(s);const t=(e=>{try{const t=`${Ao}${e}`,a=localStorage.getItem(t);if(!a)return null;const n=JSON.parse(a);return Date.now()-n.timestamp>2592e6?(localStorage.removeItem(t),null):n.templateId}catch(e){return console.warn("Failed to load template preference:",e),null}})(e);let n=null;if(t&&(n=s.find((e=>e.id===t))),!n){n=s.find((e=>"default"===e.id))||s[0]}a(n)}}),[s,e]);const d=async t=>{t=xo(t),i(t);try{return await(0,y.IU)(`${w}/system/templates`,{method:"POST",nonce:N,json:{category:e,templates:t}})}catch(e){console.error(e),alert(e.message)}},m=So((()=>{if(!t||0===r.length)return!1;if(Object.keys(t).length!==Object.keys(r.find((e=>e.id===t.id))).length)return!0;const e=r.find((e=>e.id===t.id));return Object.keys(e).some((a=>e[a]!==t[a]))}),[t,r]),u=t=>{a(t),t&&t.id&&((e,t)=>{try{const a=`${Ao}${e}`,n={templateId:t,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(n))}catch(e){console.warn("Failed to save template preference:",e)}})(e,t.id)},p=()=>{const e=r.find((e=>e.id===t.id));e&&u({...e})},E=()=>{const e=prompt(ge.COMMON.NAME,t.name||ge.TEMPLATES.NEW_TEMPLATE_NAME);if(!e)return!1;const a={...t,id:ko(),name:e};d([...r,a]),u({...a})},g=()=>{const e=r.map((e=>e.id===t.id?t:e));d(e),u({...t})},R=()=>{const e=prompt("Template Name",t.name),a={...r[0],id:ko(),name:e};d([...r,a]),u({...a})},v=()=>{const e=prompt("Template Name",t.name);if(!e)return;const a=r.map((a=>a.id===t.id?{...a,name:e}:a));d([...a]),u({...a.find((e=>e.id===t.id))})},f=()=>{if(!confirm(ge.TEMPLATES.DELETE_ALL_CONFIRM))return;let t=[];"imagesGenerator"===e?t=[...Oo]:"playground"===e?t=[...To]:"contentGenerator"===e&&(t=[...No]),d(t),u({...t[0]})},b=So((()=>m&&!!t),[m,t]),_=So((()=>t&&"default"!==t.id),[t]),C=So((()=>t&&"default"!==t.id),[t]),T=So((()=>React.createElement("div",{style:{margin:"0"}},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("h3",{style:{margin:0}},ge.TEMPLATES.TEMPLATE),React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement(Je.S,{small:!0,onLabel:ge.TEMPLATES.EDIT,offLabel:ge.TEMPLATES.EDIT,width:60,onChange:l,checked:n}))),c&&React.createElement("div",{style:{display:"flex",marginTop:30,justifyContent:"center"}},React.createElement("div",{style:{width:60}},React.createElement(Ro.X,{width:20}))),React.createElement(le.g,null),n&&React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex"}},React.createElement(h.M,{className:"primary",style:{flex:3},onClick:R},"New"),React.createElement(h.M,{onClick:E,style:{flex:1}},"Duplicate")),React.createElement(le.g,{tiny:!0})),React.createElement(ae.u,{scrolldown:!0,name:"template",value:null==t?void 0:t.id,onChange:e=>{const t=r.find((t=>t.id===e));u({...t})}},r.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name})))),(m||n)&&React.createElement("div",null,React.createElement(le.g,{tiny:!0}),React.createElement("div",{style:{display:"flex"}},React.createElement(h.M,{className:"secondary",style:{flex:1},disabled:!b,onClick:p},"Reset"),React.createElement(h.M,{className:"primary",style:{flex:3},disabled:!b,onClick:g},"Save")),n&&React.createElement(React.Fragment,null,React.createElement(le.g,{tiny:!0}),React.createElement("div",{style:{display:"flex"}},React.createElement(h.M,{small:!0,className:"danger",style:{flex:1},disabled:!C,onClick:()=>(e=>{if(!confirm(ge.TEMPLATES.DELETE_CONFIRM))return;const t=r.filter((t=>t.id!==e.id));d([...t]),u({...t[0]})})(t)},"Delete"),React.createElement(h.M,{small:!0,className:"secondary",style:{flex:3},disabled:!_,onClick:v},"Rename")))),n&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement("div",{style:{display:"flex"}},React.createElement(h.M,{className:"danger",style:{flex:1},onClick:f},"Reset All Templates"))))),[r,t,n,m,b,c]);return{template:t,templates:r,clearTemplate:p,setTemplate:u,jsxTemplates:T,isEdit:n}},{useState:Do,useMemo:Lo}=wp.element,Fo=e=>{const[t,a]=Do(0),[n,l]=Do(0),r=()=>{a(0),l(0)};return{addUsage:(n,r,o)=>{const i=e(n,r,o);l(i),a(t+i)},jsxUsageCosts:Lo((()=>{let e=(0,y.FE)(ge.COMMON.USAGE_HELP);return O||(e=React.createElement(React.Fragment,null,e," ",(0,y.FE)(ge.COMMON.USAGE_PRO_HELP))),React.createElement(React.Fragment,null,React.createElement("div",null,"Session: ",React.createElement("span",{style:{float:"right"}},"$",t.toFixed(4))),React.createElement("div",null,"Last Request: ",React.createElement("span",{style:{float:"right"}},"$",n.toFixed(4))),React.createElement(le.g,{height:15}),React.createElement("p",{style:{fontSize:11,lineHeight:1.4,opacity:.6,margin:0}},e),React.createElement(le.g,{height:15}),React.createElement(h.M,{fullWidth:!0,onClick:r},"Reset Usage"))}),[t,n])}},{useState:Bo,useEffect:Uo,useRef:Ho}=wp.element,jo=(0,L.Ay)(Ke.m)`
  .neko-textarea-container {
  
    textarea {
      color: white;
      font-size: 13px;
      padding: 10px;
      font-family: monospace;
      background: #333d4e;
      border: none;

      &:focus {
        background-color: #333d4e;
      }
    }
  }
`,Go=()=>{const{template:e,setTemplate:t,jsxTemplates:a}=Po("playground"),[n,l]=Bo(""),[r,o]=Bo(!1),[i,s]=Bo(""),[d,m]=Bo(),[p,g]=Bo(),[R,v]=Bo(!0),f=Ho(),b=(null==e?void 0:e.prompt)??"",_=(null==e?void 0:e.model)??"gpt-3.5-turbo",C=(null==e?void 0:e.mode)??"query",T=(null==e?void 0:e.temperature)??1,O=(null==e?void 0:e.envId)??"",{calculatePrice:S,completionModels:A}=(null==e||e.stopSequence,null==e||e.maxTokens,Ce(I,O||null)),{addUsage:x,jsxUsageCosts:P}=Fo(S),D=(null==I?void 0:I.ai_envs)||[],L=(a,n)=>{const l={...e,[n]:a};"envId"===n&&""===a&&(l.model=""),t(l)},F=a=>{t({...e,prompt:a})};Uo((()=>{e&&l("")}),[e]);const B=async(e=b)=>{f.current=new AbortController,o(!0),m(new Date);try{var t,a;const n=k?e=>{l(e)}:null,r=await(0,Ga.ti)(`${w}/ai/completions`,{scope:"playground",session:M,message:e,temperature:T,envId:O,model:_,stream:k},N,k,f.current.signal),o=!1,i=await(0,Ga.Pn)(r,n,o?"PLAYGROUND":null,null,o);if(!1===(null==i?void 0:i.success))throw new Error(null==i?void 0:i.message);console.log("Completions",{prompt:e,result:i}),"continuous"===C?F(e+"\n"+i.data+"\n"):l(i.data),x(_,(null==i||null===(t=i.usage)||void 0===t?void 0:t.prompt_tokens)||0,(null==i||null===(a=i.usage)||void 0===a?void 0:a.completion_tokens)||0)}catch(e){"AbortError"!==e.name&&g(e.message)}m(),o(!1)};return React.createElement(u.z,{nekoErrors:[]},React.createElement($e,{title:ge.COMMON.PLAYGROUND}),React.createElement(E.N,null,React.createElement(_e,{options:I}),(null==I?void 0:I.intro_message)&&React.createElement(E.Y,{fullWidth:!0},React.createElement(re.L,{style:{marginBottom:0}},React.createElement(c.s,{p:!0},(0,y.FE)(ge.PLAYGROUND.INTRO)))),React.createElement(E.Y,null,React.createElement(Aa,null,a),React.createElement(le.g,null),React.createElement(Aa,null,React.createElement(h.M,{fullWidth:!0,onClick:B,onStopClick:()=>{var e;null===(e=f.current)||void 0===e||e.abort(),m(),o(!1)},isBusy:r,startTime:d,style:{height:50,fontSize:16,flex:4}},ge.COMMON.GENERATE))),React.createElement(E.Y,{style:{flex:3}},React.createElement(Aa,null,"continuous"!==C&&React.createElement(React.Fragment,null,React.createElement(jo,{rows:12,onChange:F,value:b})),"continuous"===C&&React.createElement(React.Fragment,null,React.createElement(jo,{rows:18,onChange:F,value:b}),React.createElement("div",{style:{display:"flex"}},React.createElement("span",{className:"dashicons dashicons-format-continuous",style:{position:"absolute",color:"white",zIndex:200,fontSize:28,marginTop:12,marginLeft:10}}),React.createElement(xa,{name:"continuousEntry",value:i,onChange:s,onEnter:()=>{const e=b+"Human: "+i;F(e),s(""),B(e)},disabled:r})))),React.createElement(le.g,null),(n||r)&&React.createElement(Aa,null,React.createElement(Ga.CI,{content:n,isStreaming:k&&r}))),React.createElement(E.Y,null,React.createElement(Aa,null,React.createElement(ze,{onClick:()=>v(!R),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginTop:0,marginBottom:0}},ge.COMMON.SETTINGS),React.createElement(Ye.z,{icon:R?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),R&&React.createElement(React.Fragment,null,React.createElement(le.g,{tiny:!0}),React.createElement("label",null,ge.COMMON.ENVIRONMENT,":"),React.createElement(ae.u,{scrolldown:!0,name:"envId",value:O??"",onChange:L},D.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(ae.j,{value:"",label:"Default"})),React.createElement("label",null,ge.COMMON.MODEL,":"),React.createElement(ae.u,{name:"model",value:_||"",scrolldown:!0,disabled:!O,onChange:L},React.createElement(ae.j,{value:"",label:O?"None":"Default"}),A.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name})))),React.createElement("label",null,ge.COMMON.TEMPERATURE,":"),React.createElement(ne.A,{name:"temperature",value:T,type:"number",onChange:e=>L(parseFloat(e),"temperature"),description:React.createElement("span",{style:{fontSize:11,opacity:.6}},ge.HELP.TEMPERATURE)}))),React.createElement(le.g,null),React.createElement(Aa,null,React.createElement(ze,null,React.createElement("h2",{style:{marginTop:0,marginBottom:0}},ge.COMMON.USAGE)),React.createElement(le.g,{tiny:!0}),P))),React.createElement(ie.n,{isOpen:p,onRequestClose:()=>{g()},okButton:{onClick:()=>{g()}},title:"Error",content:React.createElement("p",null,p)}))},$o=L.Ay.div`
  margin-bottom: 5px;
`,zo=L.Ay.div`
  margin-top: 5px;
  padding: 10px;
  font-size: 14px;
  cursor: pointer;
  background: #dbf2ff;

  &:hover {
    background: #037cba;
    color: white;
  }
`,{useState:Wo,useEffect:qo,useMemo:Vo}=wp.element,Yo=e=>{const{post:t,onTitleClick:a={},onClose:n={}}=e,[l,r]=Wo([]),[o,i]=Wo(!1),[c,s]=Wo(!1);qo((()=>{t&&d(t)}),[t]);const d=async({postId:e,postTitle:t})=>{i(!0);try{var a;const t=await(0,y.IU)(`${w}/ai/magic_wand`,{method:"POST",nonce:N,json:{action:"suggestTitles",data:{postId:e}}});r(null===(a=t.data)||void 0===a?void 0:a.results)}catch(e){console.error(e),s(e.message)}i(!1)},m=async()=>{n(),r([]),s(),i(!1)},u=Vo((()=>o?React.createElement(Ro.X,{type:"circle",size:"10%"}):c?React.createElement(React.Fragment,null,"Error: ",c):(null==l?void 0:l.length)>0?React.createElement(React.Fragment,null,"Pick a new title by clicking on it.",React.createElement($o,null,l.map((e=>React.createElement(zo,{key:e,onClick:()=>{(async e=>{i(!0);try{await a(e),m()}catch(e){s(e.message)}i(!1)})(e)}},e))))):React.createElement(React.Fragment,null,"Nothing to display.")),[o,l,c]);return React.createElement(E.N,null,React.createElement(ie.n,{isOpen:t,onRequestClose:m,title:`New title for "${null==t?void 0:t.postTitle}"`,content:u,okButton:{label:"Close",onClick:m}}))},{useState:Ko,useEffect:Xo,useMemo:Qo}=wp.element,Jo=e=>{const{post:t,onExcerptClick:a={},onClose:n={}}=e,[l,r]=Ko([]),[o,i]=Ko(!1),[c,s]=Ko(!1);Xo((()=>{t&&d(t)}),[t]);const d=async({postId:e})=>{i(!0);try{var t;const a=await(0,y.IU)(`${w}/ai/magic_wand`,{method:"POST",nonce:N,json:{action:"suggestExcerpts",data:{postId:e}}});r(null===(t=a.data)||void 0===t?void 0:t.results)}catch(e){console.error(e),s(e.message)}i(!1)},m=async()=>{n(),r([]),s(),i(!1)},u=Qo((()=>o?React.createElement(Ro.X,{type:"circle",size:"10%"}):c?React.createElement(React.Fragment,null,"Error: ",c):(null==l?void 0:l.length)>0?React.createElement(React.Fragment,null,"Pick a new excerpt by clicking on it.",React.createElement($o,null,l.map((e=>React.createElement(zo,{key:e,onClick:()=>{(async e=>{i(!0);try{await a(e),m()}catch(e){s(e.message)}i(!1)})(e)}},e))))):React.createElement(React.Fragment,null,"Nothing to display.")),[o,l,c]);return React.createElement(E.N,null,React.createElement(ie.n,{isOpen:t,onRequestClose:m,title:`New excerpt for "${null==t?void 0:t.postTitle}"`,content:u,okButton:{label:"Close",onClick:m}}))},{useState:Zo,useEffect:ei}=wp.element,ti=()=>{const[e,t]=Zo();ei((()=>{document.querySelectorAll(".mwai-link-title").forEach((e=>{const a=e.getAttribute("data-id"),n=e.getAttribute("data-title");e.addEventListener("click",(()=>{t({postId:a,postTitle:n,mode:"title"})}),!1)})),document.querySelectorAll(".mwai-link-excerpt").forEach((e=>{const a=e.getAttribute("data-id"),n=e.getAttribute("data-title");e.addEventListener("click",(()=>{t({postId:a,postTitle:n,mode:"excerpt"})}),!1)}))}),[]);return React.createElement(r.A,null,React.createElement(E.N,null,React.createElement(Yo,{post:"title"===(null==e?void 0:e.mode)?e:null,onTitleClick:async a=>{const n=await(0,y.IU)(`${w}/helpers/update_post_title`,{method:"POST",nonce:N,json:{postId:e.postId,title:a}});if(!n.success)throw new Error(n.message);{t();const n=document.querySelector(`tr[id="post-${e.postId}"]`);if(n){const e=n.querySelector(".row-title");e&&(e.innerHTML=a)}const l=n.querySelector(".hidden .post_title");l&&(l.innerHTML=a)}},onClose:()=>{t()}}),React.createElement(Jo,{post:"excerpt"===(null==e?void 0:e.mode)?e:null,onExcerptClick:async a=>{const n=await(0,y.IU)(`${w}/helpers/update_post_excerpt`,{method:"POST",nonce:N,json:{postId:e.postId,excerpt:a}});if(!n.success)throw new Error(n.message);t()},onClose:()=>{t()}})))},{useState:ai,useEffect:ni,useMemo:li,useRef:ri}=wp.element,oi=()=>{const[e,t]=ai(""),[a,n]=ai(""),{template:l,setTemplate:r,clearTemplate:i,jsxTemplates:s}=Po("contentGenerator"),d=(0,nt.XS)(),[p,g]=ai(!1),[R,v]=ai(),[f,b]=ai(!1),[_,C]=ai(!1),[T,O]=ai(!1),[S,k]=ai(!1),[A,x]=ai(),[P,D]=ai("post"),[L,F]=ai([]),[B,U]=ai([]),[H,j]=ai({}),G=ri(),{isLoading:$,data:z}=(0,o.I)({queryKey:["postTypes"],queryFn:rt}),W=d.busy||p,q=(null==l?void 0:l.title)??"",V=(null==l?void 0:l.sections)??"",Y=(null==l?void 0:l.mode)??"single",K=(null==l?void 0:l.topic)??"",X=(null==l?void 0:l.topics)??"",Q=(null==l?void 0:l.context)??"",J=(null==l?void 0:l.model)??(null==I?void 0:I.ai_default_model)??null,Z=(null==l?void 0:l.sectionsCount)??2,ee=(null==l?void 0:l.paragraphsCount)??3,te=(null==l?void 0:l.writingStyle)??"creative",ce=(null==l?void 0:l.writingTone)??"cheerful",se=(null==l?void 0:l.titlePromptFormat)??"",de=(null==l?void 0:l.sectionsPromptFormat)??"",me=(null==l?void 0:l.contentPromptFormat)??"",ue=(null==l?void 0:l.excerptPromptFormat)??"",pe=(null==l?void 0:l.envId)??"",Ee=(null==l?void 0:l.temperature)??.6,he=(null==l||l.maxTokens,(null==l?void 0:l.topicsAreTitles)??!1),fe=!de||!Z,{completionModels:be,calculatePrice:we}=(null==l||l.useMaxTokens,Ce(I,pe||null)),{addUsage:Te,jsxUsageCosts:Oe}=Fo(we),Ne=(null==I?void 0:I.ai_envs)||[],{jsxLanguageSelector:Ie,currentLanguage:Me,isCustom:Se,currentHumanLanguage:ke}=(({disabled:e,options:t,language:a})=>{const[n,l]=ye(a??"en"),r=(null==t?void 0:t.languages)||[],o=Re((()=>Object.keys(r).map((e=>({value:e,label:r[e]})))),[r]);ve((()=>{l(a)}),[a]),ve((()=>{const e=localStorage.getItem("mwai_preferred_language");if(e&&o.find((t=>t.value===e)))return void l(e);const t=(document.querySelector("html").lang||navigator.language||navigator.userLanguage).substr(0,2);o.find((e=>e.value===t))&&l(t)}),[]);const i=Re((()=>{const e=o.find((e=>e.value===n));return e?e.label:(console.warn("A system language should be set."),"English")}),[n,o]),c=(e,t)=>{l(e,t),localStorage.setItem("mwai_preferred_language",e)};return{jsxLanguageSelector:Re((()=>React.createElement(ae.u,{scrolldown:!0,name:"language",disabled:e,description:(0,y.FE)(ge.CONTENT_GENERATOR.CUSTOM_LANGUAGE_HELP),value:n,onChange:c},o.map((e=>React.createElement(ae.j,{key:e.value,value:e.value,label:e.label}))))),[n,i,o]),currentLanguage:n,currentHumanLanguage:i}})({options:I,language:null==l?void 0:l.language,customLanguage:null==l?void 0:l.customLanguage}),Ae=li((()=>(e=>{if(!e)return null;const t=e.split(" ").length,a=e.length,n=[];return a?(t<3?n.push(ge.CONTENT_GENERATOR.TITLE_TOO_SHORT):t>8?n.push(ge.CONTENT_GENERATOR.TITLE_TOO_LONG):a<40?n.push(ge.CONTENT_GENERATOR.TITLE_TOO_SHORT):a>70&&n.push(ge.CONTENT_GENERATOR.TITLE_TOO_LONG_2),n.join(" ")):void 0})(q)),[q]),xe=(e,t)=>{r((a=>{const n={...a,[t]:e};return"envId"===t&&""===e&&(n.model=""),n}))};ni((()=>{const e=X.split("\n").map((e=>e.trim())).filter((e=>!!e));F(e)}),[X]),ni((()=>{l&&xe("","sections")}),[q,Z]),ni((()=>{t(""),n(""),x()}),[V,ee]),ni((()=>{l&&(!Se&&l.customLanguage&&xe(null,"customLanguage"),Se&&l.customLanguage!==ke&&xe(ke,"customLanguage"),l.language!==Me&&xe(Me,"language"))}),[Se,Me,ke]);const Pe=(e,t=Q)=>{let a="";return t&&t.trim()?a=t:e=(e=e.replace(/### CONTEXT:[\s\S]*?(?=(###|Write|Create|Generate)|$)/g,"").trim()).replace(/### WRITING CONTEXT:[\s\S]*?(?=(###|Write|Create|Generate)|$)/g,"").trim(),e.replace("{LANGUAGE}",ke).replace("{WRITING_STYLE}",te).replace("{WRITING_TONE}",ce).replace("{PARAGRAPHS_PER_SECTION}",ee).replace("{SECTIONS_COUNT}",Z).replace("{CONTEXT}",a)},De=li((()=>{const e=(e,t)=>!!t.find((t=>t.includes(e))),t=[se,de,me,ue];return{language:e("{LANGUAGE}",t),writingStyle:e("{WRITING_STYLE}",t),writingTone:e("{WRITING_TONE}",t),sectionsCount:e("{SECTIONS_COUNT}",t),paragraphsCount:e("{PARAGRAPHS_PER_SECTION}",t),context:e("{CONTEXT}",t)}}),[se,de,me,ue,Z,ee]),Le=async(e,t=!1)=>{G.current||(G.current=new AbortController);try{var a,n;const t={scope:"admin-tools",envId:pe||null,model:J||null,session:M,message:e,temperature:Ee},l=await(0,y.IU)(`${w}/ai/completions`,{method:"POST",nonce:N,signal:G.current.signal,json:t});Te(J,(null==l||null===(a=l.usage)||void 0===a?void 0:a.prompt_tokens)||0,(null==l||null===(n=l.usage)||void 0===n?void 0:n.completion_tokens)||0);let r=l.data.trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.substring(1,r.length-1)),r}catch(e){if(t)throw new Error(e.message);return"AbortError"!==e.name&&(console.error(e),v(e.message)),null}},Fe=async(e=K,t=q,a=!1)=>{if(!t)return void alert(ge.CONTENT_GENERATOR.TITLE_MISSING);g(!0),j({...H,sections:new Date}),xe("","sections");let n=de.replace("{TITLE}",t).replace("{TOPIC}",e);n=Pe(n);let l=await Le(n,a);var r;return l=(r=l)?r.split("\n").map((e=>((e=e.replace(/^\d+\.\s/,"")).startsWith('"')&&(e=e.slice(1)).endsWith('"')&&(e=e.slice(0,-1)),e))).filter((e=>e)).join("\n"):r,l&&xe(l,"sections"),g(!1),j({...H,sections:null}),l},Be=async(e=K,a=q,n=V,l=!1)=>{if(!a)return void alert(ge.CONTENT_GENERATOR.TITLE_MISSING);if(!fe&&!n)return void alert(ge.CONTENT_GENERATOR.SECTIONS_MISSING);g(!0),j({...H,content:new Date}),t((()=>""));let r=me.replace("{TITLE}",a).replace("{SECTIONS}",n).replace("{TOPIC}",e);r=Pe(r);let o=await Le(r,l);return o&&(o=o.replace(/^===INTRO:\n/,"").replace(/^===INTRO: \n/,"").replace(/===INTRO: /,"").replace(/===OUTRO:\n/,"").replace(/===OUTRO: \n/,"").replace(/===OUTRO: /,""),t((()=>o))),g(!1),j({...H,content:null}),o},Ue=async(e=K,t=q,a=!1)=>{if(!t)return void alert(ge.CONTENT_GENERATOR.TITLE_MISSING);g(!0),j({...H,excerpt:new Date}),n((()=>""));let l=ue.replace("{TITLE}",t).replace("{TOPIC}",e);l=Pe(l);const r=await Le(l,a);return r&&n((()=>r)),g(!1),j({...H,excerpt:null}),r},He=async(e=K,t=!1)=>{g(!0),G.current=new AbortController,j({...H,all:new Date});try{let a=e;if(!he||!t){const n=Pe(se.replace("{TOPIC}",e));a=await Le(n,t)}let n=null,l=null,r=null;return g(!1),a&&(xe(a,"title"),fe||(j((e=>({...e,sections:new Date}))),n=await Fe(e,a,t),j((e=>({...e,sections:null})))),(n||fe)&&(j((e=>({...e,content:new Date}))),l=await Be(e,a,n,t),j((e=>({...e,content:null}))),l&&(j((e=>({...e,excerpt:new Date}))),r=await Ue(e,a,t),j((e=>({...e,excerpt:null})))))),{title:a,heads:n,content:l,excerpt:r}}catch(e){throw console.error(e),g(!1),j({}),e}},je=async(t=q,n=e,l=a,r=!1)=>{g(!0),G.current=new AbortController;try{const e=await(0,y.IU)(`${w}/helpers/create_post`,{method:"POST",nonce:N,signal:G.current.signal,json:{title:t,content:n,excerpt:l,postType:P}});return r||x(e.postId),e.postId}catch(e){return"AbortError"!==e.name&&(console.error(e),v(e.message)),null}finally{g(!1)}};return React.createElement(u.z,{nekoErrors:[]},React.createElement($e,{title:ge.COMMON.CONTENT_GENERATOR}),React.createElement(E.N,null,React.createElement(_e,{options:I}),(null==I?void 0:I.intro_message)&&React.createElement(E.Y,{fullWidth:!0},React.createElement(re.L,{style:{marginBottom:0}},React.createElement(c.s,{p:!0},(0,y.FE)(ge.CONTENT_GENERATOR.INTRO)))),React.createElement(E.Y,{style:{flex:1}},React.createElement(Aa,null,s),React.createElement(le.g,null),React.createElement(Aa,null,React.createElement("h2",{style:{marginTop:0}},"bulk"===Y?ge.COMMON.CONTEXT||"Context":ge.COMMON.TOPIC),"bulk"===Y?React.createElement(React.Fragment,null,React.createElement("p",{style:{marginTop:0,marginBottom:10,fontSize:12,opacity:.6}},"Provide context that will be used for all generated posts to make them more accurate and relevant."),React.createElement(Ke.m,{name:"context",disabled:W||$,rows:14,value:Q,onChange:xe,placeholder:"Example: This is for a cat enthusiast blog targeting pet owners and cat lovers. The tone should be friendly, informative, and occasionally playful. Include practical tips and scientific facts when relevant."})):React.createElement(Ke.m,{name:"topic",disabled:W||$,rows:16,value:K,onChange:xe,placeholder:"Example: Write a comprehensive guide about adopting a rescue cat, covering the adoption process, preparing your home, first days together, and tips for helping the cat adjust to their new environment. Include advice for families with children or other pets."}),React.createElement(le.g,null),React.createElement(h.M,{fullWidth:!0,disabled:!K||"bulk"===Y||$,isBusy:W,onClick:()=>He(),onStopClick:()=>{var e;null===(e=G.current)||void 0===e||e.abort(),g(!1),j({})},startTime:null==H?void 0:H.all,style:{height:50,fontSize:16,flex:4}},ge.COMMON.GENERATE))),React.createElement(E.Y,{style:{flex:2}},React.createElement(oe.o,{name:"mode",value:Y,disabled:W,onChange:xe},React.createElement(oe.K,{title:ge.CONTENT_GENERATOR.SINGLE_GENERATE,value:"single"}),React.createElement(oe.K,{title:ge.CONTENT_GENERATOR.BULK_GENERATE,value:"bulk",count:L.length})),React.createElement(le.g,null),"bulk"===Y&&React.createElement(Aa,null,React.createElement("p",{style:{marginTop:0,marginBottom:20}},(0,y.FE)(ge.CONTENT_GENERATOR.TOPICS_HELP)),React.createElement("div",{style:{display:"flex"}},React.createElement(h.M,{disabled:W||!L.length,onClick:async()=>{U([]);const e=L.map(((e,t)=>async()=>{console.log("Topic "+t);try{const{title:t,content:a,excerpt:n}=await He(e,!0);if(t&&a&&n){const l=await je(t,a,n,!0);U((r=>[...r,{postId:l,topic:e,title:t,content:a,excerpt:n}]))}else console.warn("Could not generate the post for: "+e)}catch(e){confirm(ge.CONTENT_GENERATOR.BULK_ERROR_CONFIRM.replace("{MESSAGE}",e.message))||(d.stop(),d.reset(),g(!1))}return{success:!0}}));await d.start(e),d.reset()}},ge.COMMON.GENERATE),React.createElement(at.j,{busy:d.busy,style:{marginLeft:10,flex:"auto"},value:d.value,max:d.max,onStopClick:d.stop})),React.createElement(le.g,null),React.createElement("h3",null,ge.COMMON.TOPICS),React.createElement(Ke.m,{name:"topics",rows:10,value:X,onChange:xe,placeholder:"Example:\nWhy Cats Make Perfect Companions\nUnderstanding Cat Body Language\nThe Science Behind Purring\nIndoor vs Outdoor Cats Debate\nBest Cat Breeds for Families"}),React.createElement(m.R,{name:"topicsAreTitles",label:ge.CONTENT_GENERATOR.USE_TOPICS_AS_TITLES,value:"1",checked:he,onChange:xe}),React.createElement("h3",null,ge.CONTENT_GENERATOR.GENERATED_POSTS),!B.length&&React.createElement("i",null,ge.CONTENT_GENERATOR.NOTHING_YET),B.length>0&&React.createElement("ul",null,B.map((e=>React.createElement("li",{key:e.postId},e.title," ",React.createElement("a",{target:"_blank",href:`/?p=${e.postId}`,rel:"noreferrer"},ge.COMMON.VIEW)," ","or"," ",React.createElement("a",{target:"_blank",href:`/wp-admin/post.php?post=${e.postId}&action=edit`,rel:"noreferrer"},ge.COMMON.EDIT)))))),"single"===Y&&React.createElement(Aa,null,React.createElement("h2",{style:{marginTop:0}},ge.COMMON.TITLE),React.createElement(ne.A,{name:"title",disabled:W,value:q,onChange:xe,placeholder:"The title will appear here after clicking 'Generate'"}),Ae&&React.createElement("div",{className:"information"},ge.CONTENT_GENERATOR.ADVICE,": ",Ae),de&&React.createElement(React.Fragment,null,React.createElement(le.g,null),React.createElement(ze,null,React.createElement("h2",{style:{marginBottom:0}},ge.CONTENT_GENERATOR.SECTIONS),React.createElement("div",{style:{display:"flex",alignItems:"center"}},De.sectionsCount&&React.createElement(React.Fragment,null,React.createElement("label",{style:{margin:"0 5px 0 0"}},ge.CONTENT_GENERATOR.NUMBER_OF_SECTIONS,":"," "),React.createElement(ae.u,{scrolldown:!0,name:"sectionsCount",disabled:W,style:{marginRight:10},value:Z,description:"",onChange:xe},[2,3,4,5,6,8,10,12].map((e=>React.createElement(ae.j,{key:e,value:e,label:e}))))),Z>0&&React.createElement(h.M,{variant:"secondary",disabled:!q,isBusy:W,startTime:null==H?void 0:H.sections,onClick:()=>Fe()},ge.CONTENT_GENERATOR.GENERATE_SECTIONS))),Z>0&&React.createElement(React.Fragment,null,React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{name:"sections",disabled:W,rows:4,value:V,description:ge.CONTENT_GENERATOR.SECTIONS_HELP,onChange:xe,placeholder:"Sections will appear here after clicking 'Generate'"}))),React.createElement(le.g,null),React.createElement(ze,null,React.createElement("h2",{style:{marginBottom:0}},ge.COMMON.CONTENT),React.createElement("div",{style:{display:"flex",alignItems:"center"}},De.paragraphsCount&&React.createElement(React.Fragment,null,React.createElement("label",{style:{margin:"0 5px 0 0"}},ge.CONTENT_GENERATOR.PARAGRAPHS_PER_SECTION,": "),React.createElement(ae.u,{scrolldown:!0,name:"paragraphsCount",disabled:W,style:{marginRight:10},value:ee,description:"",onChange:xe},[1,2,3,4,6,8,10].map((e=>React.createElement(ae.j,{key:e,value:e,label:e}))))),React.createElement(h.M,{variant:"secondary",disabled:!q,isBusy:W,startTime:null==H?void 0:H.content,onClick:()=>Be()},ge.CONTENT_GENERATOR.GENERATE_CONTENT))),React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{countable:"words",disabled:W,rows:12,value:e,description:ge.CONTENT_GENERATOR.CONTENT_HELP,onChange:t,placeholder:"Your article content will appear here after clicking 'Generate'"}),React.createElement(le.g,null),React.createElement(ze,null,React.createElement("h2",{style:{marginBottom:0}},ge.COMMON.EXCERPT),React.createElement(h.M,{variant:"secondary",disabled:!q,isBusy:W,startTime:null==H?void 0:H.excerpt,onClick:()=>Ue()},ge.CONTENT_GENERATOR.GENERATE_EXCERPT)),React.createElement(le.g,{tiny:!0}),React.createElement(Ke.m,{disabled:W,value:a,onBlur:n,rows:3,placeholder:"The excerpt will appear here after clicking 'Generate'"}),React.createElement(le.g,null),React.createElement(h.M,{fullWidth:!0,style:{height:60,fontSize:16},onClick:()=>je(),isBusy:W,disabled:!q||!e},ge.CONTENT_GENERATOR.CREATE_POST))),React.createElement(E.Y,{style:{flex:1}},React.createElement(Aa,null,React.createElement("h2",{style:{marginTop:0}},ge.COMMON.CONTENT),!De.language&&!De.writingStyle&&!De.writingTone&&!P&&React.createElement("div",{style:{fontSize:11,lineHeight:"14px"}},ge.CONTENT_GENERATOR.CONTENT_PARAMS_INTRO),De.language&&React.createElement(React.Fragment,null,React.createElement("label",null,ge.COMMON.LANGUAGE,":"),Ie),De.writingStyle&&React.createElement(React.Fragment,null,React.createElement("label",null,ge.CONTENT_GENERATOR.WRITING_STYLE,":"),React.createElement(ae.u,{scrolldown:!0,name:"writingStyle",disabled:W,value:te,description:"",onChange:xe},yo.map((e=>React.createElement(ae.j,{key:e.value,value:e.value,label:e.label}))))),De.writingTone&&React.createElement(React.Fragment,null,React.createElement("label",null,ge.CONTENT_GENERATOR.WRITING_TONE,":"),React.createElement(ae.u,{scrolldown:!0,name:"writingTone",disabled:W,value:ce,description:"",onChange:xe},vo.map((e=>React.createElement(ae.j,{key:e.value,value:e.value,label:e.label}))))),React.createElement(React.Fragment,null,React.createElement("label",null,ge.COMMON.POST_TYPE,":"),React.createElement(ae.u,{scrolldown:!0,disabled:W,name:"postType",onChange:D,value:P},null==z?void 0:z.map((e=>React.createElement(ae.j,{key:e.type,value:e.type,label:e.name})))))),React.createElement(le.g,null),React.createElement(Aa,null,React.createElement(ze,{onClick:()=>b(!f),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginBottom:0}},ge.COMMON.MODEL),React.createElement(Ye.z,{icon:f?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),f&&React.createElement(React.Fragment,null,React.createElement("label",null,ge.COMMON.ENVIRONMENT,":"),React.createElement(ae.u,{scrolldown:!0,name:"envId",value:pe??"",onChange:xe},Ne.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(ae.j,{value:"",label:"Default"})),React.createElement("label",null,ge.COMMON.MODEL,":"),React.createElement(ae.u,{name:"model",value:J||"",scrolldown:!0,disabled:!pe,onChange:xe},React.createElement(ae.j,{value:"",label:pe?"None":"Default"}),be.map((e=>React.createElement(ae.j,{key:e,value:e.model,label:e.name})))),React.createElement("label",null,ge.COMMON.TEMPERATURE,":"),React.createElement(ne.A,{name:"temperature",value:Ee,type:"number",onChange:xe,onBlur:xe,description:ge.HELP.TEMPERATURE}))),React.createElement(le.g,null),React.createElement(Aa,null,React.createElement(ze,{onClick:()=>O(!T),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginBottom:0}},(0,y.FE)(ge.COMMON.PROMPTS)),React.createElement(Ye.z,{icon:T?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),T&&React.createElement(React.Fragment,null,React.createElement("p",{style:{fontSize:11,lineHeight:"14px",opacity:.6}},ge.CONTENT_GENERATOR.PROMPTS_INTRO),React.createElement("label",null,(0,y.FE)(ge.CONTENT_GENERATOR.PROMPT_TITLE)),React.createElement(Ke.m,{disabled:W||"default"===(null==l?void 0:l.id),name:"titlePromptFormat",value:se,onChange:xe}),React.createElement("label",null,(0,y.FE)(ge.CONTENT_GENERATOR.PROMPT_SECTIONS)),React.createElement(Ke.m,{disabled:W||"default"===(null==l?void 0:l.id),name:"sectionsPromptFormat",value:de,onChange:xe}),React.createElement("label",null,(0,y.FE)(ge.CONTENT_GENERATOR.PROMPT_CONTENT)),React.createElement(Ke.m,{disabled:W||"default"===(null==l?void 0:l.id),name:"contentPromptFormat",value:me,onChange:xe}),React.createElement("label",null,(0,y.FE)(ge.CONTENT_GENERATOR.PROMPT_EXCERPT)),React.createElement(Ke.m,{disabled:W||"default"===(null==l?void 0:l.id),name:"excerptPromptFormat",value:ue,onChange:xe}))),React.createElement(le.g,null),React.createElement(Aa,null,React.createElement(ze,{onClick:()=>k(!S),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginBottom:0}},ge.COMMON.USAGE),React.createElement(Ye.z,{icon:S?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),S&&React.createElement(React.Fragment,null,React.createElement(le.g,{tiny:!0}),Oe)))),React.createElement(ie.n,{isOpen:A,onRequestClose:()=>x(),okButton:{label:ge.CONTENT_GENERATOR.EDIT_POST,onClick:()=>{window.open(`/wp-admin/post.php?post=${A}&action=edit`,"_blank"),i(),x()}},cancelButton:{label:ge.COMMON.CLOSE,onClick:()=>{x()}},title:ge.CONTENT_GENERATOR.POST_CREATED,content:React.createElement("p",null,ge.CONTENT_GENERATOR.POST_CREATED_AS_DRAFT)}),React.createElement(ie.n,{isOpen:R,onRequestClose:()=>{v()},okButton:{onClick:()=>{v()}},title:ge.COMMON.ERROR,content:React.createElement("p",null,R)}))},{useState:ii,useEffect:ci,useMemo:si,useRef:di}=wp.element,mi=[1,2,3,4,5,6,7,8,9,10,12,14,16,18,20,40,60,80,100];const ui=L.Ay.div`
  margin-bottom: 5px;
  label {
    margin-bottom: 5px;
    display: block;
  }
`,pi=L.Ay.div`
  position: relative;
  width: 100%;
  margin-bottom: 10px;
  
  img {
    width: 100%;
    display: block;
  }
  
  canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    cursor: ${e=>e.maskMode?"none":"default"};
    pointer-events: ${e=>e.maskMode?"auto":"none"};
  }
`,Ei=L.Ay.div`
  position: absolute;
  pointer-events: none;
  border: 2px solid rgba(255, 0, 0, 0.8);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  opacity: ${e=>e.visible?1:0};
  transition: opacity 0.1s;
`,gi=()=>{var e,t,a;const{template:n,setTemplate:l,jsxTemplates:r}=Po("imagesGenerator"),[o,i]=ii(),s=new URLSearchParams(window.location.search).get("editId"),[d,p]=ii(s?"edit":"generate"),[g,R]=ii(!1),[v,f]=ii(),[_,C]=ii(!0),[T,O]=ii(!1),[S,k]=ii(!1),[A,x]=ii(!1),[P,D]=ii(!1),L=(null==I?void 0:I.ai_envs)||[],{imageModels:F,getModel:B}=Ce(I,(null==n?void 0:n.envId)||null),U=B(null==n?void 0:n.model),[H,j]=ii([]),[G,$]=ii([]),[z,W]=ii(),[q,V]=ii(""),[Y,K]=ii(""),[X,Q]=ii(""),[J,Z]=ii(""),[ee,te]=ii(""),[ce,se]=ii([]),[de,me]=ii(!1),[ue,pe]=ii(null),[Ee,he]=ii(30),[Re,ye]=ii(!0),[ve,fe]=ii(!0),[be,we]=ii({x:0,y:0,visible:!1}),Te=di(),Oe=di(),Ne=di(),Ie=(di([]),null==n?void 0:n.prompt),[Me,Se]=ii(1),[ke,Ae]=ii(0),[xe,Pe]=ii(0),De=di(),Le=()=>{var e;null===(e=De.current)||void 0===e||e.abort(),j([]),Ae(0),Pe(0),O(!1)},Fe=(null==n?void 0:n.style)??null,Be=(e,t)=>{l((a=>{const n={...a,[t]:e};return"envId"===t&&""===e&&(n.model="",n.resolution=""),"model"===t&&(n.resolution=""),n}))};ci((()=>{if(z){const e=G.indexOf(z)+1,t=(function(e,t=42){let a=e.replace(/[\s|,]+/g,"-");a=a.replace(/--+/g,"-");const n=a.split("-");let l=n[0],r=1;for(;r<n.length&&n[r]&&l.length+n[r].length<t;)l+="-"+n[r],r++;return l.length>t+1&&(l=l.slice(0,t+2)),l}(Ie).toLowerCase()||"image")+".png";te(t),V(`Untitled Image #${e||1}`),K(Ie||""),Q(""),Z("")}}),[z]),ci((()=>{s&&fetch(`${b}/wp/v2/media/${s}`).then((e=>e.json())).then((e=>f(e.source_url)))}),[s]),ci((()=>{if(v&&Oe.current&&Te.current){const e=Oe.current,t=Te.current;e.onload=()=>{t.width=e.naturalWidth,t.height=e.naturalHeight;t.getContext("2d").clearRect(0,0,t.width,t.height),Ne.current||(Ne.current=document.createElement("canvas")),Ne.current.width=t.width,Ne.current.height=t.height}}}),[v]),ci((()=>{if(!de)return;const e=e=>{"["===e.key?(e.preventDefault(),he((e=>Math.max(5,e-5)))):"]"===e.key&&(e.preventDefault(),he((e=>Math.min(200,e+5))))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)}),[de]);const Ue=di();ci((()=>{if(v&&Oe.current&&Ue.current){const e=Oe.current,t=Ue.current;e.onload=()=>{t.width=e.naturalWidth,t.height=e.naturalHeight}}}),[v]);const He=(e,t,a,n,l)=>{const r=e.createRadialGradient(t,a,0,t,a,n/2);if(l>=1)r.addColorStop(0,"rgba(255, 0, 0, 1)"),r.addColorStop(1,"rgba(255, 0, 0, 1)");else{const e=.5*l;r.addColorStop(0,"rgba(255, 0, 0, 1)"),r.addColorStop(e,"rgba(255, 0, 0, 1)"),r.addColorStop(1,"rgba(255, 0, 0, 0)")}e.fillStyle=r,e.beginPath(),e.arc(t,a,n/2,0,2*Math.PI),e.fill()},je=()=>{var e;if(Ie)if("edit"!==d||null!=U&&null!==(e=U.tags)&&void 0!==e&&e.includes("image-edit")){for(let e=0;e<Me;e++){const e={prompt:Ie,envId:n.envId,model:n.model,resolution:n.resolution,style:n.style};j((t=>[...t,e]))}Ae((e=>e+Me))}else i("This model does not support image editing.");else console.error("Prompt is empty, cannot add to queue.")};ci((()=>{H.length>0&&!T&&(async()=>{if(0===H.length||T)return;O(!0),De.current=new AbortController;const e=H[0];try{const t="edit"===d?"image_edit":"images",a={env:"admin-tools",envId:e.envId,model:e.model,resolution:e.resolution,style:e.style,scope:"admin-tools",session:M,message:e.prompt,maxResults:1,mediaId:s,local_download:null};let n;if(console.log("Image Edit Request:",{mode:d,endpoint:t,hasMask:!!ue,editId:s,requestData:a}),"edit"===d&&ue){const e=new FormData;Object.keys(a).forEach((t=>{null!==a[t]&&void 0!==a[t]&&e.append(t,String(a[t]))})),e.append("mask",ue,"mask.png"),console.log("FormData contents:");for(let[t,a]of e.entries())console.log(t,a);if(n=await fetch(`${w}/ai/${t}`,{method:"POST",headers:{"X-WP-Nonce":N},signal:De.current.signal,body:e}),!n.ok){const e=await n.json();throw new Error(e.message||"Request failed")}n=await n.json()}else n=await(0,y.IU)(`${w}/ai/${t}`,{method:"POST",nonce:N,signal:De.current.signal,json:a});n.data&&n.data.length>0&&$((e=>[...e,n.data[0]])),j((e=>e.slice(1))),Pe((e=>e+1)),1===H.length&&(Ae(0),Pe(0))}catch(e){"AbortError"===e.name||/aborted/i.test(e.message)||(console.error(e),i(e.message+(H.length>1?" The other tasks will continue.":"")),j((e=>e.slice(1))),Ae((e=>e-1)))}finally{O(!1)}})()}),[H,T]);const Ge=async(e=!1)=>{k(!0);try{const t=await(0,y.IU)(`${w}/helpers/create_image`,{method:"POST",nonce:N,json:{url:z,title:q,description:Y,caption:X,alt:J,filename:ee}});se([...ce,{id:t.attachmentId,url:z}]),e&&(window.location.href=`edit.php?page=mwai_images_generator&editId=${t.attachmentId}`),W()}catch(e){"AbortError"===e.name||/aborted/i.test(e.message)||(console.error(e),i(e.message))}finally{k(!1)}};return React.createElement(u.z,{nekoErrors:[]},React.createElement($e,{title:ge.COMMON.IMAGES_GENERATOR}),React.createElement(E.N,null,React.createElement(_e,{options:I}),(null==I?void 0:I.intro_message)&&React.createElement(E.Y,{fullWidth:!0},React.createElement(re.L,{style:{marginBottom:0}},React.createElement(c.s,{p:!0},(0,y.FE)(ge.COMMON.IMAGES_GENERATOR_INTRO)))),React.createElement(E.Y,{style:{flex:1}},React.createElement(Aa,null,"edit"===d&&v&&React.createElement(React.Fragment,null,React.createElement(pi,{maskMode:de,onMouseMove:e=>{if(de){const t=e.currentTarget.getBoundingClientRect();we({x:e.clientX-t.left,y:e.clientY-t.top,visible:!0})}},onMouseLeave:()=>we((e=>({...e,visible:!1})))},React.createElement("img",{ref:Oe,src:v}),React.createElement("canvas",{ref:Te,onMouseDown:e=>{if(!de)return;const t=Te.current,a=t.getBoundingClientRect(),n=t.getContext("2d"),l=t.width/a.width,r=t.height/a.height,o=Ee*l;let i=!0,c=(e.clientX-a.left)*l,s=(e.clientY-a.top)*r;const d=.5;let m=null;const u=e=>{n.save(),n.globalAlpha=e,He(n,c,s,o,.5),n.restore()};let p=d,E=!0;const g=()=>{i&&(E?(u(d),E=!1):(p=Math.min(p+.05,1),u(.05)),m=requestAnimationFrame(g))};g();const h=e=>{if(!i)return;const t=(e.clientX-a.left)*l,m=(e.clientY-a.top)*r,u=t-c,g=m-s,h=Math.sqrt(u*u+g*g);if(h>1){const e=Math.ceil(h/2);for(let t=1;t<=e;t++){const a=t/e,l=c+u*a,r=s+g*a;n.save(),n.globalAlpha=.15,He(n,l,r,o,.5),n.restore()}c=t,s=m,p=d,E=!0}},R=()=>{i=!1,m&&cancelAnimationFrame(m),(e=>{const t=Te.current,a=document.createElement("canvas");a.width=t.width,a.height=t.height;const n=a.getContext("2d");n.fillStyle="black",n.fillRect(0,0,a.width,a.height);const l=t.getContext("2d").getImageData(0,0,t.width,t.height),r=n.getImageData(0,0,a.width,a.height);for(let e=0;e<l.data.length;e+=4){const t=l.data[e],a=l.data[e+3];t>200&&a>100&&(r.data[e]=0,r.data[e+1]=0,r.data[e+2]=0,r.data[e+3]=0)}n.putImageData(r,0,0),a.toBlob(e,"image/png")})((e=>{pe(e)})),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",R)};document.addEventListener("mousemove",h),document.addEventListener("mouseup",R)}}),React.createElement(Ei,{visible:be.visible&&de,style:{left:be.x,top:be.y,width:Ee,height:Ee}})),React.createElement("div",{style:{display:"flex",gap:5,marginBottom:5}},React.createElement(h.M,{onClick:()=>{if(de){const e=Te.current;e.getContext("2d").clearRect(0,0,e.width,e.height),pe(null),me(!1)}else me(!0)},style:{flex:2}},de?"Remove Mask":"Create Mask"),de&&React.createElement(React.Fragment,null,React.createElement(h.M,{onClick:()=>he((e=>Math.max(5,e-5))),style:{flex:1},title:"Decrease brush size"},"−"),React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"0 10px",border:"1px solid #ddd",borderRadius:4,background:"#f5f5f5",minWidth:40}},Ee),React.createElement(h.M,{onClick:()=>he((e=>Math.min(200,e+5))),style:{flex:1},title:"Increase brush size"},"+"))),de&&React.createElement("div",{style:{fontSize:11,opacity:.6,marginBottom:10,textAlign:"center"}},"Use [ and ] keys to adjust brush size")),"edit"!==d&&r),React.createElement(le.g,null),React.createElement(Aa,null,!z&&React.createElement(React.Fragment,null,React.createElement("h2",{style:{marginTop:0}},(0,y.FE)(ge.COMMON.PROMPT)),React.createElement(Ke.m,{value:Ie,onChange:e=>{l({...n,prompt:e})},rows:10,placeholder:"Enter your prompt here..."}),React.createElement(le.g,{tiny:!0}),React.createElement(ze,null,React.createElement("div",{style:{display:"flex",flexDirection:"column",flex:1}},React.createElement("div",{style:{display:"flex",gap:5}},T&&React.createElement(h.M,{disabled:!Ie,onClick:je,style:{flex:1}},"Add to Queue"),G.length>0&&React.createElement(h.M,{onClick:()=>{$([])},style:{flex:1}},"Clear")),React.createElement("div",{style:{marginTop:5}},React.createElement(ae.u,{scrolldown:!0,id:"totalImagesToGenerate",name:"totalImagesToGenerate",style:{width:"100%"},value:Me,onChange:e=>Se(e)},mi.map((e=>React.createElement(ae.j,{key:e,id:e,value:e,label:`${e} ${e>1?"Images":"Image"}`}))))))))),React.createElement(le.g,null),React.createElement(Aa,null,React.createElement(h.M,{fullWidth:!0,disabled:!Ie,onClick:je,onStopClick:Le,isBusy:T,style:{height:50,fontSize:16,flex:4}},ge.COMMON.GENERATE))),React.createElement(E.Y,{style:{flex:2}},React.createElement(oe.o,{value:d,onChange:e=>{"generate"===e?location.href="edit.php?page=mwai_images_generator":"edit"===e&&(s?p("edit"):R(!0))}},React.createElement(oe.K,{title:"Create",value:"generate"}),React.createElement(oe.K,{title:"Editor",value:"edit"})),React.createElement(le.g,null),React.createElement(at.j,{busy:T,value:xe,max:ke,onStopClick:Le,status:()=>`${xe} / ${ke}`}),React.createElement(le.g,null),React.createElement("div",null,React.createElement(ie.n,{isOpen:!!z,title:q||"Image Preview",size:"larger",onRequestClose:()=>W(),hideButtons:!0,content:z&&React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",marginBottom:20}},React.createElement("div",{style:{flex:2}},React.createElement("a",{href:z,target:"_blank",rel:"noreferrer"},React.createElement("img",{src:z,style:{maxWidth:"100%",maxHeight:"60vh",objectFit:"contain"}}))),React.createElement("div",{style:{flex:1,marginLeft:10,display:"flex",flexDirection:"column"}},React.createElement(ui,null,React.createElement("label",null,"Title:"),React.createElement(ne.A,{value:q,onChange:V})),React.createElement(ui,null,React.createElement("label",null,"Caption:"),React.createElement(Ke.m,{value:X,onBlur:Q,rows:2})),React.createElement(ui,null,React.createElement("label",null,"Description:"),React.createElement(Ke.m,{value:Y,onBlur:K,rows:2})),React.createElement(ui,null,React.createElement("label",null,"Alternative Text:"),React.createElement(Ke.m,{value:J,onBlur:Z,rows:2})),React.createElement(ui,null,React.createElement("label",null,"Filename:"),React.createElement(ne.A,{value:ee,onChange:te})),React.createElement(le.g,{tiny:!0}),React.createElement(h.M,{onClick:async()=>{D(!0);try{const e=await(0,y.IU)(`${w}/helpers/generate_image_meta`,{method:"POST",nonce:N,json:{url:z}});null!=e&&e.data&&(V(e.data.title||""),K(e.data.description||""),Q(e.data.description||""),Z(e.data.description||""),e.data.filename&&te(e.data.filename))}catch(e){"AbortError"===e.name||/aborted/i.test(e.message)||(console.error(e),i(e.message))}finally{D(!1)}},isBusy:P},"Generate Meta"),React.createElement(le.g,{tiny:!0}))),React.createElement("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",borderTop:"1px solid #e0e0e0",paddingTop:20,marginTop:20}},React.createElement(h.M,{onClick:()=>W(),secondary:!0},"Close"),React.createElement(h.M,{onClick:()=>{x(!0),Ge(!0).finally((()=>x(!1)))},isBusy:A,secondary:!0},"Add to Media Library & Edit"),React.createElement(h.M,{onClick:()=>Ge(!1),isBusy:S},"Add to Media Library")))}),!z&&React.createElement(React.Fragment,null,React.createElement(We,null,G.map((e=>{const t=ce.find((t=>t.url===e));return React.createElement("div",{key:e,className:"image-wrapper",onClick:()=>W(e)},React.createElement("img",{src:e}),t&&React.createElement("div",{className:"media-label",onClick:e=>{e.stopPropagation(),window.open(`/wp-admin/post.php?post=${t.id}&action=edit`,"_blank")}},"Media #",t.id),React.createElement("div",{className:"delete-icon",onClick:t=>{t.stopPropagation(),$(G.filter((t=>t!==e))),se(ce.filter((t=>t.url!==e)))}},"×"))})),[...Array(Math.max(3-G.length,0)).keys()].map(((e,t)=>React.createElement("div",{key:t,className:"empty-image"}))))))),React.createElement(E.Y,{style:{flex:1}},React.createElement(Aa,{style:{marginBottom:25}},React.createElement(ze,{onClick:()=>ye(!Re),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginTop:0,marginBottom:0}},ge.COMMON.MODEL),React.createElement(Ye.z,{icon:Re?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),Re&&React.createElement(React.Fragment,null,React.createElement(le.g,{tiny:!0}),React.createElement("label",null,ge.COMMON.ENVIRONMENT,":"),React.createElement(ae.u,{scrolldown:!0,name:"envId",value:(null==n?void 0:n.envId)??"",onChange:Be},L.map((e=>React.createElement(ae.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(ae.j,{value:"",label:"Default"})),React.createElement("label",null,ge.COMMON.MODEL,":"),React.createElement(ae.u,{scrolldown:!0,name:"model",value:(null==n?void 0:n.model)||"",disabled:!(null!=n&&n.envId),onChange:Be},React.createElement(ae.j,{value:"",label:null!=n&&n.envId?"None":"Default"}),F.map((e=>React.createElement(ae.j,{key:e.model,value:e.model,label:e.name})))),(null==U||null===(e=U.resolutions)||void 0===e?void 0:e.length)>0&&React.createElement(React.Fragment,null,React.createElement("label",null,ge.COMMON.RESOLUTION,":"),React.createElement(ae.u,{scrolldown:!0,name:"resolution",value:(null==n?void 0:n.resolution)||"",onChange:Be},React.createElement(ae.j,{value:"",label:"Default"}),null==U||null===(t=U.resolutions)||void 0===t?void 0:t.map((e=>React.createElement(ae.j,{key:e.name,value:e.name,label:e.label}))))),"custom"===(null==n?void 0:n.resolution)&&React.createElement(React.Fragment,null,React.createElement("label",null,"Custom Resolution:"),React.createElement(ne.A,{name:"customResolution",value:null==n?void 0:n.customResolution,onChange:e=>Be(e,"customResolution")})),(null==U||null===(a=U.model)||void 0===a?void 0:a.startsWith("dall-e-3"))&&React.createElement(React.Fragment,null,React.createElement("label",null,ge.COMMON.STYLE,":"),React.createElement(ae.u,{scrolldown:!0,name:"style",value:Fe,onChange:Be},React.createElement(ae.j,{key:"none",value:null,label:"None"}),React.createElement(ae.j,{key:"natural",value:"natural",label:"Natural"}),React.createElement(ae.j,{key:"vivid",value:"vivid",label:"Vivid"}))))),React.createElement(Aa,{style:{marginBottom:25}},React.createElement(ze,{onClick:()=>fe(!ve),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginTop:0,marginBottom:0}},ge.COMMON.SETTINGS),React.createElement(Ye.z,{icon:ve?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),ve&&React.createElement(React.Fragment,null,React.createElement(le.g,{tiny:!0}),React.createElement(m.R,{id:"continuous_mode ",label:"Continuous",value:"1",checked:_,description:React.createElement("span",{style:{fontSize:11,opacity:.6}},"New images will be added to the already generated images."),onChange:C}))))),React.createElement(ie.n,{isOpen:o,onRequestClose:()=>{i()},okButton:{onClick:()=>{i()}},title:"Error",content:React.createElement("p",null,o)}),React.createElement(ie.n,{isOpen:g,onRequestClose:()=>R(!1),okButton:{onClick:()=>R(!1)},title:"Image Edit",content:React.createElement("p",null,"Editing images is only available via the Edit action in the Media Library and is still in active development.")}))},{useState:hi,useEffect:Ri,useMemo:yi}=wp.element,vi=e=>{const{isOpen:t=!1,title:a,error:n,results:l,busy:o=!1,onClick:i=(()=>{})}=e,c=e=>{let t=0;if(0===e.length)return t;for(let a=0;a<e.length;a++){t=(t<<5)-t+e.charCodeAt(a),t|=0}return t},s=yi((()=>o?React.createElement(Ro.X,{type:"circle",size:"10%"}):n?React.createElement(React.Fragment,null,"Error: ",n):(null==l?void 0:l.length)>0?React.createElement(React.Fragment,null,"Pick one of those results:",React.createElement($o,null,l.map((e=>React.createElement(zo,{key:c(e),onClick:()=>{i(e)}},e))))):React.createElement(React.Fragment,null,"Nothing to display.")),[l,n]);return React.createElement(r.A,null,React.createElement(E.N,null,React.createElement(ie.n,{isOpen:t,title:a??"Results",content:s,onRequestClose:()=>i(),okButton:{label:"Close",onClick:()=>i()}})))},{useState:fi,useEffect:bi,Fragment:wi}=wp.element,{__:_i}=wp.i18n,{registerPlugin:Ci}=wp.plugins,{Button:Ti,ToolbarDropdownMenu:Oi,ToolbarGroup:Ni,Spinner:Ii,MenuGroup:Mi,MenuItem:Si}=wp.components,{BlockControls:ki}=wp.blockEditor,{PluginDocumentSettingPanel:Ai}=wp.editor,{addFilter:xi}=wp.hooks,{createHigherOrderComponent:Pi}=wp.compose,{registerFormatType:Di}=wp.richText,{useSelect:Li}=wp.data;function Fi(){const[e,t]=fi(!1),[a,n]=fi([]),[l,r]=fi(""),o=Li((e=>e("core/block-editor").getSelectedBlock()),[]);if(!o)return null;const i=e=>{e.style.opacity=.15,e.style.pointerEvents="none",e.style.userSelect="none",e.style.animation="neko-fade-animation 0.85s infinite linear"},c=e=>{e.style.opacity=1,e.style.pointerEvents="auto",e.style.userSelect="auto",e.style.animation="none"};bi((()=>{if(null==o||!o.clientId)return;let t=document.getElementById("block-"+o.clientId);t||(t=document.querySelector(`[data-block="${o.clientId}"]`)),t||(t=document.querySelector(`.wp-block[data-block="${o.clientId}"]`)),t?e?i(t):c(t):console.warn("AI Engine: Could not find block element for",o.name,o.clientId)}),[e,o]);const s=()=>{let e=document.getElementById("block-"+o.clientId);e||(e=document.querySelector(`[data-block="${o.clientId}"]`)),e||(e=document.querySelector(`.wp-block[data-block="${o.clientId}"]`)),e?c(e):console.warn("AI Engine: Could not find block element for",o.name,o.clientId)},d=(e,t=!1)=>{switch(e.name){case"core/list":if(e.innerBlocks&&e.innerBlocks.length>0){if(t){const t=e.innerBlocks.filter((e=>"core/list-item"===e.name)).map((e=>{if(e.attributes.content)return e.attributes.content;if(e.originalContent){const t=document.createElement("div");t.innerHTML=e.originalContent;const a=t.querySelector("li");return a&&(a.textContent||a.innerText)||""}return""}));return{type:"list",items:t}}return e.innerBlocks.filter((e=>"core/list-item"===e.name)).map((e=>{if(e.attributes.content)return e.attributes.content;if(e.originalContent){const t=document.createElement("div");t.innerHTML=e.originalContent;const a=t.querySelector("li");return a&&(a.textContent||a.innerText)||""}return""})).join("\n")}if(t){const t=e.attributes.values||"",a=document.createElement("div");a.innerHTML=t;return{type:"list",items:Array.from(a.querySelectorAll("li")).map((e=>e.textContent||e.innerText||""))}}const a=e.attributes.values||"",n=document.createElement("div");return n.innerHTML=a,n.textContent||n.innerText||"";case"core/list-item":const l=e.attributes.content;if(l&&"object"==typeof l&&l.originalHTML){const e=document.createElement("div");return e.innerHTML=l.originalHTML,e.textContent||e.innerText||""}return"string"==typeof l?l:"";case"core/quote":return e.attributes.value||"";case"core/table":const r=e.attributes.body||[],o=e=>{if(e&&"object"==typeof e&&e.originalHTML){const t=document.createElement("div");return t.innerHTML=e.originalHTML,t.textContent||t.innerText||""}return"string"==typeof e?e:""};if(t)return{type:"table",rows:r.map((e=>({cells:e.cells?e.cells.map((e=>o(e.content))):[]})))};let i="";return r.forEach((e=>{e&&e.cells&&(e.cells.forEach((e=>{const t=o(e.content);t&&(i+=t+" ")})),i+="\n")})),i.trim();default:const c=e.attributes.content;if(c&&"object"==typeof c&&c.originalHTML){const e=document.createElement("div");return e.innerHTML=c.originalHTML,e.textContent||e.innerText||""}return c||""}},m=(e,t,a=!1)=>{let n={};switch(e.name){case"core/list":if(a&&"object"==typeof t&&t.items){n={values:t.items.map((e=>`<li>${e}</li>`)).join("")}}else{n={values:t.split("\n").filter((e=>e.trim())).map((e=>`<li>${e.trim()}</li>`)).join("")}}break;case"core/list-item":const l=e.attributes.content;n=l&&"object"==typeof l&&void 0!==l.originalHTML?{content:{originalHTML:t}}:{content:t};break;case"core/quote":n={value:t};break;case"core/table":if(a&&"object"==typeof t&&t.rows){const a=e.attributes.body||[];n={body:t.rows.map(((e,t)=>{const n=a[t]||{cells:[]};return{cells:e.cells.map(((e,t)=>{var a;const l=null===(a=n.cells)||void 0===a?void 0:a[t];null==l||l.content;return{...l,content:e}}))}}))}}else console.warn("AI Wand: Table requires structured data for proper update");break;default:n={content:t}}wp.data.dispatch("core/block-editor").updateBlockAttributes(e.clientId,n)},u=async e=>{const{getSelectedBlockClientId:a,getBlockIndex:l,getCurrentPost:c}=wp.data.select("core/editor"),u=l(a()),{id:p}=c();t(!0),(()=>{let e=document.getElementById("block-"+o.clientId);e||(e=document.querySelector(`[data-block="${o.clientId}"]`)),e||(e=document.querySelector(`.wp-block[data-block="${o.clientId}"]`)),e?i(e):console.warn("AI Engine: Could not find block element for",o.name,o.clientId)})(),document.activeElement.blur();const E=!!o&&["core/list","core/table"].includes(o.name),g=o?d(o,E):"",h=E&&"object"==typeof g?"":g,R=window.getSelection().toString();"suggestSynonyms"===e&&R&&r(R);const v={postId:p};E?(v.json=g,v.blockType=o.name):(v.text=h,v.selectedText=R);try{const a=await(0,y.IU)(`${w}/ai/magic_wand`,{method:"POST",nonce:N,json:{action:e,data:v}});s(),t(!1);const{mode:l,result:r,results:i,type:c}=a.data;if("replace"===l)"json"===c&&E?"object"==typeof r&&null!==r?m(o,r,!0):(console.error("AI Wand: Expected JSON object but got:",typeof r),alert("Error: Invalid response format from AI")):"text"!==c&&E?(console.error("AI Wand: Unexpected response type:",c),alert("Error: Unexpected response type")):(e=>{m(o,e,!1)})(r);else if("suggest"===l)n(i);else if("insertMedia"===l){const{media:e}=a.data,{createBlock:t}=wp.blocks,n=t("core/image",{id:e.id,url:e.url,title:e.title,caption:e.caption,alt:e.alt});wp.data.dispatch("core/block-editor").insertBlock(n,u+1)}}catch(e){s(),t(!1);let a="An error occurred";e.response&&e.response.data&&e.response.data.message?a=e.response.data.message:e.message&&(a=e.message),alert("AI Wand Error: "+a),console.error("AI Wand Error:",e)}};return React.createElement(React.Fragment,null,React.createElement("style",null,"\n        @keyframes neko-fade-animation {\n          0% { opacity: 0.15; }\n          50% { opacity: 0.3; }\n          100% { opacity: 0.15; }\n        }\n    "),React.createElement(ki,null,React.createElement(Ni,null,React.createElement(Oi,{icon:e?React.createElement(Ii,null):React.createElement(Ge,{icon:"wand",style:{marginRight:0}}),label:_i("AI Wand")},(()=>React.createElement(React.Fragment,null,React.createElement(Mi,null,React.createElement(Si,{onClick:()=>u("correctText")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Correct Text"),React.createElement("small",null,"Grammar & Spelling"))),React.createElement(Si,{onClick:()=>u("enhanceText")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Enhance Text"),React.createElement("small",null,"Readibility & Quality"))),React.createElement(Si,{onClick:()=>u("longerText")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Longer Text"),React.createElement("small",null,"Readibility"))),React.createElement(Si,{onClick:()=>u("shorterText")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Shorter Text"),React.createElement("small",null,"Readibility"))),React.createElement(Si,{onClick:()=>u("translateText")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Translate Text"),React.createElement("small",null,"To Post Language")))),React.createElement(Mi,null,React.createElement(Si,{disabled:!window.getSelection().toString(),onClick:()=>u("suggestSynonyms")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Suggest Synonyms"),React.createElement("small",null,"For Selected Words")))),React.createElement(Mi,null,React.createElement(Si,{onClick:()=>u("generateImage")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Generate Image"),React.createElement("small",null,"For this Text"))))))))),React.createElement(vi,{isOpen:null==a?void 0:a.length,results:a,onClick:e=>{n([]),e?(e=>{const t=wp.data.select("core/block-editor").getSelectedBlock(),a=d(t),n=l||window.getSelection().toString();if(n&&a.includes(n)){const l=a.replace(n,e);m(t,l),r("")}else console.warn("AI Wand: Could not find selection, replacing entire block content"),m(t,e)})(e.trim()):r("")},onClose:()=>n([])}))}const Bi=async(e,t)=>{if(!e)return e;const{getCurrentPost:a}=wp.data.select("core/editor"),{id:n}=a();return(await(0,y.IU)(`${w}/ai/magic_wand`,{method:"POST",nonce:N,json:{action:"translateSection",data:{postId:n,context:t,text:e}}})).data.result},Ui=()=>{const e=null==I?void 0:I.module_suggestions,[t,a]=fi(),[n,l]=fi();return e?React.createElement(r.A,null,React.createElement(Ai,{name:"mwai-document-settings",title:React.createElement(React.Fragment,null,React.createElement(Ge,null)," AI Engine"),className:"mwai-document-settings"},React.createElement("p",null,"Suggest:"),React.createElement("div",{style:{display:"flex"}},React.createElement(Ti,{variant:"primary",onClick:()=>{const{getCurrentPost:e}=wp.data.select("core/editor"),{id:t,title:n}=e();a({postId:t,postTitle:n})},style:{flex:1,marginRight:10,textAlign:"center"}},React.createElement(Ge,{icon:"wand",style:{marginRight:8}})," Titles"),React.createElement(Ti,{variant:"primary",onClick:()=>{const{getCurrentPost:e}=wp.data.select("core/editor"),{id:t,title:a}=e();l({postId:t,postTitle:a})},style:{flex:1,textAlign:"center"}},React.createElement(Ge,{icon:"wand",style:{marginRight:8}})," Excerpts")),React.createElement("div",{style:{display:"flex"}},React.createElement(Ti,{variant:"primary",onClick:async()=>{await(async()=>{const{getBlocks:e,getBlockAttributes:t}=wp.data.select("core/block-editor"),{updateBlockAttributes:a}=wp.data.dispatch("core/block-editor"),{editPost:n,savePost:l}=wp.data.dispatch("core/editor"),{createInfoNotice:r,removeNotice:o}=wp.data.dispatch("core/notices"),{getEditedPostAttribute:i}=wp.data.select("core/editor"),c="mwai-translation-progress-notice",s=e(),d=i("title"),m=Le(),u=async e=>{r(`Translating content... ${e}%`,{id:c,isDismissible:!1}),await new Promise((e=>setTimeout(e,100)))},p=e=>{e.style.opacity=.15,e.style.pointerEvents="none",e.style.userSelect="none",e.style.animation="neko-fade-animation 0.85s infinite linear"},E=e=>{e.style.opacity=1,e.style.pointerEvents="auto",e.style.userSelect="auto",e.style.animation="none"};s.forEach((e=>{const t=document.querySelector(`[data-block="${e.clientId}"]`);t&&p(t)}));const g=document.querySelector(".editor-post-title__input");g&&p(g),await u(0);const h=s.length+2;let R=0,y="";try{y=await Bi(d,m),R++,n({title:y}),g&&E(g),await u(Math.round(R/h*100));for(const e of s){if(["core/paragraph","core/heading","core/list","core/list-item","core/quote","core/table"].includes(e.name)){let n,l={};switch(e.name){case"core/list":n=t(e.clientId).values;break;case"core/list-item":default:n=t(e.clientId).content;break;case"core/quote":n=t(e.clientId).value}if(n){const t=await Bi(n,m);switch(e.name){case"core/list":l={values:t};break;case"core/list-item":default:l={content:t};break;case"core/quote":l={value:t}}await a(e.clientId,l)}const r=document.querySelector(`[data-block="${e.clientId}"]`);r&&E(r),wp.data.dispatch("core/block-editor").selectBlock(e.clientId)}R++,await u(Math.round(R/h*100))}const e=i("excerpt");e&&n({excerpt:await Bi(e,m)})}finally{s.forEach((e=>{const t=document.querySelector(`[data-block="${e.clientId}"]`);t&&E(t)})),o(c)}})()},style:{flex:1,marginTop:10,textAlign:"center"}},React.createElement(Ge,{icon:"wand",style:{marginRight:8}})," Translate Post")),React.createElement(r.A,null,React.createElement(E.N,null,React.createElement(Yo,{post:t,onTitleClick:async e=>{wp.data.dispatch("core/editor").editPost({title:e})},onClose:a}),React.createElement(Jo,{post:n,onExcerptClick:async e=>{wp.data.dispatch("core/editor").editPost({excerpt:e})},onClose:l}))))):null};"undefined"!=typeof window&&(window.mwaiWand={getAllBlocks:()=>{const e=wp.data.select("core/block-editor").getBlocks(),t=["core/paragraph","core/heading","core/list","core/list-item","core/quote","core/table"],a=(e,n=0)=>{const l="  ".repeat(n),r=t.includes(e.name),o=["core/list","core/table"].includes(e.name);if(console.log(`${l}Block: ${e.name} (ID: ${e.clientId})`),console.log(`${l}  Supported: ${r}`),console.log(`${l}  Attributes:`,e.attributes),r){const t=((e,t=!1)=>{switch(e.name){case"core/list":if(e.innerBlocks&&e.innerBlocks.length>0)return t?{type:"list",items:e.innerBlocks.filter((e=>"core/list-item"===e.name)).map((e=>e.attributes.content||""))}:e.innerBlocks.filter((e=>"core/list-item"===e.name)).map((e=>e.attributes.content||"")).join("\n");if(t){const t=e.attributes.values||"",a=document.createElement("div");return a.innerHTML=t,{type:"list",items:Array.from(a.querySelectorAll("li")).map((e=>e.textContent||e.innerText||""))}}const a=e.attributes.values||"",n=document.createElement("div");return n.innerHTML=a,n.textContent||n.innerText||"";case"core/list-item":case"core/paragraph":case"core/heading":default:return e.attributes.content||"";case"core/quote":return e.attributes.value||"";case"core/table":if(t)return{type:"table",rows:(e.attributes.body||[]).map((e=>({cells:e.cells?e.cells.map((e=>e.content||"")):[]})))};const l=e.attributes.body||[];let r="";return l.forEach((e=>{e&&e.cells&&(e.cells.forEach((e=>{e&&e.content&&(r+=e.content+" ")})),r+="\n")})),r.trim()}})(e,o);console.log(`${l}  Content (${o?"JSON":"text"}):`,t),console.log(`${l}  Payload to API:`,o?{json:t,blockType:e.name}:{text:t})}e.innerBlocks&&e.innerBlocks.length>0&&(console.log(`${l}  Inner blocks:`),e.innerBlocks.forEach((e=>a(e,n+1))))};return console.log("=== AI Wand Block Analysis ==="),console.log("Supported block types:",t),console.log("\nAll blocks in editor:"),e.forEach((e=>a(e))),console.log("\n=== End of Analysis ==="),e},getSelectedBlock:()=>{const e=wp.data.select("core/block-editor").getSelectedBlock();if(!e)return console.log("No block selected"),null;console.log("Selected block:",e.name),console.log("Block ID:",e.clientId),console.log("Attributes:",e.attributes),console.log("Inner blocks:",e.innerBlocks),console.log("Original content:",e.originalContent);const t=["core/list","core/table"].includes(e.name),a=window.mwaiWand.getBlockContent(e,t),n="object"==typeof a?"":a;return console.log("Content extracted:",a),console.log("Text for API:",n),console.log("Is complex block:",t),t?console.log("Payload to API:",{json:a,blockType:e.name}):console.log("Payload to API:",{text:n}),e},getBlockContent:(e,t=!1)=>{switch(e.name){case"core/list":if(e.innerBlocks&&e.innerBlocks.length>0){if(t){const t=e.innerBlocks.filter((e=>"core/list-item"===e.name)).map((e=>{const t=e.attributes.content;if(t&&"object"==typeof t&&t.originalHTML){const e=document.createElement("div");return e.innerHTML=t.originalHTML,e.textContent||e.innerText||""}if("string"==typeof t)return t;if(e.originalContent){const t=document.createElement("div");t.innerHTML=e.originalContent;const a=t.querySelector("li");return a&&(a.textContent||a.innerText)||""}return""}));return{type:"list",items:t}}return e.innerBlocks.filter((e=>"core/list-item"===e.name)).map((e=>{const t=e.attributes.content;if(t&&"object"==typeof t&&t.originalHTML){const e=document.createElement("div");return e.innerHTML=t.originalHTML,e.textContent||e.innerText||""}if("string"==typeof t)return t;if(e.originalContent){const t=document.createElement("div");t.innerHTML=e.originalContent;const a=t.querySelector("li");return a&&(a.textContent||a.innerText)||""}return""})).join("\n")}if(t){const t=e.attributes.values||"",a=document.createElement("div");a.innerHTML=t;return{type:"list",items:Array.from(a.querySelectorAll("li")).map((e=>e.textContent||e.innerText||""))}}const a=e.attributes.values||"",n=document.createElement("div");return n.innerHTML=a,n.textContent||n.innerText||"";case"core/list-item":case"core/paragraph":case"core/heading":default:return e.attributes.content||"";case"core/quote":return e.attributes.value||"";case"core/table":const l=e.attributes.body||[],r=e=>{if(e&&"object"==typeof e&&e.originalHTML){const t=document.createElement("div");return t.innerHTML=e.originalHTML,t.textContent||t.innerText||""}return"string"==typeof e?e:""};if(t)return{type:"table",rows:l.map((e=>({cells:e.cells?e.cells.map((e=>r(e.content))):[]})))};let o="";return l.forEach((e=>{e&&e.cells&&(e.cells.forEach((e=>{const t=r(e.content);t&&(o+=t+" ")})),o+="\n")})),o.trim()}},testAction:async(e="correctText")=>{const t=wp.data.select("core/block-editor").getSelectedBlock();if(!t)return void console.error("No block selected");console.log("Testing action:",e,"on block:",t.name);const a=["core/list","core/table"].includes(t.name),n=window.mwaiWand.getBlockContent(t,a),l="object"==typeof n?"":n,r={postId:wp.data.select("core/editor").getCurrentPost().id};a?(r.json=n,r.blockType=t.name):(r.text=l,r.selectedText=window.getSelection().toString()),console.log("Payload:",{action:e,data:r});try{const t=await fetch(`${w}/ai/magic_wand`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":N},body:JSON.stringify({action:e,data:r})}),a=await t.json();return console.log("Response:",a),a}catch(e){console.error("Error:",e)}},debugListItems:()=>{const e=wp.data.select("core/block-editor").getSelectedBlock();e&&"core/list"===e.name?(console.log("=== List Block Debug ==="),console.log("List block attributes:",e.attributes),console.log("Number of inner blocks:",e.innerBlocks.length),e.innerBlocks.forEach(((e,t)=>{console.log(`\nList item ${t+1}:`),console.log("  Name:",e.name),console.log("  Attributes:",e.attributes),console.log("  Original content:",e.originalContent);const a=document.createElement("div");a.innerHTML=e.originalContent;const n=a.querySelector("li"),l=n&&(n.textContent||n.innerText)||"";console.log("  Extracted text:",l)}))):console.log("Please select a list block")},help:()=>{console.log("=== AI Wand Debug Utility ==="),console.log("Available commands:"),console.log("  mwaiWand.getAllBlocks() - Show all blocks and their content"),console.log("  mwaiWand.getSelectedBlock() - Show currently selected block info"),console.log("  mwaiWand.debugListItems() - Debug list items in selected list"),console.log("  mwaiWand.getBlockContent(block, structured) - Get content from a block"),console.log("  mwaiWand.testAction(action) - Test an AI Wand action on selected block"),console.log("\nAvailable actions: correctText, enhanceText, longerText, shorterText, translateText, suggestSynonyms"),console.log('\nExample: mwaiWand.testAction("correctText")')}},console.log("AI Wand Debug Utility loaded. Type mwaiWand.help() for usage."));const Hi=()=>{Ci("ai-engine-document-settings",{render:Ui});const e=Pi((e=>t=>{if(!["core/paragraph","core/heading","core/list","core/list-item","core/quote","core/table"].includes(t.name))return React.createElement(e,t);const a=()=>{const e=Li((e=>e("core/block-editor").getSelectedBlock()),[]);return e&&e.clientId===t.clientId?React.createElement(Fi,null):null};return React.createElement(wi,null,React.createElement(e,t),React.createElement(a,null))}),"withAIWand");xi("editor.BlockEdit","ai-engine/ai-wand",e)};function ji(){return ji=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},ji.apply(this,arguments)}const{addFilter:Gi}=wp.hooks,{useState:$i,useRef:zi,useEffect:Wi}=wp.element,{TextControl:qi,Spinner:Vi,ProgressBar:Yi,ToggleControl:Ki,Card:Xi,CardBody:Qi}=wp.components,{dispatch:Ji}=wp.data,Zi="mwai-copilot/prevent-new-block",ec=()=>{const e=e=>{const t=zi(),[a,n]=$i(!1),[l,r]=$i(""),[o,i]=$i(!1),[c,s]=$i(!1),[d,m]=$i(!1),u=wp.data.select("core/editor").getCurrentPostId(),p=async t=>{c||("Enter"===t.key?(t.preventDefault(),t.stopPropagation(),await(async t=>{const a=Le("[== CURRENT BLOCK ==]");try{i(!0);const n=await(0,y.IU)(`${w}/ai/copilot`,{method:"POST",nonce:N,json:{action:d?"image":"text",message:t,context:a,postId:u}});if(d){const{media:e}=n.data,{createBlock:t}=wp.blocks,{replaceBlock:a}=wp.data.dispatch("core/block-editor"),{getSelectedBlockClientId:l}=wp.data.select("core/block-editor"),r=t("core/image",{id:e.id,url:e.url,title:e.title,caption:e.caption,alt:e.alt});a(l(),r)}else e.setAttributes({content:n.data});setTimeout((()=>{const{getSelectedBlockClientId:e}=wp.data.select("core/block-editor"),t=document.querySelector(`[data-block="${e()}"]`);if(t){const e=document.createRange(),a=window.getSelection();e.setStart(t,1),e.collapse(!0),a.removeAllRanges(),a.addRange(e)}}),50)}catch(e){console.error("Error:",e.message),Ji("core/notices").createErrorNotice(`AI Copilot error: ${e.message}`,{isDismissible:!0})}finally{i(!1),n(!1),r("")}})(l)):("Escape"===t.key||"Backspace"===t.key&&!l)&&(t.preventDefault(),n(!1),r("")))};return Wi((()=>{a&&t.current&&t.current.focus()}),[a]),Wi((()=>{const e=e=>{if(a&&"Enter"===e.key)return e.preventDefault(),!1};return Ji("core/keyboard-shortcuts").registerShortcut({name:Zi,category:"block",description:"Prevent new block creation when AI Copilot is active",keyCombination:{character:"enter"}}),window.addEventListener("keydown",e,!0),()=>{window.removeEventListener("keydown",e,!0),Ji("core/keyboard-shortcuts").unregisterShortcut(Zi)}}),[a]),a?React.createElement(Xi,null,React.createElement(Qi,null,o?React.createElement("div",{style:{textAlign:"center",padding:20}},React.createElement(Yi,null)):React.createElement(React.Fragment,null,React.createElement(qi,{ref:t,label:React.createElement(React.Fragment,null,React.createElement(Ge,{icon:"wand",style:{marginBottom:-4}}),"AI Copilot"),value:l,placeholder:d?"Describe the image...":"Write about...",onChange:e=>r(e),onKeyDown:p,onCompositionStart:()=>s(!0),onCompositionEnd:()=>s(!1)}),React.createElement("div",{style:{display:"flex",justifyContent:"end",marginBottom:-12}},React.createElement(Ki,{label:"Image Mode",checked:d,onChange:m}))))):React.createElement("div",{onCompositionStart:()=>s(!0),onCompositionEnd:()=>s(!1),onKeyDown:e=>{var t,a;if(c)return;const l=((null==e||null===(t=e.target)||void 0===t?void 0:t.innerText)||"").trim(),r=null==e||null===(a=e.target)||void 0===a?void 0:a.localName;"Space"!==e.code||l||"p"!==r||(e.preventDefault(),n(!0))}},React.createElement(e.BlockEdit,e))};Gi("editor.BlockEdit","mwai-copilot/module",(t=>a=>"core/paragraph"===a.name?React.createElement(e,ji({BlockEdit:t},a)):React.createElement(t,a)));Gi("blocks.registerBlockType","mwai-copilot/placeholder",((e,t)=>{if("core/paragraph"===t){const t=e.edit;e.edit=e=>(e={...e,attributes:{...e.attributes,placeholder:"Type / to choose a block, or press space to summon the AI Copilot"}},t(e))}return e}))};function tc(){return tc=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},tc.apply(this,arguments)}const ac=React.createElement(Ge,{icon:"ai",style:{width:20,height:20}}),nc=L.Ay.div`
  color: black;
  display: flex;
  flex-direction: column;
  border: 1px solid black;
  font-size: 15px;
  box-sizing: content-box;
  font-weight: 400;
  font-size: 13px;
  padding: 10px;
  background: hsl(0deg 0% 100% / 75%);
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
  margin-bottom: 10px;


  .mwai-title-container {
    flex: inherit;
    padding: 5px 0px 5px 10px;
    display: flex;
    align-items: center;
    color: black;
    font-weight: 600;
    cursor: pointer;

    .mwai-hint {
      font-size: 10px;
      font-weight: 400;
      text-align: right;
      flex: auto;

      .mwai-pill {
        background: var(--wp--preset--color--vivid-cyan-blue);
        padding: 5px 10px;
        border-radius: 8px;
        color: white;
      }

      .mwai-pill-purple {
        background: var(--wp--preset--color--vivid-purple);
      }

      .mwai-pill-red {
        background: var(--wp--preset--color--vivid-red);
      }
    }
  }

  .mwai-block-container-content {
    flex: auto;
    padding: 10px;
    display: flex;
    flex-direction: column;
  }

	&.mwai-chatbot {
		background: var(--neko-main-color);

		.mwai-title-container {
			color: white;
		}	

		.mwai-block-container-content {
			margin-top: 10px;
			border-radius: 5px;
			background: var(--neko-background-color);
		}
	}

  &.is-selected {
  }
`,lc=({children:e,type:t="",title:a="",hint:n="",isSelected:l,isDisplayed:r,...o})=>{const i=(0,nt.gR)("mwai-block-container",`mwai-${t}`,{"is-selected":l,"is-meow":!0});return React.createElement(nc,tc({className:i},o),React.createElement("div",{className:"mwai-title-container"},React.createElement(Ge,{icon:"ai",style:{width:20,height:20}}),React.createElement("div",null,a),React.createElement("div",{className:"mwai-hint"},n)),(l||r)&&React.createElement("div",{className:"mwai-block-container-content"},e))},rc=(null==I?void 0:I.chatbot_defaults)||{},{registerBlockType:oc}=wp.blocks,{useMemo:ic,useState:cc,useEffect:sc}=wp.element,{PanelBody:dc,SelectControl:mc,ToggleControl:uc}=wp.components,{InspectorControls:pc,useBlockProps:Ec}=wp.blockEditor,gc=e=>e.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`)),hc=e=>{const{attributes:{chatbotId:t,isCustomChatbot:a,shortcodeParams:n}}=e;if(a){return`${Object.entries(n).filter((([,e])=>null!=e&&""!==e)).reduce(((e,[t,a])=>{const n=gc(t),l=encodeURIComponent(a);return"bot_id"===n?`${e} custom_id="${l}"`:`${e} ${n}="${l}"`}),"[mwai_chatbot")}]`}{const e={id:{value:t,insertIfNull:!0}};return`${Object.entries(e).filter((([,{value:e,insertIfNull:t}])=>!!e||t)).reduce(((e,[t,{value:a}])=>`${e} ${gc(t)}="${encodeURIComponent(a)}"`),"[mwai_chatbot")}]`}},Rc=e=>{const{attributes:{chatbotId:t,isCustomChatbot:a,shortcodeParams:n},setAttributes:l,isSelected:r}=e,[o,i]=cc((()=>Object.keys(n||{}).length?n:rc));sc((()=>{!a||n&&Object.keys(n).length||(i(rc),l({shortcodeParams:rc}))}),[a]);const c=Ec(),s=ic((()=>{const e=A.map((e=>({label:e.name,value:e.botId})));return e.unshift({label:"None",value:null}),e}),[A]),d=ic((()=>A.find((e=>e.botId===t))),[t]),m=ic((()=>a?"Custom Chatbot":d?`Chatbot (${d.name})`:"Chatbot"),[a,t,d]);return React.createElement(React.Fragment,null,React.createElement("div",c,React.createElement(lc,{title:m,type:"chatbot",isSelected:r},a&&React.createElement(React.Fragment,null,React.createElement(Ja,{shortcodeParams:o,updateShortcodeParams:(e,t)=>{const a={...o};a[t]=e,i(a),l({shortcodeParams:a})},options:I,blockMode:!0})),!a&&React.createElement("p",null,"Selected chatbot: ",d?d.name:"None"))),React.createElement(pc,null,React.createElement(dc,{title:ge.COMMON.CHATBOT},React.createElement(uc,{label:"Custom Chatbot",checked:a,onChange:e=>l({isCustomChatbot:e})}),!a&&s&&s.length>0&&React.createElement(mc,{label:ge.COMMON.CHATBOT,value:t,options:s,onChange:e=>l({chatbotId:e})})),!a&&React.createElement(dc,{title:ge.COMMON.SETTINGS})))},yc=()=>{oc("ai-engine/chatbot",{title:"AI Chatbot",description:"Embed an AI Engine Chatbot in your content.",icon:ac,category:"layout",keywords:["ai","openai","chatbot"],attributes:{id:{type:"string",default:""},chatbotId:{type:"string",default:"default"},isCustomChatbot:{type:"boolean",default:!1},shortcodeParams:{type:"object",default:rc}},edit:Rc,save:hc})},{registerBlockType:vc}=wp.blocks,{useMemo:fc}=wp.element,{PanelBody:bc,SelectControl:wc,ToggleControl:_c,TextControl:Cc}=wp.components,{InspectorControls:Tc,useBlockProps:Oc}=wp.blockEditor,Nc=e=>{const{attributes:{isCustomChatbot:t,chatbotId:a,customId:n,textNewChat:l}}=e,r={};t?n&&(r.customId=n):a&&(r.id=a),l&&(r.textNewChat=l);return`${Object.entries(r).filter((([,e])=>null!=e&&""!==e)).reduce(((e,[t,a])=>{const n=(e=>e.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`)))(t);return`${e} ${n}="${a}"`}),"[mwai_discussions")}]`},Ic=e=>{const{attributes:{isCustomChatbot:t,chatbotId:a,customId:n,textNewChat:l},setAttributes:r,isSelected:o}=e,i=Oc(),c=fc((()=>{const e=A.map((e=>({label:e.name,value:e.botId})));return e.unshift({label:"None",value:""}),e}),[A]),s=fc((()=>A.find((e=>e.botId===a))),[a]),d=fc((()=>t?"Discussions (Custom Chatbot)":s?`Discussions (${s.name})`:"Discussions"),[t,s]);return React.createElement(React.Fragment,null,React.createElement("div",i,React.createElement(lc,{title:d,type:"discussions",isSelected:o},React.createElement("span",null,t?`Custom ID: ${n||"None"}`:`Selected chatbot: ${s?s.name:"None"}`),React.createElement("span",null,"New Chat: ",l||"Default"))),React.createElement(Tc,null,React.createElement(bc,{title:"Discussions Settings"},React.createElement(_c,{label:"Custom Chatbot",checked:t,onChange:e=>r({isCustomChatbot:e})}),t?React.createElement(Cc,{label:"Custom Chatbot ID",value:n,onChange:e=>r({customId:e})}):React.createElement(wc,{label:"Select Chatbot",value:a,options:c,onChange:e=>r({chatbotId:e})}),React.createElement(Cc,{label:"Text for New Chat Button",value:l,onChange:e=>r({textNewChat:e})}))))},Mc=()=>{vc("ai-engine/discussions",{title:"AI Discussions",description:"Embed AI Engine Discussions in your content.",icon:ac,category:"layout",keywords:["ai","openai","discussions"],attributes:{isCustomChatbot:{type:"boolean",default:!1},chatbotId:{type:"string",default:""},customId:{type:"string",default:""},textNewChat:{type:"string",default:""}},edit:Ic,save:Nc})};function Sc(){return Sc=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},Sc.apply(this,arguments)}const{__:kc}=wp.i18n,{registerBlockType:Ac}=wp.blocks,{useEffect:xc}=wp.element,{PanelBody:Pc,SelectControl:Dc,TextControl:Lc}=wp.components,{InspectorControls:Fc,InnerBlocks:Bc,useBlockProps:Uc}=wp.blockEditor,Hc=e=>{const t=Uc.save(),{attributes:{id:a,theme:n}}=e,l=`[mwai-form-container id="${a}" theme="${n}"]`;return React.createElement("div",Sc({},t,{id:`mwai-form-container-${a}`,className:"mwai-form-container"}),l,React.createElement(Bc.Content,null))},jc=e=>{const{attributes:{id:t,theme:a},setAttributes:n}=e,l=Uc();return xc((()=>{if(!t){const e=Math.random().toString(36).substr(2,9);n({id:e})}}),[t]),React.createElement(React.Fragment,null,React.createElement("div",l,React.createElement(lc,{title:"Container",type:"container",isDisplayed:!0},React.createElement(Bc,null))),React.createElement(Fc,null,React.createElement(Pc,{title:ge.COMMON.STYLE},React.createElement("p",null,"The theme will be applied to all the AI elements in this container."),React.createElement(Dc,{label:"Theme",value:a,onChange:e=>n({theme:e}),options:[{label:"None",value:"none"},{label:"ChatGPT",value:"ChatGPT"},{label:"Timeless",value:"Timeless"}]}),React.createElement(Lc,{label:"ID",value:t,onChange:e=>n({id:e})}))))},Gc=()=>{Ac("ai-engine/form-container",{title:"AI Form Container",description:"Container to embed the blocks relative to a specific AI Form.",icon:ac,category:"layout",keywords:[kc("ai"),kc("openai"),kc("form")],attributes:{id:{type:"string",default:""},theme:{type:"string",default:"ChatGPT"}},edit:jc,save:Hc})},{__:$c}=wp.i18n,{registerBlockType:zc}=wp.blocks,{useEffect:Wc}=wp.element,{Button:qc,PanelBody:Vc,TextControl:Yc,SelectControl:Kc,CheckboxControl:Xc}=wp.components,{useBlockProps:Qc,InspectorControls:Jc}=wp.blockEditor;const Zc=e=>{const{attributes:{id:t,label:a,type:n,name:l,options:r=[],placeholder:o,rows:i,defaultValue:c,maxlength:s,required:d}}=e,m=encodeURIComponent((0,y.F1)(r)),u=Qc.save();let p="[mwai-form-field";return t&&(p+=` id="${t}"`),a&&(p+=` label="${a}"`),n&&(p+=` type="${n}"`),l&&(p+=` name="${l}"`),m&&(p+=` options="${m}"`),o&&(p+=` placeholder="${o}"`),"textarea"===n&&i&&(p+=` rows="${i}"`),c&&(p+=` default="${c}"`),s&&(p+=` maxlength="${s}"`),d&&(p+=` required="${d}"`),p+="]",React.createElement("div",u,p)},es=e=>{const{attributes:{id:t,type:a,name:n,options:l=[],label:r,placeholder:o,rows:i,defaultValue:c,maxlength:s,required:d},setAttributes:m,isSelected:u}=e,p=Qc();Wc((()=>{if(!t){const e=Math.random().toString(36).substr(2,9);m({id:"mwai-"+e})}}),[t]);return React.createElement(React.Fragment,null,React.createElement("div",p,React.createElement(lc,{title:`${E=a,E.charAt(0).toUpperCase()+E.slice(1)}`,type:"field",isSelected:u,hint:React.createElement("span",{className:"mwai-pill"},"{",n,"}")},React.createElement("div",null,r),React.createElement("div",{style:{flex:"auto"}}),React.createElement("div",null,n))),React.createElement(Jc,null,React.createElement(Vc,{title:$c("Field")},React.createElement(Yc,{label:"Label Text",value:r,onChange:e=>{m({label:e});const t=e.trim().replace(/ /g,"_").replace(/[^\w-]+/g,"").toUpperCase();t&&m({name:t})}}),React.createElement(Yc,{label:"Field Name",value:n,onChange:e=>m({name:e})}),React.createElement(Kc,{label:"Field Type",value:a,onChange:e=>m({type:e}),options:[{label:"Input",value:"input"},{label:"Select",value:"select"},{label:"Checkbox",value:"checkbox"},{label:"Radio",value:"radio"},{label:"Text Area",value:"textarea"}]}),("input"===a||"textarea"===a)&&React.createElement(Yc,{label:"Placeholder",value:o,onChange:e=>m({placeholder:e})}),("input"===a||"textarea"===a)&&React.createElement(Yc,{label:"Default Value",value:c,onChange:e=>m({defaultValue:e})}),("input"===a||"textarea"===a)&&React.createElement(Yc,{label:"Max Length",value:s,onChange:e=>m({maxlength:e})}),"textarea"===a&&React.createElement(Yc,{label:ge.COMMON.ROWS,value:i,onChange:e=>m({rows:e}),type:"number",step:"1",min:"1",max:"100"}),React.createElement(Xc,{label:"Required",checked:d,onChange:e=>m({required:e})})),("select"===a||"radio"===a||"checkbox"===a)&&React.createElement(Vc,{title:React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"}},React.createElement("div",null,$c("Options")))},l.map(((e,t)=>React.createElement("div",{key:t,style:{display:"flex",marginBottom:-25}},React.createElement("div",{style:{marginRight:5}},React.createElement(Yc,{style:{marginRight:10},label:"Label",isInline:!0,value:e.label,onChange:e=>{const a=[...l];a[t].label=e,m({options:a})}})),React.createElement(Yc,{style:{},label:"Value",isSubtle:!0,value:e.value,onChange:e=>{const a=[...l];a[t].value=e,m({options:a})}}),React.createElement("div",{style:{marginLeft:5,position:"relative",top:23}},React.createElement(qc,{style:{height:30},isDestructive:!0,icon:"trash",isSmall:!0,onClick:()=>{const e=[...l];e.splice(t,1),m({options:e})}}))))),React.createElement(qc,{isPrimary:!0,style:{width:"100%",marginTop:10},onClick:()=>{const e=[...l];e.push({label:"",value:""}),m({options:e})}},"Add Option")),React.createElement(Vc,{title:ge.COMMON.SYSTEM},React.createElement(Yc,{label:"ID",value:t,onChange:e=>m({id:e})}))));var E},ts=()=>{zc("ai-engine/form-field",{apiVersion:3,title:"AI Form Field",description:"An AI Field for your AI Form.",icon:ac,category:"layout",keywords:[$c("ai"),$c("openai"),$c("form")],supports:{dimensions:{width:!0}},attributes:{id:{type:"string",default:""},name:{type:"string",default:"LABEL"},type:{type:"string",default:"input"},options:{type:"array",default:[]},label:{type:"string",default:"Label: "},placeholder:{type:"string",default:""},defaultValue:{type:"string",default:""},maxlength:{type:"string",default:""},rows:{type:"rows",default:4},required:{type:"boolean",default:!0}},edit:es,save:Zc})},{__:as}=wp.i18n,{registerBlockType:ns}=wp.blocks,{useEffect:ls}=wp.element,{Button:rs,PanelBody:os,TextControl:is,SelectControl:cs,CheckboxControl:ss}=wp.components,{useBlockProps:ds,InspectorControls:ms}=wp.blockEditor;const us=e=>{const{attributes:{id:t,label:a,name:n,required:l,accept:r,customAccept:o,multiple:i}}=e,c=ds.save(),s=function(e,t){switch(e){case"all-images":return"image/*";case"all-documents":return".pdf,.doc,.docx,.txt,.xls,.xlsx";case"all":default:return"";case"custom":return t||""}}(r,o);let d="[mwai-form-upload";return t&&(d+=` id="${t}"`),a&&(d+=` label="${a}"`),n&&(d+=` name="${n}"`),""!==s&&(d+=` accept="${s}"`),i&&(d+=' multiple="true"'),l&&(d+=' required="true"'),d+="]",React.createElement("div",c,d)},ps=e=>{const{attributes:{id:t,label:a,name:n,required:l,accept:r,customAccept:o,multiple:i},setAttributes:c,isSelected:s}=e,d=ds();ls((()=>{if(!t){const e=Math.random().toString(36).substr(2,9);c({id:"mwai-"+e})}}),[t]);return React.createElement(React.Fragment,null,React.createElement("div",d,React.createElement(lc,{title:"Upload Field",type:"field",isSelected:s,hint:React.createElement("span",{className:"mwai-pill"},"{"+n+"}")},React.createElement("div",null,a),React.createElement("div",{style:{flex:"auto"}}),React.createElement("div",null,n))),React.createElement(ms,null,React.createElement(os,{title:as("Upload Field Settings")},React.createElement(is,{label:"Label Text",value:a,onChange:e=>{if(c({label:e}),!n||"LABEL"===n){const t=e.trim().replace(/ /g,"_").replace(/[^\w-]+/g,"").toUpperCase();t&&c({name:t})}}}),React.createElement(is,{label:"Field Name",value:n,onChange:e=>c({name:e})}),React.createElement(cs,{label:"Accept",value:r,onChange:e=>c({accept:e}),options:[{label:"All Images",value:"all-images"},{label:"All Documents",value:"all-documents"},{label:"Any Files",value:"all"},{label:"Custom",value:"custom"}]}),"custom"===r&&React.createElement(is,{label:"Custom MIME Types",help:"Comma-separated list (e.g. .png,.jpg)",value:o,onChange:e=>c({customAccept:e})}),React.createElement(ss,{label:"Multiple",checked:i,onChange:e=>c({multiple:e})}),React.createElement(ss,{label:"Required",checked:l,onChange:e=>c({required:e})})),React.createElement(os,{title:ge.COMMON.SYSTEM},React.createElement(is,{label:"ID",value:t,onChange:e=>c({id:e})}))))},Es=()=>{ns("ai-engine/upload-field",{apiVersion:3,title:"AI Upload Field",description:"A File Upload field for your AI Form.",icon:ac,category:"layout",keywords:[as("ai"),as("openai"),as("form"),as("upload")],attributes:{id:{type:"string",default:""},label:{type:"string",default:"Upload:"},name:{type:"string",default:"UPLOAD"},required:{type:"boolean",default:!1},accept:{type:"string",default:"all-images"},customAccept:{type:"string",default:".png,.jpg"},multiple:{type:"boolean",default:!1}},edit:ps,save:us})},{__:gs}=wp.i18n,{registerBlockType:hs}=wp.blocks,{useEffect:Rs}=wp.element,{PanelBody:ys,TextControl:vs,CheckboxControl:fs}=wp.components,{InspectorControls:bs,useBlockProps:ws}=wp.blockEditor,_s=e=>{const{attributes:{id:t,copyButton:a}}=e,n=ws.save(),l={id:{value:t,insertIfNull:!0},copy_button:{value:a,insertIfNull:!1}};let r=Object.entries(l).filter((([,{value:e,insertIfNull:t}])=>!1!==e&&""!==e||t)).reduce(((e,[t,{value:a}])=>`${e} ${t}="${a}"`),"[mwai-form-output");return r=`${r}]`,React.createElement("div",n,r)},Cs=e=>{const{attributes:{id:t,copyButton:a},setAttributes:n,isSelected:l}=e,r=ws();return Rs((()=>{if(!t){const e=Math.random().toString(36).substr(2,9);n({id:"mwai-"+e})}}),[t]),React.createElement(React.Fragment,null,React.createElement("div",r,React.createElement(lc,{title:"Output",type:"output",isSelected:l,hint:React.createElement("span",{className:"mwai-pill mwai-pill-purple"},"#",t)},React.createElement("div",null),React.createElement("div",{style:{flex:"auto"}}),React.createElement("div",null,"#",t))),React.createElement(bs,null,React.createElement(ys,{title:ge.FORMS.OUTPUT},React.createElement(fs,{label:"Copy Button",checked:a,onChange:e=>n({copyButton:e})}),React.createElement(vs,{label:"ID",value:t,onChange:e=>n({id:e})}))))},Ts=()=>{hs("ai-engine/form-output",{title:"AI Form Output",description:"An Output Field for your AI Form.",icon:ac,category:"layout",keywords:[gs("ai"),gs("openai"),gs("form")],supports:{dimensions:{minHeight:!0}},attributes:{id:{type:"string",default:""},copyButton:{type:"boolean",default:!0}},edit:Cs,save:_s})},{__:Os}=wp.i18n,{registerBlockType:Ns}=wp.blocks,{useMemo:Is,useEffect:Ms}=wp.element,{PanelBody:Ss,TextControl:ks,TextareaControl:As,SelectControl:xs,CheckboxControl:Ps}=wp.components,{InspectorControls:Ds,useBlockProps:Ls}=wp.blockEditor,Fs=e=>{const{attributes:{id:t,scope:a,label:n,prompt:l,message:r,outputElement:o,aiEnvId:i,embeddingsEnvId:c,index:s,namespace:d,localMemory:m,model:u,temperature:p,maxTokens:E,isAssistant:g,assistantId:h,resolution:R}}=e,y=encodeURIComponent(l),v=encodeURIComponent(r),f=Ls.save(),b={id:{value:t,insertIfNull:!0},scope:{value:a,insertIfNull:!1},local_memory:{value:m,insertIfNull:!1},label:{value:n,insertIfNull:!0},prompt:{value:y,insertIfNull:!1},message:{value:v,insertIfNull:!1},output_element:{value:o,insertIfNull:!0},model:{value:u,insertIfNull:!1},temperature:{value:p,insertIfNull:!1},max_tokens:{value:E,insertIfNull:!1},is_assistant:{value:g,insertIfNull:!1},env_id:{value:i,insertIfNull:!1},embeddings_env_id:{value:c,insertIfNull:!1},embeddings_index:{value:s,insertIfNull:!1},embeddings_namespace:{value:d,insertIfNull:!1},assistant_id:{value:h,insertIfNull:!1},resolution:{value:R,insertIfNull:!1}};let w=Object.entries(b).filter((([,{value:e,insertIfNull:t}])=>!!e||t)).reduce(((e,[t,{value:a}])=>`${e} ${t}="${a}"`),"[mwai-form-submit");return w=`${w}]`,React.createElement("div",f,w)},Bs=e=>{var t;const a=Ls(),{attributes:{id:n,scope:l,label:r,message:o,model:i,temperature:c,maxTokens:s,aiEnvId:d,embeddingsEnvId:m,index:u,namespace:p,assistantId:E,resolution:g,isAssistant:h,localMemory:R,outputElement:y,placeholders:v=[]},setAttributes:f,isSelected:b}=e,w=Is((()=>I.embeddings_envs||[]),[]),_=Is((()=>w.find((e=>e.id===m))||null),[w,m]),C=Is((()=>(null==_?void 0:_.indexes)||[]),[_]),T=Is((()=>(null==_?void 0:_.namespaces)||[]),[_]),O=Is((()=>I.ai_envs||[]),[]),{models:N,getModel:M}=Ce(I,d),S=M(i),k=null==S||null===(t=S.features)||void 0===t?void 0:t.includes("text-to-image"),A=Is((()=>O.find((e=>e.id===d))||null),[O,d]),x=Is((()=>(null==A?void 0:A.assistants)||[]),[A]),P=Is((()=>x.find((e=>e.id===E))||null),[x,E]);Ms((()=>{!d&&!i||A||f({aiEnvId:null,model:null})}),[d]),Ms((()=>{(m||u||p)&&!_&&f({embeddingsEnvId:null,index:null,namespace:null})}),[m]),Ms((()=>{P&&P.model&&P.model!==i&&f({model:P.model})}),[P]),Ms((()=>{l||f({scope:"form"})}),[l]),Ms((()=>{h||f({assistantId:""})}),[h]),Ms((()=>{if(!n){const e=Math.random().toString(36).substr(2,9);f({id:"mwai-"+e})}}),[n]),Ms((()=>{d||""===i||f({model:""})}),[d]),Ms((()=>{const e=o.match(/{([^}]+)}/g);if(e){const t=e.map((e=>e.replace("{","").replace("}","")));t.join(",")!==v.join(",")&&f({placeholders:t})}else f({placeholders:[]})}),[o]);const D=Is((()=>v?v.length:0),[v]),L=Is((()=>{const e=x.map((e=>({label:e.name,value:e.id})));return e.unshift({label:"None",value:""}),e}),[x]),F=Is((()=>{const e=N.map((e=>({label:e.rawName,value:e.model})));return e.unshift({label:"Default",value:""}),e}),[N]),B=Is((()=>{var e;if(!S||!k)return[];const t=(null==S||null===(e=S.resolutions)||void 0===e?void 0:e.map((e=>({label:e.label,value:e.name}))))||[];return t.unshift({label:"None",value:""}),t}),[S,k]),U=Is((()=>{const e=C.map((e=>({label:e.name,value:e.name})));return e.unshift({label:"None",value:""}),e}),[C]),H=Is((()=>{const e=O.map((e=>({label:e.name,value:e.id})));return e.unshift({label:"Default",value:""}),e}),[O]),j=Is((()=>{const e=w.map((e=>({label:e.name,value:e.id})));return e.unshift({label:"None",value:""}),e}),[w]),G=Is((()=>{const e=T.map((e=>({label:e,value:e})));return e.unshift({label:"None",value:""}),e}),[T]),$=Is((()=>0===D?"N/A":React.createElement("span",{className:"mwai-pill"},D," field",D>1?"s":"")),[D]);return React.createElement(React.Fragment,null,React.createElement("div",a,React.createElement(lc,{title:"Submit",type:"submit",isSelected:b,hint:React.createElement(React.Fragment,null,"IN:"," ",React.createElement("span",{className:"mwai-pill"},$)," ","OUT:"," ",React.createElement("span",{className:"mwai-pill mwai-pill-purple"},y||"N/A"))},"Input Fields: ",v.join(", "),React.createElement("br",null),"Prompt: ",o,React.createElement("br",null),"Output Element: ",y)),React.createElement(Ds,null,React.createElement(Ss,{title:ge.COMMON.OUTPUT},React.createElement(ks,{label:ge.COMMON.LABEL,value:r,onChange:e=>f({label:e})}),React.createElement(As,{label:ge.COMMON.PROMPT,value:o,onChange:e=>f({message:e}),help:ge.FORMS.PROMPT_INFO}),React.createElement(ks,{label:ge.FORMS.OUTPUT_ELEMENT,value:y,onChange:e=>f({outputElement:e}),help:ge.FORMS.OUTPUT_ELEMENT_INFO})),React.createElement(Ss,{title:ge.COMMON.MODEL_PARAMS},O&&O.length>0&&React.createElement(xs,{label:ge.COMMON.ENVIRONMENT,value:d,options:H,onChange:e=>f({aiEnvId:e})}),O&&O.length>0&&React.createElement(Ps,{label:"Assistant Mode",checked:h,onChange:e=>f({isAssistant:e})}),h&&x&&x.length>0&&React.createElement(React.Fragment,null,React.createElement(xs,{label:ge.COMMON.ASSISTANT,value:E,options:L,onChange:e=>f({assistantId:e})})),!h&&React.createElement(React.Fragment,null,N&&N.length>0&&React.createElement(xs,{label:ge.COMMON.MODEL,value:i,options:F,disabled:!d,onChange:e=>f({model:e})}),!k&&React.createElement(React.Fragment,null,React.createElement(ks,{label:ge.COMMON.TEMPERATURE,value:c,onChange:e=>f({temperature:parseFloat(e)}),type:"number",step:"0.1",min:"0",max:"1",help:ge.HELP.TEMPERATURE}),React.createElement(ks,{label:ge.COMMON.MAX_TOKENS,value:s,onChange:e=>f({maxTokens:parseInt(e)}),type:"number",step:"16",min:"32",max:"4096",help:React.createElement(La,{model:S,maxTokens:s,onRecommendedClick:e=>f({maxTokens:e})})})),k&&React.createElement(React.Fragment,null,React.createElement(xs,{label:ge.COMMON.RESOLUTION,value:g,options:B,onChange:e=>f({resolution:e})})))),!k&&React.createElement(React.Fragment,null,React.createElement(Ss,{title:ge.COMMON.CONTEXT_PARAMS},w&&w.length>0&&React.createElement(xs,{label:ge.COMMON.EMBEDDINGS_ENV,value:m,options:j,disabled:!(null!=j&&j.length),onChange:e=>f({embeddingsEnvId:e})}),C&&C.length>0&&React.createElement(xs,{label:ge.COMMON.EMBEDDINGS_INDEX,value:u,options:U,disabled:!(null!=j&&j.length),onChange:e=>f({index:e})}),"pinecone"===(null==_?void 0:_.type)&&T&&T.length>0&&React.createElement(xs,{label:ge.COMMON.NAMESPACE,value:p,options:G,disabled:!(null!=j&&j.length),onChange:e=>f({namespace:e})}))),React.createElement(Ss,{title:ge.COMMON.SYSTEM},React.createElement(ks,{label:"ID",value:n,onChange:e=>f({id:e})}),React.createElement(Ps,{label:"Local Memory",checked:R,onChange:e=>f({localMemory:e}),help:"Store the forms data in the browser's local storage for 12 hours."}),React.createElement(ks,{label:"Scope",value:l,onChange:e=>f({scope:e}),help:"The scope of the form. Different forms can have the same scope."}))))},Us=()=>{Ns("ai-engine/form-submit",{title:"AI Form Submit",description:"The Submit Button for your AI Form.",icon:ac,category:"layout",keywords:[Os("ai"),Os("openai"),Os("form")],supports:{dimensions:{minHeight:!1}},attributes:{id:{type:"string",default:""},scope:{type:"string",default:"form"},localMemory:{type:"boolean",default:!1},label:{type:"string",default:"Submit"},prompt:{type:"string",default:""},message:{type:"string",default:""},outputElement:{type:"string",default:""},model:{type:"string",default:""},temperature:{type:"number",default:.8},maxTokens:{type:"number",default:4096},placeholders:{type:"array",default:[]},aiEnvId:{type:"string",default:""},embeddingsEnvId:{type:"string",default:""},index:{type:"string",default:""},namespace:{type:"string",default:null},isAssistant:{type:"boolean",default:!1},assistantId:{type:"string",default:""},resolution:{type:"string",default:null}},edit:Bs,save:Fs})},{__:Hs}=wp.i18n,{registerBlockType:js}=wp.blocks,{useMemo:Gs,useEffect:$s}=wp.element,{PanelBody:zs,TextControl:Ws,CheckboxControl:qs}=wp.components,{InspectorControls:Vs,useBlockProps:Ys}=wp.blockEditor,Ks=e=>{const{attributes:{id:t,label:a,localMemory:n}}=e,l=Ys.save();let r=`[mwai-form-reset id="${t}" label="${a}"`;return n&&(r+=' local_memory="true"'),r+="]",React.createElement("div",l,r)},Xs=e=>{const t=Ys(),{attributes:{id:a,label:n,localMemory:l},setAttributes:r,isSelected:o}=e;return $s((()=>{if(!a){const e=Math.random().toString(36).substr(2,9);r({id:"mwai-reset-"+e})}}),[a]),React.createElement(React.Fragment,null,React.createElement("div",t,React.createElement(lc,{title:"Reset",type:"reset",isSelected:o,hint:React.createElement(React.Fragment,null,Hs("This block resets the AI form fields","ai-engine"))},Hs("ID:","ai-engine")," ",a,React.createElement("br",null),Hs("Label:","ai-engine")," ",n)),React.createElement(Vs,null,React.createElement(zs,{title:Hs("Reset Button Settings","ai-engine")},React.createElement(Ws,{label:Hs("ID","ai-engine"),value:a,onChange:e=>r({id:e}),help:Hs("Unique identifier. If omitted, one is auto-generated.","ai-engine")}),React.createElement(Ws,{label:Hs("Label","ai-engine"),value:n,onChange:e=>r({label:e}),help:Hs("Text on the reset button.","ai-engine")}),React.createElement(qs,{label:Hs("Local Memory","ai-engine"),checked:l,onChange:e=>r({localMemory:e}),help:Hs("Clear local storage for this form’s key when resetting.","ai-engine")}))))},Qs=()=>{js("ai-engine/form-reset",{title:"AI Form Reset",description:"A reset button for your AI Form.",icon:ac,category:"layout",keywords:[Hs("ai"),Hs("openai"),Hs("form"),Hs("reset")],supports:{dimensions:{minHeight:!1}},attributes:{id:{type:"string",default:""},label:{type:"string",default:"Reset"},localMemory:{type:"boolean",default:!1}},edit:Xs,save:Ks})};function Js(){return Js=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},Js.apply(this,arguments)}const{__:Zs}=wp.i18n,{registerBlockType:ed}=wp.blocks,{useEffect:td,useMemo:ad}=wp.element,{PanelBody:nd,TextControl:ld,SelectControl:rd,Button:od}=wp.components,{InspectorControls:id,InnerBlocks:cd,useBlockProps:sd}=wp.blockEditor,{useSelect:dd}=wp.data,md=e=>{const{attributes:{id:t,conditions:a=[],logic:n="AND",conditionField:l,conditionValue:r}}=e,o=sd.save();let i=`[mwai-form-conditional id="${t}"`;const c=a.length?a:l?[{field:l,operator:"eq",value:r}]:[];return c.length&&(i+=` conditions="${encodeURIComponent(JSON.stringify(c))}" logic="${n}"`),i+="]",React.createElement("div",Js({},o,{id:`mwai-form-conditional-${t}`,className:"mwai-form-conditional",style:{display:"none"}}),i,React.createElement(cd.Content,null))},ud=[{label:"Equals",value:"eq"},{label:"Not Equals",value:"neq"},{label:"Contains",value:"contains"},{label:"Does Not Contain",value:"not_contains"},{label:"Is Empty",value:"empty"},{label:"Is Not Empty",value:"not_empty"}],pd=[{label:"AND",value:"AND"},{label:"OR",value:"OR"}],Ed=e=>{const{attributes:{id:t,conditions:a=[],logic:n="AND",conditionField:l,conditionValue:r},setAttributes:o,clientId:i}=e,c=sd();td((()=>{if(!t){const e=Math.random().toString(36).substr(2,9);o({id:e})}a.length||!l&&!r||o({conditions:[{field:l,operator:"eq",value:r}]})}),[t]);const s=dd((e=>{const{getBlock:t,getBlockRootClientId:a}=e("core/block-editor");let n=a(i);for(;n;){const e=t(n);if("ai-engine/form-container"===(null==e?void 0:e.name))break;n=a(n)}const l=[];if(n){const e=t(n),a=e=>{var t;"ai-engine/form-field"===e.name&&null!==(t=e.attributes)&&void 0!==t&&t.name&&l.push(e.attributes.name),e.innerBlocks&&e.innerBlocks.forEach(a)};e.innerBlocks.forEach(a)}return l}),[i]),d=ad((()=>{const e=s.map((e=>({label:e,value:e})));return e.unshift({label:"[N/A]",value:""}),e}),[s]);td((()=>{if(1===s.length&&a.some((e=>!e.field))){const e=s[0],t=a.map((t=>t.field?t:{...t,field:e}));o({conditions:t})}}),[s,a]);const m=ad((()=>0===a.length||a.some((e=>!e.field))?React.createElement("span",{className:"mwai-pill mwai-pill-red"},"[N/A]"):React.createElement("span",{className:"mwai-pill"},a.length," condition",a.length>1?"s":"")),[a]),u=ad((()=>{if(!a.length)return null;const e={eq:"=",neq:"≠",contains:"contains",not_contains:"does not contain",empty:"is empty",not_empty:"is not empty"};return a.map(((t,l)=>{if(!t.field)return null;const r=e[t.operator]||t.operator;let o=`${t.field} ${r}`;return"empty"!==t.operator&&"not_empty"!==t.operator&&t.value&&(o+=` "${t.value}"`),React.createElement("div",{key:l,style:{fontSize:"12px",color:"#666",marginBottom:"4px",fontFamily:"monospace",padding:"4px 8px",background:"#f5f5f5",borderRadius:"3px"}},o,l<a.length-1&&React.createElement("span",{style:{color:"#0073aa",fontWeight:"bold",marginLeft:"8px"}},n))})).filter(Boolean)}),[a,n]);return React.createElement(React.Fragment,null,React.createElement("div",c,React.createElement(lc,{title:"Conditional",type:"conditional",isDisplayed:!0,hint:m},u&&u.length>0&&React.createElement("div",{style:{marginBottom:"12px",padding:"8px",background:"#fafafa",border:"1px solid #e0e0e0",borderRadius:"4px"}},React.createElement("div",{style:{fontSize:"11px",textTransform:"uppercase",color:"#999",marginBottom:"6px",fontWeight:"600"}},"Conditions:"),u),React.createElement(cd,null))),React.createElement(id,null,React.createElement(nd,{title:ge.COMMON.CONDITIONS},a.map(((e,t)=>React.createElement("div",{key:t,style:{marginBottom:"8px"},className:"mwai-condition-panel"},React.createElement(nd,{title:`${ge.COMMON.CONDITION} ${t+1}`,initialOpen:!0},React.createElement(rd,{label:"Field",value:e.field,options:d,onChange:e=>{const n=[...a];n[t].field=e,o({conditions:n})}}),React.createElement(rd,{label:"Operator",value:e.operator,options:ud,onChange:e=>{const n=[...a];n[t].operator=e,o({conditions:n})}}),"empty"!==e.operator&&"not_empty"!==e.operator&&React.createElement(ld,{label:"Value",value:e.value,onChange:e=>{const n=[...a];n[t].value=e,o({conditions:n})}}),React.createElement(od,{isSecondary:!0,isDestructive:!0,icon:"trash",style:{width:"100%"},onClick:()=>{const e=a.filter(((e,a)=>a!==t));o({conditions:e})}},ge.COMMON.REMOVE)),t<a.length-1&&React.createElement(rd,{label:"",value:n,options:pd,onChange:e=>o({logic:e})})))),React.createElement(od,{isPrimary:!0,style:{width:"100%",marginBottom:"8px"},icon:"plus",onClick:()=>{const e=1===s.length?s[0]:"";o({conditions:[...a,{field:e,operator:"eq",value:""}]})}},ge.COMMON.ADD_CONDITION),React.createElement(ld,{label:"ID",value:t,onChange:e=>o({id:e})}))))},gd=()=>{ed("ai-engine/form-conditional",{title:"AI Form Conditional",description:"Display inner blocks only when a condition is met.",icon:ac,category:"layout",keywords:[Zs("ai"),Zs("openai"),Zs("form")],attributes:{id:{type:"string",default:""},conditions:{type:"array",default:[]},logic:{type:"string",default:"AND"},conditionField:{type:"string",default:""},conditionValue:{type:"string",default:""}},edit:Ed,save:md})},{render:hd}=wp.element,Rd=new n.E({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnMount:!1,retry:!1,placeholderData:e=>e}}}),yd=I.module_chatbots,vd=I.module_suggestions,fd=I.module_forms;yd&&(yc(),Mc()),fd&&(ts(),Es(),Ts(),Us(),Qs(),Gc(),gd()),vd&&(Hi(),ec()),document.addEventListener("DOMContentLoaded",(function(){const e=document.getElementById("mwai-admin-settings");e&&hd(React.createElement(l.Ht,{client:Rd},React.createElement(r.A,null,React.createElement(ho,null))),e);const t=document.getElementById("mwai-content-generator");t&&hd(React.createElement(l.Ht,{client:Rd},React.createElement(r.A,null,React.createElement(oi,null))),t);const a=document.getElementById("mwai-image-generator");a&&hd(React.createElement(l.Ht,{client:Rd},React.createElement(r.A,null,React.createElement(gi,null))),a);const n=document.getElementById("mwai-playground");if(n&&hd(React.createElement(l.Ht,{client:Rd},React.createElement(r.A,null,React.createElement(Go,null))),n),vd){const e=document.getElementById("mwai-admin-postsList");e&&hd(React.createElement(r.A,null,React.createElement(ti,null)),e)}const o=document.getElementById("meow-common-dashboard");o&&hd(React.createElement(l.Ht,{client:Rd},React.createElement(r.A,null,React.createElement(te,null))),o)}))},1594:e=>{e.exports=React},5206:e=>{e.exports=ReactDOM}},__webpack_module_cache__={},deferred,inProgress,dataWebpackPrefix;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].call(a.exports,a,a.exports,__webpack_require__),a.exports}__webpack_require__.m=__webpack_modules__,deferred=[],__webpack_require__.O=(e,t,a,n)=>{if(!t){var l=1/0;for(c=0;c<deferred.length;c++){for(var[t,a,n]=deferred[c],r=!0,o=0;o<t.length;o++)(!1&n||l>=n)&&Object.keys(__webpack_require__.O).every((e=>__webpack_require__.O[e](t[o])))?t.splice(o--,1):(r=!1,n<l&&(l=n));if(r){deferred.splice(c--,1);var i=a();void 0!==i&&(e=i)}}return e}n=n||0;for(var c=deferred.length;c>0&&deferred[c-1][2]>n;c--)deferred[c]=deferred[c-1];deferred[c]=[t,a,n]},__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__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__.f={},__webpack_require__.e=e=>Promise.all(Object.keys(__webpack_require__.f).reduce(((t,a)=>(__webpack_require__.f[a](e,t),t)),[])),__webpack_require__.u=e=>"pdfjs.js",__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),inProgress={},dataWebpackPrefix="ai-engine:",__webpack_require__.l=(e,t,a,n)=>{if(inProgress[e])inProgress[e].push(t);else{var l,r;if(void 0!==a)for(var o=document.getElementsByTagName("script"),i=0;i<o.length;i++){var c=o[i];if(c.getAttribute("src")==e||c.getAttribute("data-webpack")==dataWebpackPrefix+a){l=c;break}}l||(r=!0,(l=document.createElement("script")).charset="utf-8",l.timeout=120,__webpack_require__.nc&&l.setAttribute("nonce",__webpack_require__.nc),l.setAttribute("data-webpack",dataWebpackPrefix+a),l.src=e),inProgress[e]=[t];var s=(t,a)=>{l.onerror=l.onload=null,clearTimeout(d);var n=inProgress[e];if(delete inProgress[e],l.parentNode&&l.parentNode.removeChild(l),n&&n.forEach((e=>e(a))),t)return t(a)},d=setTimeout(s.bind(null,void 0,{type:"timeout",target:l}),12e4);l.onerror=s.bind(null,l.onerror),l.onload=s.bind(null,l.onload),r&&document.head.appendChild(l)}},__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;__webpack_require__.g.importScripts&&(e=__webpack_require__.g.location+"");var t=__webpack_require__.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var a=t.getElementsByTagName("script");if(a.length)for(var n=a.length-1;n>-1&&(!e||!/^http(s?):/.test(e));)e=a[n--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),__webpack_require__.p=e})(),(()=>{var e={57:0};__webpack_require__.f.j=(t,a)=>{var n=__webpack_require__.o(e,t)?e[t]:void 0;if(0!==n)if(n)a.push(n[2]);else{var l=new Promise(((a,l)=>n=e[t]=[a,l]));a.push(n[2]=l);var r=__webpack_require__.p+__webpack_require__.u(t),o=new Error;__webpack_require__.l(r,(a=>{if(__webpack_require__.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var l=a&&("load"===a.type?"missing":a.type),r=a&&a.target&&a.target.src;o.message="Loading chunk "+t+" failed.\n("+l+": "+r+")",o.name="ChunkLoadError",o.type=l,o.request=r,n[1](o)}}),"chunk-"+t,t)}},__webpack_require__.O.j=t=>0===e[t];var t=(t,a)=>{var n,l,[r,o,i]=a,c=0;if(r.some((t=>0!==e[t]))){for(n in o)__webpack_require__.o(o,n)&&(__webpack_require__.m[n]=o[n]);if(i)var s=i(__webpack_require__)}for(t&&t(a);c<r.length;c++)l=r[c],__webpack_require__.o(e,l)&&e[l]&&e[l][0](),e[l]=0;return __webpack_require__.O(s)},a=self.wpJsonMwai=self.wpJsonMwai||[];a.forEach(t.bind(null,0)),a.push=t.bind(null,a.push.bind(a))})(),__webpack_require__.nc=void 0;var __webpack_exports__=__webpack_require__.O(void 0,[121],(()=>__webpack_require__(2701)));__webpack_exports__=__webpack_require__.O(__webpack_exports__)})();
Page not found – Hello World !