Current File : /home/mdkeenpw/www/wp-content/plugins/ai-engine/app/index.js |
(()=>{"use strict";var __webpack_modules__={3233:(e,t,a)=>{a.d(t,{A:()=>o});const{__:n,sprintf:l}=wp.i18n,r={};r.COMMON={GENERAL:n("General","ai-engine"),MODULES:n("Modules","ai-engine"),CLIENT_MODULES:n("Client Modules","ai-engine"),BACKEND_MODULES:n("Admin Modules","ai-engine"),SERVER_MODULES:n("Server Modules","ai-engine"),ADVISOR:n("Advisor","ai-engine"),SETTINGS:n("Settings","ai-engine"),CHATBOT:n("Chatbot","ai-engine"),CHATBOTS:n("Chatbots","ai-engine"),CHATBOT_HELP:n("Build intelligent conversational experiences with fully customizable AI-powered chatbots.","ai-engine"),INSIGHTS:n("Insights","ai-engine"),STYLE:n("Style","ai-engine"),ENABLE:n("Enable","ai-engine"),NAME:n("Name","ai-engine"),SUBMIT:n("Submit","ai-engine"),MODEL:n("Model","ai-engine"),AI_MODEL:n("AI Model","ai-engine"),TEMPERATURE:n("Temperature","ai-engine"),MAX_TOKENS:n("Max Tokens","ai-engine"),CONTEXT_MAX_LENGTH:n("Context Max Length","ai-engine"),STOP_SEQUENCE:n("Stop Sequence","ai-engine"),MODE:n("Mode","ai-engine"),CONTEXT:n("Context","ai-engine"),IMAGES_NUMBER:n("Number of Images","ai-engine"),AVATAR:n("Avatar","ai-engine"),AI_NAME:n("AI Name","ai-engine"),GUEST_NAME:n("Guest Name","ai-engine"),USER_NAME:n("User Name","ai-engine"),PLACEHOLDER:n("Placeholder","ai-engine"),START_SENTENCE:n("Start Sentence","ai-engine"),SEND:n("Send","ai-engine"),CLEAR:n("Clear","ai-engine"),CLOSE:n("Close","ai-engine"),VIEW:n("View","ai-engine"),EDIT:n("Edit","ai-engine"),SYSTEM_NAME:n("System Name","ai-engine"),ID:n("ID","ai-engine"),SCOPE:n("Scope","ai-engine"),POPUP:n("Popup","ai-engine"),POSITION:n("Position","ai-engine"),CENTER:n("Center","ai-engine"),OPEN_DELAY:n("Open Delay","ai-engine"),WINDOW_ANIMATION:n("Window Animation","ai-engine"),ZOOM:n("Zoom","ai-engine"),SLIDE:n("Slide","ai-engine"),FADE:n("Fade","ai-engine"),VOICE:n("Voice","ai-engine"),ICON:n("Icon","ai-engine"),ICON_TEXT:n("Icon Text","ai-engine"),ICON_TEXT_DELAY:n("Icon Text Delay","ai-engine"),FULL_SCREEN:n("Full Screen","ai-engine"),CASUALLY_FINE_TUNED:n("Casually Fine-Tuned","ai-engine"),CONTENT_AWARE:n("Content Aware","ai-engine"),TITLE:n("Title","ai-engine"),TOPIC:n("Topic","ai-engine"),TOPICS:n("Topics","ai-engine"),SPACING:n("Spacing","ai-engine"),BORDER_RADIUS:n("Border Radius","ai-engine"),FONT_SIZE:n("Font Size","ai-engine"),FONT_COLOR:n("Font Color","ai-engine"),BORDER_COLOR:n("Border Color","ai-engine"),BACK_PRIMARY_COLOR:n("Back Primary Color","ai-engine"),BACK_SECONDARY_COLOR:n("Back 2nd Color","ai-engine"),HEADER_COLOR:n("Header Color","ai-engine"),HEADER_BACKGROUND_COLOR:n("Header Back Color","ai-engine"),HEADER_SUBTITLE:n("Header Subtitle","ai-engine"),BUBBLE_COLOR:n("Bubble Color","ai-engine"),BACK_USER_COLOR:n("Back User Color","ai-engine"),BACK_AI_COLOR:n("Back AI Color","ai-engine"),BACK_AI_SECONDARY_COLOR:n("Back AI 2nd Color","ai-engine"),AVATAR_MESSAGE_BACKGROUND_COLOR:n("Message Back","ai-engine"),AVATAR_MESSAGE_FONT_COLOR:n("Message Color","ai-engine"),POPUP_ICON:n("Popup Icon","ai-engine"),CUSTOM_ICON:n("Custom Icon (URL or Emoticon)","ai-engine"),FEATURES:n("Features","ai-engine"),TIMEFRAME:n("Timeframe","ai-engine"),ABSOLUTE:n("Absolute","ai-engine"),NONE:n("None","ai-engine"),EDITORS_ADMINS:n("Editors & Admins","ai-engine"),ADMINS_ONLY:n("Admins Only","ai-engine"),MAINTENANCE:n("Maintenance","ai-engine"),CREDITS:n("Credits","ai-engine"),TYPE:n("Type","ai-engine"),LIMITS:n("Limits","ai-engine"),USERS:n("Users","ai-engine"),USER:n("User","ai-engine"),GUESTS:n("Guests","ai-engine"),GUEST:n("Guest","ai-engine"),OPENAI:n("Open AI","ai-engine"),LICENSE_TAB:n("License","ai-engine"),FINETUNES:n("Finetunes","ai-engine"),MODELS:n("Models","ai-engine"),FILES:n("Files","ai-engine"),ASSISTANT:n("Assistant","ai-engine"),ASSISTANTS:n("Assistants","ai-engine"),UTILITIES:n("Utilities","ai-engine"),POSTS_SUGGESTIONS:n("AI Copilot, AI Suggestions, Magic Wands","ai-engine"),POSTS_SUGGESTIONS_HELP:n("Tools to brainstorm/write faster and better.","ai-engine"),GENERATORS:n("Generators","ai-engine"),CONTENT_GENERATOR:n("Content Generator","ai-engine"),CONTENT_GENERATOR_HELP:n("Transform ideas into polished articles with AI-powered content creation.","ai-engine"),IMAGES_GENERATOR:n("Images Generator","ai-engine"),IMAGES_GENERATOR_HELP:n("Bring your vision to life with stunning AI-generated visuals.","ai-engine"),IMAGES_GENERATOR_INTRO:n("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:n("Playground","ai-engine"),PLAYGROUND_HELP:n("Experiment with AI models and unlock endless creative possibilities.","ai-engine"),FORMS:n("Forms","ai-engine"),FORMS_HELP:n("Create dynamic, intelligent forms that adapt and respond based on user input with conditional logic.","ai-engine"),SEARCH:n("Search","ai-engine"),SEARCH_HELP:n("Override the default WordPress search with AI powered keywords or embeddings.","ai-engine"),INSIGHTS_HELP:n("Enable Query Logs, Usage and Limits.","ai-engine"),CLIENT_DEBUG:n("Client Debug","ai-engine"),CLIENT_DEBUG_HELP:n("Debugging information for Chatbots and Forms will be displayed in the Browser Console.","ai-engine"),SERVER_DEBUG:n("Server Debug","ai-engine"),SERVER_DEBUG_HELP:n("API calls and server events will be logged and displayed in the Logs Console.","ai-engine"),MCP_DEBUG:n("MCP Debug","ai-engine"),MCP_DEBUG_HELP:n("Debugging information from MCP will be written directly to the PHP error logs using error_log().","ai-engine"),QUERIES_DEBUG:n("Queries Debug","ai-engine"),QUERIES_DEBUG_HELP:n("Full queries and responses will be written directly to the PHP error logs using error_log().","ai-engine"),DEV_MODE:n("Dev Mode","ai-engine"),DEV_MODE_HELP:n("Run tasks frequently for debugging.","ai-engine"),CLEAR_LOGS:n("Clear Logs","ai-engine"),REFRESH_LOGS:n("Refresh Logs","ai-engine"),API_KEY:n("API Key","ai-engine"),USAGE_HELP:n("Estimates only. Check your AI service for actual costs. Insights module provides better accuracy.","ai-engine"),RESET_USAGE_SURE:n("Are you sure you want to reset the usage data?","ai-engine"),USAGE_PRO_HELP:n("If you would like to have better control on the amounts, add conditions or set limits to the usage of the AI, consider %s.","ai-engine"),USAGE_PRO_HELP_URL:"https://meowapps.com/ai-engine/",USAGE_PRO_HELP_LINK_TEXT:n("AI Engine Pro ↗","ai-engine"),LANGUAGE:n("Language","ai-engine"),HIDE:n("Hide","ai-engine"),SHOW:n("Show","ai-engine"),CONTENT:n("Content","ai-engine"),IMAGES:n("Images","ai-engine"),IMAGES_AND_FILES:n("Images & Files","ai-engine"),EXCERPT:n("Excerpt","ai-engine"),GENERATE:n("Generate","ai-engine"),MODEL_PARAMS:n("Model Params","ai-engine"),CONTEXT_PARAMS:n("Context Params","ai-engine"),PROMPT:n("Prompt","ai-engine"),PROMPTS:n("Prompts","ai-engine"),LABEL:n("Label","ai-engine"),SYSTEM:n("System","ai-engine"),SHORTCODE:n("Shortcode","ai-engine"),SHORTCODES:n("Shortcodes","ai-engine"),RESOLVE:n("Resolve","ai-engine"),MAX_MESSAGES:n("Max Messages","ai-engine"),INPUT_MAX_LENGTH:n("Input Max Length","ai-engine"),COMPLIANCE_TEXT:n("Compliance Text","ai-engine"),MODERATION:n("Moderation","ai-engine"),MODERATION_HELP:n("Moderation features with AI.","ai-engine"),FORMATTING:n("Formatting","ai-engine"),FORMATTING_HELP:n("Format the reply from AI into HTML. This is already done automatically if Markdown is detected in the reply.","ai-engine"),LOGS:n("Logs","ai-engine"),QUERY:n("Query","ai-engine"),REPLY:n("Reply","ai-engine"),CODE:n("Code","ai-engine"),EMBEDDINGS:n("Embeddings","ai-engine"),QUERY_LOGS:n("Query Logs","ai-engine"),KNOWLEDGE:n("Knowledge","ai-engine"),KNOWLEDGE_HELP:n("Searchable data for AI. Powered by <b>embeddings</b> for now, alternatives will come later.","ai-engine"),REMOTE_ACCESS:n("Remote Access","ai-engine"),OTHERS:n("Others","ai-engine"),PINECONE_APIKEY_HELP:n("You can get your API Keys in your %s.","ai-engine"),PINECONE_APIKEY_URL:"https://app.pinecone.io/organizations/keys",PINECONE_APIKEY_LINK_TEXT:n("Pinecone Account ↗","ai-engine"),QDRANT_APIKEY_HELP:n("You can get your API Keys in your %s.","ai-engine"),QDRANT_APIKEY_URL:"https://cloud.qdrant.io/accounts/",QDRANT_APIKEY_LINK_TEXT:n("Qdrant Account ↗","ai-engine"),SERVER:n("Server","ai-engine"),PINECONE_SERVER_HELP:n("The URL of your host (check your Indexes).","ai-engine"),PINECONE_NAMESPACE_HELP:n("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:n("The URL of your cluster (known as Cluster URL).","ai-engine"),QDRANT_COLLECTION_HELP:n("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:n("Cost","ai-engine"),USAGE:n("Usage","ai-engine"),USAGE_ESTIMATES_NOTE:n("Costs and tokens are estimates. For accurate data and detailed analytics, visit the Insights tab.","ai-engine"),ACTIVITY:n("Activity","ai-engine"),TRANSCRIPTION:n("Transcription","ai-engine"),TRANSCRIPTION_HELP:n("Introduces a 'Transcribe' tab to easily transform audio/images into text and get AI answers in JSON format.","ai-engine"),AUDIO_TRANSCRIPTION:n("Audio-to-Text","ai-engine"),IMAGE_TRANSCRIPTION:n("Image-to-Text","ai-engine"),AUDIO_TO_TEXT:n("Audio ➡ Text","ai-engine"),IMAGE_TO_TEXT:n("Image ➡ Text","ai-engine"),EMBEDDINGS_ENV:n("Environment","ai-engine"),EMBEDDINGS_INDEX:n("Index","ai-engine"),NAMESPACE:n("Namespace","ai-engine"),NAMESPACES:n("Namespaces","ai-engine"),NAMESPACE_HELP:n("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:n("Enter the namespaces you would like to use on this site, separated by commas.","ai-engine"),ERROR:n("Error","ai-engine"),RETRY:n("Retry","ai-engine"),AUTO_RETRY:n("Auto Retry","ai-engine"),SKIP:n("Skip","ai-engine"),AUTO_SKIP:n("Auto Skip","ai-engine"),STOP:n("Stop","ai-engine"),AUTO_RETRY_DESCRIPTION:n("Auto Retry retries actions up to 10 times with increasing delay to avoid timeouts.","ai-engine"),WIDTH:n("Width","ai-engine"),MAX_HEIGHT:n("Max Height","ai-engine"),APPEARANCE:n("Appearance","ai-engine"),THRESHOLDS:n("Thresholds","ai-engine"),DASHBOARD:n("Dashboard","ai-engine"),ADVANCED:n("Advanced","ai-engine"),DISCUSSIONS:n("Discussions","ai-engine"),DISCUSSION_TITLES:n("Discussion Titles","ai-engine"),SUMMARIZE:n("Summarize","ai-engine"),ROWS:n("Rows","ai-engine"),POST_TYPE:n("Post Type","ai-engine"),GENERATE_CONTENT:n("Generate Content","ai-engine"),GENERATE_IMAGES:n("Generate Images","ai-engine"),REST_API:n("REST API","ai-engine"),ADMIN_BAR:n("Admin Bar","ai-engine"),REFRESH:n("Refresh","ai-engine"),DELETE:n("Delete","ai-engine"),DELETE_ALL:n("Delete All","ai-engine"),DELETE_SELECTED:n("Delete Selected","ai-engine"),OPENAI_ORGANIZATION_ID:n("Organization ID","ai-engine"),OPENAI_AZURE_API_KEY:n("API Key","ai-engine"),OPENAI_AZURE_DEPLOYMENT_NAME:n("Deployment Name","ai-engine"),OPENAI_AZURE_DEPLOYMENTS:n("Deployments","ai-engine"),ENDPOINT:n("Endpoint","ai-engine"),HUGGINGFACE_MODELS:n("Models","ai-engine"),HUGGINGFACE_MODEL_NAME:n("Name","ai-engine"),HUGGINGFACE_MODEL_URL:n("API URL","ai-engine"),THEME:n("Theme","ai-engine"),THEMES:n("Themes","ai-engine"),BANNED_WORDS:n("Banned Words","ai-engine"),WORD_BOUNDARIES:n("Word Boundaries","ai-engine"),IGNORE:n("Ignore","ai-engine"),BANNED_IPS:n("Banned IPs","ai-engine"),SECURITY:n("Security","ai-engine"),POST_TYPES:n("Post Types","ai-engine"),COPY_BUTTON:n("Copy Button","ai-engine"),AI_AVATAR:n("AI Avatar","ai-engine"),GUEST_AVATAR:n("Guest Avatar","ai-engine"),SITE_WIDE_CHATBOT:n("Site-Wide Chatbot","ai-engine"),QUERIES_DATA:n("Queries Data","ai-engine"),QUERIES_FORMS_DATA:n("Queries Form Data","ai-engine"),WEBSPEECH_API:n("Web Speech API","ai-engine"),GDPR_CONSENT:n("GDPR Consent","ai-engine"),GDPR_TEXT:n("GDPR Text","ai-engine"),GDPR_BUTTON:n("GDPR Button","ai-engine"),FIX:n("Fix","ai-engine"),SPEECH_RECOGNITION:n("Speech Recognition","ai-engine"),SPEECH_SYNTHESIS:n("Speech Synthesis","ai-engine"),QUERIES:n("Queries","ai-engine"),LOCAL_MEMORY:n("Local Memory","ai-engine"),ACTIONS:n("Actions","ai-engine"),RESET:n("Reset","ai-engine"),INCIDENTS_OPENAI:n("Incidents (OpenAI)","ai-engine"),PREVIEW:n("Preview","ai-engine"),LEGACY_FORMS:n("Legacy Forms","ai-engine"),LEGACY_FEATURES:n("Legacy Features","ai-engine"),DUPLICATE:n("Duplicate","ai-engine"),CHATBOT_EDITOR:n("Chatbot Editor","ai-engine"),THEME_EDITOR:n("Theme Editor","ai-engine"),STREAMING:n("Streaming","ai-engine"),SYNTAX_HIGHLIGHT:n("Syntax Highlight","ai-engine"),EVENT_LOGS:n("Event Logs","ai-engine"),PRIVACY_FIRST:n("Privacy First","ai-engine"),DATA_NOT_AVAILABLE:n("Data not available.","ai-engine"),EXPORT:n("Export","ai-engine"),IMPORT:n("Import","ai-engine"),MODIFY_EMBEDDING:n("Modify Embedding","ai-engine"),ADD_EMBEDDING:n("Add Embedding","ai-engine"),DEV_TOOLS:n("Dev Tools","ai-engine"),SINGLE_GENERATE:n("Single Generate","ai-engine"),PUBLIC_API:n("Public API","ai-engine"),USER_INTERFACE:n("User Interface","ai-engine"),INTRO_MESSAGE:n("Intro Message","ai-engine"),ADDONS:n("Add-ons","ai-engine"),AI_ENVIRONMENT_DEFAULTS:n("Default Environments for AI","ai-engine"),ENVIRONMENTS_FOR_AI:n("Environments for AI","ai-engine"),ENVIRONMENT_ID:n("Environment ID","ai-engine"),EMBEDDINGS_ENVIRONMENT_DEFAULT:n("Default Embeddings Environment","ai-engine"),ENVIRONMENT:n("Environment","ai-engine"),PLUGIN_DATA:n("Plugin Data","ai-engine"),PLUGIN_DATA_DESCRIPTION:n("The database and all the options of the plugin will be removed on uninstall.","ai-engine"),RESET_LIMITS:n("Reset Limits","ai-engine"),VISION:n("Vision","ai-engine"),FILE_SEARCH:n("File Search","ai-engine"),PROMPT_TO_JSON:n("Prompt ➡ JSON","ai-engine"),RESOLUTION:n("Resolution","ai-engine"),DEFAULT:n("Default","ai-engine"),DEFAULTS:n("Defaults","ai-engine"),DEFAULT_FAST:n("Fast","ai-engine"),REFRESH_MODELS:n("Refresh Models","ai-engine"),AUDIO:n("Audio","ai-engine"),JSON:n("JSON","ai-engine"),AI_ENVIRONMENT:n("AI Environment","ai-engine"),OVERRIDE_DEFAULTS:n("Override Defaults","ai-engine"),REGION:n("Region","ai-engine"),PROJECT_ID:n("Project ID","ai-engine"),BEARER_TOKEN:n("Bearer Token","ai-engine"),DIMENSIONS:n("Dimensions","ai-engine"),EMBEDDINGS_MODEL:n("Embeddings Model","ai-engine"),MIN_SCORE:n("Min Score","ai-engine"),MAX_SELECT:n("Max Results","ai-engine"),QDRANT_COLLECTION:n("Collection","ai-engine"),INSTRUCTIONS:n("Instructions","ai-engine"),FUNCTIONS:n("Functions","ai-engine"),TOOLS:n("Tools","ai-engine"),WEB_SEARCH:n("Web Search","ai-engine"),IMAGE_GENERATION:n("Image Generation","ai-engine"),CODE_INTERPRETER:n("Code Interpreter","ai-engine"),HISTORY_STRATEGY:n("History Strategy","ai-engine"),AUTOMATIC:n("Automatic","ai-engine"),FULL_HISTORY:n("Full History","ai-engine"),INCREMENTAL:n("Incremental","ai-engine"),BUBBLE:n("Bubble","ai-engine"),TABS:n("Tabs","ai-engine"),DROPDOWN:n("Dropdown","ai-engine"),CHATBOT_SELECT:n("Chatbot Select","ai-engine"),CONDITIONS:n("Conditions","ai-engine"),CONDITION:n("Condition","ai-engine"),ADD_CONDITION:n("Add Condition","ai-engine"),REMOVE:n("Remove","ai-engine"),MCP_NO_OPTIONS:n("MCP is enabled but no options are selected. Please enable at least one option.","ai-engine"),ORCHESTRATION:n("Orchestration","ai-engine"),ORCHESTRATION_HELP:n("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:n("MCP Servers","ai-engine"),MCP_FUNCTIONS:n("MCP Functions","ai-engine"),URL:n("URL","ai-engine"),TOKEN:n("Token","ai-engine"),SERVER_ID:n("Server ID","ai-engine"),PRICE:n("Price","ai-engine"),UNITS:n("Units","ai-engine"),FAMILY:n("Family","ai-engine"),DAILY:n("Daily","ai-engine"),MONTHLY:n("Monthly","ai-engine"),UNKNOWN_MODEL:n("Unknown Model","ai-engine"),CONTEXTUAL:n("Contextual","ai-engine"),COMPLETION:n("Completion","ai-engine"),TOTAL_MAX_TOKENS:n("Total Max Tokens","ai-engine"),RECOMMENDED:n("Recommended","ai-engine"),SESSION:n("Session","ai-engine"),LAST_REQUEST:n("Last Request","ai-engine"),RESET_USAGE:n("Reset Usage","ai-engine"),COPIED:n("Copied!","ai-engine"),CLIPBOARD_ERROR:n("Clipboard is not enabled (only works with https).","ai-engine"),VIEW_IN_PLATFORM:n("View in OpenAI Platform","ai-engine")},r.FORMS={PROMPT_INFO:n("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:n("Output","ai-engine"),OUTPUT_ELEMENT:n("Output Element","ai-engine"),OUTPUT_ELEMENT_INFO:n("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")},r.HELP={TEMPERATURE:n("Between 0 and 1. Higher values means the model will take more risks.","ai-engine"),MAX_TOKENS:n("The maximum number of tokens to generate. The model will stop generating once it hits this limit.","ai-engine"),STOP_SEQUENCE:n("The sequence of tokens that will cause the model to stop generating text. You absolutely need this with fine-tuned models.","ai-engine"),COST:n("Keeps track of the current costs.","ai-engine"),RESOLVE_SHORTCODE:n("Will resolve the shortcode in your content when needed (Content-Aware will use this, for instance).","ai-engine"),FINETUNES:n("Train your own AI models.","ai-engine"),DISCUSSIONS:n("Keep the conversations and enable browsing them via the Conversations tab.","ai-engine"),DISCUSSION_TITLES:n("Generate titles for the discussions automatically with AI.","ai-engine"),DISCUSSION_SUMMARY:n("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:n("Add your deployments below and define what kind of model they are. GPT-5 models will automatically use the Responses API, while other models will use the Chat Completions API.","ai-engine"),BANNED_WORDS:n("Reject queries containing these words; separate with commas.","ai-engine"),WORD_BOUNDARIES:n("Ignore standard word separation (space) and match banned words anywhere in the text.","ai-engine"),BANNED_IPS:n("Block access from specified IP addresses or ranges using CIDR notation; separate with commas.","ai-engine"),GDPR_CONSENT:n("If enabled, the user will have to accept the conditions before using the chatbot.","ai-engine"),POST_TYPES:n("Enable for these post types; separate with commas.","ai-engine"),POST_STATUS:n("Enable for these post statuses (publish, draft, future, private, etc); separate with commas.","ai-engine"),POST_CATEGORIES:n("Enable for these categories (slugs); separate with commas. If none, it will be enabled for all.","ai-engine"),CONTEXT_MAX_LENGTH:n("Truncate the context (Content-Aware, Embeddings, etc) to make sure it is below this number of characters.","ai-engine"),MAX_MESSAGES:n("Maximum number of historical messages that is sent to the AI model.","ai-engine"),INPUT_MAX_LENGTH:n("Maximum number of characters that can be input by the user.","ai-engine"),STATISTICS:n(" 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:n("Record the queries and their replies.","ai-engine"),QUERIES_FORMS_DATA:n("Capture form data neatly for simple reuse.","ai-engine"),SPEECH_RECOGNITION:n("Enable speech-to-text. Depends on the browser and OS used by the user.","ai-engine"),SPEECH_SYNTHESIS:n("Enable text-to-speech.","ai-engine"),CUSTOM_SHORTCODE:n("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:n("Type an User ID, or an IP.","ai-engine"),STREAMING:n("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:n("Enable syntax highlighting for the code blocks.","ai-engine"),EVENT_LOGS:n("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:n("Only essential data is stored. IPs, conversations, and other private details are minimized and kept as anonymous as possible.","ai-engine"),DEV_TOOLS:n("Enable a new tab with debugging tools. For developers only.","ai-engine"),DEV_MODE:n("Run tasks very frequently for debugging.","ai-engine"),PUBLIC_API:n("Enable the Public REST API.","ai-engine"),INTRO_MESSAGE:n("Enable introduction messages on some modules.","ai-engine"),ADDONS:n("Enable the AI Addons section under the Meow Apps menu.","ai-engine"),OPENAI_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),OPENAI_API_KEY_URL:"https://platform.openai.com/api-keys",OPENAI_API_KEY_LINK_TEXT:n("OpenAI Account ↗","ai-engine"),OPENAI_ORGANIZATION_ID:n("You can link this environment to an %s. This is optional.","ai-engine"),OPENAI_ORGANIZATION_URL:"https://platform.openai.com/account/organization",OPENAI_ORGANIZATION_LINK_TEXT:n("Organization ↗","ai-engine"),AZURE_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),AZURE_API_KEY_URL:"https://oai.azure.com/portal",AZURE_API_KEY_LINK_TEXT:n("Azure Account ↗","ai-engine"),AZURE_ENDPOINT:n("Enter just your Azure resource domain (e.g., <code>myresource.openai.azure.com</code>). AI Engine will automatically construct the appropriate API endpoint based on the model type.","ai-engine"),ANTHROPIC_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),ANTHROPIC_API_KEY_URL:"https://console.anthropic.com/settings/keys",ANTHROPIC_API_KEY_LINK_TEXT:n("Anthropic Account ↗","ai-engine"),OPENROUTER_API_KEY:n("You can get your API Keys in your %s.","ai-engine"),OPENROUTER_API_KEY_URL:"https://openrouter.ai/keys",OPENROUTER_API_KEY_LINK_TEXT:n("OpenRouter Account ↗","ai-engine"),QDRANT:n("Use the code <b>#AIENGINE5</b> when you %s. You will get 5% off.","ai-engine"),QDRANT_URL:"https://qdrant.to/cloud",QDRANT_LINK_TEXT:n("Create a Qdrant Account ↗","ai-engine"),ASSISTANTS:n("The Assistants API is designed to help developers build powerful AI assistants capable of performing a variety of tasks.","ai-engine"),ASSISTANTS_INTRO:n("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 %s 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_INTRO_URL:"https://beta.openai.com/assistants",ASSISTANTS_INTRO_LINK_TEXT:n("OpenAI Assistants ↗","ai-engine"),ASSISTANTS_WARNINGS:n("Assistants are also %1$s, both for OpenAI and AI Engine. OpenAI did not add streaming support for them yet. Pricing is still quite unclear and %2$s. AI Engine can only perform an estimation. If you want to discuss assistants with other users, visit the %3$s.","ai-engine"),ASSISTANTS_BETA_URL:"https://platform.openai.com/docs/api-reference/assistants",ASSISTANTS_BETA_TEXT:n("in beta ↗","ai-engine"),ASSISTANTS_PRICING_URL:"https://openai.com/pricing",ASSISTANTS_PRICING_TEXT:n("tricky ↗","ai-engine"),ASSISTANTS_DISCORD_URL:"https://discord.gg/bHDGh38",ASSISTANTS_DISCORD_TEXT:n("Meow Apps Discord Server ↗","ai-engine"),BEARER_TOKEN:n("The Public API will be usable by using this Bearer Token. If not set, you will need to %s by using the <i>mwai_allow_public_api</i> filter.","ai-engine"),BEARER_TOKEN_URL:"https://meowapps.com/ai-engine/api/#public-rest-api",BEARER_TOKEN_LINK_TEXT:n("build your own authentication ↗","ai-engine"),REST_API_INTRO:n("The REST API enables integration with automation platforms and external applications. Use it with %s, n8n, Zapier, or any platform that supports REST APIs to automate AI workflows and connect your WordPress site with other services.","ai-engine"),REST_API_MAKE_URL:"https://www.make.com/en/integrations/ai-engine",REST_API_MAKE_TEXT:n("Make.com ↗","ai-engine"),MCP_BEARER_TOKEN:n("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:n("Enabling the SSE Endpoint creates a Model Context Protocol (MCP) server that provides various tools depending on the options selected below. %s. 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_TUTORIAL_URL:"https://meowapps.com/claude-wordpress-mcp/",MCP_TUTORIAL_TEXT:n("This tutorial is highly recommended ↗","ai-engine"),MCP_SERVER_URL:n("The URL of the MCP server. Must start with https://","ai-engine"),MCP_SERVER_TOKEN:n("Bearer token for authenticating with the MCP server.","ai-engine"),NO_EMBEDDINGS_RESULTS:n("No results for this search. Make sure the Minimum Score is not too high.","ai-engine"),NO_EMBEDDINGS_ROWS:n("No embeddings yet in this environment.","ai-engine"),MIN_SCORE:n("The minimum score the embeddings need to have to be returned. Between 0 and 100 and defaults to 35.","ai-engine"),MAX_SELECT:n("The maximum number of embeddings to return and to use as context. Between 1 and 100 and defaults to 10.","ai-engine"),FUNCTIONS:n("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:n("There are no functions available. Please use %s to add some. The Pro Version of AI Engine is also required for this feature.","ai-engine"),FUNCTIONS_CODE_ENGINE_URL:"https://wordpress.org/plugins/code-engine/",FUNCTIONS_CODE_ENGINE_TEXT:n("Code Engine ↗","ai-engine"),MCP_SERVERS:n("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:n("No MCP servers are available. Configure them in Settings > Orchestration.","ai-engine"),TOOLS:n("Enable AI tools to enhance your chatbot capabilities. Web Search and Image Generation work with OpenAI and Google. Code Interpreter is OpenAI-only.","ai-engine"),WEB_SEARCH:n("Allow the AI to search the web for current information","ai-engine"),IMAGE_GENERATION:n("Allow the AI to generate images based on text descriptions","ai-engine"),CODE_INTERPRETER:n("Allow the AI to write and run Python code to solve complex problems, process data, and generate visualizations","ai-engine"),HISTORY_STRATEGY:n("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:n("In your Dashboard will be displayed daily recommendations tailored to your WordPress setup. Admins only.","ai-engine"),BUBBLE:n("The popup will be displayed as a bubble.","ai-engine"),ICON_TEXT:n("If set, this text will appear next to the icon/bubble.","ai-engine"),ICON_TEXT_DELAY:n("Delay before text appears.","ai-engine"),WIDTH:n("Width of the chatbot when open.","ai-engine"),OPEN_DELAY:n("Auto-open after X seconds.","ai-engine"),CHATBOT_SELECT:n("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")},r.SETTINGS={AI_ENV_SETUP:n('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 %s website. Once obtained, navigate to the <b>Settings</b> tab and input your OpenAI API Key in the "Environments for AI" section.',"ai-engine"),AI_ENV_SETUP_URL:"https://platform.openai.com/api-keys",AI_ENV_SETUP_LINK_TEXT:n("OpenAI ↗","ai-engine"),PINECONE_SETUP:n("You choose to use Embeddings. To use them, you need to a Pinecone account. Visit the %s website to create an account, then insert your Pinecone API Key in the <b>Settings</b> tab.","ai-engine"),PINECONE_SETUP_URL:"https://app.pinecone.io",PINECONE_SETUP_LINK_TEXT:n("Pinecone ↗","ai-engine"),INTRO:n("Boost your WordPress with AI, now! Please start with our %1$s. Then move to our %2$s. Have a look at our %3$s. And make sure you read the %4$s. Have fun! 🎵","ai-engine"),INTRO_TUTORIAL_URL:"https://meowapps.com/ai-engine/tutorial/",INTRO_TUTORIAL_TEXT:n("tutorial ↗","ai-engine"),INTRO_DOCS_URL:"https://ai.thehiddendocs.com/",INTRO_DOCS_TEXT:n("documentation ↗","ai-engine"),INTRO_ADDONS_URL:"https://meowapps.com/products/category/ai-add-ons/",INTRO_ADDONS_TEXT:n("add-ons ↗","ai-engine"),INTRO_DISCLAIMER_URL:"https://meowapps.com/ai-engine/disclaimer/",INTRO_DISCLAIMER_TEXT:n("disclaimer ↗","ai-engine"),MODULES_INTRO:n("To avoid cluttering the UI and your WP, only enable the features you need.","ai-engine"),ALERT_INJECT_BUT_NO_POPUP:n("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:n("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:n("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 %s.","ai-engine"),ALERT_CONTENTAWARE_URL:"https://meowapps.com/ai-engine/tutorial/#contextualization",ALERT_CONTENTAWARE_LINK_TEXT:n("here ↗","ai-engine"),SET_AS_DEFAULT_PARAMETERS:n("Set as Default Parameters","ai-engine"),SET_AS_DEFAULT_PARAMETERS_HELP:n("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:n("Inject Default Chatbot in Entire Website","ai-engine"),INJECT_DEFAULT_CHATBOT_HELP:n("Inject the chatbot [mwai_chat] in the entire website.","ai-engine"),CHATGPT_STYLE_INTRO:n("Keep in mind that you can also style the chatbot (or a specific chatbot, if you use many) by injecting CSS. Have a look %1$s. More information in the %2$s.","ai-engine"),CHATGPT_STYLE_CSS_URL:"https://meowapps.com/ai-engine/tutorial/#apply-custom-style-to-the-chatbot",CHATGPT_STYLE_CSS_TEXT:n("here ↗","ai-engine"),CHATGPT_STYLE_FAQ_URL:"https://meowapps.com/ai-engine/faq",CHATGPT_STYLE_FAQ_TEXT:n("FAQ ↗","ai-engine"),TYPEWRITER_EFFECT:n("Typewriter Effect","ai-engine"),TYPEWRITER_EFFECT_HELP:n("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:n("If the conversation seems offensive, the chatbot will reject it.","ai-engine"),CUSTOM_URL:n("Custom URL","ai-engine"),ASSISTANT_NO_FILE_SEARCH:n("This assistant does not support File Search. You can activate it on the %s dashboard. Then, use the Refresh button in the Assistants tab.","ai-engine"),ASSISTANT_NO_FILE_SEARCH_URL:"https://platform.openai.com/assistants",ASSISTANT_NO_FILE_SEARCH_LINK_TEXT:n("OpenAI Assistants ↗","ai-engine"),ASSISTANT_FILE_SEARCH:n("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:n("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:n("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:n("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 %1$s 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 %2$s.</b>","ai-engine"),KNOWLEDGE_PINECONE_URL:"https://www.pinecone.io/",KNOWLEDGE_PINECONE_TEXT:n("Pinecone ↗","ai-engine"),KNOWLEDGE_DISCORD_URL:"https://discord.gg/bHDGh38",KNOWLEDGE_DISCORD_TEXT:n("Meow Apps Discord Server ↗","ai-engine"),ORCHESTRATION_INFO:n("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")},r.CHATBOT={CHATBOT_BUILDER:n("Chatbot Builder","ai-engine"),RESET_PARAMS:n("Reset Parameters","ai-engine")},r.STATISTICS={ABSOLUTE_HELP:n("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:n("Message for No Credits","ai-engine"),FULL_ACCESS_USERS:n("Full-Access Users","ai-engine"),ENABLE_LIMITS:n("Enable Limits","ai-engine")},r.CONTENT_GENERATOR={INTRO:n("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:n("Title is missing!","ai-engine"),SECTIONS_MISSING:n("Sections are missing!","ai-engine"),SINGLE_GENERATE:n("Single Generate","ai-engine"),BULK_GENERATE:n("Bulk Generate","ai-engine"),CONTENT_PARAMS:n("Content Params","ai-engine"),POST_PARAMS:n("Post Params","ai-engine"),CONTENT_PARAMS_INTRO:n("Input fields are displayed for certain placeholders used in prompts, such as {LANGUAGE} or {WRITING_TONE}","ai-engine"),CUSTOM_LANGUAGE:n("Custom Language","ai-engine"),WRITING_STYLE:n("Writing Style","ai-engine"),WRITING_TONE:n("Writing Tone","ai-engine"),CUSTOM_LANGUAGE_HELP:n("AI supports all languages with varying quality. %s.","ai-engine"),CUSTOM_LANGUAGE_URL:"https://meowapps.com/ai-engine/faq/#languages",CUSTOM_LANGUAGE_LINK_TEXT:n("Learn more ↗","ai-engine"),MODEL_HELP:n("It is recommended to use Turbo or GPT-4 to write texts.","ai-engine"),PROMPTS_INTRO:n("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:n("Prompt for <b>Title</b>","ai-engine"),PROMPT_SECTIONS:n("Prompt for <b>Sections</b>","ai-engine"),PROMPT_CONTENT:n("Prompt for <b>Content</b>","ai-engine"),PROMPT_EXCERPT:n("Prompt for <b>Excerpt</b>","ai-engine"),POST_CREATED:n("Post Created","ai-engine"),POST_CREATED_AS_DRAFT:n("The post was created as a draft.","ai-engine"),CONTENT_HELP:n('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:n('Add, rewrite, remove, or reorganize those sections as you wish before (re)clicking on "Generate Content". Markdown format is recommended.',"ai-engine"),GENERATE_EXCERPT:n("Generate Excerpt","ai-engine"),GENERATE_CONTENT:n("Generate Content","ai-engine"),GENERATE_SECTIONS:n("Generate Sections","ai-engine"),PARAGRAPHS_PER_SECTION:n("# of Paragraphs per Section","ai-engine"),NUMBER_OF_SECTIONS:n("# of Sections","ai-engine"),ADVICE:n("Advice","ai-engine"),SECTIONS:n("Sections","ai-engine"),USE_MAX_TOKENS:n("Use Max Tokens","ai-engine"),TOPICS_HELP:n("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:n("Generated Posts","ai-engine"),USE_TOPICS_AS_TITLES:n("Use Topics as Titles","ai-engine"),NOTHING_YET:n("Nothing yet.","ai-engine"),BULK_ERROR_CONFIRM:n("An error was caught ({MESSAGE}). Should we continue?","ai-engine"),GENERATE_ALL:n("Generate All","ai-engine"),EDIT_POST:n("Edit Post","ai-engine"),CREATE_POST:n("Create Post","ai-engine"),TITLE_TOO_SHORT:n("The title is too short. It should be at least 3 words.","ai-engine"),TITLE_TOO_SHORT_2:n("The title is too short. It should be at least 40 characters.","ai-engine"),TITLE_TOO_LONG:n("The title is too long. It should be less than 8 words.","ai-engine"),TITLE_TOO_LONG_2:n("The title is too long. It should be less than 70 characters.","ai-engine")},r.TEMPLATES={TEMPLATE:n("Template","ai-engine"),TEMPLATES:n("Templates","ai-engine"),DELETE_CONFIRM:n("Are you sure you want to delete this template?","ai-engine"),DELETE_ALL_CONFIRM:n("Are you sure you want to delete all the templates?","ai-engine"),NEW_TEMPLATE_NAME:n("New Template","ai-engine"),EDIT:n("EDIT","ai-engine")},r.PLAYGROUND={INTRO:n("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:n("Query / Prompt","ai-engine"),REPLY:n("Reply","ai-engine")},r.ALERTS={FINETUNING_STARTED:n("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:n("This will delete all the rows in the builder. Are you sure?","ai-engine"),DELETE_FINETUNE:n("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:n("This fine-tune was already deleted. It will be removed from the list.","ai-engine"),CHECK_CONSOLE:n("Error! Check your console for more details.","ai-engine"),DATASET_UPLOADED:n("Uploaded successfully! You can now train a model based on this dataset.","ai-engine"),ONLY_SUPPORTS_FILES:n("This only supports JSON, JSONL, and CSV files. Check the Instructions section below.","ai-engine"),EMPTY_LINES_DATASET:n("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:n("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:n("Are you sure?","ai-engine")},r.FINETUNING={MODELS_INTRO:n("The AI models you have fine-tuned. To create more, visit <b>Files</b>.","ai-engine"),LEGACY_MODELS_INTRO:n("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 %s for January 4th, 2024.</b><br />","ai-engine"),LEGACY_MODELS_DEPRECATION_URL:"https://platform.openai.com/docs/guides/legacy-fine-tuning",LEGACY_MODELS_DEPRECATION_TEXT:n("announced by OpenAI ↗","ai-engine"),FILES_INTRO:n("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:n("Model Finetune","ai-engine"),MODELS_FILES:n("Models & Files","ai-engine"),DATASET_EDITOR:n("Dataset Editor","ai-engine"),EDITOR:n("Editor","ai-engine"),GENERATOR:n("Generator","ai-engine"),HUGE_DATASET_WARNING:n("Caution: The data is too large to be saved in your browser's local storage.","ai-engine"),NO_FINETUNES_YET:n("No fine-tunes found. Refresh the list, or create a new one (via a dataset).","ai-engine"),CLEAN_MODELS_LIST:n("Clean Models List","ai-engine"),DELETED_FINETUNE_ISSUE:n("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")},r.DISCUSSIONS={NEW_CHAT:n("New Chat","ai-engine"),NO_MESSAGES_YET:n("No messages yet","ai-engine"),RENAME:n("Rename","ai-engine"),DELETE:n("Delete","ai-engine"),UNTITLED:n("Untitled","ai-engine"),TITLE_GENERATION_PROMPT:n("Based on the following conversation, generate a concise and specific title for the discussion, strictly less than 64 characters. Focus on the main topic, avoiding unnecessary words such as articles, pronouns, or adjectives. Do not include any punctuation at the end. Do not include anything else than the title itself, only one sentence, no line breaks, just the title.","ai-engine")},r.WRITING_STYLES={INFORMATIVE:n("Informative","ai-engine"),DESCRIPTIVE:n("Descriptive","ai-engine"),CREATIVE:n("Creative","ai-engine"),NARRATIVE:n("Narrative","ai-engine"),PERSUASIVE:n("Persuasive","ai-engine"),REFLECTIVE:n("Reflective","ai-engine"),ARGUMENTATIVE:n("Argumentative","ai-engine"),ANALYTICAL:n("Analytical","ai-engine"),EVALUATIVE:n("Evaluative","ai-engine"),JOURNALISTIC:n("Journalistic","ai-engine"),TECHNICAL:n("Technical","ai-engine")},r.WRITING_TONES={NEUTRAL:n("Neutral","ai-engine"),FORMAL:n("Formal","ai-engine"),ASSERTIVE:n("Assertive","ai-engine"),CHEERFUL:n("Cheerful","ai-engine"),HUMOROUS:n("Humorous","ai-engine"),INFORMAL:n("Informal","ai-engine"),INSPIRATIONAL:n("Inspirational","ai-engine"),PROFESSIONAL:n("Professional","ai-engine"),CONFLUENT:n("Confluent","ai-engine"),EMOTIONAL:n("Emotional","ai-engine"),PERSUASIVE:n("Persuasive","ai-engine"),SUPPORTIVE:n("Supportive","ai-engine"),SARCASTIC:n("Sarcastic","ai-engine"),CONDESCENDING:n("Condescending","ai-engine"),SKEPTICAL:n("Skeptical","ai-engine"),NARRATIVE:n("Narrative","ai-engine"),JOURNALISTIC:n("Journalistic","ai-engine")},r.EMBEDDINGS={EDIT:n("EDIT","ai-engine"),AI_SEARCH:n("AI SEARCH","ai-engine"),SYNC_POSTS:n("Sync Posts","ai-engine"),AUTO_SYNC_POSTS:n("Auto-Sync Posts","ai-engine"),AUTO_SYNC_POSTS_DESCRIPTION:n("Embeddings will be created, updated or removed based on the activity related to your posts.","ai-engine"),REWRITE_CONTENT:n("Rewrite Content","ai-engine"),REWRITE_CONTENT_DESCRIPTION:n("Shorten and improve the content for your embedding using the default model.","ai-engine"),FORCE_RECREATE:n("Force Recreate","ai-engine"),FORCE_RECREATE_DESCRIPTION:n("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:n("Delete All Embeddings","ai-engine"),DELETE_ALL_EMBEDDINGS_CONFIRM:n("Are you sure you want to delete all the embeddings in this environment?","ai-engine"),REWRITE_PROMPT_DESCRIPTION:n("Prompt for the rewrite. Supports {CONTENT}, {TITLE}, {URL}, {EXCERPT}, {LANGUAGE}, {ID}.","ai-engine"),SYNC_ALL:n("Sync All","ai-engine"),SYNC_ONE:n("Sync One","ai-engine"),ADD_INDEX:n("Add Index","ai-engine"),ADD_INDEX_DESCRIPTION:n("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:n("Note: This server does not support namespaces.","ai-engine")},r.ERROR={UPDATING_OPTIONS:n("An error occurred while updating the options."),GETTING_OPTIONS:n("An error occurred while getting the options."),CHECK_YOUR_CONSOLE:n('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"),SESSION_EXPIRED:n("Your session has expired. Please refresh the page to continue using AI Engine.","ai-engine"),COULD_NOT_PARSE_ERROR_STREAM:n("Could not parse the 'error' stream.","ai-engine"),COULD_NOT_PARSE_END_STREAM:n("Could not parse the 'end' stream.","ai-engine"),INVALID_API_KEY:n("Invalid API key: Please check your OpenAI API key in settings.","ai-engine"),RATE_LIMIT_EXCEEDED:n("Rate limit exceeded: Too many requests. Please try again later.","ai-engine"),NETWORK_ERROR:n("Network error: Failed to establish connection to the AI service.","ai-engine"),AUTHENTICATION_FAILED:n("Authentication failed: Your session has expired. Please refresh the page.","ai-engine"),INTERNAL_SERVER_ERROR:n("Internal server error: An unexpected error occurred. Please try again.","ai-engine"),PROCESSING_ERROR:n("An error occurred while processing your request. Please try again.","ai-engine"),MEDIADEVICES_NOT_AVAILABLE:n("MediaDevices API not available. Please ensure you are using HTTPS and a modern browser.","ai-engine"),MICROPHONE_ACCESS_FAILED:n("Failed to access microphone. Please ensure microphone permissions are granted and try again.","ai-engine"),CONNECTION_FAILED:n("Failed to establish connection with OpenAI servers. Please try again.","ai-engine")},r.DEBUG={CRASH_IN_MARKDOWN:n("Crash in markdown-to-jsx! Reverting to plain text.","ai-engine"),AI_ENGINE_COULD_NOT_FIND_BLOCK:n("AI Engine: Could not find block element for","ai-engine"),AI_WAND_TABLE_REQUIRES_DATA:n("AI Wand: Table requires structured data for proper update","ai-engine"),AI_WAND_COULD_NOT_FIND_SELECTION:n("AI Wand: Could not find selection, replacing entire block content","ai-engine"),NEW_TOKEN_RECEIVED:n("[MWAI] 🔐 New token received","ai-engine"),NONCE_ERROR_DETECTED:n("[MWAI] Nonce error detected, attempting to refresh...","ai-engine")};const o=r},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,__=e=>"undefined"!=typeof wp&&wp.i18n&&wp.i18n.__?wp.i18n.__(e,"ai-engine"):e,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},clamp01=e=>Math.min(1,Math.max(0,e)),hexToRgb=e=>{if(!e||"string"!=typeof e)return null;const t=e.replace("#","").trim(),a=3===t.length?t.split("").map((e=>e+e)).join(""):t,n=parseInt(a,16);return Number.isNaN(n)||6!==a.length?null:{r:n>>16&255,g:n>>8&255,b:255&n}},rgbToHsl=({r:e,g:t,b:a})=>{e/=255,t/=255,a/=255;const n=Math.max(e,t,a),l=Math.min(e,t,a);let r=0,o=0,i=(n+l)/2;if(n!==l){const s=n-l;switch(o=i>.5?s/(2-n-l):s/(n+l),n){case e:r=(t-a)/s+(t<a?6:0);break;case t:r=(a-e)/s+2;break;case a:r=(e-t)/s+4}r/=6}return{h:r,s:o,l:i}},hslToRgb=({h:e,s:t,l:a})=>{const n=(e,t,a)=>(a<0&&(a+=1),a>1&&(a-=1),a<1/6?e+6*(t-e)*a:a<.5?t:a<2/3?e+(t-e)*(2/3-a)*6:e);let l,r,o;if(0===t)l=r=o=a;else{const i=a<.5?a*(1+t):a+t-a*t,s=2*a-i;l=n(s,i,e+1/3),r=n(s,i,e),o=n(s,i,e-1/3)}return{r:Math.round(255*l),g:Math.round(255*r),b:Math.round(255*o)}},rgbToHex=({r:e,g:t,b:a})=>`#${[e,t,a].map((e=>e.toString(16).padStart(2,"0"))).join("")}`,lightenHex=(e,t=.4)=>{const a=hexToRgb(e);if(!a)return e;const n=rgbToHsl(a);return n.l=clamp01(n.l+(1-n.l)*t),n.s=clamp01(1.05*n.s),rgbToHex(hslToRgb(n))},gradientFromBase=(e,t=.55)=>`linear-gradient(130deg, ${e} 0%, ${lightenHex(e,t)} 100%)`,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}),[uploadedFiles,setUploadedFiles]=useState([]),[windowed,setWindowed]=useState((()=>{const e=Boolean(params.window),t=Boolean(params.fullscreen);return e||!t})),[open,setOpen]=useState(!1),[opening,setOpening]=useState(!1),[closing,setClosing]=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),[containerType,setContainerType]=useState(params.containerType),[headerType,setHeaderType]=useState(params.headerType),[messagesType,setMessagesType]=useState(params.messagesType||"standard"),[inputType,setInputType]=useState(params.inputType||"standard"),[footerType,setFooterType]=useState(params.footerType);useEffect((()=>{setContainerType(params.containerType),setHeaderType(params.headerType),setMessagesType(params.messagesType||"standard"),setInputType(params.inputType||"standard"),setFooterType(params.footerType)}),[params.containerType,params.headerType,params.messagesType,params.inputType,params.footerType]);const{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,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,popupTitle,fullscreen,localMemory:localMemoryParam,icon,iconText,iconTextDelay,iconAlt,iconPosition,centerOpen,width,openDelay,iconBubble,imageUpload,fileUpload,multiUpload,fileSearch,windowAnimation}=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);let r=Object.keys(shortcodeStyles).reduce(((e,t)=>(e[`--mwai-${t}`]=shortcodeStyles[t],e)),{});if(null!=shortcodeStyles&&shortcodeStyles.iconTextBackgroundColor||null==shortcodeStyles||!shortcodeStyles.avatarMessageBackgroundColor||(r["--mwai-iconTextBackgroundColor"]=shortcodeStyles.avatarMessageBackgroundColor),null!=shortcodeStyles&&shortcodeStyles.iconTextColor||null==shortcodeStyles||!shortcodeStyles.avatarMessageFontColor||(r["--mwai-iconTextColor"]=shortcodeStyles.avatarMessageFontColor),"timeless"===(null==theme?void 0:theme.themeId)&&null!=shortcodeStyles&&shortcodeStyles.backgroundHeaderColor){const e=shortcodeStyles.backgroundHeaderColor;"string"==typeof e&&e.trim().startsWith("#")&&(r["--mwai-backgroundHeaderColor"]=gradientFromBase(e,.55),r["--mwai-accentColor"]=e)}if("timeless"===(null==theme?void 0:theme.themeId)&&null!=shortcodeStyles&&shortcodeStyles.backgroundUserColor){const e=shortcodeStyles.backgroundUserColor;"string"==typeof e&&e.trim().startsWith("#")&&(r["--mwai-backgroundUserColor"]=gradientFromBase(e,.16))}return{cssVariables:r,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((()=>{const e="timeless"===(null==theme?void 0:theme.themeId);return{text:textSend,textSend,textClear,imageSend:null,imageClear:null,useLucide:e,lucideSend:"send-horizontal"}}),[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(),key:`start-${Date.now()}`}];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||eventLogs)&&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=multiUpload?uploadedFiles:[],l=null==uploadedFile?void 0:uploadedFile.uploadedUrl,r=null==uploadedFile||null===(t=uploadedFile.localFile)||void 0===t?void 0:t.type,o=!!r&&r.startsWith("image");let i=e;if(multiUpload&&n.length>0){i=`${n.map((e=>{var t;const a=null===(t=e.localFile)||void 0===t?void 0:t.type;return!!a&&a.startsWith("image")?``:`[${(null===(n=e.localFile)||void 0===n?void 0:n.name)||"Uploaded File"}](${e.uploadedUrl})`;var n})).join("\n")}\n${e}`}else l&&(i=o?`\n${e}`:`[Uploaded File](${l})\n${e}`);setBusy(!0),setInputText(""),setShortcuts([]),setBlocks([]),resetUploadedFile(),multiUpload&&resetUploadedFiles();const s=[...messages,{id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"user",content:i,who:rawUserName,timestamp:(new Date).getTime()}];saveMessages(s);const c=(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),d=[...s,{id:c,role:"assistant",content:stream?"":null,who:rawAiName,timestamp:null,isQuerying:!stream,isStreaming:!!stream,streamEvents:stream&&(debugMode||eventLogs)?[]:void 0}];if(setMessages(d),"[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=[...s,r];return setMessages(o),saveMessages(o),void setLastFailedQuery({text:e,file:a})}const m={botId,customId,session:sessionId,chatId,contextId,messages:messages.filter((e=>"error"!==e.role&&!e.isError)),newMessage:e,newFileId:multiUpload?null:null==a?void 0:a.uploadedId,newFileIds:multiUpload?n.map((e=>e.uploadedId)).filter((e=>e)):null,stream,...atts};previousResponseId&&(m.previousResponseId=previousResponseId);try{debugMode&&console.log("[CHATBOT] OUT: ",m);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||eventLogs)&&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`,m,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=[...d];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"===d[t].role){const e=d[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})},addUploadedFile=e=>{setUploadedFiles((t=>[...t,e]))},removeUploadedFile=e=>{setUploadedFiles((t=>t.filter(((t,a)=>a!==e))))},resetUploadedFiles=()=>{setUploadedFiles([])},onMultiFileUpload=async(e,t="N/A",a="N/A")=>{try{if(null===e)return;const n={type:t,purpose:a},l=`${restUrl}/mwai-ui/v1/files/upload`,r={localFile:e,uploadedId:null,uploadedUrl:null,uploadProgress:0,tempId:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)()};addUploadedFile(r);const o=uploadedFiles.length,i=restNonceRef.current??await refreshRestNonce(),s=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.uE)(l,e,i,(e=>{setUploadedFiles((t=>t.map(((t,a)=>a===o?{...t,uploadProgress:e}:t))))}),n);setUploadedFiles((t=>t.map(((t,a)=>a===o?{localFile:e,uploadedId:s.data.id,uploadedUrl:s.data.url,uploadProgress:null,tempId:t.tempId}:t))))}catch(e){console.error("onMultiFileUpload Error",e),addErrorMessage(e.message||"An unknown error occurred"),setUploadedFiles((e=>e.filter(((e,t)=>t!==uploadedFiles.length))))}},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 updateComponentConfig=e=>{void 0!==e.containerType&&setContainerType(e.containerType),void 0!==e.headerType&&setHeaderType(e.headerType),void 0!==e.contentType&&setContentType(e.contentType),void 0!==e.footerType&&setFooterType(e.footerType)},actions={setInputText,saveMessages,setMessages,resetMessages,setError,resetError,addErrorMessage,retryLastQuery,onClear,onSubmit,onSubmitAction,onFileUpload,onUploadFile,resetUploadedFile,setUploadedFile,onMultiFileUpload,addUploadedFile,removeUploadedFile,resetUploadedFiles,setUploadedFiles,setOpen,setOpening,setClosing,setWindowed,setShowIconMessage,setIsListening,setDraggingType,setIsBlocked,onStartRealtimeSession,onRealtimeFunctionCallback,onCommitStats,onCommitDiscussions,updateComponentConfig},state={theme,botId,customId,userData,pluginUrl,inputText,messages,shortcuts,blocks,busy,error,setBusy,typewriter,speechRecognition,speechSynthesis,localMemory,isRealtime,imageUpload,fileUpload,multiUpload,uploadedFile,uploadedFiles,fileSearch,textSend,textClear,textInputMaxLength,textInputPlaceholder,textCompliance,aiName,userName,guestName,aiAvatar,userAvatar,guestAvatar,aiAvatarUrl,userAvatarUrl,guestAvatarUrl,isWindow,copyButton,headerSubtitle,popupTitle,fullscreen,icon,iconText,iconAlt,iconPosition,centerOpen,width,openDelay,iconBubble,windowAnimation,cssVariables,iconUrl,chatbotInputRef,conversationRef,isMobile,open,opening,closing,locked,windowed,showIconMessage,timeElapsed,isListening,speechRecognitionAvailable,uploadIconPosition,submitButtonConf,draggingType,isBlocked,busyNonce,debugMode,eventLogs,system,containerType,headerType,messagesType,inputType,footerType};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)}))}clearCookies(){document.cookie="mwai_gdpr_accepted=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";document.cookie.split(";").forEach((e=>{const[t]=e.trim().split("=");t.startsWith("mwai_")&&(document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`)}))}}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,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:s,useCallback:c}=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=s(null);function n(e){return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`}return i((()=>()=>{clearInterval(a.current)}),[]),{timeElapsed:e,startChrono:function(){if(null!==a.current)return;const e=Date.now();t(n(0)),a.current=setInterval((()=>{const a=Math.floor((Date.now()-e)/1e3);t(n(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,s,c,d,m,u,p,g,h,R,y,v;const b=(null===(a=e.guestName)||void 0===a?void 0:a.trim())??"",f=(null===(n=e.textSend)||void 0===n?void 0:n.trim())??"",w=(null===(l=e.textClear)||void 0===l?void 0:l.trim())??"",_=parseInt(e.textInputMaxLength),C=(null===(r=e.textInputPlaceholder)||void 0===r?void 0:r.trim())??"";let T=(null===(o=e.textCompliance)||void 0===o?void 0:o.trim())??"",A="",N="";const O=Boolean(e.window),I=Boolean(e.copyButton),S=Boolean(e.fullscreen),M=(null===(i=e.icon)||void 0===i?void 0:i.trim())??"";let k=(null===(s=e.iconText)||void 0===s?void 0:s.trim())??"";const x=parseInt(e.iconTextDelay||1),P=(null===(c=e.iconAlt)||void 0===c?void 0:c.trim())??"",L=(null===(d=e.iconPosition)||void 0===d?void 0:d.trim())??"",D=Boolean(e.centerOpen),F=(null===(m=e.width)||void 0===m?void 0:m.trim())??"",U=e.openDelay?parseInt(e.openDelay):null,B=Boolean(e.iconBubble),H=(null===(u=e.windowAnimation)||void 0===u?void 0:u.trim())??"zoom",j=(null===(p=e.aiName)||void 0===p?void 0:p.trim())??"",G=(null===(g=e.userName)||void 0===g?void 0:g.trim())??"",$=Boolean(null==e?void 0:e.aiAvatar),W=Boolean(null==e?void 0:e.userAvatar),z=Boolean(null==e?void 0:e.guestAvatar),V=$?(null==e||null===(h=e.aiAvatarUrl)||void 0===h?void 0:h.trim())??"":null,q=W?(null==e||null===(R=e.userAvatarUrl)||void 0===R?void 0:R.trim())??"":null,K=z?(null==e||null===(y=e.guestAvatarUrl)||void 0===y?void 0:y.trim())??"":null,Y=Boolean(e.localMemory),X=Boolean(e.imageUpload),Q=Boolean(e.fileUpload),J=Boolean(e.multiUpload),Z=Boolean(e.fileSearch),ee=(null===(v=e.mode)||void 0===v?void 0:v.trim())??"chat";var te,ae;null===e.headerSubtitle||void 0===e.headerSubtitle?A="Discuss with":A=(null===(te=e.headerSubtitle)||void 0===te?void 0:te.trim())??"";null===e.popupTitle||void 0===e.popupTitle?N="AI Engine":N=(null===(ae=e.popupTitle)||void 0===ae?void 0:ae.trim())??"";return t&&(T=E(T,t),k=E(k,t)),{textSend:f,textClear:w,textInputMaxLength:_,textInputPlaceholder:C,textCompliance:T,mode:ee,window:O,copyButton:I,fullscreen:S,localMemory:Y,imageUpload:X,fileUpload:Q,multiUpload:J,fileSearch:Z,icon:M,iconText:k,iconTextDelay:x,iconAlt:P,iconPosition:L,centerOpen:D,width:F,openDelay:U,iconBubble:B,windowAnimation:H,headerSubtitle:A,popupTitle:N,aiName:j,userName:G,guestName:b,aiAvatar:$,userAvatar:W,guestAvatar:z,aiAvatarUrl:V,userAvatarUrl:q,guestAvatarUrl:K}},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[s,c]=r(!1),[d,m]=r("mwai-transition");i((()=>{a?c(e):e?(c(!0),setTimeout((()=>{m("mwai-transition mwai-transition-visible")}),150)):m("mwai-transition")}),[e,a]);return s?React.createElement("div",l({className:`${t} ${a?"":d}`,onTransitionEnd:()=>{"mwai-transition"!==d||a||c(!1)}},o),n):null}},7678:(e,t,a)=>{a.d(t,{CI:()=>E,F1:()=>s,Pn:()=>c,Ve:()=>h,rn:()=>p,ti:()=>d,uE:()=>m,vx:()=>u});var n=a(6841);const{useMemo:l,useEffect:r,useState:o}=wp.element;let i=null;try{i=a(3233).A}catch(e){i={ERRORS:{COULD_NOT_PARSE_ERROR_STREAM:"Could not parse the 'error' stream.",COULD_NOT_PARSE_END_STREAM:"Could not parse the 'end' stream.",SESSION_EXPIRED:"Your session has expired. Please refresh the page to continue using AI Engine."}}}function s(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 s="",c="";for(;;){const{value:e,done:d}=await r.read();if(s+=o.decode(e,{stream:!0}),d)break;const m=s.split("\n");for(let e=0;e<m.length-1;e++){if(0!==m[e].indexOf("data: "))continue;const r=JSON.parse(m[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:i.ERRORS.COULD_NOT_PARSE_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:i.ERRORS.COULD_NOT_PARSE_END_STREAM}}}s=m[m.length-1]}try{const e=JSON.parse(s);return a&&console.log(`[${a} STREAM] IN: `,e),e}catch(e){return console.error("Could not parse the buffer.",{err:e,buffer:s}),{success:!1,message:"Could not parse the buffer."}}}async function d(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:s(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(i.ERRORS.SESSION_EXPIRED)}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 m(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 s=new XMLHttpRequest;s.open("POST",e,!0),a&&s.setRequestHeader("X-WP-Nonce",a),s.upload.onprogress=function(e){if(e.lengthComputable&&n){const t=e.loaded/e.total*100;n(t)}},s.onload=function(){if(s.status>=200&&s.status<300)try{const e=JSON.parse(s.responseText);r(e)}catch(e){o({status:s.status,statusText:s.statusText,error:"The server response is not valid JSON"})}else{try{const e=JSON.parse(s.responseText);return void o({status:s.status,message:e.message})}catch(e){}o({status:s.status,statusText:s.statusText})}},s.onerror=function(){o({status:s.status,statusText:s.statusText})},s.send(i)}))}function u(){return Math.random().toString(36).substring(2)}const p=()=>{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})},E=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 s=l((()=>{const e=[o];return a&&e.push("mwai-error"),e}),[a]),c=l((()=>({wrapper:"div",forceWrapper:!0,overrides:{BlinkingCursor:{component:p},a:{props:{target:"_blank"}}}})),[]);return React.createElement(n.Ay,{options:c,className:s.join(" "),children:i})},g=/([\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 h(e){return e&&2===e.length&&g.test(e)}},5658:(e,t,a)=>{a.d(t,{UT:()=>r,zM:()=>l});var n=a(1594);const l=()=>{const[e,t]=(0,n.useState)(!1),[a,l]=(0,n.useState)(!1),[r,o]=(0,n.useState)(!1),[i,s]=(0,n.useState)(!1),[c,d]=(0,n.useState)(0),[m,u]=(0,n.useState)(0),[p,E]=(0,n.useState)([]),g=(0,n.useRef)(!1),h=(0,n.useRef)(null),R=(0,n.useRef)(null),y=(0,n.useCallback)((async(e,a={})=>{const{onProgress:n=null,onError:i=null,delayBetweenTasks:c=100}=a,m=`op_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;R.current=m,g.current=!1,h.current=new AbortController,l(!1),t(!0),o(!1),s(!1),d(0),u(e.length),E([]);const p={completed:0,errors:[],stopped:!1,aborted:!1};try{for(let t=0;t<e.length;t++){if(g.current){p.stopped=!0,p.softStopped=!0,console.log(`[AsyncProcessor] Soft stop: Completed ${t} of ${e.length} tasks`);break}if(R.current!==m){p.stopped=!0;break}try{const a=e[t],n=r?null:h.current.signal,l=await a(n,m);!1!==(null==l?void 0:l.success)&&p.completed++}catch(e){var y,v;if("AbortError"===e.name||null!==(y=e.message)&&void 0!==y&&y.includes("abort")||null!==(v=e.message)&&void 0!==v&&v.includes("cancelled")){p.stopped=!0,p.aborted=!0;break}const a={index:t,error:e.message||e.toString()};p.errors.push(a),E((e=>[...e,a])),i&&i(a)}const a=t+1;d(a),n&&n(a,e.length),t<e.length-1&&c>0&&await new Promise((e=>setTimeout(e,c)))}}finally{g.current&&p.stopped?(o(!1),s(!0),setTimeout((()=>{t(!1),s(!1)}),1e3)):(t(!1),o(!1)),h.current=null,g.current=!1,R.current=null}return p}),[]),v=(0,n.useCallback)((()=>{l(!0),t(!1),o(!1),s(!1),d(0),u(0),E([]),g.current=!1}),[]),b=(0,n.useCallback)((()=>(console.log("[AsyncProcessor] Soft stop requested"),g.current=!0,o(!0),Promise.resolve())),[]),f=(0,n.useCallback)((()=>{if(console.log("[AsyncProcessor] Hard stop requested"),g.current=!0,R.current=null,h.current)try{h.current.abort()}catch(e){}return t(!1),l(!1),o(!1),s(!1),new Promise((e=>setTimeout(e,100)))}),[]),w=(0,n.useCallback)((()=>{if(t(!1),l(!1),o(!1),s(!1),d(0),u(0),E([]),g.current=!1,R.current=null,h.current){try{h.current.abort()}catch(e){}h.current=null}}),[]);return{isProcessing:e,isPreparing:a,isStopping:r,justStopped:i,progress:c,total:m,errors:p,processTasks:y,startPreparing:v,stop:b,hardStop:f,reset:w,percentage:m>0?Math.round(c/m*100):0,isActive:e||a||i,variant:r?"danger":i?"info":null}},r=(e,t={})=>async(t,a)=>{if(t&&t.aborted)return{success:!0};try{return await e(t,a)}catch(e){var n,l;if("AbortError"===e.name||null!==(n=e.message)&&void 0!==n&&n.includes("abort")||null!==(l=e.message)&&void 0!==l&&l.includes("cancelled"))return{success:!0};throw 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},1253:(e,t,a)=>{var n=a(5323),l=a(7665),r=a(2564),o=a(9270),i=a(7097),s=a(4977),c=a(7039),d=a(4536),m=a(5263),u=a(6913),p=a(2158),E=a(4547),g=a(3676),h=a(9296),R=a(4461),y=a(8135),v=a(2714),b=a(197),f=a(3185);const w=f.Ay.div`
color: white;
padding: 15px;
margin-bottom: -15px;
a {
color: #7dedff;
text-decoration: none;
}
p {
font-size: 15px;
}
`,_=(0,f.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;
}
}
`,C=f.Ay.img`
height: 125px;
width: auto;
border-radius: 10px;
background: lightgray;
`,T=f.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;
}
`,A=f.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:N,useEffect:O}=wp.element,I=`${v.gh}/meow-common/v1`,S=({request:e,title:t,max:a})=>{const[n,l]=N(!1),[r,o]=N([]),i=r.length>0?r.reduce((function(e,t){return e+t})):0,c=r.length>0?Math.ceil(i/r.length):0,d=!r.length&&n;O((()=>{n&&setTimeout((async()=>{const t=(new Date).getTime();await(0,y.IU)(`${I}/${e}`,{method:"POST",nonce:v.ok});const a=(new Date).getTime()-t;o((e=>[...e,a]))}),1e3)}),[r]);return React.createElement(w,{style:{width:200,textAlign:"center"}},React.createElement(s.s,{h2:!0,style:{color:"white"}},t),React.createElement(b.X,{size:200,value:d?a:c,max:a},React.createElement("span",{style:{fontSize:20}},d?"START":c+" 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:M,useEffect:k}=wp.element;v.y0&&v.gh&&v.Hm||console.error("[@common/dashboard] apiUrl, restUrl and pluginUrl are mandatory.");const x=`${v.gh}/meow-common/v1`,P=React.createElement(w,null,React.createElement(s.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! 🌴🙀")),L=React.createElement(w,null,React.createElement(s.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.")),D=React.createElement(w,null,React.createElement(s.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"))))),F=async()=>(await(0,y.IU)(`${x}/all_settings/`,{method:"POST",nonce:v.ok})).data,U=async({value:e,id:t})=>await(0,y.IU)(`${x}/update_option`,{method:"POST",nonce:v.ok,json:{name:t,value:e}}),B=async()=>(await(0,y.IU)(`${x}/error_logs`,{method:"POST",nonce:v.ok})).data.reverse(),H=()=>{const e=(0,l.jE)(),[t,a]=M(!1),[n,r]=M(""),{data:y,error:v}=(0,o.I)({queryKey:["all_settings"],queryFn:F}),b=(0,i.n)({mutationFn:U,onSuccess:()=>{e.invalidateQueries(["all_settings"])}}),f=(0,i.n)({mutationFn:B}),N=null==y?void 0:y.meowapps_hide_meowapps,O=null==y?void 0:y.force_sslverify;k((()=>{v&&!t&&(a(!0),console.error("Error from useQuery",v.message))}),[v]),k((()=>{const e=document.getElementById("meow-common-phpinfo");e&&r(e.innerHTML)}),[]);const I=(e,t)=>{b.mutate({value:e,id:t})},x=React.createElement(c.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(s.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:b.isPending,checked:N,onChange:I}))),H=React.createElement(c.d,{title:"SSL Verify"},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"force_sslverify",label:"Force (Not Recommended)",description:React.createElement(s.s,{p:!0},"This will enforce the usage of SSL when checking the license or updating the plugin."),value:"1",disabled:b.isPending,checked:O,onChange:I})));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"},P,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},React.createElement(_,{title:"AI Engine",className:"primary"},React.createElement(C,{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(_,{title:"Media Cleaner",className:"primary"},React.createElement(C,{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(_,{title:"Database Cleaner",className:"primary"},React.createElement(C,{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(_,{title:"Media File Renamer",className:"primary"},React.createElement(C,{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(_,{title:"Social Engine",className:"primary"},React.createElement(C,{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(_,{title:"Meow Analytics",className:"primary"},React.createElement(C,{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(_,{title:"Contact Form Block",className:"primary"},React.createElement(C,{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(_,{title:"Meow Gallery",className:"primary"},React.createElement(C,{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(_,{title:"Meow Lightbox",className:"primary"},React.createElement(C,{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(_,{title:"Perfect Images (Retina)",className:"primary"},React.createElement(C,{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(_,{title:"Photo Engine",className:"primary"},React.createElement(C,{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(_,{title:"Contact Form Block",className:"primary"},React.createElement(C,{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"},L,React.createElement("div",{style:{display:"flex",justifyContent:"space-around",marginBottom:25}},React.createElement(S,{title:"Empty Request Time",request:"empty_request",max:2500}),React.createElement(S,{title:"File Operation Time",request:"file_operation",max:2600}),React.createElement(S,{title:"SQL Request Time",request:"sql_request",max:2800})),D),React.createElement(g.V,{title:"PHP Info"},React.createElement(T,{dangerouslySetInnerHTML:{__html:n}})),React.createElement(g.V,{title:"PHP Error Logs"},React.createElement(w,null,React.createElement(h.M,{style:{marginBottom:10},color:"#ccb027",onClick:()=>{f.mutate()},disabled:f.isPending,isBusy:f.isPending},"Load PHP Error Logs"),React.createElement(A,null,(f.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(s.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"},x,H))))))};var j=a(3516),G=a(8696),$=a(6734),W=a(1543),z=a(1843),V=a(9794),q=a(7213);const{useState:K,useEffect:Y}=wp.element,X=`${v.gh}/meow-licenser/${v.Pl}/v1`,Q=()=>{const[e,t]=K(!1),[a,n]=K(!1),[l,r]=K(null),[o,i]=K(null),[c,d]=K(""),m=v.zN&&(!o||"valid"!==o.license),u=async()=>{if("MEOW_OVERRIDE"===c)return n(!0),i(null),void d("");t(!0);try{const e=await(0,y.IU)(`${X}/set_license`,{method:"POST",nonce:v.ok,json:{serialKey:c}});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)};Y((()=>{(async()=>{if(v.am){t(!0);try{const e=await(0,y.IU)(`${X}/get_license`,{method:"POST",nonce:v.ok});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":v.zN?"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 b=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===c)&&React.createElement(React.Fragment,null,React.createElement("div",{style:{marginBottom:10}},"License Key:"),React.createElement(G.A,{id:"mfrh_pro_serial",name:"mfrh_pro_serial",disabled:e,value:c,onChange:e=>d(e),placeholder:"Type your license key..."}),React.createElement(s.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(q.X,{variant:"danger"},g),(m||o)&&E&&React.createElement(q.X,{variant:"success"},g),React.createElement("div",{style:{marginTop:15,display:"flex",justifyContent:"end"}},o&&!E&&React.createElement(h.M,{className:"secondary",disabled:e||!c,onClick:u},"Retry to validate"),o&&o.key===c&&React.createElement(h.M,{className:"secondary",disabled:e||!c,onClick:async()=>{t(!0);try{(await(0,y.IU)(`${X}/set_license`,{method:"POST",nonce:v.ok,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||!c||o&&o.key===c,onClick:u},"Validate License"),a&&!E&&React.createElement(h.M,{disabled:e||!c||o&&o.key===c,onClick:async()=>{t(!0);try{const e=await(0,y.IU)(`${X}/set_license`,{method:"POST",nonce:v.ok,json:{serialKey:c,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(V.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(V.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 v.am?f:b};var J=a(3233);function Z(){return Z=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},Z.apply(this,arguments)}const{useMemo:ee,useState:te,useEffect:ae,useRef:ne}=wp.element,le=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&&((0,v.pK)(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")}},re={title:"",content:"",refId:null,type:"manual",behavior:"context"},oe=({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(q.X,{variant:"danger",style:{marginTop:0,marginBottom:25}},be(J.A.SETTINGS.AI_ENV_SETUP,J.A.SETTINGS.AI_ENV_SETUP_URL,J.A.SETTINGS.AI_ENV_SETUP_LINK_TEXT)),!n&&React.createElement(q.X,{variant:"danger",style:{marginTop:0,marginBottom:25}},be(J.A.SETTINGS.PINECONE_SETUP,J.A.SETTINGS.PINECONE_SETUP_URL,J.A.SETTINGS.PINECONE_SETUP_LINK_TEXT)))};const ie=(e,t,a=!1)=>{const[n,l]=te(null==e?void 0:e.ai_default_model),r=ne(new Set),o=t||(null==e?void 0:e.ai_default_env),i=(null==e?void 0:e.ai_envs)??[],s=ee((()=>{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]),c=ee((()=>{var t;if(a)return s;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,s]),d=ee((()=>{let e=(null==c?void 0:c.finetunes_deleted)||[];return Array.isArray(null==c?void 0:c.legacy_finetunes_deleted)&&(e=[...e,...c.legacy_finetunes_deleted]),e}),[c]),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=ee((()=>{let t=[];if(!0===(null==c?void 0:c.fake))for(const a of e.ai_engines)Array.isArray(a.models)&&(t=[...t,...a.models]);else if("azure"===(null==c?void 0:c.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=c.deployments)||void 0===t?void 0:t.find((t=>t.model===e.model))})))??[]}else if("huggingface"===(null==c?void 0:c.type)){var a;t=(null==c||null===(a=c.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==c?void 0:c.type)));t=(null==a?void 0:a.models)??[]}let n=(null==c?void 0:c.finetunes)??[];return Array.isArray(null==c?void 0:c.legacy_finetunes)&&(n=[...n,...c.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,c]),g=ee((()=>E.filter((e=>!d.includes(e.model)))),[E,d]),h=ee((()=>E.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("core")}))),[E]),R=ee((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("image")}))),[g]),y=ee((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("embedding")}))),[g]),v=ee((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("vision")}))),[g]),b=ee((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("chat")}))),[g]),f=ee((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("audio")}))),[g]),w=ee((()=>g.filter((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("json")}))),[g]),_=ee((()=>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("gpt-5-nano")?t="gpt-5-nano":t.startsWith("gpt-5-mini")?t="gpt-5-mini":t.startsWith("gpt-5")?t="gpt-5":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},A=(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:b,imageModels:R,visionModels:v,coreModels:h,embeddingsModels:y,audioModels:f,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:A,getModel:C,calculatePrice:(e,t,a,n="1024x1024")=>{const l=T(e),r=A(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}}},se=async e=>{const t=await le(`${v.y0}/vectors/remote_list`,{nonce:(0,v.c3)(),method:"POST",json:e});return t?{total:t.total,vectors:t.vectors}:{total:0,vectors:[]}},ce=async e=>{const t={...e,offset:(e.page-1)*e.limit},a=await le(`${v.y0}/discussions/list`,{nonce:(0,v.c3)(),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:[]}},de=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 le(`${v.y0}/vectors/list`,{nonce:(0,v.c3)(),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 me(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 ue(e,t){const a=t?(()=>{if(t.startsWith("hashed_")){const e=13;return t.length>e?t.substring(0,e)+"~":t}if((t.match(/:/g)||[]).length>=3){const e=t.split(":");if(e.length>3)return e.slice(0,3).join(":")+"~"}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,J.A.COMMON.GUEST),e&&React.createElement(React.Fragment,null,React.createElement("a",{target:"_blank",href:`/wp-admin/user-edit.php?user_id=${e}`,rel:"noreferrer"},J.A.COMMON.USER," #",e)),React.createElement("br",null),React.createElement("small",{style:{color:"var(--neko-gray)"}},a))}const pe=(e=6)=>{const t="abcdefghijklmnopqrstuvwxyz0123456789";let a="";for(let n=0;n<e;n++)a+=t[Math.floor(36*Math.random())];return a},Ee=({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",Z({width:e,height:e},n,{style:l,alt:"OpenAI",src:v.Hm+"/images/chat-openai.svg"}))},ge=({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",Z({width:e,height:e},n,{style:l,alt:"Anthropic",src:v.Hm+"/images/chat-anthropic.svg"}))},he=({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",Z({width:e,height:e},n,{style:l,alt:"Google",src:v.Hm+"/images/chat-google.svg"}))},Re=({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",Z({width:e,height:e},n,{style:l,alt:"JavaScript",src:v.Hm+"/images/code-js.svg"}))},ye=({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",Z({width:e,height:e},n,{style:l,alt:"PHP",src:v.Hm+"/images/code-php.svg"}))},ve=(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()},be=(e,t,a,n="_blank")=>{const{sprintf:l}=wp.i18n,r=`<a href="${t}" target="${n}">${a}</a>`;return(0,y.FE)(l(e,r))},{useState:fe,useEffect:we,useMemo:_e}=wp.element,Ce=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"})))),Te=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"})),Ae=({icon:e="ai",size:t=20,style:a={}}={})=>{const n=_e((()=>{switch(e){case"ai":default:return Ce;case"wand":return Te}}),[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)},Ne=({title:e=J.A.COMMON.SETTINGS,options:t=v.fF})=>{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",section:e,subtitle:"By Meow Apps",isPro:v.am},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(Ae,{icon:"wand",style:{marginRight:8}}),J.A.COMMON.CONTENT),l&&React.createElement(h.M,{className:"header",icon:"",onClick:()=>location.href="edit.php?page=mwai_images_generator"},React.createElement(Ae,{icon:"wand",style:{marginRight:8}}),J.A.COMMON.IMAGES),a&&React.createElement(h.M,{className:"header",icon:"",onClick:()=>location.href="tools.php?page=mwai_dashboard"},React.createElement(Ae,{icon:"wand",style:{marginRight:8}}),J.A.COMMON.PLAYGROUND),React.createElement(h.M,{className:"header",icon:"tools",onClick:()=>location.href="admin.php?page=mwai_settings"})))},Oe=((0,f.Ay)(h.M)`
`,f.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;
}
`),Ie=f.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 Se=a(4809),Me=a.n(Se),ke=a(5484),xe=a(3896),Pe=a(5900),Le=a(7494),De=a(8482),Fe=a(209),Ue=a(8668),Be=a(520),He=a(851),je=a(6897);const Ge=async(e,t={})=>{const a=(0,v.c3)(),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(J.A.DEBUG.NEW_TOKEN_RECEIVED);(0,v.pK)(t.new_token)}return t}catch(a){if(a.message&&a.message.includes("nonce")){console.log(J.A.DEBUG.NONCE_ERROR_DETECTED);const a=await(0,y.IU)(`${v.y0}/start_session`,{method:"POST"});if(a&&a.restNonce)return(0,v.pK)(a.restNonce),await(0,y.IU)(e,{...t,nonce:a.restNonce})}throw a}},$e=async()=>{const e=await Ge(`${v.y0}/helpers/post_types`);if(!e.success)throw new Error(e.message);return e.postTypes},We=async(e=null,t=!1)=>{const a=await Ge(`${v.y0}/openai/finetunes/list_deleted?envId=${e}&legacy=${t}`);if(!a.success)throw new Error(a.message);return null==a?void 0:a.finetunes},ze=async()=>{const e=await Ge(`${v.y0}/settings/themes`,{method:"GET"});return null==e?void 0:e.themes},Ve=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 Ge(`${v.y0}/settings/themes`,{method:"POST",json:{themes:e}});return null==a?void 0:a.themes},qe=async()=>{const e=await Ge(`${v.y0}/settings/chatbots`,{method:"GET"});if(!e.success)throw new Error(null==e?void 0:e.message);return null==e?void 0:e.chatbots},Ke=async e=>{const t=await Ge(`${v.y0}/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},Ye=async()=>{const e=await Ge(`${v.y0}/settings/options`,{method:"GET"});return null==e?void 0:e.options},Xe=async()=>{try{return(await Ge(`${v.y0}/get_logs`,{method:"GET"})).data}catch(e){throw new Error(e.message)}},Qe=async()=>{try{await Ge(`${v.y0}/clear_logs`)}catch(e){throw new Error(e.message)}},Je=async()=>{const e=await Ge(`${v.y0}/forms/list`);if(!e.success)throw new Error(e.message);return e.forms},{useState:Ze,useRef:et}=wp.element,tt=({instructions:e,setMessages:t})=>{const[a,n]=Ze("post"),[l,r]=Ze(0),[i,s]=Ze(!1),[c,d]=Ze("Generate 30 questions and answers from this text. Questions use a neutral tone. Answers use the same tone as the text."),m=et(),{isLoading:u,data:p}=(0,o.I)({queryKey:["postTypes"],queryFn:$e}),{isLoading:E,data:g}=(0,o.I)({queryKey:["postsCount-"+a],queryFn:()=>(async e=>{const t=await Ge(`${v.y0}/helpers/count_posts?postType=${e}`);return null!=t&&t.count?parseInt(null==t?void 0:t.count):null})(a)}),R=(0,je.XS)({i18n:J.A,onStop:()=>{s(),R.reset()}}),b=i||R.busy||E||u,f=async(t=0,n=void 0,l=void 0)=>{let o=c+"\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 Ge(`${v.y0}/helpers/post_content?postType=${e}&offset=${t}&postId=${a}`))(a,t,n||void 0);let s=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)(`${v.y0}/ai/completions`,{method:"POST",json:{scope:"admin-tools",session:v.dZ,message:o},signal:l,nonce:v.ok});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),s=i.message;null!=l&&l.aborted&&w();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),b={content:m,prompt:o,rawData:d,entries:R,error:s,tokens:E};return console.log("Result:",b),b},w=()=>{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:b,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;s("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{s(!1)}},isBusy:"singleGenerate"===i},J.A.COMMON.SINGLE_GENERATE),React.createElement("span",{style:{color:"#d1e8f2",fontSize:"22px",padding:5}},"|"),React.createElement(h.M,{disabled:b,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),s(!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(j.u,{id:"postType",scrolldown:!0,disabled:b,name:"postType",style:{width:100,marginLeft:10},onChange:n,value:a},null==p?void 0:p.map((e=>React.createElement(j.j,{key:e.type,value:e.type,label:e.name})))),React.createElement(He.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(xe.m,{id:"generatePrompt",name:"generatePrompt",rows:2,style:{marginTop:10,marginBottom:5},value:c,onBlur:d,disabled:b})),R.TasksErrorModal)},{useState:at,useMemo:nt,useRef:lt,useEffect:rt}=wp.element,ot=({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."))},it=[{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"}],st=[{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"}],dt=[{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"}],mt=({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(ke.z,{title:e,icon:"replay",spinning:!0,width:24,color:n});break;case"succeeded":case"processed":i=React.createElement(ke.z,{title:e,icon:"check-circle",width:24,color:l});break;case"failed":i=React.createElement(ke.z,{title:e,icon:"close",width:24,color:o});break;case"cancelled":i=React.createElement(ke.z,{title:e,icon:"close",width:24,color:n});break;default:i=React.createElement(ke.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},ut=({children:e,data:t,onChange:a=(()=>{})})=>{const[n,l]=at(!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(xe.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)},pt=({options:e,updateOption:t,refreshOptions:a})=>{var n;const{colors:i}=(0,r.z)(),s=(0,l.jE)(),[c,d]=at(!1),[u,p]=at(),[R,b]=at(!1),[f,w]=at("finetunes"),[_,C]=at("current"),[T,A]=at("fine-tune"),[N,O]=at("meow"),[I,S]=at(!1),[M,k]=at(4),[x,P]=at(4),[L,D]=at(.1),[F,U]=at(.01),[B,H]=at(!1),[K,Y]=at(null==e||null===(n=e.ai_envs)||void 0===n||null===(n=n[0])||void 0===n?void 0:n.id),X=nt((()=>(null==e?void 0:e.ai_envs)||[]),[e]),Q=nt((()=>null==X?void 0:X.find((e=>e.id===K))),[K,X]),Z=(null==Q?void 0:Q.finetunes_deleted)||[],ee=(null==Q?void 0:Q.finetunes)||[],{isFetching:te,error:ae,data:ne}=(0,o.I)({queryKey:["datasets-"+K+"-"+T],enabled:B,queryFn:()=>(async(e=null,t=null)=>{var a;let n=`${v.y0}/openai/files/list?envId=${e}`;t&&(n+=`&purpose=${t}`);const l=await Ge(n);if(!l.success)throw new Error(l.message);return null==l||null===(a=l.files)||void 0===a?void 0:a.data})(K,T)}),[le,re]=at("gpt-4o-mini-2024-07-18"),oe=async(e,a)=>{const n=X.map((t=>t.id===K?{...t,[e]:a}:t));return t(n,"ai_envs")};rt((()=>{"files"!==f||B||H(!0)}),[f]),rt((()=>{ae&&!c&&d(ae)}),[ae]);const ie=10,[se,ce]=at(!0),[de,me]=at(1),[ue,pe]=at([]),[Ee,ge]=at(!1),[he,Re]=at("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."),[ye,ve]=at(""),[be,fe]=at(!1),[we,_e]=at([]),Ce=nt((()=>ue.length),[ue]);rt((()=>{if(0===ue.length)return void fe(!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));_e(e),fe(0===e.length)}),[ue]);const Te=({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(j.u,{scrolldown:!0,name:"role",value:e.role,style:{width:120},onChange:n=>a(t,n,e.content,l+1)},React.createElement(j.j,{value:"assistant",label:"Assistant"}),React.createElement(j.j,{value:"user",label:"User"}),React.createElement(j.j,{value:"system",label:"System"}))),React.createElement(ut,{data:e.content,style:{flex:"auto"},onChange:n=>a(t,e.role,n,l+1)},e.content))))),Ae=async()=>{await s.invalidateQueries("datasets")},Ne=async()=>{b("finetunes"),ee.length?await(async(e=null,t=!1)=>{const a=await Ge(`${v.y0}/openai/finetunes/list?envId=${e}&legacy=${t}`);if(!a.success)throw new Error(a.message);return null==a?void 0:a.finetunes})(K):await We(K),await a(),b(!1)},Oe=(e=!0)=>{e&&!confirm(J.A.ALERTS.RESET_BUILDER)||(pe([]),ke({instructions:he,entries:[]}))};rt((()=>{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&&Re(t.instructions)}}}),[]);const Ie=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))}}},Se=e=>{Re(e),Ee||Ie(e)},ke=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"),ve(`MEOW-${t}.jsonl`)})();try{e?localStorage.setItem("mwai_builder_data_v2",(0,y.F1)(e)):localStorage.removeItem("mwai_builder_data_v2"),ce(!0)}catch(e){localStorage.removeItem("mwai_builder_data_v2"),ce(!1)}};rt((()=>{ue&&(null==ue?void 0:ue.length)>0&&ke({instructions:he,entries:ue})}),[ue]),rt((()=>{he&&(null==he?void 0:he.length)>0&&ke({instructions:he,entries:ue})}),[he]);const He=(e,t)=>{const a=[...ue];a[e-1].messages.splice(t-1,1),pe(a)},je=(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)},$e=nt((()=>{let e=(de-1)*ie;const t=null==ue?void 0:ue.slice((de-1)*ie,(de-1)*ie+ie);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(Te,{entries:ue,messages:r,currentRow:a,onUpdateDataRow:je,onDeleteDataRow:He}),question:React.createElement(ut,{data:n,onChange:e=>je(a,"user",e)},n),answer:React.createElement(ut,{data:l,onChange:e=>je(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&&ke({instructions:he,entries:[]})})(a)}))}}))}),[ue,de,ie,Ee,je,He]),ze=async e=>{if(confirm(J.A.ALERTS.DELETE_FINETUNE)){b(!0);try{await oe("finetunes_deleted",[...Z,e])}catch(e){console.error(e),alert(J.A.ALERTS.CHECK_CONSOLE)}b(!1)}},Ve=nt((()=>null==ne?void 0:ne.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(mt,{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)=>{b(!0);try{const a=await(0,y.IU)(`${v.y0}/openai/files/download`,{method:"POST",nonce:v.ok,json:{envId:K,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(J.A.ALERTS.CHECK_CONSOLE)}b(!1)})(t,a)}),React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>(async e=>{b(!0);try{const t=await(0,y.IU)(`${v.y0}/openai/files/delete`,{method:"POST",nonce:v.ok,json:{envId:K,fileId:e}});t.success?await Ae():alert(t.message)}catch(e){console.error(e),alert(J.A.ALERTS.CHECK_CONSOLE)}b(!1)})(t)}))}}))),[ne]),qe=e=>Z.includes(e.model)||Z.includes(e.id),Ke=e=>"failed"===e.status||"cancelled"===e.status,Ye=e=>!Ke(e)&&!qe(e),Xe=nt((()=>{if(!ee)return[];let e=ee;return"current"===_?e=e.filter(Ye):"deleted"===_?e=e.filter(qe):"failed"===_&&(e=e.filter(Ke)),e.map((e=>{const t=new Date(e.createdOn);return{...e,model:e.model?e.model:React.createElement(ot,{createdOn:e.createdOn,estimatedOn:e.estimatedOn}),status:React.createElement(mt,{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(J.A.ALERTS.DELETE_FINETUNE)){b(!0);try{const t=await(0,y.IU)(`${v.y0}/openai/finetunes/delete`,{method:"POST",nonce:v.ok,json:{envId:K,modelId:e}});t.success?await oe("finetunes_deleted",[...Z,e]):t.message.indexOf("does not exist")>-1?(alert(J.A.ALERTS.FINETUNE_ALREADY_DELETED),await oe("finetunes_deleted",[...Z,e])):alert(t.message)}catch(e){console.error(e),alert(J.A.ALERTS.CHECK_CONSOLE)}b(!1)}})(e.model)}),"cancelled"===e.status&&React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>ze(e.id)}),"failed"===e.status&&React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>ze(e.id)}),"pending"===e.status&&React.createElement(h.M,{className:"danger",rounded:!0,icon:"close",onClick:()=>(async e=>{b(!0);try{const t=await(0,y.IU)(`${v.y0}/openai/finetunes/cancel`,{method:"POST",nonce:v.ok,json:{envId:K,finetuneId:e}});t.success?Ne():alert(t.message)}catch(e){console.error(e),alert(J.A.ALERTS.CHECK_CONSOLE)}b(!1)})(e.id)}))}}))}),[_,Z,ee]),Qe=te||R,Je=nt((()=>{const e=new Date,t=e.getFullYear(),a=e.getMonth()+1,n=e.getDate(),l=e.getHours(),r=e.getMinutes(),o=e.getSeconds();return`${le}:ft-your-org:${N}-${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}`}),[N,le]),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)},et=lt(null),pt=null==ee?void 0:ee.filter(Ye).length,Et=null==ee?void 0:ee.filter(Ke).length,gt=null==ee?void 0:ee.filter(qe).length,ht=nt((()=>React.createElement(j.u,{scrolldown:!0,value:K,onChange:Y,style:{marginLeft:5}},X.filter((e=>"openai"===e.type)).map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))))),[K,X]),Rt=nt((()=>{if(0===we.length)return null;const e=we.slice(0,10).map(((e,t)=>React.createElement("span",{key:e,style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>(e=>{const t=Math.floor(e/ie);me(t+1)})(e)},e,t<we.slice(0,10).length-1?", ":"")));return we.length>10?React.createElement(React.Fragment,null,"Some entries are invalid, for example those ones: ",e,", and ",we.length-10," more."):React.createElement(React.Fragment,null,"Some entries are invalid, for example those ones: ",e)}),[we,ie]);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)=>{w(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:Ne,className:"secondary"},J.A.COMMON.REFRESH_MODELS),ht),"files"===f&&React.createElement(React.Fragment,null,React.createElement(h.M,{disabled:R,onClick:async()=>{b(!0),await Ae(),b(!1)},className:"secondary"},"Refresh Files"),ht),"editor"===f&&React.createElement(React.Fragment,null,React.createElement("label",{style:{marginRight:10}},"Filename:"),React.createElement(G.A,{disabled:!Ce||R,value:Ce?ye:"",onChange:ve,style:{width:220,marginRight:5}}),React.createElement(h.M,{className:"secondary",disabled:!be||R,icon:"upload",onClick:async()=>{b(!0);try{const e=ue.map((e=>(0,y.F1)(e))).join("\n"),t=await(0,y.IU)(`${v.y0}/openai/files/upload`,{method:"POST",nonce:v.ok,json:{envId:K,filename:ye,data:e}});await Ae(),t.success?(Oe(!1),alert(J.A.ALERTS.DATASET_UPLOADED),w("files")):alert(t.message)}catch(e){console.error(e),alert(J.A.ALERTS.CHECK_CONSOLE)}b(!1)}},"Upload to OpenAI"),ht))},React.createElement(g.V,{title:J.A.COMMON.MODELS,key:"finetunes"},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("div",null,(0,y.FE)(J.A.FINETUNING.MODELS_INTRO)),React.createElement(z.o,{value:_,onChange:e=>{C(e)}},React.createElement(z.K,{title:"Current",value:"current",count:pt??"-"}),React.createElement(z.K,{title:"Failed",value:"failed",count:Et??"-"}),React.createElement(z.K,{title:"Deleted",value:"deleted",count:gt??"-"}))),React.createElement($.g,null),React.createElement(Pe.o,{busy:Qe,data:Xe,columns:dt,emptyMessage:J.A.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()=>{b("clean"),await We(K),await a(),b(!1)},className:"primary"},J.A.FINETUNING.CLEAN_MODELS_LIST),React.createElement("small",{style:{marginLeft:5}},J.A.FINETUNING.DELETED_FINETUNE_ISSUE))),React.createElement(g.V,{title:J.A.COMMON.FILES,key:"files"},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("div",null,(0,y.FE)(J.A.FINETUNING.FILES_INTRO)),React.createElement(z.o,{value:T,onChange:e=>{A(e)}},React.createElement(z.K,{title:"Datasets",value:"fine-tune"}),React.createElement(z.K,{title:"All",value:null}))),React.createElement($.g,null),React.createElement(Pe.o,{busy:Qe,data:Ve,columns:ct,emptyMessage:React.createElement(React.Fragment,null,"You do not have any dataset files yet.")})),React.createElement(g.V,{title:J.A.FINETUNING.DATASET_EDITOR,key:"editor"},!se&&React.createElement("p",{style:{color:"red"}},J.A.FINETUNING.HUGE_DATASET_WARNING),React.createElement(Le.V,{style:{display:"flex"}},React.createElement(h.M,{icon:"plus",onClick:()=>((e="Question?",t="Answer.")=>{pe([...ue,{messages:[{role:"system",content:he},{role:"user",content:e},{role:"assistant",content:t}]}])})(),disabled:R},"Add Entry"),Ee&&React.createElement(h.M,{onClick:()=>Ie(he),disabled:R},"Rewrite Instructions"),React.createElement("div",{style:{flex:"auto"}}),React.createElement(De.S,{style:{marginLeft:5},onLabel:"Expert",offLabel:"Easy",width:90,onBackgroundColor:i.purple,offBackgroundColor:i.green,onChange:ge,checked:Ee}),React.createElement(Fe.Z,{ref:et,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(J.A.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=Me().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,""),s=null==l?void 0:l.replace(/\n\n###\n\n$/g,"");return l&&r?{messages:[{role:"system",content:he},{role:"user",content:s.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(J.A.ALERTS.ONLY_SUPPORTS_FILES)},n.readAsText(a)):(alert(J.A.ALERTS.ONLY_SUPPORTS_FILES),console.warn(a))}},accept:"",style:{paddingLeft:5}},React.createElement(h.M,{className:"secondary",onClick:()=>et.current.click()},"Import")),React.createElement(h.M,{disabled:!Ce,onClick:Oe,className:"secondary"},"Clear")),React.createElement($.g,null),ue.length>0&&(null==we?void 0:we.length)>0&&React.createElement(React.Fragment,null,React.createElement(q.X,{variant:"danger"},Rt),React.createElement($.g,null)),React.createElement(Ue.Zc,{keepState:"datasetEditor"},React.createElement(Ue.y2,{title:"Dataset"},React.createElement($.g,{tiny:!0}),React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(Be.Q,{currentPage:de,limit:ie,total:Ce,onCurrentPageChanged:me,onClick:me})),React.createElement($.g,{tiny:!0}),React.createElement(Pe.o,{busy:R,data:$e,columns:Ee?st:it,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($.g,{tiny:!0}),React.createElement("div",{style:{display:"flex"}},React.createElement("div",{style:{flex:"auto"}}),React.createElement(Be.Q,{currentPage:de,limit:ie,total:Ce,onCurrentPageChanged:me,onClick:me}),React.createElement(h.M,{disabled:!Ce,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(Ue.y2,{title:J.A.COMMON.CONTEXT},React.createElement($.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($.g,null),React.createElement(xe.m,{id:"instructions",name:"instructions",rows:2,value:he,onBlur:Se,onEnter:Se})),React.createElement(Ue.y2,{title:"Generator"},React.createElement($.g,null),React.createElement(tt,{options:e,instructions:he,setMessages:pe}),React.createElement(q.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(Ue.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(W.L,{style:{margin:10}},React.createElement(V.n,{isOpen:c,title:"Error",onRequestClose:()=>d(),okButton:{label:"Ok",onClick:()=>d()},content:React.createElement(React.Fragment,null,React.createElement("p",null,null==c?void 0:c.message))}),React.createElement(V.n,{isOpen:u,title:"Train a new model",onRequestClose:()=>p(),okButton:{label:"Start",disabled:R,onClick:async()=>{const e=u,t=N;b(!0);let a={envId:K,fileId:e,model:le,suffix:t};I&&(a={...a,nEpochs:M,batchSize:x,learningRateMultiplier:L,promptLossWeight:F});try{const e=await(0,y.IU)(`${v.y0}/openai/files/finetune`,{method:"POST",nonce:v.ok,json:a});e.success?(Ne(),alert(J.A.ALERTS.FINETUNING_STARTED),w("finetunes"),p()):alert(e.message)}catch(e){console.log(e.message),alert(e.message)}b(!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($.g,{height:5}),React.createElement(G.A,{value:le,onChange:re,description:React.createElement(React.Fragment,null,"As of August 2024, you can use ",React.createElement("a",{href:"#",onClick:()=>re("gpt-4o-mini-2024-07-18")},"gpt-4o-mini-2024-07-18"),", ",React.createElement("a",{href:"#",onClick:()=>re("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/model-optimization",target:"_blank",rel:"noreferrer"},"here"),".")}),React.createElement($.g,{height:10}),React.createElement("label",null,"Suffix (for new model name):"),React.createElement($.g,{height:5}),React.createElement(G.A,{value:N,onChange:O}),React.createElement($.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,Je),"."),React.createElement($.g,{line:!0,height:20}),React.createElement(m.R,{label:"Enable HyperParams",checked:I,onChange:S}),I&&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(G.A,{style:{marginRight:5},value:M,onChange:k,type:"number"}),React.createElement("label",{style:{marginRight:5}},"Batch Size:"),React.createElement(G.A,{value:x,onChange:P,type:"number"})),React.createElement("div",{style:{display:"flex",flexDirection:"row",alignItems:"center"}},React.createElement("label",{style:{marginRight:5}},"Learning Rate Multiplier:"),React.createElement(G.A,{style:{marginRight:5},value:L,onChange:D,type:"number"}),React.createElement("label",{style:{marginRight:5}},"Prompt Loss Weight:"),React.createElement(G.A,{value:F,onChange:U,type:"number"}))))})))},{useState:Et}=wp.element,gt=({options:e,updateOption:t,busy:a})=>{const[n,l]=Et("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]=Et([]),[i,s]=Et(""),[d,u]=Et(!1),p=null==e?void 0:e.chatbot_moderation,g=d||a,b=React.createElement(c.d,{title:J.A.COMMON.CHATBOT},React.createElement(m.R,{name:"chatbot_moderation",label:J.A.COMMON.ENABLE,value:"1",checked:p,description:J.A.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:J.A.COMMON.SETTINGS,className:"primary"},React.createElement("p",null,"You can enable moderation various parts of WordPress. It will slow down the processing a little."),b)),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(xe.m,{name:"context",rows:8,value:n,onChange:l}),React.createElement($.g,null),React.createElement(h.M,{fullWidth:!0,onClick:async()=>{u(!0);const e=await(0,y.IU)(`${v.y0}/ai/moderate`,{method:"POST",nonce:v.ok,json:{text:n}});if(e.success){let t=e.results;o(null==t?void 0:t.results)}else s(e.message);u(!1)}},"Moderation Check"),React.createElement($.g,null),React.createElement("label",null,"Results:"),React.createElement("pre",null,(0,y.F1)(r,2))))))};var ht=a(9425),Rt=a(8956),yt=a(5658);const{useState:vt,useEffect:bt,useMemo:ft}=wp.element,wt=({modal:e,busy:t,setModal:a,onAddEmbedding:n,onModifyEmbedding:l})=>{const[r,o]=vt(!1),i=t;bt((()=>{"edit"!==(null==e?void 0:e.type)&&"add"!==(null==e?void 0:e.type)||o((null==e?void 0:e.data)||{})}),[e]);const s=ft((()=>{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(V.n,{isOpen:"edit"===(null==e?void 0:e.type)||"add"===(null==e?void 0:e.type),title:"edit"===(null==e?void 0:e.type)?J.A.COMMON.MODIFY_EMBEDDING:J.A.COMMON.ADD_EMBEDDING,okButton:{label:"edit"===(null==e?void 0:e.type)?J.A.COMMON.MODIFY_EMBEDDING:J.A.COMMON.ADD_EMBEDDING,disabled:!s||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($.g,null),React.createElement("label",null,"Title:"),React.createElement($.g,{tiny:!0}),React.createElement(G.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($.g,null),React.createElement("label",null,"Content:"),React.createElement($.g,{tiny:!0}),React.createElement(xe.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($.g,null),React.createElement("div",{style:{display:"flex",justifyContent:"space-between"}},React.createElement("div",{style:{flex:3}},React.createElement("label",null,"Behavior:"),React.createElement($.g,{tiny:!0}),React.createElement(j.u,{scrolldown:!0,name:"behavior",disabled:i||!0,value:null==r?void 0:r.behavior,onChange:e=>{o({...r,behavior:e})}},React.createElement(j.j,{value:"context",label:"Context"}),React.createElement(j.j,{value:"reply",label:"Reply"}))),React.createElement("div",{style:{flex:3,marginLeft:5}},React.createElement("label",null,"Type:"),React.createElement($.g,{tiny:!0}),React.createElement(j.u,{scrolldown:!0,name:"type",disabled:i||!0,value:null==r?void 0:r.type,onChange:e=>{o({...r,type:e})}},React.createElement(j.j,{value:"manual",label:"Manual"}),React.createElement(j.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($.g,{tiny:!0}),React.createElement(G.A,{value:null==r?void 0:r.refId,disabled:!0,onChange:e=>o({...r,refId:e})}))))}))},{useState:_t}=wp.element;function Ct(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 Tt=({modal:e,setModal:t})=>{const[a,n]=_t(!1),[l,r]=_t(0),[o,i]=_t(0),s=null==e?void 0:e.data,c=async()=>{let e=!1;const t={page:1,limit:20,filters:{envId:s.envId,dbIndex:s.dbIndex,dbNS:s.dbNS}};let a=[];for(;!e;){const n=await de(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(V.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 c(),t=Me().unparse(e),a=new Date,l=a.getFullYear(),o=a.getMonth()+1;Ct(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 c(),t=(0,y.F1)(e,2),a=new Date,l=a.getFullYear(),o=a.getMonth()+1;Ct(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(He.j,{busy:a,style:{flex:"auto"},value:o,max:l}))}))},{useState:At}=wp.element,Nt=({modal:e,setModal:t,onAddEmbedding:a,onModifyEmbedding:n})=>{var l;const[r,o]=At(!1),[i,s]=At(0),[c,d]=At(0),[u,p]=At({add:[],modify:[],same:[],total:0,isReady:!1}),E=(null==e||null===(l=e.data)||void 0===l?void 0:l.importVectors)??[],[g,R]=At({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}),b=(e,t,a)=>Object.keys(a).every((n=>!a[n]||e[n]===t[n])),f=()=>{t(null),o(!1),s(0),d(0),p({add:[],modify:[],same:[],total:0,isReady:!1})};return React.createElement(React.Fragment,null,React.createElement(V.n,{isOpen:"import"===(null==e?void 0:e.type),title:"Import Embeddings",onRequestClose:f,okButton:{label:"Close",onClick:f,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 de(t);n.vectors.length<2&&(e=!0),s((()=>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=>b(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{s(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}),f()}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($.g,null),React.createElement(Ue.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($.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($.g,null),React.createElement(He.j,{busy:r,style:{flex:"auto"},value:c,max:i})),React.createElement($.g,null),React.createElement(Ue.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($.g,null),React.createElement(He.j,{busy:r,style:{flex:"auto"},value:c,max:i})),React.createElement($.g,null))}))},{useState:Ot,useMemo:It,useEffect:St,useRef:Mt,lazy:kt,Suspense:xt}=wp.element,Pt=v.am?kt((()=>Promise.all([a.e(121),a.e(115)]).then(a.bind(a,9473)).then((e=>({default:e.default}))))):null,Lt=[{accessor:"status",title:"Status",width:"90px"},{accessor:"title",title:"Title / Model",sortable:!0,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"}],Dt=[{accessor:"status",title:"Status",sortable:!0,width:"90px"},{accessor:"title",title:"Title / Model",sortable:!0,width:"100%"},{accessor:"type",title:"Ref",sortable:!0,width:"90px"},{accessor:"updated",title:"Updated",sortable:!0,width:"90px"},{accessor:"actions",title:"",width:"110px"}],Ft=({embedding:e,envName:t,isDifferentModel:a})=>{const{colors:n}=(0,r.z)(),{status:l,content:o,error:i}=e,s=It((()=>{if("ok"===l){if(!t)return"env_issue";if(!o)return"empty";if(a)return"warning"}return"outdated"===l?"stale":l}),[l,t,o,a]),c=It((()=>"orphan"===s?"This embedding was retrieved from the Vector DB, but it has no content. Add some, or delete it.":"env_issue"===s?"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"===s?"This embedding has no content.":"warning"===s?"This embedding was created with a different model. Sync will update it to use the current model.":i||null),[s,i]),{icon:d,color:m}=It((()=>{const e={outdated:{icon:"alert",color:n.orange},stale:{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[s]||e.default}),[s,n]);return React.createElement("div",{style:{display:"flex",alignItems:"center"},title:c},React.createElement(ke.z,{icon:d,width:24,color:m,title:c}),React.createElement("span",{style:{textTransform:"uppercase",fontSize:9,marginLeft:3}},s))},Ut=({environmentId:e,isSidebarCollapsed:t})=>{const a=Bt(),n={environmentId:void 0!==e?e||null:a.environmentId,isSidebarCollapsed:void 0!==t?t:a.isSidebarCollapsed};localStorage.setItem("mwai-admin-embeddings",(0,y.F1)(n))},Bt=()=>{const e=localStorage.getItem("mwai-admin-embeddings");try{const t=JSON.parse(e);return{environmentId:(null==t?void 0:t.environmentId)||null,isSidebarCollapsed:(null==t?void 0:t.isSidebarCollapsed)||!1}}catch(e){return{environmentId:null,isSidebarCollapsed:!1}}},Ht=({options:e,updateOption:t})=>{const a=(0,l.jE)(),{colors:n}=(0,r.z)(),[i,c]=Ot("post"),[d,u]=Ot(""),[p,E]=Ot(!1),[b,f]=Ot(!1),[w,_]=Ot(!1),[C,T]=Ot(null),[A,N]=Ot(""),[O,I]=Ot(!1),[S,M]=Ot([]),[k,x]=Ot({type:null,data:null}),[P,L]=Ot(null),[D,F]=Ot(!1),[U,B]=Ot(null),[H,W]=Ot(null);St((()=>{if(H&&0===H.stats.errors){const e=setTimeout((()=>W(null)),1e4);return()=>clearTimeout(e)}}),[H]);const[z,K]=Ot((()=>Bt().isSidebarCollapsed)),Y=e.embeddings||{},X=Mt(null),Q=ie(e,!1,!0),Z=e.embeddings_envs||[],[ee,te]=Ot(Bt().environmentId),ae=It((()=>Z.find((e=>e.id===ee))||null),[Z,ee]),ne=(null==ae?void 0:ae.min_score)>=0?ae.min_score:35,oe=((null==ae?void 0:ae.max_select)>=0&&ae.max_select,It((()=>null!=ae&&ae.ai_embeddings_override&&null!=ae&&ae.ai_embeddings_env&&null!=ae&&ae.ai_embeddings_model?Q.getModel(ae.ai_embeddings_model):Q.getModel(e.ai_embeddings_default_model)),[ae,Y.model])),{isLoading:ce,data:me}=(0,o.I)({queryKey:["postTypes"],queryFn:$e}),{isLoading:ue,data:pe}=(0,o.I)({queryKey:["postsCount-"+i+"-"+(null==Y?void 0:Y.syncPostStatus)??"publish"],queryFn:()=>(async(e,t="publish")=>{const a=await le(`${v.y0}/helpers/count_posts?postType=${e}&postStatus=${t}`,{nonce:(0,v.c3)()});return null!=a&&a.count?parseInt(null==a?void 0:a.count):null})(i,(null==Y?void 0:Y.syncPostStatus)??"publish")}),[Ee,ge]=Ot({filters:{envId:ee,search:C,debugMode:!1},sort:{accessor:"updated",by:"desc"},page:1,limit:20}),{isFetching:he,data:Re,error:ye}=(0,o.I)({queryKey:["vectors",(0,y.F1)(Ee)],queryFn:()=>de(Ee),staleTime:3e5,gcTime:6e5}),ve=he||"searchVectors"===p,be=b?Lt:Dt,fe=(0,yt.zM)(),we=p||ve||fe.isActive||fe.isPreparing||ce,_e=b?"search":"edit",Ce=async e=>{E("updateSettings"),await t({...e},"embeddings"),E(null)},Te=It((()=>Y.syncPosts&&(null==Y?void 0:Y.syncPostsEnvId)!==ee),[ee,Y]);St((()=>{!Y.syncPosts&&Y.syncPostsEnvId&&Ce({...Y,syncPostsEnvId:null})}),[Y.syncPosts]);const Ae=It((()=>Z.find((e=>e.id===Y.syncPostsEnvId))||null),[Y.syncPostsEnvId]);St((()=>{ge((e=>e.filters.envId===ee&&e.filters.search===C&&e.filters.debugMode===P?e:{...e,filters:{envId:ee,search:C,debugMode:P}})),Ut({environmentId:ee})}),[ee,P,C]),St((()=>{Ut({isSidebarCollapsed:z})}),[z]),St((()=>{const e="edit"===_e?null:"";T(e),N(e||""),ge((t=>{const a="edit"===_e?"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}}))}),[_e]),St((()=>{var e,t;null!=Y&&null!==(e=Y.syncPostTypes)&&void 0!==e&&e.length&&null!=Y&&null!==(t=Y.syncPostStatus)&&void 0!==t&&t.length||Ce({...Y,syncPostTypes:["post","page","product"],syncPostStatus:["publish"]})}),[Y.syncPostTypes]);const Ne=It((()=>{const e={padding:"8px 10px"};return Y.syncPosts&&!Ae?React.createElement(q.X,{variant:"danger",style:e},"Pick a valid environment for Sync."):Y.syncPosts?React.createElement(q.X,{variant:"success",style:e},"Sync Active on ",React.createElement("b",null,null==Ae?void 0:Ae.name)):React.createElement(q.X,{variant:"disabled",style:e},"Sync Inactive")}),[Y]),Oe=async()=>{T(A),A!==Ee.filters.search?ge((e=>({...e,filters:{...e.filters,search:A}}))):a.invalidateQueries({queryKey:["vectors"]})},Ie=async(e=O,t=!1)=>{t||E("addEmbedding");try{const t={...e};t.envId||(t.envId=ae.id);const a=await(0,y.IU)(`${v.y0}/vectors/add`,{nonce:v.ok,method:"POST",json:{vector:t}});We(null==a?void 0:a.vector,!0),I(!1),console.log("Embedding Added",e)}catch(e){throw console.error(e),new Error(e.message??"Unknown error, check your console logs.")}finally{t||E(!1)}return!0},Se=async(e=O,t)=>{t||E("addEmbedding");try{const t={...e};t.envId||(t.envId=ae.id);const a=await(0,y.IU)(`${v.y0}/vectors/update`,{nonce:v.ok,method:"POST",json:{vector:t}});We(null==a?void 0:a.vector),I(!1),console.log("Embeddings updated.",a)}catch(e){throw console.error(e),new Error(e.message??"Unknown error, check your console logs.")}finally{t||E(!1)}return!0},ke=async(e,t)=>{t||E("deleteEmbedding");try{await(0,y.IU)(`${v.y0}/vectors/delete`,{nonce:v.ok,method:"POST",json:{envId:ae.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)(`${v.y0}/vectors/delete`,{nonce:v.ok,method:"POST",json:{envId:ae.id,ids:e,force:!0}})}finally{t||E(!1)}console.log("Embeddings deleted.",{ids:e}),a.invalidateQueries({queryKey:["vectors"]}),b&&console.error("We should update the vectors data with the deleted embeddings.")},Ue=It((()=>(null==Re?void 0:Re.total)||0),[Re]),je=It((()=>{const e=Re;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 s=i.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),c=e.score?React.createElement("span",{style:{color:e.score>ne/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=Q.getModel(e.model),u=(null==m?void 0:m.rawName)??e.model,p=e.model,E=e.model&&e.model!==(null==oe?void 0:oe.model),g=e.envId!==ee,R=null===(t=Z.find((t=>t.id===e.envId)))||void 0===t?void 0:t.name,y="outdated"===e.status||"stale"===e.status||"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=Q.getModel(null==oe?void 0:oe.model),a=(null==t?void 0:t.rawName)||(null==t?void 0:t.name)||(null==oe?void 0:oe.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==oe?void 0:oe.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:c,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(Ft,{embedding:e,envName:R,isDifferentModel:E}),updated:o,created:s,actions:React.createElement("div",null,React.createElement(h.M,{className:"primary",rounded:!0,icon:"pencil",disabled:we,onClick:()=>x({type:"edit",data:e})}),React.createElement(h.M,{className:y?"warning":"primary",rounded:!0,icon:"lightning",disabled:we,onClick:()=>Ge(e.id)}),React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",disabled:we,onClick:()=>ke([e.id])}))}})):[]}),[_e,Re,we]),Ge=async e=>{E("syncEmbedding");try{await ze(e)}catch(e){console.error(e),alert((null==e?void 0:e.message)??e)}E(!1)},We=(e,t=!1)=>{a.invalidateQueries({queryKey:["vectors"]})},ze=async(e=null,t=null,a=void 0)=>{if(a&&a.aborted)throw new DOMException("Operation was cancelled","AbortError");const n=await(async({vectorId:e,postId:t,envId:a},n=null)=>await le(`${v.y0}/vectors/sync`,{nonce:(0,v.c3)(),method:"POST",json:{vectorId:e,postId:t,envId:a},signal:n}))({vectorId:e,postId:t,envId:ee},a);return n.success&&We(n.vector),n},Ve=async()=>{if(fe.isActive)return void fe.stop();W(null),fe.startPreparing(),E("bulkPullAll"),await new Promise((e=>setTimeout(e,10)));const e={page:1,limit:1e4,filters:{envId:ee}};let t=[],n=[],l=!1;for(;!l;)try{const a=await se(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 E(!1)}for(console.log("Remote vectors retrieved.",{remoteVectors:t}),l=!1,e.limit=20,e.page=0;!l;){const t=await de(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 E(!1),void W({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=>(0,yt.UT)((async t=>(await(async(e,t)=>await le(`${v.y0}/vectors/add_from_remote`,{nonce:(0,v.c3)(),method:"POST",json:e,signal:t}))({envId:ee,dbId:e},t),await a.invalidateQueries({queryKey:["vectors"]}),o.added++,{success:!0}))))),s=await fe.processTasks(i,{onError:({index:e,error:t})=>{o.errors++,o.errorDetails.push({dbId:r[e],error:t})}});E(!1),!s.stopped&&o.total>0&&W({type:"pull",stats:o})},qe=async(e=!1)=>{if(fe.isActive)return void fe.stop();W(null),fe.startPreparing(),E("bulkPushAll"),await new Promise((e=>setTimeout(e,10)));let t=[];const a={total:0,added:0,updated:0,upToDate:0,skipped:0,errors:0,errorDetails:[]};if(e||0===S.length){const e=await(async(e,t="publish")=>{const a=await le(`${v.y0}/helpers/posts_ids?postType=${e}&postStatus=${t}`,{nonce:(0,v.c3)()});return null!=a&&a.postIds?a.postIds:[]})(i,Y.syncPostStatus);a.total=e.length,t=e.map(((e,t)=>(0,yt.UT)((async t=>{const n=await ze(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}}))))}else{const e=Re.vectors.filter((e=>S.includes(e.id)));a.total=e.length,t=e.map(((e,t)=>(0,yt.UT)((async t=>{let n;if(e.refId?n=await ze(e.id,null,t):(await Se(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}}))))}const n=await fe.processTasks(t);E(!1),!n.stopped&&a.total>0&&W({type:"push",stats:a,selectedType:e?`All ${i}s`:"Selected items"})},Ke=async(e=null)=>{if(e){E("singleRun");try{await ze(null,e),u("")}catch(e){console.error(e),alert((null==e?void 0:e.message)??e)}E(!1)}},Ye=It((()=>null!=ye&&ye.message?React.createElement(q.X,{variant:"danger",style:{margin:"5px 5px"}},React.createElement("b",null,ye.message),React.createElement("br",null),React.createElement("small",null,"Check your Console Logs and PHP Error Logs for more information.")):b?J.A.HELP.NO_EMBEDDINGS_RESULTS:ae?b?React.createElement("div",{style:{padding:"40px 20px",textAlign:"center",color:"#666"}},React.createElement("p",{style:{margin:0,fontSize:14}},"No results for this search. Try different keywords or adjust your search parameters.")):React.createElement("div",{style:{padding:"40px 20px",backgroundColor:"#f9f9f9",borderRadius:8,margin:"20px"}},React.createElement("div",{style:{maxWidth:500,margin:"0 auto",lineHeight:1.6}},React.createElement("h3",{style:{marginBottom:20,color:"#333"}},"Let's Create a Knowledge Base"),React.createElement("p",{style:{marginBottom:20}},"Your ",React.createElement("b",null,null==ae?void 0:ae.name)," environment is selected. Now let's add some content to create your knowledge base made of embeddings."),React.createElement(q.X,{variant:"success",style:{marginBottom:20,fontSize:13}},"Click ",React.createElement("b",null,"Create New")," to manually create an embedding,"," ",React.createElement("b",null,"Push All")," to push all your posts, ",React.createElement("b",null,"Upload PDF")," for documents, or enable ",React.createElement("b",null,"Sync")," to keep embeddings updated based on the content on this WordPress site."),React.createElement("p",{style:{marginTop:20,fontSize:13}},"Learn more about this on ",React.createElement("a",{href:"https://ai.thehiddendocs.com/knowledge/",target:"_blank",rel:"noopener noreferrer",style:{color:"#0073aa"}},"The Hidden Docs ↗")))):React.createElement("div",{style:{padding:"40px 20px",backgroundColor:"#f9f9f9",borderRadius:8,margin:"20px"}},React.createElement("div",{style:{maxWidth:600,margin:"0 auto",lineHeight:1.6}},React.createElement("h3",{style:{marginBottom:20,color:"#333"}},"Let's Create a Knowledge Base"),React.createElement(q.X,{variant:"info",style:{marginBottom:20,fontSize:13}},React.createElement("b",null,"First, create an Embeddings Environment.")," This can be done in"," ",React.createElement("b",{style:{whiteSpace:"nowrap"}},"Settings → Knowledge →")," ",React.createElement("b",{style:{whiteSpace:"nowrap"}},"Environments for Embeddings"),". Once configured, come back to this screen and choose your environment in the select dropdown above."),React.createElement("p",{style:{marginBottom:15}},React.createElement("b",null,"What are embeddings?")," Embeddings are numerical representations of text that allow AI to understand semantic meaning and relationships. They power features like intelligent search, contextual responses, and RAG (Retrieval Augmented Generation)."),React.createElement("p",{style:{marginTop:20,fontSize:13}},"Learn more about this on ",React.createElement("a",{href:"https://ai.thehiddendocs.com/knowledge/",target:"_blank",rel:"noopener noreferrer",style:{color:"#0073aa"}},"The Hidden Docs ↗"))))),[_e,ye,ae]);return React.createElement(React.Fragment,null,React.createElement(ht.J,{mainFlex:3,sidebarFlex:1,minimal:!0,isCollapsed:z,onToggle:()=>K(!z),showToggle:!1},React.createElement(ht.J.Main,null,React.createElement(R.z,{className:"primary",title:React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},React.createElement("span",null,"Embeddings"),!b&&React.createElement(h.M,{className:"success",rounded:!0,small:!0,icon:"plus",disabled:!ae||we,onClick:()=>x({type:"add",data:re})})),action:React.createElement("div",{style:{display:"flex",alignItems:"center",gap:5}},React.createElement(j.u,{scrolldown:!0,name:"environment",style:{width:180},disabled:we,value:(null==ae?void 0:ae.id)??null,onChange:e=>{te(e)}},Z.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))),!(null!=Z&&Z.length)&&React.createElement(j.j,{value:null,label:"None"})),React.createElement(h.M,{className:"secondary",disabled:!ae||ve||fe.isActive,onClick:()=>{a.invalidateQueries({queryKey:["vectors"]})}},J.A.COMMON.REFRESH),React.createElement(Rt.A,{isCollapsed:z,onClick:()=>K(!z),border:"left",direction:"right"}))},fe.isActive&&React.createElement(Le.V,{style:{marginBottom:15}},React.createElement(He.j,{busy:!fe.justStopped,style:{width:"100%"},value:fe.progress,max:fe.total,status:fe.isPreparing?"Preparing...":fe.isStopping?"Please wait...":fe.justStopped?"Stopped":void 0,variant:fe.variant,onStopClick:fe.justStopped?null:fe.stop})),b&&React.createElement(Le.V,{style:{marginBottom:15}},React.createElement("div",{style:{display:"flex",width:"100%"}},React.createElement(G.A,{style:{flex:"auto",marginRight:5},placeholder:"Search",disabled:!ae||we,value:A,onChange:N,onEnter:Oe,onReset:async()=>{T(""),N(""),ge((e=>({...e,filters:{...e.filters,search:""}})))}}),React.createElement(h.M,{className:"primary",onClick:Oe,disabled:!ae||we||!A,isBusy:"searchVectors"===p},"Search"))),React.createElement(Pe.o,{busy:we,sort:Ee.sort,onSortChange:(e,t)=>{ge((a=>({...a,sort:{accessor:e,by:t}})))},emptyMessage:Ye,data:je,columns:be,onSelectRow:e=>{1===S.length&&S[0]===e&&M([]),M([e])},onSelect:e=>{M([...S,...e])},onUnselect:e=>{M([...S.filter((t=>!e.includes(t)))])},selectedItems:S}),React.createElement($.g,null),!b&&React.createElement("div",{style:{display:"flex",alignItems:"center"}},!b&&S.length>0&&React.createElement(React.Fragment,null,React.createElement(h.M,{className:"primary",icon:"lightning",disabled:we,isBusy:"bulkPushAll"===p,onClick:()=>qe(!1)},"Sync"),React.createElement(h.M,{className:"danger",style:{marginLeft:5},disabled:we,onClick:async()=>{confirm("Are you sure you want to delete the selected embeddings?")&&(E("deleteEmbeddings"),await ke(S),M([]),E(!1))}},"Delete"),React.createElement("div",{style:{display:"flex",alignItems:"center",marginLeft:10}},S.length," selected")),React.createElement("div",{style:{flex:"auto"}}),React.createElement(Be.Q,{currentPage:Ee.page,limit:Ee.limit,onCurrentPageChanged:e=>ge((t=>({...t,page:e}))),total:Ue,onClick:e=>{ge((t=>({...t,page:e})))}}),w&&React.createElement(h.M,{className:"primary",style:{marginLeft:5},disabled:!ae,onClick:()=>{x({type:"export",data:{envId:ee}})}},J.A.COMMON.EXPORT)))),React.createElement(ht.J.Sidebar,null,React.createElement("div",{style:{margin:"20px 8px 20px 8px"}},React.createElement(s.s,{h2:!0,style:{color:"white",marginBottom:10}},"Mode"),React.createElement($.g,null),React.createElement(R.z,{className:"primary",style:{margin:"-20px -10px -10px -10px"}},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}},React.createElement("label",{style:{fontWeight:"normal"}},"Query Mode"),React.createElement(De.S,{checked:b,onChange:f,disabled:we})),React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},React.createElement("label",{style:{fontWeight:"normal"}},"Expert Mode"),React.createElement(De.S,{checked:w,onChange:_,disabled:we})))),React.createElement("div",{style:{margin:"20px 8px 8px 8px"}},React.createElement(s.s,{h2:!0,style:{color:"white",marginBottom:10}},"Environment"),React.createElement(g._,{inversed:!0},React.createElement(g.V,{title:"Info",inversed:!0},ae?React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",gap:10,marginBottom:10}},React.createElement("div",{style:{flex:1}},React.createElement("label",null,"Min Score (%)"),React.createElement(G.A,{type:"number",value:void 0!==(null==ae?void 0:ae.min_score)?ae.min_score:35,min:0,max:100,disabled:!ae||we||D,onFinalChange:async e=>{if(ae){F(!0);try{const a=Z.map((t=>t.id===ee?{...t,min_score:parseInt(e)||0}:t));await t(a,"embeddings_envs")}finally{F(!1)}}}})),React.createElement("div",{style:{flex:1}},React.createElement("label",null,"Max Results"),React.createElement(G.A,{type:"number",value:void 0!==(null==ae?void 0:ae.max_select)?ae.max_select:10,min:1,max:100,disabled:!ae||we||D,onFinalChange:async e=>{if(ae){F(!0);try{const a=Z.map((t=>t.id===ee?{...t,max_select:parseInt(e)||1}:t));await t(a,"embeddings_envs")}finally{F(!1)}}}}))),React.createElement("p",{style:{fontSize:12,color:"var(--neko-grey)",marginBottom:10}},"The best ",React.createElement("b",null,(null==ae?void 0:ae.max_select)||10)," embedding(s) with a score of ",React.createElement("b",null,(null==ae?void 0:ae.min_score)||35,"%")," or more will provide additional context to your AI queries."),React.createElement($.g,{tiny:!0}),Ne):React.createElement("p",{style:{color:"var(--neko-grey)",margin:0}},"No environment selected. Select one from the dropdown above.")),w&&React.createElement(g.V,{title:"Settings",inversed:!0},React.createElement(m.R,{label:J.A.EMBEDDINGS.REWRITE_CONTENT,disabled:p,checked:Y.rewriteContent,onChange:e=>{Ce({...Y,rewriteContent:e})},description:J.A.EMBEDDINGS.REWRITE_CONTENT_DESCRIPTION}),Y.rewriteContent&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(xe.m,{value:Y.rewritePrompt,rows:5,disabled:p,onBlur:e=>{Ce({...Y,rewritePrompt:e})},description:J.A.EMBEDDINGS.REWRITE_PROMPT_DESCRIPTION}),React.createElement($.g,null)),React.createElement(m.R,{label:J.A.EMBEDDINGS.FORCE_RECREATE,checked:Y.forceRecreate,disabled:p,onChange:e=>{Ce({...Y,forceRecreate:e})},description:J.A.EMBEDDINGS.FORCE_RECREATE_DESCRIPTION})),React.createElement(g.V,{title:"Sync",inversed:!0},ae&&Te&&React.createElement(React.Fragment,null,React.createElement(q.X,{variant:"danger",style:{marginBottom:10}},"The currently selected environment is not used for Sync. Do you want to use this one?"),React.createElement(h.M,{fullWidth:!0,className:"primary",disabled:we,onClick:()=>Ce({...Y,syncPostsEnvId:ee}),style:{marginBottom:10}},"Use Current Environment")),React.createElement(m.R,{label:"Enable Sync",checked:Y.syncPosts,disabled:p,onChange:e=>{Ce({...Y,syncPosts:e})},description:J.A.EMBEDDINGS.AUTO_SYNC_POSTS_DESCRIPTION}),Y.syncPosts&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(G.A,{name:"syncPostTypes",value:Y.syncPostTypes,isCommaSeparatedArray:!0,description:J.A.HELP.POST_TYPES,onBlur:e=>{Ce({...Y,syncPostTypes:e})}}),w&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(G.A,{name:"syncPostStatus",value:Y.syncPostStatus||"publish",isCommaSeparatedArray:!0,description:J.A.HELP.POST_STATUS,onBlur:e=>{Ce({...Y,syncPostStatus:e})}}),React.createElement($.g,null),React.createElement(G.A,{name:"syncPostCategories",value:Y.syncPostCategories||"publish",isCommaSeparatedArray:!0,description:J.A.HELP.POST_CATEGORIES,onBlur:e=>{Ce({...Y,syncPostCategories:e})}})))),w&&React.createElement(g.V,{title:"Admin",inversed:!0},React.createElement(h.M,{fullWidth:!0,className:"primary",disabled:!ae||we,isBusy:"bulkPullAll"===p,onClick:()=>Ve()},"Pull All"),React.createElement($.g,{tiny:!0}),React.createElement(h.M,{className:"danger",fullWidth:!0,disabled:!ae||p,isBusy:"deleteAllEmbeddings"===p,onClick:async()=>{if(ae&&confirm(J.A.EMBEDDINGS.DELETE_ALL_EMBEDDINGS_CONFIRM+`\n\n${ae.name}`)){E("deleteAllEmbeddings");try{await(0,y.IU)(`${v.y0}/vectors/delete_all`,{nonce:v.ok,method:"POST",json:{envId:ee}}),a.invalidateQueries({queryKey:["vectors"]})}catch(e){alert((null==e?void 0:e.message)??e)}E(!1)}}},"deleteAllEmbeddings"===p?"Deleting...":"Delete All"),React.createElement($.g,null),React.createElement("div",{style:{marginBottom:10}},React.createElement("label",{style:{fontWeight:"bold",marginBottom:5,display:"block"}},"Debug Filter"),React.createElement(j.u,{scrolldown:!0,name:"debugMode",style:{width:"100%"},disabled:we,value:P||null,onChange:L},React.createElement(j.j,{value:null,label:"Current Environment"}),React.createElement(j.j,{value:"includeOrphans",label:"With Orphans"}),React.createElement(j.j,{value:"includeAll",label:"All Envs & Orphans"}))),React.createElement("p",{style:{fontSize:12,color:"var(--neko-grey)",margin:0}},React.createElement("b",null,"Current Environment:")," Shows embeddings from the selected environment only.",React.createElement("br",null),React.createElement("b",null,"With Orphans:")," Includes embeddings that exist in the vector database but have no local content.",React.createElement("br",null),React.createElement("b",null,"All Envs & Orphans:")," Shows all embeddings across all environments, including orphans.")))),!b&&React.createElement("div",{style:{margin:"20px 8px 8px 8px"}},React.createElement(s.s,{h2:!0,style:{color:"white",marginBottom:10}},"Build Knowledge"),React.createElement($.g,null),React.createElement(R.z,{className:"primary",style:{margin:"-20px -10px -10px -10px"}},React.createElement(h.M,{fullWidth:!0,className:"success",icon:"plus",disabled:!ae||we,onClick:()=>x({type:"add"}),style:{marginBottom:w?15:8}},"Create New"),React.createElement("div",{style:{marginBottom:w?15:0}},w&&React.createElement("label",{style:{fontWeight:"bold",marginBottom:5,display:"block"}},"From Internal"),w&&React.createElement("div",{style:{display:"flex",alignItems:"center",marginBottom:8,gap:8}},React.createElement(h.M,{className:"primary",icon:"sync",style:{flex:"0 0 55%"},disabled:!ae||we,isBusy:"singleRun"===p,onClick:()=>{d&&Ke(d)}},"Push"),React.createElement(G.A,{type:"number",placeholder:"Post ID",value:d,onChange:u,style:{flex:"0 0 45%"},disabled:!ae||we,onEnter:e=>{e&&(Ke(e),u(""))}})),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:w?0:8}},React.createElement(h.M,{className:"primary",icon:"sync",style:{flex:"0 0 55%"},disabled:!ae||we,isBusy:"bulkPushAll"===p,onClick:()=>qe(!0)},"Push All ",!ue&&React.createElement(React.Fragment,null,"(",`${pe}`,")")),React.createElement(j.u,{id:"postType",scrolldown:!0,disabled:we,name:"postType",style:{flex:"0 0 45%"},onChange:c,value:i},null==me?void 0:me.map((e=>React.createElement(j.j,{key:e.type,value:e.type,label:e.name})))))),React.createElement("div",null,w&&React.createElement("label",{style:{fontWeight:"bold",marginBottom:5,display:"block"}},"From External"),v.am&&React.createElement(React.Fragment,null,React.createElement(h.M,{fullWidth:!0,className:"primary",icon:"file-upload",disabled:!ae||we,onClick:()=>x({type:"pdf-import"}),style:{marginBottom:w?8:0}},"Upload PDF")),w&&React.createElement(Fe.Z,{ref:X,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=Me().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 s=[],c=[];if(n.forEach(((e,t)=>{var a,n;if(!e||"object"!=typeof e)return void c.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?s.push({title:l,content:r,type:e.type||null,refId:e.refId||null,refUrl:e.refUrl||null}):c.push(`Row ${t+1}: Missing content`):c.push(`Row ${t+1}: Missing title`):c.push(`Row ${t+1}: Both title and content are empty`)})),0===s.length)return void B({title:"No Valid Entries",message:"No entries with both title and content were found",details:c.slice(0,5).join("\n")+(c.length>5?`\n...and ${c.length-5} more issues`:""),help:"Each entry must have both a 'title' and 'content' field with non-empty values."});c.length>0&&console.warn("Import validation issues:",c),x({type:"import",data:{importVectors:s,envId:ee,totalEntries:n.length,validEntries:s.length,invalidEntries:c.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",icon:"file-upload",disabled:!ae||we,onClick:()=>X.current.click()},"Upload CSV or JSON"))))))),React.createElement(wt,{modal:k,setModal:x,busy:p,onAddEmbedding:Ie,onModifyEmbedding:Se}),React.createElement(Tt,{modal:k,setModal:x,busy:p}),React.createElement(Nt,{modal:k,setModal:x,busy:p,onAddEmbedding:Ie,onModifyEmbedding:Se}),Pt&&React.createElement(xt,{fallback:React.createElement("div",null)},React.createElement(Pt,{modal:k,setModal:x,onAddEmbedding:Ie,environment:ae})),React.createElement(V.n,{isOpen:!!U,title:(null==U?void 0:U.title)||"Import Error",onRequestClose:()=>B(null),okButton:{label:"Close",onClick:()=>B(null)},content:React.createElement("div",null,React.createElement("p",{style:{marginBottom:10}},null==U?void 0:U.message),(null==U?void 0:U.details)&&React.createElement("div",{style:{backgroundColor:"#f5f5f5",padding:10,borderRadius:4,marginBottom:10,fontFamily:"monospace",fontSize:"12px",whiteSpace:"pre-wrap",maxHeight:"150px",overflowY:"auto"}},U.details),(null==U?void 0:U.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),U.help))}),React.createElement(V.n,{isOpen:!!H,title:"push"===(null==H?void 0:H.type)?"Push Complete":"Pull Complete",onRequestClose:()=>W(null),okButton:{label:"Close",onClick:()=>W(null)},content:H&&React.createElement("div",null,React.createElement(q.X,{variant:0===H.stats.errors?"success":"warning",style:{marginBottom:15}},React.createElement("strong",null,0===H.stats.errors?"Success":"⚠️ Completed with Issues"),React.createElement("br",null),"push"===H.type?React.createElement(React.Fragment,null,React.createElement("strong",null,H.stats.added)," added •",React.createElement("strong",null,H.stats.updated)," updated •",React.createElement("strong",null,H.stats.upToDate)," up-to-date",H.stats.skipped>0&&React.createElement(React.Fragment,null," • ",React.createElement("strong",null,H.stats.skipped)," skipped")):`Successfully pulled ${H.stats.added} embeddings`,H.stats.errors>0&&React.createElement(React.Fragment,null,React.createElement("br",null),React.createElement("strong",{style:{color:"var(--neko-red)"}},H.stats.errors," error",H.stats.errors>1?"s":""))),!1,H.stats.errors>0&&H.stats.errorDetails.length>0&&React.createElement(q.X,{variant:"danger",style:{marginBottom:15}},React.createElement("strong",null,"Error Details:"),React.createElement("div",{style:{maxHeight:150,overflowY:"auto",marginTop:8}},H.stats.errorDetails.slice(0,5).map(((e,t)=>React.createElement("div",{key:t,style:{fontSize:12,marginTop:4}},"• ",e.postId?`Post #${e.postId}`:e.title||e.dbId||`Item ${t+1}`,": ",e.error))),H.stats.errorDetails.length>5&&React.createElement("div",{style:{marginTop:8,fontSize:12,fontStyle:"italic"}},"...and ",H.stats.errorDetails.length-5," more errors"))),"pull"===H.type&&H.stats.remoteTotal>0&&React.createElement(q.X,{variant:"info",style:{marginTop:15}},React.createElement("strong",null,H.stats.remoteTotal)," total embeddings found in the vector database"))}))};var jt=a(2262),Gt=a(4731);const{useState:$t,useMemo:Wt,Fragment:zt}=wp.element;jt.t1.register(jt.PP,jt.kc,jt.E8,jt.m_,jt.s$);const Vt=({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"}},J.A.COMMON.DATA_NOT_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(zt,{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"}},J.A.COMMON.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"}},J.A.COMMON.QUERIES)))));const l=e.name===J.A.COMMON.UNKNOWN_MODEL?`⚠️ ${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"}},J.A.COMMON.QUERIES.toLowerCase()))})))):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(zt,{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)}$`:"-"))})))),qt=({options:e})=>{const{models:t,getModel:a,calculatePrice:n}=ie(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)(),[s,c]=$t("family"),[d,m]=$t("price"),[u,p]=$t("daily"),E=Wt((()=>{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,c=null,d=!1,m=!1;l?"image"===l.type?(c=(null==t?void 0:t.images)||0,m=!0):"second"===l.type?(c=(null==t?void 0:t.seconds)||0,d=!0):(i=(null==t?void 0:t.prompt_tokens)||0,c=(null==t?void 0:t.completion_tokens)||0):(i=(null==t?void 0:t.prompt_tokens)||0,c=(null==t?void 0:t.completion_tokens)||0);const u=l?n(e,i,c):0,p=m?c:i+c,E=(null==t?void 0:t.queries)||0,g="family"===s&&null!=l&&l.family?l.family:e,h="family"===s&&null!=l&&l.family?l.family:l?l.rawName:J.A.COMMON.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"===s&&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,s]),g=Wt((()=>{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=Wt((()=>{const e=Object.keys(g).sort(),a=[],n=[i.blue,i.green,i.yellow,i.orange,i.red,i.purple];if("model"===s){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=>e.name===J.A.COMMON.UNKNOWN_MODEL));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:J.A.COMMON.UNKNOWN_MODEL,data:l,backgroundColor:"rgba(128, 128, 128, 0.5)"})}else if("family"===s){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,s,d,i]),R=Wt((()=>{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"}},J.A.COMMON.DATA_NOT_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(z.o,{name:"metric",value:d,onChange:m},React.createElement(z.K,{title:J.A.COMMON.PRICE,value:"price"}),React.createElement(z.K,{title:J.A.COMMON.UNITS,value:"tokens"}),React.createElement(z.K,{title:J.A.COMMON.QUERIES,value:"queries"})),React.createElement(z.o,{name:"groupBy",value:s,onChange:c},React.createElement(z.K,{title:J.A.COMMON.FAMILY,value:"family"}),React.createElement(z.K,{title:J.A.COMMON.MODEL,value:"model"}))),React.createElement(z.o,{name:"viewMode",value:u,onChange:p},React.createElement(z.K,{title:J.A.COMMON.DAILY,value:"daily"}),React.createElement(z.K,{title:J.A.COMMON.MONTHLY,value:"monthly"}))),React.createElement($.g,{size:"medium"}),React.createElement(Gt.yP,{options:y,data:h}),React.createElement($.g,{size:"medium"}),React.createElement(Ue.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()} ${J.A.COMMON.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(Ue.y2,{key:t,title:`${l} ${o} (${r})`},React.createElement(Vt,{month:e,usageData:g,groupBy:s,metric:d}))}))),React.createElement($.g,{size:"medium"}),React.createElement("div",{style:{fontSize:"var(--neko-small-font-size)",color:"var(--neko-gray-60)"}},J.A.COMMON.USAGE_ESTIMATES_NOTE)))};var Kt=a(6841);const{useState:Yt}=wp.element;function Xt(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 Qt=({modal:e,setModal:t})=>{const[a,n]=Yt(!1),[l,r]=Yt(0),[o,i]=Yt(0),s=async()=>{let e=!1;const t={page:1,limit:20,filters:{}};let a=[];for(;!e;){const n=await ce(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(V.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 s(),t=(0,y.F1)(e,2),a=new Date,l=a.getFullYear(),o=a.getMonth()+1;Xt(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(He.j,{busy:a,style:{flex:"auto"},value:o,max:l}))}))},{useMemo:Jt,useState:Zt,useEffect:ea,useCallback:ta}=wp.element,aa=()=>{const e=localStorage.getItem("mwai-admin-discussions");try{const t=JSON.parse(e);return{isSidebarCollapsed:(null==t?void 0:t.isSidebarCollapsed)||!1}}catch(e){return{isSidebarCollapsed:!1}}},na=f.Ay.div`
font-size: 12px;
border-bottom: 1px solid black;
`,la=f.Ay.span`
font-weight: bold;
text-transform: uppercase;
`,ra=f.Ay.div`
font-size: 12px;
color: #bdb8b8;
background: #eeeeee;
padding: 2px 8px;
`,oa=f.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;
}
`,ia={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>`}}},sa=({content:e})=>{const[t,a]=Zt(e||""),n=e=>new Promise((t=>{const a=new Image;a.onload=()=>t(!0),a.onerror=()=>t(!1),a.src=e}));ea((()=>{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=Jt((()=>{let e="";try{e=(0,Kt.cx)(t,ia)}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)},ca=({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(na,null,React.createElement(la,null,e.role||e.type)),(null==r?void 0:r.length)>0&&React.createElement(ra,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(sa,{content:e.content||e.text}))},da=async(e=[])=>await le(`${v.y0}/discussions/delete`,{nonce:(0,v.c3)(),method:"POST",json:{chatIds:e}}),ma=()=>{var e,t,a,n,r,i,s,c,d,u,p;const E=(0,l.jE)(),[g,b]=Zt({type:null,data:null}),[f,w]=Zt(!1),[_,C]=Zt(!1),[T,A]=Zt((()=>aa().isSidebarCollapsed)),{data:N}=(0,o.I)({queryKey:["chatbots"],queryFn:qe,initialData:v.N6});ea((()=>{(({isSidebarCollapsed:e})=>{const t=aa(),a={isSidebarCollapsed:void 0!==e?e:t.isSidebarCollapsed};localStorage.setItem("mwai-admin-discussions",(0,y.F1)(a))})({isSidebarCollapsed:T})}),[T]);const O=Jt((()=>[{accessor:"updated",title:"Time",width:"95px",sortable:!0},{accessor:"user",title:"User",width:"100px",filters:{type:"text",description:J.A.HELP.USER_FILTER}},{accessor:"botId",title:"Chatbot",width:"100px",filters:{type:"select",options:N.map((e=>({value:e.botId,label:e.name})))}},{accessor:"preview",title:J.A.COMMON.PREVIEW,width:"100%",filters:{type:"text"}},{accessor:"messages",title:"#",width:"45px"}]),[N]),[I,S]=Zt((()=>O.filter((e=>e.filters)).map((e=>({accessor:e.accessor,value:null}))))),[M,k]=Zt([]),[x,P]=Zt({filters:I,sort:{accessor:"updated",by:"desc"},page:1,limit:10}),L=ta((async()=>!document.hidden?await ce(x):new Promise((()=>{}))),[x]),{isFetching:D,data:F,error:U}=(0,o.I)({queryKey:["chats",JSON.stringify(x)],queryFn:L,refetchInterval:_?5e3:null});ea((()=>{P({...x,filters:I})}),[I]);const B=Jt((()=>(null==F?void 0:F.total)||0),[F]),H=Jt((()=>null!=F&&F.chats?F.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=me(e.created),l=me(e.updated),r=ue(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:"",s=null!=o&&o.length?o[o.length-1].content||o[o.length-1].text:"",c=N.find((t=>t.botId===e.botId)),d=null==a?void 0:a.parentBotId,m=d?N.find((e=>e.botId===d)):null;let u,p=null;c?u=c.name:m?(u=m.name,p=React.createElement(ke.z,{icon:"tools",height:"14",style:{position:"relative",top:2,marginRight:2},tooltip:"Overriden Bot"})):u=React.createElement(React.Fragment,null,React.createElement(ke.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,s));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)}})):[]),[F,N]),j=Jt((()=>{if(1!==(null==M?void 0:M.length))return null;const e=null==F?void 0:F.chats.find((e=>e.id===M[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}}),[M,F]),G=async()=>{if(w(!0),M.length){const e=null==F?void 0:F.chats.filter((e=>M.includes(e.id))),t=e.map((e=>e.chatId));await da(t),k([])}else{if(!window.confirm(J.A.ALERTS.ARE_YOU_SURE))return void w(!1);await da()}await E.invalidateQueries({queryKey:["chats"]}),E.refetchQueries({queryKey:["chats"]}),w(!1)},$=Jt((()=>React.createElement("div",null,React.createElement("div",{style:{display:"flex",flexDirection:"row"}},React.createElement(Be.Q,{currentPage:x.page,limit:x.limit,onCurrentPageChanged:e=>P({...x,page:e}),total:B,onClick:e=>{P({...x,page:e})}}),React.createElement(h.M,{className:"primary",style:{marginLeft:5},onClick:()=>{b({type:"export",data:{}})}},J.A.COMMON.EXPORT)))),[x,B]),W=Jt((()=>null!=U&&U.message?React.createElement(q.X,{variant:"danger",style:{margin:"5px 5px"}},React.createElement("b",null,U.message),React.createElement("br",null),React.createElement("small",null,"Check your Console Logs and PHP Error Logs for more information.")):null),[U]),z=me(null==j?void 0:j.created),V=me(null==j?void 0:j.updated);return React.createElement(React.Fragment,null,React.createElement(ht.J,{mainFlex:2,sidebarFlex:1,minimal:!0,isCollapsed:T,onToggle:()=>A(!T),showToggle:!1},React.createElement(ht.J.Main,null,React.createElement(R.z,{className:"primary",title:J.A.COMMON.DISCUSSIONS,action:React.createElement("div",{style:{display:"flex",alignItems:"center",gap:5}},!_&&React.createElement(h.M,{className:"secondary",disabled:D,onClick:async()=>{await E.invalidateQueries({queryKey:["chats"]})}},J.A.COMMON.REFRESH),M.length>0&&React.createElement(h.M,{className:"danger",disabled:!1,onClick:G},J.A.COMMON.DELETE),React.createElement(Rt.A,{isCollapsed:T,onClick:()=>A(!T),border:"left",direction:"right"}))},React.createElement(Pe.o,{busy:!_&&D||f,sort:x.sort,onSortChange:(e,t)=>{P({...x,sort:{accessor:e,by:t}})},emptyMessage:W,filters:I,onFilterChange:(e,t)=>{const a=[...I.filter((t=>t.accessor!==e)),{accessor:e,value:t}];S(a)},data:U?[]:H,columns:O,selectedItems:M,onSelectRow:e=>{1!==M.length||M[0]!==e?k([e]):k([])},onSelect:e=>{k([...M,...e])},onUnselect:e=>{k([...M.filter((t=>!e.includes(t)))])}}),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginTop:10}},React.createElement(h.M,{className:"danger",disabled:M.length,style:{marginRight:10},onClick:G},J.A.COMMON.DELETE_ALL),React.createElement(m.R,{name:"auto-refresh",label:"Auto Refresh",value:"1",checked:_,style:{width:180},onChange:()=>C(!_)}),React.createElement("div",{style:{flex:"auto"}}),$))),React.createElement(ht.J.Sidebar,null,React.createElement(R.z,{className:"primary",title:"Selected Discussion",action:React.createElement(React.Fragment,null)},!j&&React.createElement("div",{style:{textAlign:"center",padding:10}},"No discussion selected."),null==j||null===(e=j.messages)||void 0===e?void 0:e.map(((e,t)=>React.createElement(ca,{key:t,message:e})))),!!j&&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==j||null===(t=j.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==j?void 0:j.botId)),(null==j||null===(a=j.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==j||null===(n=j.extra)||void 0===n?void 0:n.parentBotId)),(null==j||null===(r=j.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==j||null===(i=j.extra)||void 0===i?void 0:i.context)),(null==j||null===(s=j.extra)||void 0===s?void 0:s.assistantId)&&React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Assistant ID"),React.createElement("div",null,null==j||null===(c=j.extra)||void 0===c?void 0:c.assistantId)),(null==j||null===(d=j.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==j||null===(u=j.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==j?void 0:j.chatId)),React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Session"),React.createElement("div",null,null==j||null===(p=j.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,z)),React.createElement("div",{style:{display:"flex",flexDirection:"column",marginBottom:5}},React.createElement("div",{style:{fontWeight:"bold"}},"Updated"),React.createElement("div",null,V))))),React.createElement(Qt,{modal:g,setModal:b,busy:f}))};var ua=a(5924);const pa=f.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%;
}
`,Ea=(0,f.Ay)(G.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;
}
`,ga=(f.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;
}
`,f.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;
}
`,f.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:ha}=wp.element,Ra=({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 s=ha((()=>e?r||(l?Math.floor(l/2):o?Math.floor(o/2):null):null),[r,l,o]),c=ha((()=>e?s===t?"var(--neko-green)":t>r?"var(--neko-red)":"var(--neko-yellow)":null),[r,t,s]);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,J.A.COMMON.CONTEXTUAL,": ",e.maxContextualTokens.toLocaleString(),React.createElement("br",null)),!(null==e||!e.maxCompletionTokens)&&React.createElement(React.Fragment,null,J.A.COMMON.COMPLETION,": ",e.maxCompletionTokens.toLocaleString(),React.createElement("br",null))),!(null!=e&&e.maxCompletionTokens)&&!(null==e||!e.maxTokens)&&React.createElement(React.Fragment,null,J.A.COMMON.TOTAL_MAX_TOKENS,": ",e.maxTokens.toLocaleString(),React.createElement("br",null)),!!s&&s!==t&&React.createElement(React.Fragment,null,J.A.COMMON.RECOMMENDED,": ",React.createElement("b",{onClick:i?()=>a(s):null,style:{color:c,cursor:i?"pointer":"inherit"}},s.toLocaleString(),t>r&&React.createElement(React.Fragment,null,"❗️")),React.createElement("br",null)))},{useState:ya,useMemo:va}=wp.element,ba=f.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;
}
`,fa=e=>"string"!=typeof e?e:e.replace(/"/g,""").replace(/'/g,"'").replace(/\n/g,"\\n").replace(/\[/g,"[").replace(/\]/g,"]"),wa=({currentChatbot:e,isCustom:t=!1,defaultChatbot:a,...n})=>{const[l,r]=ya(null),o=va((()=>{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=fa(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(ba,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 _a=a(7678);function Ca(){return Ca=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},Ca.apply(this,arguments)}const{useMemo:Ta,useState:Aa,useEffect:Na,useRef:Oa}=wp.element,Ia="drop-shadow(0 0 5px rgba(0,0,0,0.1))",Sa=["alloy","ash","ballad","cedar","coral","echo","marin","sage","shimmer","verse"],Ma=["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"],ka=({label:e,valueName:t,updateShortcodeParams:a,icon:n})=>{const l=n||"chat-color-green.svg",r=(0,_a.Ve)(l),o=r||(null==l?void 0:l.startsWith("https://"))||(null==l?void 0:l.startsWith("http://")),i=o?l:`${v.Hm}/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"}},Ma.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:Ia},width:24,height:24,src:`${v.Hm}/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(`${v.Hm}/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:Ia},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,J.A.COMMON.CUSTOM_ICON,":"),React.createElement(G.A,{name:"icon",value:l,onBlur:e=>a(e,t),onEnter:e=>a(e,t)})))))},xa=e=>{var t,a,n,l,r,o,i,s,c,d,u,p,g,R,b,f,w,_,C,T,A,N,O,I,S,M,k;const{themes:x,shortcodeParams:P,updateShortcodeParams:L,defaultChatbot:D,blockMode:F,deleteCurrentChatbot:U,resetCurrentChatbot:B,duplicateCurrentChatbot:H,options:W,...z}=e,V=null==W?void 0:W.dev_mode,K=null==W?void 0:W.module_cross_site,{completionModels:Y,imageModels:X,realtimeModels:Q,getModel:Z}=ie(W,P.envId||null),ee="chat"===P.mode??"chat",te="assistant"===P.mode??!1,ae="images"===P.mode??!1,ne="realtime"===P.mode??!1,le="prompt"===P.mode??!1,re=P.contentAware,oe=Ta((()=>(null==W?void 0:W.ai_envs)||[]),[W.ai_envs]),se=null==W?void 0:W.module_embeddings,ce=null==W?void 0:W.module_orchestration,de=(null==W?void 0:W.functions)||[],me=P.functions||[],[ue,pe]=Aa(!1),ve=(null==W?void 0:W.mcp_envs)||[],fe=P.mcpServers||[],we=Oa(P.envId);Na((()=>{we.current=P.envId}),[P.envId]);const _e=Ta((()=>P.instructions&&P.instructions.includes("{CONTENT}")),[P.instructions]),Ce=Ta((()=>oe.find((e=>e.id===P.envId))||null),[oe,P.envId]),Te=Ta((()=>(null==Ce?void 0:Ce.assistants)||[]),[Ce]),Ae=Ta((()=>Te.find((e=>e.id===P.assistantId))||null),[Te,P.assistantId]),Ne=Ae?Ae.model:P.model||(P.envId?null:null==W?void 0:W.ai_default_model),Oe=Z(Ne),Ie=W.embeddings_envs||[],Se=Ta((()=>{var e;return null==Oe||null===(e=Oe.tags)||void 0===e?void 0:e.includes("functions")}),[Oe]),Me=Ta((()=>{var e;return null==Oe||null===(e=Oe.tags)||void 0===e?void 0:e.includes("vision")}),[Oe]),ke=Ta((()=>{var e;return null==Oe||null===(e=Oe.tags)||void 0===e?void 0:e.includes("files")}),[Oe]),Pe=Ta((()=>{var e;return null==Oe||null===(e=Oe.tags)||void 0===e?void 0:e.includes("image")}),[Oe]),Le=Ta((()=>{var e;return(null==Oe||null===(e=Oe.tags)||void 0===e?void 0:e.includes("mcp"))||!1}),[Oe]),De=Ta((()=>{var e;return(null==Oe||null===(e=Oe.tools)||void 0===e?void 0:e.length)>0}),[Oe]),Fe=Ta((()=>{var e;return null==Oe||null===(e=Oe.tags)||void 0===e?void 0:e.includes("responses")}),[Oe]),Be=Ta((()=>{var e;return null==Oe||null===(e=Oe.tags)||void 0===e?void 0:e.includes("reasoning")}),[Oe]),He=Ta((()=>{var e;return null==Oe||null===(e=Oe.tags)||void 0===e?void 0:e.includes("verbosity")}),[Oe]),je=Ta((()=>{if(!P.embeddingsEnvId||!Oe)return!1;const e=Ie.find((e=>e.id===P.embeddingsEnvId));if(!e||"openai-vector-store"!==e.type)return!1;const t=e.openai_env_id,a=P.envId||(null==W?void 0:W.ai_default_env),n=oe.find((e=>e.id===a)),l=!n||"openai"===n.type,r=Fe,o=!1!==(null==W?void 0:W.ai_responses_api);return l&&r&&o&&t===a&&e.store_id}),[P.embeddingsEnvId,P.envId,Oe,Ie,Fe,oe,W]),$e=Ta((()=>ae?X:(ne?Q:Y)??[]),[ae,ne,Y,X,Q]);Na((()=>{const e=me.filter((e=>de.some((t=>t.id===e.id)))),t=fe.filter((e=>ve.some((t=>t.id===e.id))));if(e.length!==me.length)console.warn("Update Params: Functions has been updated."),L(e,"functions");else if(t.length!==fe.length)console.warn("Update Params: MCP Servers has been updated."),L(t,"mcpServers");else if(Pe&&!P.resolution){if(console.warn("Update Params: Resolution has been set."),null!=Oe&&Oe.resolutions){const e=Oe.resolutions.map((e=>e.name)),t=e.includes("1024x1024")?"1024x1024":e[0];L(t,"resolution")}}else!Pe&&P.resolution?(console.warn("Update Params: Resolution has been removed."),L(null,"resolution")):Pe&&ee||te&&P.model?(console.warn("Update Params: Model has been removed."),L(null,"model")):!te&&P.assistantId?(console.warn("Update Params: Assistant has been removed."),L(null,"assistantId")):!P.imageUpload||Me||ae?P.fileSearch&&!te?(console.warn("Update Params: File search has been removed."),L(null,"fileSearch")):P.model&&!P.envId?(console.warn("Update Params: Model has been removed."),L("","model")):P.envId&&!Ce?(console.warn("Update Params: Environment has been removed."),L(null,"envId")):P.model&&P.envId&&!Oe?(console.warn("Update Params: Model has been removed because it doesn't exist in the current environment."),L("","model")):!P.model&&P.envId&&$e.length>0&&we.current!==P.envId?(console.log("Update Params: Auto-selecting first available model for the environment."),L($e[0].model,"model")):!se&&P.embeddingsEnvId?(console.warn("Update Params: Embeddings environment has been removed."),L(null,"embeddingsEnvId")):!te||!P.fileSearch||null!=Ae&&Ae.has_file_search?P.aiAvatar||P.aiName?P.userAvatar||P.userName?P.guestAvatar||P.guestName||(console.warn("Update Params: Guest avatar has been set to true."),L(!0,"guestAvatar")):(console.warn("Update Params: User avatar has been set to true."),L(!0,"userAvatar")):(console.warn("Update Params: AI avatar has been set to true."),L(!0,"aiAvatar")):(console.warn("Update Params: File search has been removed."),L(null,"fileSearch")):(console.warn("Update Params: Vision has been removed."),L(null,"imageUpload"))}),[P,fe,ve,Oe,$e]);const We=Ta((()=>Pe&&Oe?Oe.resolutions?null==Oe?void 0:Oe.resolutions:(console.error("This image model does not have resolutions.",Oe),[]):[]),[Oe,Pe]),ze=Ta((()=>{const e=[ee?"Chat":te?"Assistant":ae?"Images":ne?"Realtime":le?"Prompt":null,(null==P?void 0:P.botId)||(null==D?void 0:D.id)||"default"].filter(Boolean).join(", ");return React.createElement("div",null,J.A.COMMON.CHATBOT,React.createElement("small",{style:{opacity:.5}}," ",e))}),[ee,te,null==P?void 0:P.botId,null==D?void 0:D.id]),Ve=Ta((()=>{const e=(e,t)=>{const a=oe.find((t=>t.id===e));if(!a)return null;const n=Z(t);return[a.name,null==n?void 0:n.rawName].filter(Boolean).join(", ")},t=ne&&!P.envId;if(P.envId){const t=e(P.envId,P.model);if(t)return React.createElement("div",null,J.A.COMMON.AI_MODEL,React.createElement("small",{style:{opacity:.5}}," ",t))}else{const a=e(null==W?void 0:W.ai_default_env,null==W?void 0:W.ai_default_model);if(a)return React.createElement("div",null,J.A.COMMON.AI_MODEL,React.createElement("small",{style:{opacity:.5}}," ",a),t&&React.createElement("small",{style:{color:"#ff6b6b",fontWeight:"bold"}}," (Configuration Required)"))}return React.createElement("div",null,J.A.COMMON.AI_MODEL,t&&React.createElement("small",{style:{color:"#ff6b6b",fontWeight:"bold"}}," (Configuration Required)"))}),[P.envId,P.model,oe,Z,null==W?void 0:W.ai_default_env,null==W?void 0:W.ai_default_model,ne]),qe=Ta((()=>{if(P.embeddingsEnvId){const e=Ie.find((e=>e.id===P.embeddingsEnvId));if(e){const t=[e.name,re?"Content Aware":null].filter(Boolean).join(", ");return React.createElement("div",null,J.A.COMMON.CONTEXT,React.createElement("small",{style:{opacity:.5}}," ",t))}}return J.A.COMMON.CONTEXT}),[P.embeddingsEnvId,Ie,re]),Ke=Ta((()=>{const e=J.A.COMMON.FUNCTIONS,t=me.length>0,a=t?`Enabled: ${me.length}, Total: ${de.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),!Se&&t&&React.createElement("small",{style:{color:"#ff6b6b",fontWeight:"bold"}},"(Not Supported)"))}),[me,de,Se]),Ye=Ta((()=>{const e=J.A.COMMON.MCP_SERVERS,t=fe.length>0,a=t?`Enabled: ${fe.length}, Total: ${ve.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),!Le&&t&&React.createElement("small",{style:{color:"#ff6b6b",fontWeight:"bold"}},"(Not Supported)"))}),[fe,ve,Le]),Xe=Ta((()=>{const e=P.tools||[],t=(null==Oe?void 0:Oe.tools)||[],a=J.A.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,")"))}),[P.tools,Oe]),Qe=Ta((()=>{const e=P.contextMaxLength||(null==W?void 0:W.context_max_length),t=[P.maxMessages?`Messages: ${P.maxMessages}`:null,e?`Context: ${e}`:null].filter(Boolean).join(", ");return React.createElement("div",null,J.A.COMMON.THRESHOLDS,React.createElement("small",{style:{opacity:.5}}," ",t))}),[P.contextMaxLength,P.maxMessages,null==W?void 0:W.context_max_length]),Je=Ta((()=>{const e=null==x?void 0:x.find((e=>e.themeId===P.themeId)),t=[(null==e?void 0:e.name)||P.themeId,P.window?"Popup":null].filter(Boolean).join(", ");return React.createElement("div",null,J.A.COMMON.APPEARANCE,React.createElement("small",{style:{opacity:.5}}," ",t))}),[P.themeId,P.window,x]),Ze=Ta((()=>{const e={standard:"Standard",osx:"MacOS",none:"None"},t=[P.containerType,P.headerType,P.messagesType,P.inputType,P.footerType].filter(Boolean),a=[...new Set(t)].map((t=>e[t]||t)).sort();return React.createElement("div",null,"UI Builder",a.length>0&&React.createElement("small",{style:{opacity:.5}}," ",a.join(", ")))}),[P.containerType,P.headerType,P.messagesType,P.inputType,P.footerType]);return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,Ca({minimal:!0},z),React.createElement(ga,null,React.createElement(Ue.Zc,{keepState:"chatbotParams"},React.createElement(Ue.y2,{title:ze},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.NAME,":"),React.createElement(G.A,{name:"name","data-form-type":"other",disabled:"default"===P.botId,value:P.name,onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("div",null,React.createElement("label",{style:{display:"block"}},J.A.COMMON.ID,":"),React.createElement(G.A,{name:"botId",type:"text",placeholder:"Optional",disabled:"default"===P.botId,value:P.botId,onBlur:L,onEnter:L}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("div",null,React.createElement("label",{style:{display:"block"}},J.A.COMMON.SCOPE,":"),React.createElement(G.A,{name:"scope",type:"text",placeholder:"Scope",value:P.scope,onBlur:L,onEnter:L}))),!ne&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.LOCAL_MEMORY,":"),React.createElement(m.R,{name:"localMemory",label:"Yes",checked:P.localMemory,value:"1",onChange:L}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{height:"chat"===P.mode?76:"inherit"}},React.createElement("label",null,J.A.COMMON.MODE,":"),React.createElement(j.u,{scrolldown:!0,id:"mode",name:"mode",value:P.mode,onChange:L},React.createElement(j.j,{value:"chat",label:"Chat"}),React.createElement(j.j,{value:"images",label:"Images"}),React.createElement(j.j,{value:"assistant",label:"Assistant",isPro:!0,requirePro:!v.zN}),React.createElement(j.j,{value:"realtime",label:"Realtime",isPro:!0,requirePro:!v.zN}),React.createElement(j.j,{value:"prompt",label:"Prompt",isPro:!0,requirePro:!v.zN}))),(ee||te||ne)&&!le&&React.createElement("div",{className:"mwai-builder-col",style:{flex:5}},React.createElement("label",null,J.A.COMMON.INSTRUCTIONS,":"),React.createElement(xe.m,{name:"instructions",rows:10,textAreaStyle:{resize:"none"},value:P.instructions,onBlur:L,onEnter:L})),le&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-builder-col",style:{flex:5}},React.createElement("label",null,J.A.COMMON.PROMPT_ID||"Prompt ID",":"),React.createElement(G.A,{name:"promptId",placeholder:"pmpt_abc123",disabled:!v.zN,description:v.zN?"Enter your OpenAI Prompt ID (e.g., pmpt_abc123)":"Pro Only: This feature requires a Pro license",value:P.promptId,onBlur:L,onEnter:L}))))),React.createElement(Ue.y2,{title:Ve},le&&!P.promptId&&v.zN&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(q.X,{variant:"info",style:{marginBottom:10}},"Prompt mode uses OpenAI's Prompt feature with the Responses API. Please enter a valid Prompt ID to continue.")),ne&&!P.envId&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(q.X,{variant:"warning",style:{marginBottom:10}},"Realtime chatbots require a specific AI environment to be selected.")),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.ENVIRONMENT,":"),React.createElement(j.u,{scrolldown:!0,name:"envId",value:P.envId??"",onChange:L,description:P.envId&&""!==P.envId?null:(()=>{const e=oe.find((e=>e.id===(null==W?void 0:W.ai_default_env)));return e?`→ ${e.name}`:null})()},oe.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(j.j,{value:"",label:"Default"}))),(ee||ae||ne)&&!le&&React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,J.A.COMMON.MODEL,":"),React.createElement(j.u,{scrolldown:!0,textFiltering:$e.length>16,name:"model",disabled:!P.envId,value:P.model||"",onChange:L,description:P.model&&""!==P.model||P.envId?null:`→ ${null==W?void 0:W.ai_default_model}`},React.createElement(j.j,{value:"",label:P.envId?"None":"Default"}),$e.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name}))))),le&&React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,J.A.COMMON.MODEL,":"),React.createElement(G.A,{name:"model",value:P.model||"",disabled:!0,description:"Model is configured in the Prompt"})),te&&React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,J.A.COMMON.ASSISTANT,":"),React.createElement(j.u,{scrolldown:!0,name:"assistantId",value:P.assistantId,onChange:L},React.createElement(j.j,{value:"",label:"None"}),Te.map((e=>React.createElement(j.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,J.A.COMMON.RESOLUTION,":"),React.createElement(j.u,{scrolldown:!0,name:"resolution",value:P.resolution,onChange:L},We.map((e=>React.createElement(j.j,{key:e.name,value:e.name,label:e.label}))))),(Me||ae)&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,ae?J.A.COMMON.IMAGE_UPLOAD||"Image Upload":J.A.COMMON.VISION,":"),React.createElement(m.R,{name:"imageUpload",label:J.A.COMMON.ENABLE,checked:P.imageUpload,value:"1",onChange:L})),ke&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.FILES,":"),React.createElement(m.R,{name:"fileUpload",label:J.A.COMMON.ENABLE,checked:P.fileUpload,value:"1",onChange:L}))),(ee||ne)&&!le&&React.createElement("div",{className:"mwai-builder-row"},ne&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.VOICE,":"),React.createElement(j.u,{scrolldown:!0,name:"voice",value:P.voice,onChange:L},React.createElement(j.j,{value:"",label:"Default"}),Sa.map((e=>React.createElement(j.j,{key:e,value:e,label:e.charAt(0).toUpperCase()+e.slice(1)}))))),!Be&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.TEMPERATURE,":"),React.createElement(G.A,{name:"temperature",type:"number",step:"0.1",min:"0",max:"1",value:P.temperature,onBlur:L,onEnter:L})),Be&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.REASONING||"Reasoning",":"),React.createElement(j.u,{name:"reasoningEffort",description:J.A.HELP.REASONING_EFFORT||"Controls how many reasoning tokens the model generates before producing a response",value:P.reasoningEffort||"medium",onChange:L},React.createElement(j.j,{value:"minimal",label:"Minimal"}),React.createElement(j.j,{value:"low",label:"Low"}),React.createElement(j.j,{value:"medium",label:"Medium"}),React.createElement(j.j,{value:"high",label:"High"}))),He&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.VERBOSITY||"Verbosity",":"),React.createElement(j.u,{name:"verbosity",description:J.A.HELP.VERBOSITY||"Determines how many output tokens are generated",value:P.verbosity||"medium",onChange:L},React.createElement(j.j,{value:"low",label:"Low"}),React.createElement(j.j,{value:"medium",label:"Medium"}),React.createElement(j.j,{value:"high",label:"High"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.MAX_TOKENS,":"),React.createElement(G.A,{name:"maxTokens",type:"number",description:React.createElement(Ra,{model:Oe,maxTokens:P.maxTokens,onRecommendedClick:e=>{L(e,"maxTokens")},style:{fontSize:11,lineHeight:"8px"}}),value:P.maxTokens,onBlur:L,onEnter:L})))),te&&React.createElement(Ue.y2,{title:J.A.COMMON.ASSISTANT},React.createElement(q.X,{type:"warning"},React.createElement("strong",null,"⚠️ Assistants are being deprecated by OpenAI"),React.createElement("br",null),"End of life is planned for mid-2026. We recommend using OpenAI models directly with the appropriate tools instead. For knowledge bases, you can use a Vector Store directly, which provides the same capabilities as Assistants (and often better performance). AI Engine is focusing development efforts on the Responses API going forward."),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.FILE_SEARCH,":"),React.createElement(j.u,{scrolldown:!0,name:"fileSearch",disabled:!(null!=Ae&&Ae.has_file_search),description:null!=Ae&&Ae.has_file_search?(0,y.FE)(J.A.SETTINGS.ASSISTANT_FILE_SEARCH):be(J.A.SETTINGS.ASSISTANT_NO_FILE_SEARCH,J.A.SETTINGS.ASSISTANT_NO_FILE_SEARCH_URL,J.A.SETTINGS.ASSISTANT_NO_FILE_SEARCH_LINK_TEXT),value:P.fileSearch,onChange:L},React.createElement(j.j,{value:"",label:"None"}),React.createElement(j.j,{value:"discussion",label:"For Discussion"}))))),(ee||te)&&!le&&React.createElement(Ue.y2,{title:qe},React.createElement("div",{style:{marginTop:15,fontWeight:"bold"}},J.A.COMMON.EMBEDDINGS),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.EMBEDDINGS_ENV,":"),React.createElement(j.u,{scrolldown:!0,name:"embeddingsEnvId",requirePro:!0,isPro:v.zN,disabled:!se||!(null!=Ie&&Ie.length),value:P.embeddingsEnvId,onChange:L},Ie.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(j.j,{value:"",label:"None"})))),P.embeddingsEnvId&&(()=>{const e=Ie.find((e=>e.id===P.embeddingsEnvId));if("openai-vector-store"===(null==e?void 0:e.type)){if(je)return React.createElement(q.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=P.envId||(null==W?void 0:W.ai_default_env),a=e.openai_env_id;return e.store_id?a!==t?React.createElement(q.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(q.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(q.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"}},J.A.COMMON.OTHERS),ee&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.CONTENT_AWARE,":"),React.createElement(m.R,{name:"contentAware",label:"Yes",requirePro:!0,isPro:v.zN,checked:P.contentAware,value:"1",onChange:L}))),re&&!_e&&React.createElement(q.X,{variant:"danger",style:{marginTop:15,padding:"10px 15px"}},React.createElement("p",null,be(J.A.SETTINGS.ALERT_CONTENTAWARE_BUT_NO_CONTENT,J.A.SETTINGS.ALERT_CONTENTAWARE_URL,J.A.SETTINGS.ALERT_CONTENTAWARE_LINK_TEXT)))),(Se||me.length>0)&&de.length>0&&!le&&React.createElement(Ue.y2,{title:Ke},React.createElement("p",null,React.createElement(Ee,{style:{marginRight:3}}),React.createElement(ge,{style:{marginRight:3}}),React.createElement(he,{style:{marginRight:5}}),(0,y.FE)(J.A.HELP.FUNCTIONS)),!(null!=de&&de.length)&&React.createElement(q.X,{variant:"danger"},be(J.A.HELP.FUNCTIONS_UNAVAILABLE,J.A.HELP.FUNCTIONS_CODE_ENGINE_URL,J.A.HELP.FUNCTIONS_CODE_ENGINE_TEXT)),!(null==de||!de.length)&&React.createElement("div",{style:{maxHeight:200,overflowY:"auto",border:"1px solid #d1e3f2",marginTop:10,padding:"5px 6px",borderRadius:5}},null==de?void 0:de.map((e=>React.createElement(m.R,{key:e.id,name:"functions",label:React.createElement(React.Fragment,null,"js"===e.target&&React.createElement(Re,{style:{marginRight:5}}),"js"!==e.target&&React.createElement(ye,{style:{marginRight:5}}),React.createElement("span",null,e.name)),description:e.desc,checked:me.some((t=>t.id===e.id)),value:e.id,onChange:t=>{const a=me.filter((t=>t.id!==e.id));t&&a.push({type:e.type,id:e.id}),L(a,"functions")}})))),me.length>1&&je&&Fe&&React.createElement(q.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.'),te&&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()=>{pe(!0);try{await(async(e,t,a)=>{const n=await Ge(`${v.y0}/openai/assistants/set_functions`,{method:"POST",json:{envId:e,assistantId:t,functions:a}});if(!n.success)throw new Error(n.message);return n})(P.envId,P.assistantId,me),alert("Functions have been set on the assistant.")}catch(e){alert(e.message)}pe(!1)},isBusy:ue},"Set Functions on Assistant"))),(Le||fe.length>0)&&ce&&ve.length>0&&!le&&React.createElement(Ue.y2,{title:Ye},React.createElement("p",null,React.createElement(Ee,{style:{marginRight:3}}),React.createElement(ge,{style:{marginRight:5}}),(0,y.FE)(J.A.HELP.MCP_SERVERS||"MCP (Model Context Protocol) servers enable AI models to interact with external tools and systems.")),!(null!=ve&&ve.length)&&React.createElement(q.X,{variant:"danger"},(0,y.FE)(J.A.HELP.MCP_SERVERS_UNAVAILABLE||"No MCP servers are available. Configure them in the MCP Servers section under Orchestration.")),!(null==ve||!ve.length)&&React.createElement("div",{style:{maxHeight:200,overflowY:"auto",border:"1px solid #d1e3f2",marginTop:10,padding:"5px 6px",borderRadius:5}},null==ve?void 0:ve.map((e=>React.createElement(m.R,{key:e.id,name:"mcpServers",label:e.name,description:e.url||"MCP Server",checked:fe.some((t=>t.id===e.id)),value:e.id,onChange:t=>{const a=fe.filter((t=>t.id!==e.id));t&&a.push({id:e.id}),L(a,"mcpServers")}}))))),(De||(null===(t=P.tools)||void 0===t?void 0:t.length)>0)&&((null==Oe||null===(a=Oe.tools)||void 0===a?void 0:a.length)>0||(null===(n=P.tools)||void 0===n?void 0:n.length)>0)&&!le&&React.createElement(Ue.y2,{title:Xe},React.createElement("p",null,React.createElement(Ee,{style:{marginRight:3}}),React.createElement(he,{style:{marginRight:5}}),(0,y.FE)(J.A.HELP.TOOLS||"Enable AI tools to enhance your chatbot capabilities. Web Search and Image Generation work with OpenAI and Google. Code Interpreter is OpenAI-only.")),React.createElement("div",{style:{marginTop:10}},((null==Oe||null===(l=Oe.tools)||void 0===l?void 0:l.includes("web_search"))||(null===(r=P.tools)||void 0===r?void 0:r.includes("web_search")))&&React.createElement(m.R,{name:"tools_web_search",label:J.A.COMMON.WEB_SEARCH||"Web Search",description:J.A.HELP.WEB_SEARCH||"Allow the AI to search the web for current information",checked:null===(o=P.tools)||void 0===o?void 0:o.includes("web_search"),value:"web_search",variant:null!=Oe&&null!==(i=Oe.tools)&&void 0!==i&&i.includes("web_search")||null===(s=P.tools)||void 0===s||!s.includes("web_search")?void 0:"danger",onChange:e=>{const t=P.tools||[],a=e?[...t.filter((e=>"web_search"!==e)),"web_search"]:t.filter((e=>"web_search"!==e));L(a,"tools")}}),((null==Oe||null===(c=Oe.tools)||void 0===c?void 0:c.includes("image_generation"))||(null===(d=P.tools)||void 0===d?void 0:d.includes("image_generation")))&&React.createElement(m.R,{name:"tools_image_generation",label:J.A.COMMON.IMAGE_GENERATION||"Image Generation",description:J.A.HELP.IMAGE_GENERATION||"Allow the AI to generate images based on text descriptions",checked:null===(u=P.tools)||void 0===u?void 0:u.includes("image_generation"),value:"image_generation",variant:null!=Oe&&null!==(p=Oe.tools)&&void 0!==p&&p.includes("image_generation")||null===(g=P.tools)||void 0===g||!g.includes("image_generation")?void 0:"danger",onChange:e=>{const t=P.tools||[],a=e?[...t.filter((e=>"image_generation"!==e)),"image_generation"]:t.filter((e=>"image_generation"!==e));L(a,"tools")}}),((null==Oe||null===(R=Oe.tools)||void 0===R?void 0:R.includes("thinking"))||(null===(b=P.tools)||void 0===b?void 0:b.includes("thinking")))&&React.createElement(m.R,{name:"tools_thinking",label:J.A.COMMON.THINKING||"Thinking",description:J.A.HELP.THINKING||"Enable enhanced reasoning mode for complex tasks requiring step-by-step analysis and planning",checked:null===(f=P.tools)||void 0===f?void 0:f.includes("thinking"),value:"thinking",variant:null!=Oe&&null!==(w=Oe.tools)&&void 0!==w&&w.includes("thinking")||null===(_=P.tools)||void 0===_||!_.includes("thinking")?void 0:"danger",onChange:e=>{const t=P.tools||[],a=e?[...t.filter((e=>"thinking"!==e)),"thinking"]:t.filter((e=>"thinking"!==e));L(a,"tools")}}),((null==Oe||null===(C=Oe.tools)||void 0===C?void 0:C.includes("code_interpreter"))||(null===(T=P.tools)||void 0===T?void 0:T.includes("code_interpreter")))&&React.createElement(m.R,{name:"tools_code_interpreter",label:J.A.COMMON.CODE_INTERPRETER||"Code Interpreter",description:J.A.HELP.CODE_INTERPRETER||"Allow the AI to write and run Python code to solve complex problems, process data, and generate visualizations",checked:null===(A=P.tools)||void 0===A?void 0:A.includes("code_interpreter"),value:"code_interpreter",variant:null!=Oe&&null!==(N=Oe.tools)&&void 0!==N&&N.includes("code_interpreter")||null===(O=P.tools)||void 0===O||!O.includes("code_interpreter")?void 0:"danger",onChange:e=>{const t=P.tools||[],a=e?[...t.filter((e=>"code_interpreter"!==e)),"code_interpreter"]:t.filter((e=>"code_interpreter"!==e));L(a,"tools")}}))),React.createElement(Ue.y2,{title:Qe},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.INPUT_MAX_LENGTH,":"),React.createElement(G.A,{name:"textInputMaxLength",type:"number",description:J.A.HELP.INPUT_MAX_LENGTH,step:"1",min:"8",value:P.textInputMaxLength,onBlur:L,onEnter:L})),!ne&&React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.MAX_MESSAGES,":"),React.createElement(G.A,{name:"maxMessages",type:"number",description:J.A.HELP.MAX_MESSAGES,step:"1",min:"1",max:"1024",value:P.maxMessages,onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.CONTEXT_MAX_LENGTH,":"),React.createElement(G.A,{name:"contextMaxLength",type:"number",step:"1",description:J.A.HELP.CONTEXT_MAX_LENGTH,value:P.contextMaxLength||(null==W?void 0:W.context_max_length),onBlur:L,onEnter:L})))),React.createElement(Ue.y2,{title:Je},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,J.A.COMMON.THEME,":"),React.createElement(j.u,{scrolldown:!0,name:"themeId",value:P.themeId,description:"",onChange:L},React.createElement(j.j,{value:"none",label:"None"}),React.createElement(j.j,{value:"chatgpt",label:"ChatGPT"}),React.createElement(j.j,{value:"timeless",label:"Timeless"}),React.createElement(j.j,{value:"messages",label:"Messages"}),null==x?void 0:x.filter((e=>"css"===e.type)).map((e=>React.createElement(j.j,{key:e.themeId,value:e.themeId,label:e.name}))))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.POPUP,":"),React.createElement(m.R,{name:"window",label:"Yes",checked:P.window,value:"1",onChange:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.FULL_SCREEN,":"),React.createElement(m.R,{name:"fullscreen",label:"Yes",checked:P.fullscreen,value:"1",onChange:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.COPY_BUTTON,":"),React.createElement(m.R,{name:"copyButton",label:"Yes",checked:P.copyButton,value:"1",onChange:L}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.HEADER_SUBTITLE,":"),React.createElement(G.A,{name:"headerSubtitle","data-form-type":"other",value:P.headerSubtitle,onBlur:L,onEnter:L}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.AVATAR,":"),React.createElement(m.R,{name:"aiAvatar",label:"Yes",checked:P.aiAvatar,value:"1",onChange:L,disabled:!P.aiName})),React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,J.A.COMMON.AI_NAME,":"),React.createElement(G.A,{name:"aiName","data-form-type":"other",value:P.aiName,onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:7}},React.createElement("label",null,J.A.COMMON.START_SENTENCE,":"),React.createElement(xe.m,{name:"startSentence",rows:1,value:P.startSentence,onBlur:L,onEnter:L}))),P.aiAvatar&&React.createElement(ka,{label:J.A.COMMON.AI_AVATAR,updateShortcodeParams:L,valueName:"aiAvatarUrl",icon:P.aiAvatarUrl}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.AVATAR,":"),React.createElement(m.R,{name:"userAvatar",label:"Yes",checked:P.userAvatar,value:"1",onChange:L,disabled:!P.userName})),React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,J.A.COMMON.USER_NAME,":"),React.createElement(G.A,{name:"userName","data-form-type":"other",value:P.userName,onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,J.A.COMMON.PLACEHOLDER,":"),React.createElement(G.A,{name:"textInputPlaceholder",value:P.textInputPlaceholder,onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,J.A.COMMON.SEND,":"),React.createElement(G.A,{name:"textSend",value:P.textSend,onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,J.A.COMMON.CLEAR,":"),React.createElement(G.A,{name:"textClear",value:P.textClear,onBlur:L,onEnter:L}))),P.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,J.A.COMMON.AVATAR,":"),React.createElement(m.R,{name:"guestAvatar",label:"Yes",checked:P.guestAvatar,value:"1",onChange:L,disabled:!P.guestName})),React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,J.A.COMMON.GUEST_NAME,":"),React.createElement(G.A,{name:"guestName",value:P.guestName,onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:7}},React.createElement("label",null,J.A.COMMON.COMPLIANCE_TEXT,":"),React.createElement(G.A,{name:"textCompliance",value:P.textCompliance,onBlur:L,onEnter:L}))),P.guestAvatar&&React.createElement(ka,{label:J.A.COMMON.GUEST_AVATAR,updateShortcodeParams:L,valueName:"guestAvatarUrl",icon:P.guestAvatarUrl})),React.createElement(Ue.y2,{title:J.A.COMMON.POPUP,hide:!P.window},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:4}},React.createElement("label",null,J.A.COMMON&&J.A.COMMON.POPUP_TITLE||"Popup Title",":"),React.createElement(G.A,{name:"popupTitle",value:P.popupTitle,placeholder:"AI Engine",onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:4}},React.createElement("label",null,J.A.COMMON.POSITION,":"),React.createElement(j.u,{scrolldown:!0,name:"iconPosition",value:P.iconPosition,onChange:L},React.createElement(j.j,{value:"bottom-right",label:"Bottom Right"}),React.createElement(j.j,{value:"bottom-left",label:"Bottom Left"}),React.createElement(j.j,{value:"top-right",label:"Top Right"}),React.createElement(j.j,{value:"top-left",label:"Top Left"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.BUBBLE,":"),React.createElement(m.R,{name:"iconBubble",label:"Yes",checked:P.iconBubble,value:"1",onChange:L}))),React.createElement(ka,{label:J.A.COMMON.ICON,updateShortcodeParams:L,valueName:"icon",icon:P.icon}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:4}},React.createElement("label",null,J.A.COMMON.ICON_TEXT,":"),React.createElement(G.A,{name:"iconText",description:J.A.HELP.ICON_TEXT,value:P.iconText,onBlur:L,onEnter:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,J.A.COMMON.ICON_TEXT_DELAY,":"),React.createElement(G.A,{name:"iconTextDelay",type:"number",description:J.A.HELP.ICON_TEXT_DELAY??1,value:P.iconTextDelay,onBlur:L,onEnter:L}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:3}},React.createElement("label",null,J.A.COMMON&&J.A.COMMON.WINDOW_ANIMATION||"Window Animation",":"),React.createElement(j.u,{scrolldown:!0,name:"windowAnimation",value:P.windowAnimation||"none",onChange:L},React.createElement(j.j,{value:"none",label:J.A.COMMON&&J.A.COMMON.NONE||"None"}),React.createElement(j.j,{value:"zoom",label:J.A.COMMON&&J.A.COMMON.ZOOM||"Zoom"}),React.createElement(j.j,{value:"slide",label:J.A.COMMON&&J.A.COMMON.SLIDE||"Slide"}),React.createElement(j.j,{value:"fade",label:J.A.COMMON&&J.A.COMMON.FADE||"Fade"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.CENTER,":"),React.createElement(m.R,{name:"centerOpen",label:"Yes",checked:P.centerOpen,value:"1",onChange:L})),React.createElement("div",{className:"mwai-builder-col",style:{flex:2}},React.createElement("label",null,J.A.COMMON.OPEN_DELAY,":"),React.createElement(G.A,{name:"openDelay",type:"number",value:P.openDelay||"",placeholder:"seconds",description:J.A.HELP.OPEN_DELAY,onBlur:e=>L(e,"openDelay"),onEnter:e=>L(e,"openDelay")})))),React.createElement(Ue.y2,{title:Ze},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,"Container:"),React.createElement(j.u,{scrolldown:!0,name:"containerType",value:P.containerType||"standard",onChange:L,disabled:!P.window,description:P.window?"Window frame style":"Enable Popup to customize"},React.createElement(j.j,{value:"standard",label:"Standard"}),React.createElement(j.j,{value:"osx",label:"MacOS"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,"Header:"),React.createElement(j.u,{scrolldown:!0,name:"headerType",value:P.headerType||"standard",onChange:L,disabled:!P.window,description:P.window?"Title bar with controls":"Enable Popup to customize"},React.createElement(j.j,{value:"standard",label:"Standard"}),React.createElement(j.j,{value:"osx",label:"MacOS"}),React.createElement(j.j,{value:"none",label:"None"})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,"Messages:"),React.createElement(j.u,{scrolldown:!0,name:"messagesType",value:P.messagesType||"standard",onChange:L,description:"Chat messages area"},React.createElement(j.j,{value:"standard",label:"Standard"}),React.createElement(j.j,{value:"terminal",label:"Terminal (Beta)"}),React.createElement(j.j,{value:"none",label:"None"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,"Input:"),React.createElement(j.u,{scrolldown:!0,name:"inputType",value:P.inputType||"standard",onChange:L,description:"Text input field"},React.createElement(j.j,{value:"standard",label:"Standard"}),React.createElement(j.j,{value:"none",label:"None"})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,"Footer:"),React.createElement(j.u,{scrolldown:!0,name:"footerType",value:P.footerType||"standard",onChange:L,description:"Tools & compliance text"},React.createElement(j.j,{value:"standard",label:"Standard"}),React.createElement(j.j,{value:"none",label:"None"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:1}}))),!ae&&React.createElement(Ue.y2,{title:J.A.COMMON.ADVANCED||"Advanced"},Fe&&!te&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.HISTORY_STRATEGY,":"),React.createElement(j.u,{scrolldown:!0,name:"historyStrategy",description:J.A.HELP.HISTORY_STRATEGY,value:P.historyStrategy||"",onChange:L},React.createElement(j.j,{value:"",label:J.A.COMMON.AUTOMATIC||"Automatic"}),React.createElement(j.j,{value:"internal",label:J.A.COMMON.FULL_HISTORY||"Full History"}),React.createElement(j.j,{value:"response_id",label:J.A.COMMON.INCREMENTAL||"Incremental"})))),(P.fileUpload||P.imageUpload)&&React.createElement(ua.W,{devMode:V},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement("label",null,J.A.COMMON.MULTI_UPLOAD||"Multi Upload",":"),React.createElement(m.R,{name:"multiUpload",label:J.A.COMMON.ENABLE,checked:P.multiUpload,value:"1",onChange:L}))))),!F&&v.zN&&K&&React.createElement(Ue.y2,{title:"Cross-Site"},React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1}},React.createElement(m.R,{name:"crossSiteEnabled",label:"Enable",requirePro:!0,isPro:v.zN,description:"Enable this chatbot to be embedded on external websites. You can control which domains are allowed to embed this chatbot.",checked:!(null===(I=P.crossSite)||void 0===I||!I.enabled),value:"1",onChange:e=>{const t={...P.crossSite||{}};t.enabled=!!e,L(t,"crossSite")}}))),(null===(S=P.crossSite)||void 0===S?void 0:S.enabled)&&!P.window&&React.createElement(q.X,{variant:"warning",style:{marginTop:10}},'Most users prefer popup chatbots on their sites. Enable "Popup" under Appearance to use this mode.'),(null===(M=P.crossSite)||void 0===M?void 0:M.enabled)&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,"Allowed Domains:"),React.createElement(xe.m,{name:"crossSite.allowedDomains",rows:4,placeholder:"example.com\n*.example.com\napp.example.com",description:"One domain per line. Use *.domain.com for all subdomains.",value:((null===(k=P.crossSite)||void 0===k?void 0:k.allowedDomains)||[]).join("\n"),onBlur:e=>{const t={...P.crossSite};t.allowedDomains=e.split("\n").filter((e=>e.trim())),L(t,"crossSite")}}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,"Embed Code:"),React.createElement(xe.m,{name:"embedCode",rows:8,readOnly:!0,value:P.window?`\x3c!-- AI Engine Cross-Site Chatbot --\x3e\n<script src="${v.Hm}/app/embed.js"><\/script>\n<script>\n MwaiChatbot.init({\n botId: '${P.botId}'\n });\n<\/script>`:`\x3c!-- AI Engine Cross-Site Chatbot --\x3e\n<div id="${P.botId}"></div>\n<script src="${v.Hm}/app/embed.js"><\/script>\n<script>\n MwaiChatbot.init({\n botId: '${P.botId}',\n container: '#${P.botId}'\n });\n<\/script>`,description:"Use this code to embed your chatbot on another website. For WordPress sites, use the Custom HTML block."}))))),!F&&React.createElement(Ue.y2,{title:J.A.COMMON.SHORTCODES},React.createElement(wa,{currentChatbot:P,style:{marginTop:10}}),"default"!==P.botId&&React.createElement(React.Fragment,null,React.createElement("p",null,J.A.HELP.CUSTOM_SHORTCODE),React.createElement(wa,{currentChatbot:P,isCustom:!0,defaultChatbot:D,style:{marginTop:10}}))),!F&&React.createElement(Ue.y2,{title:J.A.COMMON.ACTIONS},React.createElement("div",{style:{display:"flex",marginTop:10}},React.createElement(h.M,{className:"primary",onClick:H},J.A.COMMON.DUPLICATE),React.createElement(h.M,{className:"secondary",onClick:B},J.A.COMMON.RESET),React.createElement("div",{style:{flex:"auto"}}),React.createElement(h.M,{className:"danger",disabled:"Default"===P.name,onClick:U},J.A.COMMON.DELETE))))))))};var Pa=a(8573);const La=e=>{const{settings:t,onUpdateSettings:a}=e;return React.createElement(React.Fragment,null,React.createElement(ga,null,React.createElement(Ue.y2,{title:J.A.COMMON.STYLE,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.SPACING,":"),React.createElement(G.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:.5}},React.createElement("label",null,J.A.COMMON.BORDER_RADIUS,":"),React.createElement(G.A,{id:"borderRadius",name:"borderRadius",value:(null==t?void 0:t.borderRadius)??"10px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BORDER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"borderColor",name:"borderColor",value:(null==t?void 0:t.borderColor)??"#4f4f4f",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"borderColor",name:"borderColor",value:(null==t?void 0:t.borderColor)??"#4f4f4f",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_PRIMARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundPrimaryColor)??"#454654",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",value:(null==t?void 0:t.backgroundPrimaryColor)??"#454654",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_SECONDARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundSecondaryColor",name:"backgroundSecondaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundSecondaryColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundSecondaryColor",name:"backgroundSecondaryColor",value:(null==t?void 0:t.backgroundSecondaryColor)??"#343541",onChange:a})))),React.createElement($.g,null),React.createElement(Ue.y2,{title:J.A.COMMON.FONT||"Font",isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1.2}},React.createElement("label",null,J.A.COMMON&&J.A.COMMON.FONT_FAMILY||"Font Family",":"),React.createElement(j.u,{scrolldown:!0,name:"fontFamily",value:(null==t?void 0:t.fontFamily)||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",onChange:a},React.createElement(j.j,{value:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",label:"Native Feel"}),React.createElement(j.j,{value:"Arial, Helvetica, sans-serif",label:"Arial"}),React.createElement(j.j,{value:"Cambria, Georgia, serif",label:"Cambria"}),React.createElement(j.j,{value:"Consolas, 'Courier New', monospace",label:"Consolas"}),React.createElement(j.j,{value:"'Courier New', Courier, monospace",label:"Courier New"}),React.createElement(j.j,{value:"Georgia, serif",label:"Georgia"}),React.createElement(j.j,{value:"'Gill Sans', Calibri, sans-serif",label:"Gill Sans"}),React.createElement(j.j,{value:"Helvetica, Arial, sans-serif",label:"Helvetica"}),React.createElement(j.j,{value:"",label:"Inherit"}),React.createElement(j.j,{value:"Monaco, Consolas, monospace",label:"Monaco"}),React.createElement(j.j,{value:"Tahoma, Geneva, sans-serif",label:"Tahoma"}),React.createElement(j.j,{value:"Times, 'Times New Roman', serif",label:"Times"}),React.createElement(j.j,{value:"'Times New Roman', Times, serif",label:"Times New Roman"}),React.createElement(j.j,{value:"'Trebuchet MS', Helvetica, sans-serif",label:"Trebuchet MS"}),React.createElement(j.j,{value:"Verdana, Geneva, sans-serif",label:"Verdana"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.FONT_SIZE,":"),React.createElement(G.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,J.A.COMMON.FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onChange:a})))),React.createElement($.g,null),React.createElement(Ue.y2,{title:J.A.COMMON.POPUP,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.WIDTH,":"),React.createElement(G.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:.5}},React.createElement("label",null,J.A.COMMON.MAX_HEIGHT,":"),React.createElement(G.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,J.A.COMMON.AVATAR_MESSAGE_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#343541",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.AVATAR_MESSAGE_FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BUBBLE_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"bubbleColor",name:"bubbleColor",style:{flex:1},value:(null==t?void 0:t.bubbleColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"bubbleColor",name:"bubbleColor",value:(null==t?void 0:t.bubbleColor)??"#343541",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.HEADER_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",style:{flex:1},value:(null==t?void 0:t.backgroundHeaderColor)??"#343541",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",value:(null==t?void 0:t.backgroundHeaderColor)??"#343541",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.HEADER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"headerButtonsColor",name:"headerButtonsColor",style:{flex:1},value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"headerButtonsColor",name:"headerButtonsColor",value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onChange:a}))))))},{useMemo:Da,useState:Fa,useEffect:Ua,useCallback:Ba}=wp.element,Ha="/* Basic Template - AI Engine Pro\n Square design with clear element distinction */\n\n.mwai-THEME_ID-theme {\n /* Sizing */\n --mwai-spacing: 15px;\n --mwai-fontSize: 15px;\n --mwai-lineHeight: 1.5;\n --mwai-borderRadius: 0px;\n --mwai-width: 460px;\n --mwai-maxHeight: 600px;\n \n /* Main Colors */\n --mwai-fontColor: #333333;\n --mwai-backgroundPrimaryColor: #ffffff;\n --mwai-backgroundSecondaryColor: #343541;\n \n /* Messages */\n --mwai-backgroundUserColor: #5865f2;\n --mwai-backgroundAiColor: #f0f0f0;\n --mwai-userTextColor: #ffffff;\n \n /* UI Elements */\n --mwai-borderColor: #d4d4d4;\n --mwai-headerColor: #ffffff;\n --mwai-backgroundHeaderColor: #565869;\n --mwai-errorBackgroundColor: #fee2e2;\n --mwai-errorTextColor: #dc2626;\n \n font-family: system-ui, -apple-system, sans-serif;\n}\n\n/* Layout */\n.mwai-THEME_ID-theme * {\n box-sizing: border-box;\n}\n\n/* Override WordPress Admin styles for all form elements */\n.mwai-THEME_ID-theme input,\n.mwai-THEME_ID-theme select,\n.mwai-THEME_ID-theme textarea,\n.mwai-THEME_ID-theme button {\n /* Remove WordPress admin focus styles */\n outline: 2px solid transparent !important;\n outline-offset: 0 !important;\n}\n\n.mwai-THEME_ID-theme input:focus,\n.mwai-THEME_ID-theme select:focus,\n.mwai-THEME_ID-theme textarea:focus,\n.mwai-THEME_ID-theme button:focus {\n /* Override WordPress admin focus styles */\n outline: 2px solid transparent !important;\n outline-offset: 0 !important;\n border-color: inherit;\n box-shadow: none !important;\n}\n\n.mwai-THEME_ID-theme {\n font-size: var(--mwai-fontSize);\n line-height: var(--mwai-lineHeight);\n color: var(--mwai-fontColor);\n}\n\n.mwai-THEME_ID-theme .mwai-content {\n background: var(--mwai-backgroundPrimaryColor);\n border: 1px solid var(--mwai-borderColor);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n\n.mwai-THEME_ID-theme .mwai-body {\n flex: 1;\n display: flex;\n flex-direction: column;\n background: var(--mwai-backgroundPrimaryColor);\n}\n\n/* Header */\n.mwai-THEME_ID-theme .mwai-header {\n background: var(--mwai-backgroundHeaderColor);\n color: var(--mwai-headerColor);\n padding: var(--mwai-spacing);\n display: flex;\n align-items: center;\n justify-content: space-between;\n border-bottom: 1px solid var(--mwai-borderColor);\n gap: 10px;\n}\n\n.mwai-THEME_ID-theme .mwai-name-text {\n flex: 1;\n font-weight: 600;\n}\n\n/* Header Buttons */\n.mwai-THEME_ID-theme .mwai-header button {\n background: transparent;\n border: none;\n color: var(--mwai-headerColor);\n cursor: pointer;\n padding: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0.7;\n transition: opacity 0.2s;\n}\n\n.mwai-THEME_ID-theme .mwai-header button:hover {\n opacity: 1;\n}\n\n.mwai-THEME_ID-theme .mwai-header button svg {\n width: 18px;\n height: 18px;\n}\n\n/* Window mode header buttons */\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-buttons {\n display: flex;\n align-items: center;\n gap: 5px;\n}\n\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-resize-button,\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-close-button {\n width: 32px;\n height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n background: transparent;\n border: none;\n padding: 0;\n position: relative;\n}\n\n/* Resize button style */\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-resize-button:before {\n content: ' ';\n position: absolute;\n width: 13px;\n height: 13px;\n border: 1px solid var(--mwai-headerColor);\n transition: all 0.2s ease-out;\n}\n\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-resize-button:hover:before {\n width: 16px;\n height: 16px;\n}\n\n/* Close button style */\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-close-button:before,\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-close-button:after {\n content: ' ';\n position: absolute;\n height: 22px;\n width: 1px;\n background-color: var(--mwai-headerColor);\n transition: all 0.2s ease-out;\n}\n\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-close-button:before {\n transform: rotate(45deg);\n}\n\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-close-button:after {\n transform: rotate(-45deg);\n}\n\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-close-button:hover:before {\n transform: rotate(135deg);\n}\n\n.mwai-THEME_ID-theme.mwai-window .mwai-header .mwai-close-button:hover:after {\n transform: rotate(45deg);\n}\n\n/* Conversation */\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/* Messages */\n.mwai-THEME_ID-theme .mwai-reply {\n padding: 12px 15px;\n position: relative;\n}\n\n.mwai-THEME_ID-theme .mwai-reply.mwai-user {\n background: var(--mwai-backgroundUserColor);\n color: var(--mwai-userTextColor);\n margin-left: 20%;\n}\n\n.mwai-THEME_ID-theme .mwai-reply.mwai-ai {\n background: var(--mwai-backgroundAiColor);\n color: var(--mwai-fontColor);\n margin-right: 20%;\n}\n\n.mwai-THEME_ID-theme .mwai-reply.mwai-error {\n background: var(--mwai-errorBackgroundColor);\n color: var(--mwai-errorTextColor);\n border: 1px solid var(--mwai-errorTextColor);\n}\n\n.mwai-THEME_ID-theme .mwai-reply.mwai-system {\n background: #fef3c7;\n color: #92400e;\n text-align: center;\n padding: 8px;\n font-size: 0.9em;\n}\n\n/* Text Styling */\n.mwai-THEME_ID-theme .mwai-text {\n word-wrap: break-word;\n}\n\n.mwai-THEME_ID-theme .mwai-text p {\n margin: 0 0 10px 0;\n}\n\n.mwai-THEME_ID-theme .mwai-text p:last-child {\n margin-bottom: 0;\n}\n\n.mwai-THEME_ID-theme .mwai-text a {\n color: #2563eb;\n text-decoration: underline;\n}\n\n.mwai-THEME_ID-theme .mwai-text code {\n background: #1e1e1e;\n color: #d4d4d4;\n padding: 2px 6px;\n font-family: monospace;\n font-size: 0.9em;\n}\n\n.mwai-THEME_ID-theme .mwai-text pre {\n background: #1e1e1e;\n color: #d4d4d4;\n padding: 15px;\n overflow-x: auto;\n margin: 10px 0;\n}\n\n/* Reply Actions */\n.mwai-THEME_ID-theme .mwai-reply-actions {\n position: absolute;\n top: 5px;\n right: 5px;\n display: flex;\n gap: 5px;\n opacity: 0;\n}\n\n.mwai-THEME_ID-theme .mwai-reply:hover .mwai-reply-actions {\n opacity: 1;\n}\n\n.mwai-THEME_ID-theme .mwai-copy-button,\n.mwai-THEME_ID-theme .mwai-action-button {\n background: white;\n border: 1px solid var(--mwai-borderColor);\n outline: none;\n padding: 5px;\n cursor: pointer;\n width: 30px;\n height: 30px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.mwai-THEME_ID-theme .mwai-copy-button:hover,\n.mwai-THEME_ID-theme .mwai-action-button:hover {\n background: #e5e5e5;\n}\n\n.mwai-THEME_ID-theme .mwai-copy-button svg,\n.mwai-THEME_ID-theme .mwai-action-button svg {\n width: 16px;\n height: 16px;\n}\n\n/* Shortcuts */\n.mwai-THEME_ID-theme .mwai-shortcuts {\n background: #f9fafb;\n padding: 10px var(--mwai-spacing);\n border-bottom: 1px solid var(--mwai-borderColor);\n display: flex;\n gap: 8px;\n flex-wrap: wrap;\n}\n\n.mwai-THEME_ID-theme .mwai-shortcut {\n background: white;\n border: 1px solid var(--mwai-borderColor);\n outline: none;\n padding: 5px 10px;\n cursor: pointer;\n font-size: 0.9em;\n}\n\n.mwai-THEME_ID-theme .mwai-shortcut:hover {\n background: #e5e5e5;\n}\n\n/* Blocks */\n.mwai-THEME_ID-theme .mwai-blocks {\n background: #e8f4fd;\n padding: var(--mwai-spacing);\n border-bottom: 1px solid var(--mwai-borderColor);\n}\n\n/* Input Area */\n.mwai-THEME_ID-theme .mwai-input {\n padding: var(--mwai-spacing);\n background: white;\n border-top: 1px solid var(--mwai-borderColor);\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 border: 1px solid var(--mwai-borderColor);\n background: white;\n padding: 8px;\n}\n\n.mwai-THEME_ID-theme .mwai-input-text.mwai-focused {\n border-color: #2563eb;\n}\n\n.mwai-THEME_ID-theme .mwai-input-text textarea {\n flex: 1;\n border: none !important;\n background: transparent;\n resize: none;\n outline: none !important;\n outline-offset: 0 !important;\n box-shadow: none !important;\n font: inherit;\n min-height: 24px;\n max-height: 120px;\n}\n\n.mwai-THEME_ID-theme .mwai-input-text textarea:focus {\n outline: none !important;\n outline-offset: 0 !important;\n box-shadow: none !important;\n border: none !important;\n border-color: transparent !important;\n}\n\n.mwai-THEME_ID-theme .mwai-input-text textarea::placeholder {\n color: #9ca3af;\n}\n\n/* File Upload */\n.mwai-THEME_ID-theme .mwai-file-upload-icon {\n width: 32px;\n height: 32px;\n cursor: pointer;\n background: #f3f4f6;\n border: 1px solid var(--mwai-borderColor);\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.mwai-THEME_ID-theme .mwai-file-upload-icon:hover {\n background: #e5e7eb;\n}\n\n/* Microphone */\n.mwai-THEME_ID-theme .mwai-microphone {\n background: #f3f4f6;\n border: 1px solid var(--mwai-borderColor);\n padding: 6px;\n cursor: pointer;\n}\n\n.mwai-THEME_ID-theme .mwai-microphone:hover {\n background: #e5e7eb;\n}\n\n/* Submit Button */\n.mwai-THEME_ID-theme .mwai-input-submit {\n background: var(--mwai-backgroundSecondaryColor);\n color: white;\n border: none;\n outline: none;\n padding: 10px 20px;\n cursor: pointer;\n font-weight: 500;\n}\n\n.mwai-THEME_ID-theme .mwai-input-submit:hover:not(:disabled) {\n opacity: 0.9;\n}\n\n.mwai-THEME_ID-theme .mwai-input-submit:focus {\n box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);\n}\n\n.mwai-THEME_ID-theme .mwai-input-submit:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n/* Footer */\n.mwai-THEME_ID-theme .mwai-footer {\n background: #f9fafb;\n padding: 10px var(--mwai-spacing);\n border-top: 1px solid var(--mwai-borderColor);\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n.mwai-THEME_ID-theme .mwai-compliance {\n font-size: 0.85em;\n color: #6b7280;\n}\n\n.mwai-THEME_ID-theme .mwai-tools {\n display: flex;\n gap: 8px;\n}\n\n/* Window Mode */\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/* Hide content and body when window is closed */\n.mwai-THEME_ID-theme.mwai-window .mwai-content {\n display: none;\n max-height: var(--mwai-maxHeight);\n box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);\n}\n\n.mwai-THEME_ID-theme.mwai-window .mwai-body {\n display: none;\n opacity: 0;\n}\n\n/* Window mode header handling */\n.mwai-THEME_ID-theme.mwai-window .mwai-header {\n display: none;\n justify-content: space-between;\n align-items: center;\n background: var(--mwai-backgroundHeaderColor);\n border-radius: var(--mwai-borderRadius) var(--mwai-borderRadius) 0 0;\n}\n\n/* Show header when window is open */\n.mwai-THEME_ID-theme.mwai-window.mwai-open .mwai-header {\n display: flex !important;\n}\n\n/* Show content and body when window is open */\n.mwai-THEME_ID-theme.mwai-window.mwai-open .mwai-content {\n display: flex;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-open .mwai-body {\n display: flex;\n opacity: 1;\n transition: opacity 200ms ease-in-out 0s;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-open .mwai-trigger {\n display: none !important;\n}\n\n/* Hide trigger when window is open (with higher specificity) */\n.mwai-THEME_ID-theme.mwai-open .mwai-trigger {\n display: none !important;\n}\n\n/* Trigger Button */\n.mwai-THEME_ID-theme .mwai-trigger {\n position: absolute;\n right: 0;\n bottom: 0;\n display: flex;\n align-items: center;\n z-index: 9999;\n}\n\n/* Ensure trigger is visible when window is closed */\n.mwai-THEME_ID-theme.mwai-window:not(.mwai-open) .mwai-trigger {\n display: flex !important;\n}\n\n.mwai-THEME_ID-theme .mwai-trigger.mwai-open-button {\n cursor: pointer;\n}\n\n/* Icon Container (Chat Bubble) */\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-container {\n background: var(--mwai-backgroundSecondaryColor);\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 rgba(0, 0, 0, 0.15);\n transition: all 0.3s ease;\n}\n\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-container:hover {\n transform: scale(1.05);\n box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);\n}\n\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-container .mwai-icon {\n width: 32px;\n height: 32px;\n filter: brightness(0) invert(1);\n}\n\n/* Text Container (Message Preview) */\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-text-container {\n background: var(--mwai-backgroundPrimaryColor);\n border: 1px solid var(--mwai-borderColor);\n border-radius: 18px;\n padding: 8px 12px;\n margin-right: 12px;\n max-width: 200px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n display: flex;\n align-items: center;\n gap: 8px;\n opacity: 0;\n transform: translateX(10px);\n animation: slideIn 0.3s ease forwards;\n}\n\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-text-container.mwai-transition {\n transition: all 0.3s ease;\n}\n\n.mwai-THEME_ID-theme .mwai-trigger:hover .mwai-icon-text-container {\n transform: translateX(0);\n opacity: 1;\n}\n\n/* Text Content */\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-text {\n color: var(--mwai-fontColor);\n font-size: 14px;\n line-height: 1.4;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n/* Close Button in Text Container */\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-text-close {\n color: var(--mwai-fontColor);\n opacity: 0.6;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n transition: opacity 0.2s ease;\n flex-shrink: 0;\n}\n\n.mwai-THEME_ID-theme .mwai-trigger .mwai-icon-text-close:hover {\n opacity: 1;\n}\n\n/* Animation for text appearing */\n@keyframes slideIn {\n from {\n opacity: 0;\n transform: translateX(10px);\n }\n to {\n opacity: 1;\n transform: translateX(0);\n }\n}\n\n/* Loading */\n.mwai-THEME_ID-theme .mwai-typing {\n display: inline-block;\n padding: 5px;\n}\n\n.mwai-THEME_ID-theme .mwai-typing span {\n display: inline-block;\n width: 8px;\n height: 8px;\n background: #666;\n margin: 0 2px;\n}\n\n/* Fullscreen Mode */\n.mwai-THEME_ID-theme.mwai-window.mwai-fullscreen {\n position: fixed !important;\n left: 0 !important;\n right: 0 !important;\n top: 0 !important;\n bottom: 0 !important;\n width: 100% !important;\n height: 100% !important;\n max-width: none !important;\n max-height: none !important;\n z-index: 999999 !important;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-fullscreen .mwai-window-box {\n width: 100% !important;\n height: 100% !important;\n max-height: 100% !important;\n border-radius: 0 !important;\n box-shadow: none !important;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-fullscreen .mwai-content {\n max-height: 100% !important;\n height: 100% !important;\n border-radius: 0 !important;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-fullscreen .mwai-header {\n border-radius: 0 !important;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-fullscreen .mwai-body {\n height: 100%;\n max-height: 100%;\n border-radius: 0 !important;\n display: flex;\n flex-direction: column;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-fullscreen .mwai-conversation {\n flex: 1 1 auto;\n min-height: 0;\n overflow-y: auto;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-fullscreen .mwai-input {\n flex: 0 0 auto;\n}\n\n.mwai-THEME_ID-theme.mwai-window.mwai-fullscreen .mwai-footer {\n flex: 0 0 auto;\n}\n\n/* Fullscreen with WordPress admin bar */\n.admin-bar .mwai-THEME_ID-theme.mwai-window.mwai-fullscreen {\n top: 32px !important;\n height: calc(100% - 32px) !important;\n}\n\n/* Mobile Fullscreen (adjust for mobile admin bar) */\n@media (max-width: 782px) {\n .admin-bar .mwai-THEME_ID-theme.mwai-window.mwai-fullscreen {\n top: 46px !important;\n height: calc(100% - 46px) !important;\n }\n}\n\n/* Mobile */\n@media (max-width: 768px) {\n .mwai-THEME_ID-theme.mwai-window {\n width: 100%;\n height: 100%;\n inset: 0;\n right: 0;\n bottom: 0;\n }\n \n .mwai-THEME_ID-theme.mwai-window .mwai-content {\n max-height: 100%;\n height: 100%;\n }\n}",ja=e=>{const{theme:t,onUpdateTheme:a}=e,[n,l]=Fa(""),[r,o]=Fa(!1),[i,s]=Fa("Surprise me."),[c,d]=Fa(!1);Ua((()=>{l(t.style)}),[t]);const m=Da((()=>n!==t.style),[n,t]),u=Ba((async()=>{d(!0);try{const e=Ha.replace(/THEME_ID/g,t.themeId),n=`You are a CSS expert. Create a complete chatbot theme based on: "${i}"\n\nCRITICAL: You MUST return the COMPLETE CSS below with ALL selectors intact. Modify values (colors, sizes, borders, shadows) but keep EVERY selector and rule. The CSS has ~500 lines and ALL must be included in your response.\n\n${e}\n\nREQUIREMENTS:\n1. Return the ENTIRE CSS above (all ~500 lines including trigger button and fullscreen styles)\n2. Keep ALL selectors exactly as shown, including popup trigger and fullscreen modes\n3. Modify colors, sizes, borders, shadows, gradients to match: "${i}"\n4. Ensure good contrast and readability\n5. Add creative touches while maintaining usability\n6. Every button, input, textarea MUST be styled\n7. Include all hover/focus/active states\n8. Keep the mobile responsive section\n\nIMPORTANT FOCUS STYLING (WordPress Admin Override):\n- WordPress Admin adds unwanted focus styles (blue borders/shadows) that MUST be overridden\n- ALWAYS use !important for: outline, box-shadow, border on focus states\n- The textarea/input elements themselves should NEVER show focus styles\n- Use container classes (.mwai-input-text.mwai-focused) for ALL visual focus indication\n- Required overrides: outline: none !important; box-shadow: none !important; border-color: transparent !important;\n- Focus indication example: .mwai-input-text.mwai-focused { border-color: [accent]; box-shadow: 0 0 0 2px [accent-transparent]; }\n\nIMPORTANT: Your response must be ONLY the complete CSS code (all ~400 lines), no explanations.`,r=await(0,y.IU)(`${v.gh}/mwai/v1/ai/completions`,{nonce:v.ok,method:"POST",json:{message:n,scope:"magic-css"}});if(!r.success||!r.data)throw new Error("No response data received");{let e=r.data;e=e.replace(/```css\n?/g,"").replace(/```\n?/g,""),l(e),o(!1),a(e,"style")}}catch(e){console.error("Magic CSS generation failed:",e),alert(e.message||"Failed to generate CSS. Please try again.")}finally{d(!1)}}),[i,t.themeId]);return React.createElement(ga,null,React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.NAME,":"),React.createElement(G.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"}},J.A.COMMON.ID,":"),React.createElement(G.A,{name:"themeId",type:"text",placeholder:"Optional",value:t.themeId,onBlur:a,onEnter:a})))),React.createElement($.g,null),React.createElement("label",null,"Custom CSS:"),React.createElement(xe.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=Ha.replace(/THEME_ID/g,t.themeId);l(e)}},"Default CSS"),React.createElement(h.M,{fullWidth:!0,onClick:()=>o(!0),className:"secondary"},"🪄 Magic CSS"),React.createElement(h.M,{fullWidth:!0,onClick:()=>{a(n,"style")},disabled:!m},"Apply CSS")),React.createElement(V.n,{title:"🪄 Magic CSS Generator",isOpen:r,onRequestClose:()=>o(!1),okButton:{label:c?"Generating...":"✨ Generate Theme",disabled:c,isBusy:c,onClick:u},cancelButton:{disabled:c,onClick:()=>o(!1)},size:"normal",content:React.createElement(React.Fragment,null,React.createElement("p",null,"Describe the theme you want to create, and AI will generate a complete CSS theme for your chatbot. The generated theme will maintain all necessary structure while applying your creative vision."),React.createElement("div",{style:{marginTop:15}},React.createElement("label",null,"Theme Description:"),React.createElement("div",{style:{marginTop:8}},React.createElement(xe.m,{value:i,onChange:s,rows:5,placeholder:"E.g., Dark mode with purple accents, Minimalist and clean, Retro 80s style, Professional corporate look, Glassmorphism with blur effects...",description:"Be creative! Describe colors, mood, style, or any specific design elements you want."}))))}))},Ga=e=>{const{settings:t,onUpdateSettings:a}=e;return React.createElement(React.Fragment,null,React.createElement(ga,null,React.createElement(Ue.y2,{title:J.A.COMMON.STYLE,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.SPACING,":"),React.createElement(G.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:.5}},React.createElement("label",null,J.A.COMMON.BORDER_RADIUS,":"),React.createElement(G.A,{id:"borderRadius",name:"borderRadius",value:(null==t?void 0:t.borderRadius)??"10px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BORDER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"borderColor",name:"borderColor",value:(null==t?void 0:t.borderColor)??"#c5c5c5",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"borderColor",name:"borderColor",value:(null==t?void 0:t.borderColor)??"#c5c5c5",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_PRIMARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundPrimaryColor)??"#fafafa",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",value:(null==t?void 0:t.backgroundPrimaryColor)??"#fafafa",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_USER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundUserColor",name:"backgroundUserColor",style:{flex:1},value:(null==t?void 0:t.backgroundUserColor)??"#0084ff",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundUserColor",name:"backgroundUserColor",value:(null==t?void 0:t.backgroundUserColor)??"#0084ff",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_AI_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundAiColor",name:"backgroundAiColor",style:{flex:1},value:(null==t?void 0:t.backgroundAiColor)??"#eee",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundAiColor",name:"backgroundAiColor",value:(null==t?void 0:t.backgroundAiColor)??"#eee",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_AI_SECONDARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundAiSecondaryColor",name:"backgroundAiSecondaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundAiSecondaryColor)??"#ddd",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundAiSecondaryColor",name:"backgroundAiSecondaryColor",value:(null==t?void 0:t.backgroundAiSecondaryColor)??"#ddd",onChange:a})))),React.createElement($.g,null),React.createElement(Ue.y2,{title:J.A.COMMON.FONT||"Font",isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1.2}},React.createElement("label",null,J.A.COMMON&&J.A.COMMON.FONT_FAMILY||"Font Family",":"),React.createElement(j.u,{scrolldown:!0,name:"fontFamily",value:(null==t?void 0:t.fontFamily)||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",onChange:a},React.createElement(j.j,{value:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",label:"Native Feel"}),React.createElement(j.j,{value:"Arial, Helvetica, sans-serif",label:"Arial"}),React.createElement(j.j,{value:"Cambria, Georgia, serif",label:"Cambria"}),React.createElement(j.j,{value:"Consolas, 'Courier New', monospace",label:"Consolas"}),React.createElement(j.j,{value:"'Courier New', Courier, monospace",label:"Courier New"}),React.createElement(j.j,{value:"Georgia, serif",label:"Georgia"}),React.createElement(j.j,{value:"'Gill Sans', Calibri, sans-serif",label:"Gill Sans"}),React.createElement(j.j,{value:"Helvetica, Arial, sans-serif",label:"Helvetica"}),React.createElement(j.j,{value:"",label:"Inherit"}),React.createElement(j.j,{value:"Monaco, Consolas, monospace",label:"Monaco"}),React.createElement(j.j,{value:"Tahoma, Geneva, sans-serif",label:"Tahoma"}),React.createElement(j.j,{value:"Times, 'Times New Roman', serif",label:"Times"}),React.createElement(j.j,{value:"'Times New Roman', Times, serif",label:"Times New Roman"}),React.createElement(j.j,{value:"'Trebuchet MS', Helvetica, sans-serif",label:"Trebuchet MS"}),React.createElement(j.j,{value:"Verdana, Geneva, sans-serif",label:"Verdana"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.FONT_SIZE,":"),React.createElement(G.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,J.A.COMMON.FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onChange:a})))),React.createElement($.g,null),React.createElement(Ue.y2,{title:J.A.COMMON.POPUP,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.WIDTH,":"),React.createElement(G.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:.5}},React.createElement("label",null,J.A.COMMON.MAX_HEIGHT,":"),React.createElement(G.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,J.A.COMMON.AVATAR_MESSAGE_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#0084ff",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#0084ff",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.AVATAR_MESSAGE_FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BUBBLE_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"bubbleColor",name:"bubbleColor",style:{flex:1},value:(null==t?void 0:t.bubbleColor)??"#0084ff",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"bubbleColor",name:"bubbleColor",value:(null==t?void 0:t.bubbleColor)??"#0084ff",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.HEADER_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",style:{flex:1},value:(null==t?void 0:t.backgroundHeaderColor)??"#0084ff",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",value:(null==t?void 0:t.backgroundHeaderColor)??"#0084ff",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.HEADER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"headerButtonsColor",name:"headerButtonsColor",style:{flex:1},value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"headerButtonsColor",name:"headerButtonsColor",value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onChange:a}))))))},$a=e=>{const{settings:t,onUpdateSettings:a}=e;return React.createElement(React.Fragment,null,React.createElement(ga,null,React.createElement(Ue.y2,{title:J.A.COMMON.STYLE,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.SPACING,":"),React.createElement(G.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:.5}},React.createElement("label",null,J.A.COMMON.BORDER_RADIUS,":"),React.createElement(G.A,{id:"borderRadius",name:"borderRadius",value:(null==t?void 0:t.borderRadius)??"10px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BORDER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"borderColor",name:"borderColor",value:(null==t?void 0:t.borderColor)??"#c5c5c5",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"borderColor",name:"borderColor",value:(null==t?void 0:t.borderColor)??"#c5c5c5",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_PRIMARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundPrimaryColor)??"#fafafa",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundPrimaryColor",name:"backgroundPrimaryColor",value:(null==t?void 0:t.backgroundPrimaryColor)??"#fafafa",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_USER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundUserColor",name:"backgroundUserColor",style:{flex:1},value:(null==t?void 0:t.backgroundUserColor)??"#2768db",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundUserColor",name:"backgroundUserColor",value:(null==t?void 0:t.backgroundUserColor)??"#2768db",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_AI_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundAiColor",name:"backgroundAiColor",style:{flex:1},value:(null==t?void 0:t.backgroundAiColor)??"#F1F3F7",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundAiColor",name:"backgroundAiColor",value:(null==t?void 0:t.backgroundAiColor)??"#F1F3F7",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BACK_AI_SECONDARY_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundAiSecondaryColor",name:"backgroundAiSecondaryColor",style:{flex:1},value:(null==t?void 0:t.backgroundAiSecondaryColor)??"#ddd",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundAiSecondaryColor",name:"backgroundAiSecondaryColor",value:(null==t?void 0:t.backgroundAiSecondaryColor)??"#ddd",onChange:a})))),React.createElement($.g,null),React.createElement(Ue.y2,{title:J.A.COMMON.FONT||"Font",isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:1.2}},React.createElement("label",null,J.A.COMMON&&J.A.COMMON.FONT_FAMILY||"Font Family",":"),React.createElement(j.u,{scrolldown:!0,name:"fontFamily",value:(null==t?void 0:t.fontFamily)||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",onChange:a},React.createElement(j.j,{value:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",label:"Native Feel"}),React.createElement(j.j,{value:"Arial, Helvetica, sans-serif",label:"Arial"}),React.createElement(j.j,{value:"Cambria, Georgia, serif",label:"Cambria"}),React.createElement(j.j,{value:"Consolas, 'Courier New', monospace",label:"Consolas"}),React.createElement(j.j,{value:"'Courier New', Courier, monospace",label:"Courier New"}),React.createElement(j.j,{value:"Georgia, serif",label:"Georgia"}),React.createElement(j.j,{value:"'Gill Sans', Calibri, sans-serif",label:"Gill Sans"}),React.createElement(j.j,{value:"Helvetica, Arial, sans-serif",label:"Helvetica"}),React.createElement(j.j,{value:"",label:"Inherit"}),React.createElement(j.j,{value:"Monaco, Consolas, monospace",label:"Monaco"}),React.createElement(j.j,{value:"Tahoma, Geneva, sans-serif",label:"Tahoma"}),React.createElement(j.j,{value:"Times, 'Times New Roman', serif",label:"Times"}),React.createElement(j.j,{value:"'Times New Roman', Times, serif",label:"Times New Roman"}),React.createElement(j.j,{value:"'Trebuchet MS', Helvetica, sans-serif",label:"Trebuchet MS"}),React.createElement(j.j,{value:"Verdana, Geneva, sans-serif",label:"Verdana"}))),React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.FONT_SIZE,":"),React.createElement(G.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,J.A.COMMON.FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"fontColor",name:"fontColor",value:(null==t?void 0:t.fontColor)??"#FFFFFF",onChange:a})))),React.createElement($.g,null),React.createElement(Ue.y2,{title:J.A.COMMON.POPUP,isCollapsed:!1}),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.WIDTH,":"),React.createElement(G.A,{id:"width",name:"width",value:(null==t?void 0:t.width)??"380px",onBlur:a,onEnter:a})),React.createElement("div",{className:"mwai-builder-col",style:{flex:.5}},React.createElement("label",null,J.A.COMMON.MAX_HEIGHT,":"),React.createElement(G.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,J.A.COMMON.AVATAR_MESSAGE_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#2768db",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"iconTextBackgroundColor",name:"iconTextBackgroundColor",value:(null==t?void 0:t.iconTextBackgroundColor)??"#2768db",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.AVATAR_MESSAGE_FONT_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"iconTextColor",name:"iconTextColor",value:(null==t?void 0:t.iconTextColor)??"#FFFFFF",onChange:a})))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.BUBBLE_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"bubbleColor",name:"bubbleColor",style:{flex:1},value:(null==t?void 0:t.bubbleColor)??"#2831dc",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"bubbleColor",name:"bubbleColor",value:(null==t?void 0:t.bubbleColor)??"#2831dc",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.HEADER_BACKGROUND_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",style:{flex:1},value:(null==t?void 0:t.backgroundHeaderColor)??"#2831dc",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"backgroundHeaderColor",name:"backgroundHeaderColor",value:(null==t?void 0:t.backgroundHeaderColor)??"#2831dc",onChange:a}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.HEADER_COLOR,":"),React.createElement("div",{style:{display:"flex"}},React.createElement(G.A,{id:"headerButtonsColor",name:"headerButtonsColor",style:{flex:1},value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onBlur:a,onEnter:a}),React.createElement(Pa.V,{id:"headerButtonsColor",name:"headerButtonsColor",value:(null==t?void 0:t.headerButtonsColor)??"#FFFFFF",onChange:a}))))))},{useState:Wa,useEffect:za}=wp.element,Va=e=>{var t,a;const{theme:n,updateTheme:l,resetTheme:r,deleteTheme:o}=e,[i,s]=Wa((null===(t=n.settings)||void 0===t?void 0:t.customCSS)||""),[c,d]=Wa(!1);za((()=>{var e;s((null===(e=n.settings)||void 0===e?void 0:e.customCSS)||""),d(!1)}),[null===(a=n.settings)||void 0===a?void 0:a.customCSS]);const m=(e,t)=>{const a={...n.settings,[t]:e};l(a,"settings")};return React.createElement(React.Fragment,null,"internal"===n.type&&"chatgpt"===n.themeId&&React.createElement(La,{settings:n.settings??[],onUpdateSettings:m}),"internal"===n.type&&"messages"===n.themeId&&React.createElement(Ga,{settings:n.settings??[],onUpdateSettings:m}),"internal"===n.type&&"timeless"===n.themeId&&React.createElement($a,{settings:n.settings??[],onUpdateSettings:m}),"internal"!==n.type&&React.createElement(ja,{theme:n,onUpdateTheme:l}),"internal"===n.type&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(Ue.y2,{title:"Custom CSS",isCollapsed:!0},React.createElement("div",{style:{marginTop:10}},React.createElement(xe.m,{name:"customCSS",value:i,onChange:e=>{var t;s(e),d(e!==((null===(t=n.settings)||void 0===t?void 0:t.customCSS)||""))},placeholder:"/* Add your custom CSS here to override the theme styles */",rows:10,tabToSpaces:2}),React.createElement("div",{style:{display:"flex",marginTop:10}},React.createElement(h.M,{className:"primary",onClick:()=>{const e={...n.settings,customCSS:i};l(e,"settings"),d(!1)},disabled:!c},"Save Custom CSS"),React.createElement(h.M,{className:"secondary",onClick:()=>{s("");const e={...n.settings,customCSS:""};l(e,"settings"),d(!1)},disabled:!i},"Reset"))))),React.createElement($.g,null),React.createElement(Ue.y2,{title:J.A.COMMON.ACTIONS}),React.createElement("div",{style:{display:"flex",marginTop:10}},React.createElement(h.M,{className:"secondary",onClick:()=>{r()}},J.A.COMMON.RESET),React.createElement("div",{style:{flex:"auto"}}),React.createElement(h.M,{className:"danger",disabled:"internal"===n.type,onClick:o},J.A.COMMON.DELETE)))},{useState:qa}=wp.element,Ka=e=>{const t=(0,l.jE)(),{onSwitchTheme:a=(()=>{})}=e,[n,r]=qa(!1),{data:i}=(0,o.I)({queryKey:["themes"],queryFn:ze,initialData:v.Zj}),s=e.currentTheme,c=async(e,a)=>{try{r(!0);const n={...s,[a]:e};let l=[...i];const o=l.findIndex((e=>e.themeId===s.themeId));l[o]=n,l=await Ve(l),t.setQueryData(["themes"],l)}catch(e){console.error(e)}r(!1)},d=async()=>{r(!0);const e=[...i.filter((e=>e.themeId!==s.themeId))];a(e[0].themeId),await Ve(e),await t.setQueryData(["themes"],e),r(!1)},m=async()=>{r(!0);const e=[...i],a=e.findIndex((e=>e.themeId===s.themeId));e[a]={type:e[a].type,name:e[a].name,themeId:e[a].themeId,settings:[],style:""},await Ve(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==s?void 0:s.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 Ve([...i,{type:"css",name:"New Theme",themeId:"theme-"+pe(),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(Va,{theme:e,updateTheme:c,resetTheme:m,deleteTheme:d}))))))};var Ya=a(1469),Xa=a(6966);const Qa=new class{constructor(){this.locks=new Map,this.originalOverflow=null,this.isInAdmin=this.detectAdminEnvironment(),this.hasCheckedAdmin=!1,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{this.isInAdmin=this.detectAdminEnvironment(),this.hasCheckedAdmin=!0})):this.hasCheckedAdmin=!0}detectAdminEnvironment(){if(!document||!document.body)return!1;return!!(document.body&&document.body.classList&&document.body.classList.contains("wp-admin")||document.getElementById("wpcontent")||document.getElementById("adminmenu")||window.location.pathname.includes("/wp-admin/")||document.querySelector(".mwai-admin-container")||document.querySelector("#mwai-admin"))}updateLock(e,t){!this.hasCheckedAdmin&&document.body&&(this.isInAdmin=this.detectAdminEnvironment(),this.hasCheckedAdmin=!0),this.isInAdmin||(t?this.locks.set(e,!0):this.locks.delete(e),this.applyLockState())}removeLock(e){this.isInAdmin||(this.locks.delete(e),this.applyLockState())}applyLockState(){if(this.isInAdmin)return void("hidden"===document.body.style.overflow&&null!==this.originalOverflow&&(document.body.style.overflow=this.originalOverflow||"",this.originalOverflow=null));const e=this.locks.size>0;e&&"hidden"!==document.body.style.overflow?(null===this.originalOverflow&&(this.originalOverflow=document.body.style.overflow||""),document.body.style.overflow="hidden"):e||"hidden"!==document.body.style.overflow||(document.body.style.overflow=this.originalOverflow||"",this.originalOverflow=null)}getDebugInfo(){return{isInAdmin:this.isInAdmin,activeLocks:Array.from(this.locks.keys()),lockCount:this.locks.size,bodyOverflow:document.body.style.overflow,originalOverflow:this.originalOverflow}}};"undefined"!=typeof window&&(window.mwaiScrollLockManager=Qa);const Ja=Qa;var Za=a(1594),en=a.n(Za);const tn=f.Ay.div`
.mwai-standard-header {
display: flex;
align-items: center;
padding: 12px 16px;
background: var(--mwai-backgroundPrimaryColor);
border-bottom: 1px solid var(--mwai-borderColor);
.mwai-buttons {
display: flex;
gap: 8px;
margin-left: auto;
.mwai-resize-button,
.mwai-close-button {
width: 20px;
height: 20px;
cursor: pointer;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
opacity: 0.6;
transition: opacity 0.2s;
&:hover {
opacity: 1;
}
}
.mwai-resize-button {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>');
}
.mwai-close-button {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" preserveAspectRatio="xMidYMid meet"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>');
}
}
}
`,an=({title:e,onResize:t,onClose:a,showResize:n=!1})=>en().createElement(tn,null,en().createElement("div",{className:"mwai-modular-header mwai-standard-header"},e&&en().createElement("div",{className:"mwai-title"},e),en().createElement("div",{className:"mwai-buttons"},n&&en().createElement("div",{className:"mwai-resize-button",onClick:t}),en().createElement("div",{className:"mwai-close-button",onClick:a})))),nn=({title:e,onClose:t,onMinimize:a,onMaximize:n,theme:l,showResize:r,children:o,onDragStart:i})=>en().createElement("div",{className:"mwai-header mwai-header-osx",role:"toolbar","aria-label":"Chat header"},en().createElement("div",{className:"mwai-osx-bar",onMouseDown:i},en().createElement("div",{className:"mwai-osx-controls"},en().createElement("button",{className:"mwai-osx-close",onClick:t,"aria-label":"Close",type:"button"},en().createElement("svg",{className:"mwai-lucide-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"},en().createElement("path",{d:"M18 6 6 18"}),en().createElement("path",{d:"M6 6l12 12"}))),en().createElement("button",{className:"mwai-osx-minimize",onClick:a||t,"aria-label":"Minimize",type:"button"},en().createElement("svg",{className:"mwai-lucide-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"},en().createElement("path",{d:"M5 12h14"}))),r&&en().createElement("button",{className:"mwai-osx-maximize",onClick:n,"aria-label":"Maximize",type:"button"},en().createElement("svg",{className:"mwai-lucide-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"},en().createElement("path",{d:"M15 3h6v6"}),en().createElement("path",{d:"M9 21H3v-6"}),en().createElement("path",{d:"M21 3l-7 7"}),en().createElement("path",{d:"M3 21l7-7"})))),en().createElement("div",{className:"mwai-osx-title"},e)),o&&en().createElement("div",{className:"mwai-osx-content"},o)),ln=()=>{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 rn(){return rn=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},rn.apply(this,arguments)}const{useState:on,useEffect:sn,useRef:cn,useCallback:dn}=wp.element,mn=({enabled:e,content:t,children:a,className:n,message:l,...r})=>{var o;const i=(0,Xa.gR)(),[s,c]=on("idle"),[d,m]=on(!0),[u,p]=on([]),E=cn(null),g=cn(!1),h=cn(null),R=(null==l||null===(o=l.images)||void 0===o?void 0:o.filter((e=>e&&!e.includes("placehold.co")&&!e.includes("Expired+Image"))))||[],y=R.length>0,v=u.length>0,b=y||v;sn((()=>{const e=()=>{if(h.current){const e=h.current.querySelectorAll("img.mwai-image, img"),t=Array.from(e).map((e=>e.src)).filter((e=>e&&!e.includes("data:image")&&!e.includes("placehold.co")&&!e.includes("Expired+Image")));t.length>0?p(t):p([])}};e();const t=setTimeout(e,100);return()=>clearTimeout(t)}),[a]);const f=dn((()=>{g.current||(g.current=!0,E.current=setTimeout((()=>{m(!1)}),500))}),[]),w=dn((()=>{E.current&&clearTimeout(E.current),m(!0),g.current=!1}),[]);sn((()=>()=>{E.current&&clearTimeout(E.current)}),[]);const _="success"===s?'<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"===s?'<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" />',C=!!e||b;return React.createElement("div",rn({},r,{ref:h,onMouseLeave:w,onMouseEnter:f,onMouseOver:f}),React.createElement("span",{className:n},a),C&&React.createElement("div",{className:i("mwai-reply-actions",{"mwai-hidden":d})},e&&React.createElement("div",{className:"mwai-copy-button",onClick:()=>{try{navigator.clipboard.writeText(t),c("success")}catch(e){c("error"),console.warn("Not allowed to copy to clipboard. Make sure your website uses HTTPS.",{content:t})}finally{setTimeout((()=>{c("idle")}),2e3)}}},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:_}})),b&&React.createElement("div",{className:"mwai-download-button",onClick:async()=>{if(!b)return;const e=y?R:u;for(let t=0;t<e.length;t++){const a=e[t];try{const e=await fetch(a),n=await e.blob(),r=window.URL.createObjectURL(n),o=document.createElement("a");o.href=r;let i=`ai-image-${t+1}.png`;try{const e=a.split("/"),t=e[e.length-1];t&&!t.includes("?")&&(i=t)}catch(e){}o.download=i,document.body.appendChild(o),o.click(),document.body.removeChild(o),window.URL.revokeObjectURL(r),t<l.images.length-1&&await new Promise((e=>setTimeout(e,100)))}catch(e){console.error("Failed to download image:",e)}}}},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:'<path d="M12 2C11.4477 2 11 2.44772 11 3V12.5858L8.70711 10.2929C8.31658 9.90237 7.68342 9.90237 7.29289 10.2929C6.90237 10.6834 6.90237 11.3166 7.29289 11.7071L11.2929 15.7071C11.6834 16.0976 12.3166 16.0976 12.7071 15.7071L16.7071 11.7071C17.0976 11.3166 17.0976 10.6834 16.7071 10.2929C16.3166 9.90237 15.6834 9.90237 15.2929 10.2929L13 12.5858V3C13 2.44772 12.5523 2 12 2Z"/><path d="M5 17C4.44772 17 4 17.4477 4 18V20C4 20.5523 4.44772 21 5 21H19C19.5523 21 20 20.5523 20 20V18C20 17.4477 19.5523 17 19 17C18.4477 17 18 17.4477 18 18V19H6V18C6 17.4477 5.55228 17 5 17Z"/>'}}))))},{useState:un}=wp.element,pn=({enabled:e,content:t,children:a,className:n,message:l,...r})=>{const o=(0,Xa.gR)(),{actions:i,state:s}=(0,Ya.o)(),{setMessages:c,saveMessages:d,retryLastQuery:m}=i,{messages:u}=s,[p,E]=un("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:()=>{c((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&&(c((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:En}=wp.element;const gn=({role:e="user"})=>{const{state:t}=(0,Ya.o)(),{pluginUrl:a,iconUrl:n,userData:l,userName:r,aiName:o,guestName:i,userAvatar:s,aiAvatar:c,guestAvatar:d,userAvatarUrl:m,aiAvatarUrl:u,guestAvatarUrl:p}=t,E=En((()=>{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,_a.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,Xa.mv)(e)?e:e&&!(0,_a.Ve)(e)?t?e:`${a}/images/${e}`:(t||(0,_a.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(c,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(s,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,c,s,d,u,m,p,a]);return React.createElement("span",{className:"mwai-name"},E)},{useMemo:hn}=wp.element,Rn=({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)},yn=({message:e})=>{let t=e.content??"";const a=e.isError||"error"===e.role;(t.match(/```/g)||[]).length%2!=0&&(t+="\n```");const n=hn((()=>({forceBlock:!1,forceInline:!1,breaks:!0,overrides:{BlinkingCursor:{component:_a.rn},a:{component:Rn},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"}}}})),[]),l=hn((()=>{if(a)return t;let e="";try{let a=t;const l=[];a=a.replace(/```[\s\S]*?```/g,((e,t)=>(l.push(e),`__CODE_BLOCK_${l.length-1}__`)));const r=[];a=a.replace(/`[^`]+`/g,(e=>(r.push(e),`__INLINE_CODE_${r.length-1}__`))),a=a.replace(/(?<!\n)\n(?!\n)/g," \n"),l.forEach(((e,t)=>{a=a.replace(`__CODE_BLOCK_${t}__`,e)})),r.forEach(((e,t)=>{a=a.replace(`__INLINE_CODE_${t}__`,e)})),e=(0,Kt.cx)(a,n)}catch(a){console.error(J.A.DEBUG.CRASH_IN_MARKDOWN,{e:a,content:t}),e=t}return e}),[t,n,e.id,e.key,a]);return e.isStreaming?React.createElement(React.Fragment,null,a?React.createElement("span",{dangerouslySetInnerHTML:{__html:l}}):l,React.createElement(_a.rn,null)):a?React.createElement("span",{dangerouslySetInnerHTML:{__html:l}}):l},{useState:vn,useMemo:bn,useEffect:fn,useRef:wn}=wp.element,_n=({message:e,onRendered:t=(()=>{})})=>{const{state:a}=(0,Ya.o)(),{copyButton:n,debugMode:l}=a,[r]=vn(e.isQuerying||e.isStreaming),o=e.isQuerying,i=e.isStreaming;if(fn((()=>{r&&(!r||o||i)||t()}),[r,o,i]),o)return React.createElement(ln,null);const s=e.isError||"error"===e.role?pn:mn;return React.createElement(React.Fragment,null,React.createElement(gn,{role:e.role}),React.createElement(s,{content:e.content,enabled:n,className:"mwai-text",message:e},React.createElement(yn,{message:e})))},Cn=({message:e,onRendered:t=(()=>{})})=>{const{state:a}=(0,Ya.o)(),{copyButton:n}=a,[l,r]=vn(null==e?void 0:e.images);fn((()=>{t()}));if(e.isQuerying)return React.createElement(ln,null);const o={...e,images:l};return React.createElement(React.Fragment,null,React.createElement(gn,{role:e.role}),React.createElement(mn,{content:"",enabled:!1,className:"mwai-text",message:o},React.createElement("div",{className:"mwai-gallery"},null==l?void 0:l.map(((e,t)=>React.createElement("a",{key:t,href:e,target:"_blank",rel:"noopener noreferrer"},React.createElement("img",{key:t,src:e,onError:()=>(e=>{r((t=>t.map(((t,a)=>a===e?"https://placehold.co/600x200?text=Expired+Image":t))))})(t)})))))))},Tn=({message:e,conversationRef:t})=>{var a;const{state:n,actions:l}=(0,Ya.o)(),{typewriter:r}=n,{setMessages:o,retryLastQuery:i}=l,s=(0,Xa.gR)(),c=wn(),d=s("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(c.current&&!e.isQuerying&&!c.current.classList.contains("mwai-rendered")&&"undefined"!=typeof hljs){c.current.classList.add("mwai-rendered");c.current.querySelectorAll("pre code").forEach((e=>{hljs.highlightElement(e)}))}};return bn((()=>{if("user"===e.role)return React.createElement("div",{ref:c,className:d},React.createElement(_n,{message:e}));if("assistant"===e.role)return m?React.createElement("div",{ref:c,className:d},React.createElement(Cn,{message:e,conversationRef:t,onRendered:p})):React.createElement("div",{ref:c,className:d},React.createElement(_n,{message:e,conversationRef:t,onRendered:p}));if("system"===e.role&&!u)return React.createElement("div",{ref:c,className:d},React.createElement(_n,{message:e,conversationRef:t,onRendered:p}));if(u){const a={...e,role:"assistant"};return React.createElement("div",{ref:c,className:d},React.createElement(_n,{message:a,conversationRef:t,onRendered:p}))}return React.createElement("div",null,React.createElement("i",null,"Unhandled role."))}),[e,t,m,r])},{useRef:An,useEffect:Nn}=wp.element,On=({messages:e,conversationRef:t,onScroll:a,shortcuts:n,blocks:l})=>{const r=e.map(((e,a)=>React.createElement(Tn,{key:a,message:e,conversationRef:t})));return React.createElement(React.Fragment,null,React.createElement("div",{ref:t,className:"mwai-conversation",onScroll:a},r,n),l)};var In=a(7677);const{useMemo:Sn,useRef:Mn,useEffect:kn,useImperativeHandle:xn,useCallback:Pn,useState:Ln}=wp.element,Dn=({children:e,role:t="assistant"})=>{const a="user"===t?"mwai-terminal-user":"system"===t?"mwai-terminal-system":"mwai-terminal-assistant";return React.createElement("div",{className:`mwai-terminal-line ${a}`},e)},Fn=({messages:e,conversationRef:t,onScroll:a})=>{const{state:n,actions:l}=(0,Ya.o)(),{inputText:r,textInputMaxLength:o,busy:i,locked:s,chatbotInputRef:c}=n,{setInputText:d,onSubmitAction:m}=l,[u,p]=Ln(!1),[E,g]=Ln(!1),h=Mn(null);xn(c,(()=>({focusInput:()=>{var e,a;null==t||null===(e=t.current)||void 0===e||null===(a=e.focus)||void 0===a||a.call(e)},currentElement:()=>null==t?void 0:t.current}))),kn((()=>{null!=t&&t.current&&(t.current.scrollTop=t.current.scrollHeight)}),[e]),kn((()=>()=>{h.current&&clearTimeout(h.current)}),[]);const R=e&&e.length>0?e[e.length-1]:null,y=!(!R||"assistant"!==R.role||!R.isStreaming&&!R.isQuerying),v=!i&&!s&&!y,b=Pn((e=>{if(i||s||y)return;const t=e.key&&1===e.key.length&&!e.ctrlKey&&!e.metaKey&&!e.altKey;return(t||"Backspace"===e.key||"Tab"===e.key)&&(g(!0),h.current&&clearTimeout(h.current),h.current=setTimeout((()=>{g(!1)}),250)),"Enter"===e.key?(e.preventDefault(),m(),g(!1),void(h.current&&clearTimeout(h.current))):"Backspace"===e.key?(e.preventDefault(),void d((e=>e?e.slice(0,-1):""))):"Tab"===e.key?(e.preventDefault(),void d((e=>(e||"")+"\t"))):t?(e.preventDefault(),void d((t=>{const a=(t||"")+e.key;return o?a.slice(0,o):a}))):void 0}),[i,s,y,d,m,o]),f=Pn((e=>{var t;if(i||s)return;const a=(null===(t=e.clipboardData)||void 0===t?void 0:t.getData("text"))||"";a&&(e.preventDefault(),d((e=>{const t=(e||"")+a;return o?t.slice(0,o):t})),g(!0),h.current&&clearTimeout(h.current),h.current=setTimeout((()=>{g(!1)}),250))}),[i,s,d,o]),w=Pn((()=>{p(!0)}),[]),_=Pn((()=>{p(!1)}),[]),C=Sn((()=>e.map(((e,t)=>"user"===e.role?React.createElement(Dn,{key:t,role:"user"},React.createElement("span",{className:"mwai-terminal-prompt"},React.createElement(In.A,{size:16})),React.createElement("span",{className:"mwai-terminal-text"},e.content)):"system"===e.role?React.createElement(Dn,{key:t,role:"system"},React.createElement("span",{className:"mwai-terminal-text"},"# ",e.content)):React.createElement(Dn,{key:t,role:"assistant"},React.createElement("span",{className:"mwai-terminal-text"},React.createElement(yn,{message:e})))))),[e]);return React.createElement(React.Fragment,null,React.createElement("div",{ref:t,className:"mwai-conversation mwai-terminal",tabIndex:0,role:"textbox","aria-label":"Terminal input",onKeyDown:b,onPaste:f,onFocus:w,onBlur:_,onClick:()=>{var e;return null==t||null===(e=t.current)||void 0===e?void 0:e.focus()},onScroll:a},C,!y&&React.createElement("div",{className:"mwai-terminal-line mwai-terminal-user-typing"},React.createElement("span",{className:"mwai-terminal-prompt"},React.createElement(In.A,{size:16})),React.createElement("span",{className:"mwai-terminal-input-wrapper"},React.createElement("span",{className:"mwai-terminal-typed"},r),React.createElement("span",{className:"mwai-terminal-cursor "+(u&&v?E?"mwai-terminal-cursor-typing":"mwai-terminal-cursor-active":"mwai-terminal-cursor-inactive")})))))};var Un=a(2192),Bn=a(8117);const{useState:Hn,useMemo:jn,useRef:Gn}=wp.element,$n=()=>{var e;const t=(0,Xa.gR)(),{state:a,actions:n}=(0,Ya.o)(),{uploadedFile:l,uploadedFiles:r,multiUpload:o,busy:i,imageUpload:s,fileUpload:c,fileSearch:d,draggingType:m}=a,{onUploadFile:u,onMultiFileUpload:p,resetUploadedFiles:E}=n,[g,h]=Hn(!1),R=Gn(),y=o?r.length>0:null==l?void 0:l.uploadedId,v=s||d||c,b=()=>u(null),f=l,w=jn((()=>null!=f&&f.localFile?f.localFile.type.startsWith("image/")?"image":"document":m),[f,m]),_=jn((()=>{let e="idle";null!=f&&f.uploadProgress?e="up":m?e="add":g&&y?e="del":y?e="ok":g&&!y&&(e="add");return`mwai-file-upload-icon mwai-${w?w.toLowerCase():"idle"}-${e}`}),[w,f,m,g,y]),C=jn((()=>null!=f&&f.uploadProgress?f.uploadProgress>99?99:Math.round(f.uploadProgress):""),[f]),T=jn((()=>o?(r||[]).length||0:y?1:0),[o,r,y]);if(!v)return null;const A="timeless"===(null==a||null===(e=a.theme)||void 0===e?void 0:e.themeId),N="none"===(null==a?void 0:a.inputType),O=A||N,I=t("mwai-file-upload",{"mwai-enabled":null==l?void 0:l.uploadedId,"mwai-busy":(null==l?void 0:l.localFile)&&!(null!=l&&l.uploadedId)});return React.createElement("div",{disabled:i,onClick:()=>{y?o?E():b():i||R.current.click()},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),className:I,style:{cursor:i?"default":"pointer"}},React.createElement("div",{className:`${_}${O?" mwai-lucide":""}${O&&g&&y?" mwai-hover":""}`},O&&React.createElement(Bn.A,{size:16}),O&&T>0&&React.createElement("span",{className:"mwai-upload-count","data-count":T,onClick:e=>{e.stopPropagation(),o?E():b()}}),!O&&React.createElement("span",{className:"mwai-file-upload-progress"},C)),React.createElement("input",{type:"file",ref:R,onChange:e=>{const t=e.target.files;if(t&&t.length>0)if(o){for(let e=0;e<t.length;e++)p(t[e]);e.target.value=""}else u(t[0])},multiple:o,style:{display:"none"}}))},{useRef:Wn,useState:zn,useEffect:Vn,useImperativeHandle:qn}=wp.element,Kn=()=>{const e=(0,Xa.gR)(),{state:t,actions:a}=(0,Ya.o)(),{inputText:n,textInputMaxLength:l,textInputPlaceholder:r,error:o,speechRecognitionAvailable:i,isMobile:s,conversationRef:c,open:d,uploadIconPosition:m,locked:u,isListening:p,busy:E,speechRecognition:g,chatbotInputRef:h}=t,{onSubmitAction:R,setIsListening:y,resetError:v,setInputText:b}=a,[f,w]=zn(!1),_=Wn();qn(h,(()=>({focusInput:()=>{var e;null===(e=_.current)||void 0===e||e.focus()},currentElement:()=>_.current}))),Vn((()=>{!s&&d&&_.current.focus(),c.current&&(c.current.scrollTop=c.current.scrollHeight)}),[d,s,c]);const C=e("mwai-input-text",{"mwai-dragging":t.draggingType,"mwai-blocked":t.isBlocked});return React.createElement("div",{ref:h,className:C},"mwai-input"===m&&React.createElement($n,null),React.createElement(Un.A,{ref:_,disabled:E||u,placeholder:r,value:n,maxLength:l,onCompositionStart:()=>w(!0),onCompositionEnd:()=>w(!1),onKeyDown:e=>{f||"Enter"!==e.code||e.shiftKey||(e.preventDefault(),R())},onChange:e=>{return t=e.target.value,p&&y(!1),o&&v(),void b(t);var t}}),g&&React.createElement(Xa.tm,{active:p,disabled:!i||E,className:"mwai-microphone",onClick:()=>y(!p)}))};var Yn=a(1585),Xn=a(9500),Qn=a(7775);const{useMemo:Jn,useCallback:Zn}=wp.element,el=()=>{const{state:e,actions:t}=(0,Ya.o)(),{onClear:a,onSubmitAction:n,setIsListening:l}=t,{textClear:r,textSend:o,uploadedFile:i,inputText:s,messages:c,isListening:d,timeElapsed:m,busy:u,submitButtonConf:p,locked:E}=e,g=!(null==i||!i.uploadProgress),h=!!(null==i||!i.uploadedId)&&s.length<1&&(null==c?void 0:c.length)>1,R=Jn((()=>u?m?React.createElement("div",{className:"mwai-timer"},m):null:null!=p&&p.useLucide?h?React.createElement(Yn.A,{size:"20"}):React.createElement(Xn.A,{size:"20"}):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(Yn.A,{size:"20"}):React.createElement("span",null,h?r:o):React.createElement(Qn.A,{size:"20"})),[u,m,h,r,o,p]),y=Jn((()=>"mwai-input-submit "+(u?"mwai-busy":"")),[u]),v=Zn((()=>{d&&l(!1),h?a():n()}),[h,d,a,n,l]),b=Zn((()=>{u||v()}),[u,v]);return React.createElement("button",{className:y,disabled:u||g||E,onClick:b},R)},tl={headers:{standard:an,osx:nn},messages:{standard:On,terminal:Fn},input:{standard:({inputClassNames:e,chatbotInputRef:t,handleDrop:a,handleDrag:n})=>React.createElement("div",{className:e,onClick:()=>{var e;return null===(e=t.current)||void 0===e?void 0:e.focusInput()},onDrop:a,onDragEnter:e=>n(e,!0),onDragLeave:e=>n(e,!1),onDragOver:e=>n(e,!0)},React.createElement(Kn,null),React.createElement(el,null))}},al=(e,t)=>tl[e]&&tl[e][t]?tl[e][t]:(console.warn(`Component ${e}/${t} not found`),null),{useMemo:nl}=wp.element;function ll(e,t,a,n){if((0,_a.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,Xa.mv)(o)?o:o?`${t}/images/${o}`:null)||a||`${t}/images/chat-openai.svg`);var o,i,s;return r?(i=r,s="AI Engine",React.createElement("div",{className:"mwai-avatar"},React.createElement("img",{alt:s,src:i}))):React.createElement("div",{className:"mwai-name-text"},e)}const rl=({onDragStart:e})=>{const{state:t,actions:a}=(0,Ya.o)(),{theme:n,isWindow:l,fullscreen:r,aiName:o,pluginUrl:i,open:s,closing:c,iconUrl:d,aiAvatarUrl:m,windowed:u,headerSubtitle:p,popupTitle:E,headerType:g,windowAnimation:h}=t,{setOpen:R,setClosing:y,setWindowed:v}=a,b=()=>{if(c||!s)return;if(!h||"none"===h)return void R(!1);y(!0);const e={zoom:{close:180,tail:150},slide:{close:200,tail:150},fade:{close:180,tail:120}},t=e[h]&&e[h].close||180,a=e[h]&&e[h].tail||150;setTimeout((()=>{R(!1),setTimeout((()=>{y(!1)}),a)}),t)};if(!l)return null;if("none"===g)return null;const f=nl((()=>{const e="timeless"===(null==n?void 0:n.themeId),t=e?ll(o,i,d,m):null,a=null==p?"Discuss with":p,l="osx"!==g;return React.createElement(React.Fragment,null,e&&React.createElement(React.Fragment,null,t,React.createElement("div",{className:"mwai-name"},a&&React.createElement("small",{className:"mwai-subtitle"},a),React.createElement("div",null,o)),React.createElement("div",{style:{flex:"auto"}})),l&&React.createElement("div",{className:"mwai-buttons"},r&&React.createElement("div",{className:"mwai-resize-button",onClick:()=>v(!u)}),React.createElement("div",{className:"mwai-close-button",onClick:b})))}),[null==n?void 0:n.themeId,o,i,d,m,r,v,u,b,p,g]),w=g||"standard",_=al("headers",w);if(_&&"standard"!==w){const t={title:E||o,aiName:o,subtitle:p,pluginUrl:i,iconUrl:d,aiAvatarUrl:m,onClose:b,onResize:()=>v(!u),onMinimize:b,onMaximize:()=>v(!u),showResize:r,theme:n,isFullscreen:r&&!u,isWindowed:u,onDragStart:e},a="timeless"===(null==n?void 0:n.themeId)?f:null;return React.createElement(_,t,a)}return React.createElement("div",{className:"mwai-header",onMouseDown:e,role:"toolbar","aria-label":"Chat header"},f)},{useMemo:ol,useEffect:il}=wp.element,sl=()=>{const{state:e,actions:t}=(0,Ya.o)(),{isWindow:a,iconText:n,showIconMessage:l,iconAlt:r,iconUrl:o,open:i,opening:s,windowAnimation:c}=e,{setShowIconMessage:d,setOpen:m,setOpening:u}=t,p={zoom:{open:200},slide:{open:250},fade:{open:220}};il((()=>{i&&l&&d(!1)}),[i,d,l]);const E=ol((()=>{if(!a)return null;const e=()=>{i||s||(l&&d(!1),c&&"none"!==c?(u(!0),requestAnimationFrame((()=>{m(!0);const e=p[c]&&p[c].open||200;setTimeout((()=>{u(!1)}),e)}))):m(!0))};return React.createElement("div",{className:"mwai-trigger mwai-open-button"},React.createElement(Xa.bE,{className:"mwai-icon-text-container",if:n&&l,disableTransition:!0},React.createElement("div",{className:"mwai-icon-text-close",role:"button","aria-label":"Close tip",onClick:e=>{e.stopPropagation(),d(!1)},onMouseDown:e=>e.preventDefault()},"✕"),React.createElement("div",{className:"mwai-icon-text",onClick:e},n)),React.createElement("div",{className:"mwai-icon-container",onClick:e},(0,_a.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,d,m,u,i,s,c]);return React.createElement(React.Fragment,null,E)},{useMemo:cl}=wp.element,dl=()=>{const e=(0,Xa.gR)(),{state:t,actions:a}=(0,Ya.o)(),{busy:n,messages:l,theme:r}=t;null==r||r.themeId;if(!cl((()=>(l||[]).length>0),[l]))return null;const o=e("mwai-file-upload",{});return React.createElement("div",{className:o,style:{cursor:n?"default":"pointer"}},React.createElement("div",{className:"mwai-file-upload-icon mwai-lucide",role:"button","aria-label":"Clear conversation",title:"Clear",onClick:()=>{n||a.onClear()}},React.createElement(Yn.A,{size:16})))};var ml=a(5731),ul=a(9612),pl=a(9798),El=a(8834),gl=a(7611),hl=a(5773),Rl=a(3893),yl=a(718),vl=a(215);const{useState:bl,useRef:fl,useEffect:wl}=wp.element;function _l(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 Cl({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:s=50,pulseMaxSize:c=30}){const[d,m]=bl(0),[u,p]=bl(0),E=fl(0),g=fl(0),h=fl(null),R=fl(null),y=fl(null),v=fl(null),b=fl(null);wl((()=>{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,b.current=new Uint8Array(v.current.frequencyBinCount),l.connect(v.current));const s=()=>{let e=0;R.current&&y.current&&(e=_l(R.current,y.current));let t=0;v.current&&b.current&&(t=_l(v.current,b.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(s)};return s(),()=>{n&&n.disconnect(),R.current&&R.current.disconnect(),l&&l.disconnect(),v.current&&v.current.disconnect(),r&&cancelAnimationFrame(r)}}),[e,t,o,i]);const f=s+Math.min(d/20,1)*c,w=s+Math.min(u/20,1)*c,_=s+c,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:f,height:f,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",opacity:.5};a&&(T.backgroundColor=a);const A={width:s,height:s,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"flex",justifyContent:"center",alignItems:"center",overflow:"hidden",color:"#fff"};n&&(A.backgroundColor=n);const N={width:s,height:s,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 O="mwai-visualizer";u>d?O+=" mwai-user-talking":d>u&&(O+=" mwai-assistant-talking");const I=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:O},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:A},I(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},I(r))))}const Tl="tool_call",Al="tool_result",Nl="status",Ol="error",Il="transcript";const Sl=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(Nl,"Starting realtime session...")}sessionConnected(){const e=this.sessionStartTime?(new Date).getTime()-this.sessionStartTime:0;this.emit(Nl,`Realtime session connected in ${e}ms.`)}sessionEnding(){this.emit(Nl,"Ending realtime session...")}sessionError(e){this.emit(Ol,`Realtime session error: ${e}`)}userStartedSpeaking(){this.emit(Nl,"User speaking...",{visibility:"collapsed"})}userStoppedSpeaking(){this.emit(Nl,"User finished speaking.",{visibility:"collapsed"})}assistantStartedSpeaking(){this.emit(Nl,"Assistant speaking...",{visibility:"collapsed"})}assistantStoppedSpeaking(){this.emit(Nl,"Assistant finished speaking.",{visibility:"collapsed"})}functionCalling(e,t){this.emit(Tl,`Calling ${e}...`,{metadata:{tool_name:e,arguments:t}})}functionResult(e,t){this.emit(Al,`Got result from ${e}.`,{metadata:{tool_name:e,result:t}})}functionError(e,t){this.emit(Ol,`Function ${e} failed: ${t}`,{metadata:{tool_name:e}})}userTranscribed(e){this.emit(Nl,`User: "${e}"`,{visibility:"collapsed"})}assistantTranscribed(e){this.emit(Nl,`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(Nl,`Tokens used: ${r} (Text: ${t}/${n}, Audio: ${a}/${l})`,{visibility:"collapsed",metadata:{usage:e}})}},{useState:Ml,useRef:kl,useCallback:xl,useMemo:Pl,useEffect:Ll}=wp.element,Dl=e=>"undefined"!=typeof wp&&wp.i18n&&wp.i18n.__?wp.i18n.__(e,"ai-engine"):e,Fl=1,Ul=3,Bl=Fl;function Hl(e,...t){Bl>=e&&console.log(...t)}function jl(e,t="user"){const{pluginUrl:a,iconUrl:n,userData:l,userName:r,aiName:o,guestName:i,userAvatar:s,aiAvatar:c,guestAvatar:d,userAvatarUrl:m,aiAvatarUrl:u,guestAvatarUrl:p}=e,E=(e,t,n,l,r=!1)=>{if(t){const e=((e,t=!1)=>(0,Xa.mv)(e)?e:e&&!(0,_a.Ve)(e)?t?e:`${a}/images/${e}`:null)(n,r)||l;if(e)return{emoji:null,text:null,image:e,use:"image"}}return(0,_a.Ve)(e)?{emoji:e,text:null,image:null,use:"emoji"}:{emoji:null,text:e,image:null,use:"text"}};if("assistant"===t)return E(o,c,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,s,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 Gl=({onMessagesUpdate:e,onStreamEvent:t})=>{const{state:a,actions:n}=(0,Ya.o)(),{busy:l,locked:r,open:o,popup:i,system:s,blocks:c,params:d}=a,{onStartRealtimeSession:m,onRealtimeFunctionCallback:u,onCommitStats:p,onCommitDiscussions:E}=n,g=(null==s||s.debugMode,(null==s?void 0:s.eventLogs)||!1),h=!0===(null==d?void 0:d.imageUpload)||!0===(null==s?void 0:s.imageUpload),[R,y]=Ml(!1),[v,b]=Ml(!1),[f,w]=Ml(!1),[_,C]=Ml(null),[T,A]=Ml(null),[N,O]=Ml(null),[I,S]=Ml(null),[M,k]=Ml(!1),[x,P]=Ml({text_input_tokens:0,audio_input_tokens:0,text_output_tokens:0,audio_output_tokens:0,text_cached_tokens:0,audio_cached_tokens:0}),L=kl(null),D=kl(null),[F,U]=Ml(!1),[B,H]=Ml(0),[j,G]=Ml(!1),[$,W]=Ml(!1),[z,V]=Ml(!1),[q,K]=Ml([]),Y=kl(new Set),X=xl(((e,a)=>{a&&a.subtype&&t&&t({...a,timestamp:a.timestamp||(new Date).getTime(),messageId:"realtime-session"})}),[t]),Q=kl(null);Ll((()=>{Q.current=new Sl(X,g)}),[X,g]);const J=kl(null),Z=kl(null),ee=kl(null),te=kl(null),[ae,ne]=Ml(!0),[le,re]=Ml(!0),[oe,ie]=Ml(!1),[se,ce]=Ml(!1),[de,me]=Ml(null),ue=kl([]),pe=Pl((()=>jl(a,"user")),[a]),Ee=Pl((()=>jl(a,"assistant")),[a]);Ll((()=>{!o&&v&&i&&ve()}),[o,i,v]),Ll((()=>{e&&e(q)}),[q,e]);const ge=xl((async e=>{const t=await p(e);t.overLimit&&(g&&Q.current&&Q.current.emit(Ol,t.limitMessage||Dl("Usage limit exceeded"),{visibility:"visible",error:!0}),console.warn("Usage limit exceeded, stopping realtime connection:",t.limitMessage),te.current&&te.current())}),[p,g]),he=xl((()=>{Z.current&&"open"===Z.current.readyState?(Z.current.send(JSON.stringify({type:"session.update",session:{input_audio_transcription:{model:"whisper-1"}}})),Hl(Fl,"Sent session.update to enable Whisper.")):console.error("Data channel is not open yet; cannot enable transcription.")}),[]),Re=xl((async(e,t,a)=>{let n={};try{n=JSON.parse(a||"{}")}catch(e){console.error("Could not parse function arguments.",a)}const l=ue.current.find((e=>e.name===t));if(l)try{var r;const a=await u(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(g&&Q.current){const a="string"==typeof o?o:JSON.stringify(o),n=a.length>100?a.substring(0,100)+"...":a;Q.current.emit(Al,`Got result from ${t}.`,{metadata:{tool_name:t,result:n,call_id:e}})}"open"===(null===(r=Z.current)||void 0===r?void 0:r.readyState)&&(Hl(Fl,"Send callback value:",o),Z.current.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(o)}})),Z.current.send(JSON.stringify({type:"response.create",response:{instructions:"Reply based on the function's output."}})))}catch(e){console.error("Error in handleFunctionCall.",e)}else console.error(`No match for callback: '${t}'.`)}),[u,g]),ye=xl((async(e,t)=>{y(!0),g&&Q.current&&Q.current.emit(Nl,"Starting realtime session...",{visibility:"visible"});const a=new RTCPeerConnection;let n;J.current=a,a.addEventListener("connectionstatechange",(()=>{console.log("PC connection state:",a.connectionState),"failed"!==a.connectionState&&"closed"!==a.connectionState&&"disconnected"!==a.connectionState||F&&(O(Dl("Connection lost. Please try again.")),U(!1),H(0))}));try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error(Dl("MediaDevices API not available. Please ensure you are using HTTPS and a modern browser."));n=await navigator.mediaDevices.getUserMedia({audio:!0}),ee.current=n,n.getTracks().forEach((e=>a.addTrack(e,n)))}catch(e){return console.error("Error accessing microphone.",e),g&&Q.current&&Q.current.emit(Nl,Dl("Failed to access microphone: ")+e.message,{visibility:"visible",error:!0}),O(Dl("Failed to access microphone. Please ensure microphone permissions are granted and try again.")),void y(!1)}a.ontrack=e=>{const t=document.getElementById("mwai-audio");t&&(t.srcObject=e.streams[0]),me(e.streams[0])};const l=a.createDataChannel("oai-events");Z.current=l,l.addEventListener("open",(()=>{Hl(Fl,"Data channel open."),g&&Q.current&&Q.current.emit(Nl,"Realtime session connected",{visibility:"visible"}),he()})),l.addEventListener("close",(()=>{console.log("Data channel closed"),F&&(O(Dl("Connection lost while uploading image. Please try again.")),U(!1),H(0))})),l.addEventListener("error",(e=>{console.error("Data channel error:",e),F&&(O(Dl("Error uploading image. Please try again.")),U(!1),H(0))})),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(Bl>=Ul)console.log("Incoming message from Realtime API.",t);else if(Bl===Fl){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(g&&t.type&&Q.current){let e="",a=Nl,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=Il,n=!0;break;case"response.audio_transcript.done":e="Got transcript from assistant.",a=Il,n=!0;break;case"response.function_call_arguments.done":e=`Calling ${t.name}...`,a=Tl,n=!0}n&&Q.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;Y.current.has(e)||(Y.current.add(e),K((t=>[...t,{id:e,role:"user",content:"[Audio]"}]))),A("user");break}case"conversation.item.created":var n,l;console.log("Conversation item created:",t),null!==(n=t.item)&&void 0!==n&&null!==(n=n.content)&&void 0!==n&&n.some((e=>"input_image"===e.type||"input_image_url"===e.type))&&(console.log("Image item confirmed by API"),W((e=>e?(console.log("Clearing processing state - image confirmed by API"),!1):e)),U(!1),H(0),V(!0),setTimeout((()=>{V(!1)}),2e3)),"assistant"===(null===(l=t.item)||void 0===l?void 0:l.role)&&(console.log("Assistant response started"),$&&(console.log("Clearing processing state - assistant is responding"),W(!1)));break;case"conversation.item.input_audio_transcription.completed":{const e=t.item_id,a=(t.transcript||"[Audio]").trim();K((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();A("assistant"),Y.current.has(e)||(Y.current.add(e),K((t=>[...t,{id:e,role:"assistant",content:a}])));break}case"response.text.done":{const e=t.item_id,a=t.text||"";a&&!Y.current.has(e)&&(Y.current.add(e),K((t=>[...t,{id:e,role:"assistant",content:a}])));break}case"response.output_item.done":{console.log("Output item done:",t);const e=t.item;if($&&(console.log("Clearing processing state after response"),W(!1)),F&&(console.log("Clearing upload state after response"),U(!1),H(0)),e&&(console.log("Item structure:",{hasContent:!!e.content,contentType:Array.isArray(e.content)?"array":typeof e.content,contentLength:Array.isArray(e.content)?e.content.length:0,firstContent:Array.isArray(e.content)&&e.content[0]?e.content[0]:null}),e.content))if(Array.isArray(e.content)){const t=e.content.find((e=>"text"===e.type));t&&t.text&&!Y.current.has(e.id)&&(Y.current.add(e.id),K((a=>[...a,{id:e.id,role:e.role||"assistant",content:t.text}])),console.log("Added text response from output_item array:",t.text))}else"string"==typeof e.content&&(Y.current.has(e.id)||(Y.current.add(e.id),K((t=>[...t,{id:e.id,role:e.role||"assistant",content:e.content}])),console.log("Added text response from output_item string:",e.content)));break}case"response.function_call_arguments.done":{const{call_id:e,name:a,arguments:n}=t;Hl(Fl,"Function call requested.",e,a),Re(e,a,n);break}case"response.done":{const e=t.response;if(W((e=>e?(console.log("Response completed after image processing"),!1):e)),U((e=>e?(console.log("Response completed while still uploading"),H(0),!1):e)),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&&P((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 ge(a),a}))}A("user");break}case"error":var r;console.error("Realtime API error:",t),null!==(r=t.error)&&void 0!==r&&r.message&&O(`API Error: ${t.error.message}`),U(!1),W(!1),H(0);break;default:!t.type||t.type.startsWith("response.audio")||t.type.startsWith("input_audio")||console.log("Unhandled Realtime event:",t.type,t)}}));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),y(!1),O(Dl("Failed to establish connection with OpenAI servers. Please try again.")),void(g&&Q.current&&Q.current.emit(Ol,Dl("Failed to establish connection with OpenAI servers. Please try again."),{visibility:"visible",error:!0}));const s=await i.text();await a.setRemoteDescription({type:"answer",sdp:s}),Hl(Fl,"Realtime connection established."),y(!1),b(!0),w(!1),A("user")}),[he,Re,ge,g]),ve=xl((()=>{S(null),g&&Q.current&&Q.current.emit(Nl,"Ending realtime session...",{visibility:"visible"});try{J.current&&(J.current.close(),J.current=null),ee.current&&(ee.current.getTracks().forEach((e=>e.stop())),ee.current=null),Z.current=null,y(!1),b(!1),w(!1),A(null),E(q),K([]),P({text_input_tokens:0,audio_input_tokens:0,text_output_tokens:0,audio_output_tokens:0,text_cached_tokens:0,audio_cached_tokens:0}),Hl(Fl,"Stopped Realtime connection.")}catch(e){console.error("Error stopping connection.",e)}}),[q,x,E]);Ll((()=>{te.current=ve}),[ve]);const be=xl((()=>{if(!ee.current)return;const e=ee.current.getAudioTracks();e.length&&(f?(e.forEach((e=>{e.enabled=!0})),Hl(Fl,"Resumed microphone."),w(!1)):(e.forEach((e=>{e.enabled=!1})),Hl(Fl,"Paused microphone."),w(!0)))}),[f]),fe=xl(((e,t=800,a=800,n=.6)=>new Promise((l=>{const r=new Image;r.onload=()=>{let e=r.width,o=r.height;if(e>t||o>a){const n=Math.min(t/e,a/o);e=Math.round(e*n),o=Math.round(o*n)}const i=document.createElement("canvas");i.width=e,i.height=o;i.getContext("2d").drawImage(r,0,0,e,o);const s=i.toDataURL("image/jpeg",n);l(s)},r.src=e}))),[]),we=xl((async e=>{if(!e.type.startsWith("image/"))return void O(Dl("Please select an image file."));if(e.size>20971520)O(Dl("Image file size must be less than 20MB."));else{U(!0),H(0);try{const t=new FileReader;t.onprogress=e=>{if(e.lengthComputable){const t=e.loaded/e.total*100;H(t)}},t.onload=async e=>{var t;let a=e.target.result;const n=a.length,l=204800;if(n>l){console.log(`Image too large (${(n/1024).toFixed(0)}KB), resizing...`),H(30);let e=.7,t=800,r=await fe(a,t,t,e);for(;r.length>l&&e>.3;)e-=.1,t=Math.max(400,t-100),console.log(`Still too large (${(r.length/1024).toFixed(0)}KB), trying quality ${e.toFixed(1)} and size ${t}...`),r=await fe(a,t,t,e);a=r,console.log(`Image resized to ${(a.length/1024).toFixed(0)}KB`)}if("open"===(null===(t=Z.current)||void 0===t?void 0:t.readyState)){g&&Q.current&&Q.current.emit(Nl,"Sending image...",{visibility:"visible"}),H(50),console.log("Image details:",{totalLength:a.length,hasDataPrefix:a.includes("data:"),mimeType:a.substring(5,a.indexOf(";")),sizeKB:(a.length/1024).toFixed(0)+"KB"});const e={type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"I've uploaded an image for you to analyze."},{type:"input_image",image_url:a}]}},t=JSON.stringify(e);if(console.log("Sending image message to Realtime API...",{messageType:e.type,contentTypes:e.item.content.map((e=>e.type)),totalSize:t.length,sizeKB:(t.length/1024).toFixed(0)+"KB"}),t.length>256e3)throw new Error(`Image message too large (${(t.length/1024).toFixed(0)}KB). Please try a smaller image.`);try{if("open"!==Z.current.readyState)throw new Error("Data channel is not open. State: "+Z.current.readyState);const e=Z.current.bufferedAmount;console.log("Data channel buffered amount before send:",e),e>0&&(console.log("Waiting for buffer to clear..."),await new Promise((e=>setTimeout(e,100)))),Z.current.send(t);const a=Z.current.bufferedAmount;console.log("Data channel buffered amount after send:",a),console.log("Image message queued for sending"),H(100),setTimeout((()=>{U(!1),W(!0),H(0),console.log("Processing image with AI...")}),300),console.log("Waiting for AI response to image...")}catch(e){return console.error("Failed to send image message:",e),O(Dl("Failed to send image. Please try again.")),U(!1),void H(0)}K((e=>[...e,{id:`img-${Date.now()}`,role:"user",content:"[Image uploaded - processing...]"}])),L.current&&(L.current.value="")}else O(Dl("Please start a session before uploading images.")),U(!1),H(0)},t.onerror=()=>{O(Dl("Failed to read image file.")),U(!1),H(0)},t.readAsDataURL(e)}catch(e){console.error("Error uploading image:",e),O(Dl("Failed to upload image.")),U(!1),H(0)}}}),[Z,g,fe]),_e=xl((async e=>{const t=e.target.files[0];t&&we(t)}),[we]),Ce=xl((e=>{e.preventDefault(),e.stopPropagation(),F||$||l||r||f||!v||G(!0)}),[F,$,l,r,f,v]),Te=xl((e=>{e.preventDefault(),e.stopPropagation(),D.current&&!D.current.contains(e.relatedTarget)&&G(!1)}),[]),Ae=xl((e=>{if(e.preventDefault(),e.stopPropagation(),G(!1),F||$||l||r||f||!v)return;const t=e.dataTransfer.files;t&&t.length>0&&we(t[0])}),[F,$,l,r,f,v,we]),Ne=xl((async()=>{y(!0),O(null);try{const e=await m();if(null==e||!e.success){console.error("Could not start realtime session.",e),y(!1);const t=(null==e?void 0:e.message)||Dl("Could not start realtime session.");return O(t),void(g&&Q.current&&Q.current.emit(Ol,t,{visibility:"visible",error:!0}))}ue.current=e.function_callbacks||[],C(e.session_id),S(e.model),console.log("Vision support from server:",e.supports_vision),k(!0===e.supports_vision),await ye(e.client_secret,e.model)}catch(e){console.error("Error in handlePlay.",e),y(!1);const t=e.message||Dl("An error occurred while starting the realtime session.");O(t),g&&Q.current&&Q.current.emit(Ol,t,{visibility:"visible",error:!0})}}),[m,ye,g]),Oe=xl((()=>ve()),[ve]),Ie=xl((()=>re((e=>!e))),[]),Se=xl((()=>ce((e=>!e))),[]),Me=xl((()=>ie((e=>!e))),[]),ke=Pl((()=>f?"mwai-pause mwai-active":"mwai-pause"),[f]),xe=Pl((()=>{const e=[...q].reverse().find((e=>"assistant"===e.role));return e?e.content.length>256?`${e.content.slice(0,256)}...`:e.content:"..."}),[q]),Pe=Pl((()=>le?"mwai-option mwai-option-users mwai-active":"mwai-option mwai-option-users"),[le]),Le=Pl((()=>oe?"mwai-option mwai-option-captions mwai-active":"mwai-option mwai-option-captions"),[oe]),De=Pl((()=>se?"mwai-option mwai-option-statistics mwai-active":"mwai-option mwai-option-statistics"),[se]);Ll((()=>{c&&c.length>0&&c.forEach((e=>{var t;if("content"===e.type&&null!==(t=e.data)&&void 0!==t&&t.script)try{const t=document.createElement("script");t.textContent=e.data.script,document.body.appendChild(t),setTimeout((()=>{t.parentNode&&t.parentNode.removeChild(t)}),0)}catch(e){console.error("Error executing block script:",e)}}))}),[c]);const Fe=Pl((()=>c&&0!==c.length?React.createElement("div",{className:"mwai-blocks"},c.map(((e,t)=>{const{type:a,data:n}=e;if("content"!==a)return console.warn(`Block type ${a} is not supported.`),null;const{html:l,variant:r}=n,o=["mwai-block"];return"success"===r&&o.push("mwai-success"),"danger"===r&&o.push("mwai-danger"),"warning"===r&&o.push("mwai-warning"),"info"===r&&o.push("mwai-info"),React.createElement("div",{className:o.join(" "),key:e.id||t,dangerouslySetInnerHTML:{__html:l}})}))):null),[c]);return React.createElement("div",null,Fe,N&&React.createElement("div",{className:"mwai-error",style:{padding:"10px",margin:"10px 0",backgroundColor:"#fee",border:"1px solid #fcc",borderRadius:"5px",color:"#c00",textAlign:"center"}},N),React.createElement("audio",{id:"mwai-audio",autoPlay:!0}),le&&React.createElement("div",{style:{display:"flex",justifyContent:"center"}},React.createElement(Cl,{assistantStream:de,userUI:pe,assistantUI:Ee,userStream:ee.current})),React.createElement("div",{className:"mwai-controls"},!v&&!R&&React.createElement(React.Fragment,null,React.createElement("button",{onClick:Ne,className:"mwai-play",disabled:l||r,"aria-label":"Play"},React.createElement(ml.A,{size:16})),h&&React.createElement("button",{className:"mwai-upload",disabled:!0,"aria-label":"Upload Image (Start session first)",style:{opacity:.5,cursor:"not-allowed"},title:Dl("Start session to upload images")},React.createElement(ul.A,{size:16}))),R&&React.createElement(React.Fragment,null,React.createElement("button",{className:"mwai-play",disabled:!0},React.createElement(pl.A,{size:16,style:{animation:"spin 0.8s linear infinite"}})),h&&React.createElement("button",{className:"mwai-upload",disabled:!0,"aria-label":"Upload Image (Connecting...)",style:{opacity:.5,cursor:"not-allowed"}},React.createElement(ul.A,{size:16}))),v&&!R&&React.createElement(React.Fragment,null,React.createElement("button",{onClick:Oe,className:"mwai-stop",disabled:l||r,"aria-label":"Stop"},React.createElement(El.A,{size:16})),React.createElement("button",{onClick:be,className:ke,disabled:l||r,"aria-label":"Pause"},React.createElement(gl.A,{size:16})),(M||h)&&React.createElement(React.Fragment,null,React.createElement("input",{ref:L,type:"file",accept:"image/*",style:{display:"none"},onChange:_e}),React.createElement("button",{ref:D,onClick:()=>{var e;return null===(e=L.current)||void 0===e?void 0:e.click()},className:`mwai-upload ${j?"mwai-dragging":""} ${$?"mwai-processing":""} ${z?"mwai-success":""}`,disabled:l||r||F||$||z||f,"aria-label":"Upload Image",onDragOver:Ce,onDragLeave:Te,onDrop:Ae,style:{position:"relative",overflow:"visible",cursor:F||$?"wait":z?"default":"pointer",transition:"all 0.3s ease",...j?{transform:"scale(1.1)",backgroundColor:"rgba(34, 197, 94, 0.2)",borderColor:"rgb(34, 197, 94)"}:z?{backgroundColor:"rgba(34, 197, 94, 0.1)",borderColor:"rgb(34, 197, 94)"}:{}}},(F||$)&&React.createElement("svg",{style:{position:"absolute",top:"-2px",left:"-2px",width:"calc(100% + 4px)",height:"calc(100% + 4px)",transform:"rotate(-90deg)",pointerEvents:"none",animation:$?"spin 1s linear infinite":"none"}},$?React.createElement("circle",{cx:"50%",cy:"50%",r:"calc(50% - 2px)",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeDasharray:"20 10",strokeLinecap:"round",style:{opacity:.8}}):React.createElement("circle",{cx:"50%",cy:"50%",r:"calc(50% - 2px)",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeDasharray:1.26*B+" 126",strokeLinecap:"round",style:{transition:"stroke-dasharray 0.3s ease",opacity:.8}})),React.createElement("div",{style:{position:"relative",width:16,height:16,display:"flex",alignItems:"center",justifyContent:"center"}},React.createElement(ul.A,{size:16,style:{position:"absolute",top:0,left:0,opacity:z?0:F||$?.5:1,transition:"opacity 0.3s ease, transform 0.3s ease",transform:z?"scale(0.8)":"scale(1)",transformOrigin:"center"}}),React.createElement(hl.A,{size:16,style:{position:"absolute",top:0,left:0,opacity:z?1:0,transition:"opacity 0.3s ease, transform 0.3s ease",transform:z?"scale(1)":"scale(0.8)",transformOrigin:"center",color:"rgb(34, 197, 94)"}})))))),oe&&xe&&xe.length>0&&React.createElement("div",{className:"mwai-last-transcript"},xe),se&&React.createElement("div",{className:"mwai-statistics"},React.createElement("div",null,React.createElement("label",null,"Text In"),React.createElement("span",null,x.text_input_tokens)),React.createElement("div",null,React.createElement("label",null,"Text Out"),React.createElement("span",null,x.text_output_tokens)),React.createElement("div",null,React.createElement("label",null,"Text Cached"),React.createElement("span",null,x.text_cached_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio In"),React.createElement("span",null,x.audio_input_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio Out"),React.createElement("span",null,x.audio_output_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio Cached"),React.createElement("span",null,x.audio_cached_tokens))),ae&&React.createElement("div",{className:"mwai-options"},React.createElement(Rl.A,{size:13,title:"Show Users",className:Pe,onClick:Ie}),React.createElement(yl.A,{size:18,title:"Show Captions",className:Le,onClick:Me}),React.createElement(vl.A,{size:14,title:"Show Statistics",className:De,onClick:Se})))};var $l=a(6816),Wl=a(6844),zl=a(7073),Vl=a(8445),ql=a(7946),Kl=a(8697),Yl=a(942),Xl=a(3324),Ql=a(5107);const{useState:Jl,useMemo:Zl,useEffect:er}=wp.element,tr=({allStreamData:e,debugMode:t,onClear:a,hasData:n,isWindow:l})=>{const[r,o]=Jl({}),[i,s]=Jl(!1),[c,d]=Jl(!l),m=Zl((()=>{if(!e||0===e.length)return[];const t=e.map(((e,t)=>({...e,id:`${e.messageId}-${t}`,displayTime:new Date(e.timestamp).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}))).reverse();return c?t.slice(0,20):t.slice(0,1)}),[e,c]),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=Zl((()=>{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(Wl.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(Kl.A,{size:12})),!l&&React.createElement("div",{className:"mwai-chunks-toggle",onClick:()=>d(!c),title:c?"Show minimal (last event only)":"Show detailed (all events)"},c?React.createElement(Yl.A,{size:12}):React.createElement(Xl.A,{size:12}))),React.createElement("div",{className:"mwai-chunks-toggle",onClick:()=>s(!i),title:i?"Hide events":"Show events"},i?React.createElement(Ql.A,{size:12}):React.createElement(In.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(Wl.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($l.A,{size:14});case"mcp":case"output":default:return React.createElement(Wl.A,{size:14});case"thinking":return React.createElement(zl.A,{size:14});case"search":return React.createElement(Vl.A,{size:14});case"error":case"warning":return React.createElement(ql.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(In.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,Kt.cx)(t)}catch(e){return React.createElement("pre",null,t)}})()):React.createElement("pre",null,JSON.stringify(e.metadata,null,2))))}))))};var ar=a(2708);const{useMemo:nr}=wp.element,lr=()=>{const{state:e,actions:t}=(0,Ya.o)(),{uploadedFiles:a,multiUpload:n}=e,{removeUploadedFile:l}=t;if(!n||0===a.length)return null;return React.createElement("div",{className:"mwai-files"},a.map(((e,t)=>((e,t)=>{var a,n,r;const o=null===(a=e.localFile)||void 0===a||null===(a=a.type)||void 0===a?void 0:a.startsWith("image/"),i=(null===(n=e.localFile)||void 0===n?void 0:n.name)||"Unknown file",s=null!==(r=e.localFile)&&void 0!==r&&r.size?`${Math.round(e.localFile.size/1024)}KB`:"";return React.createElement("div",{key:e.tempId||t,className:"mwai-file-preview"},React.createElement("div",{className:"mwai-file-content"},o&&e.uploadedUrl?React.createElement("img",{src:e.uploadedUrl,alt:i,className:"mwai-file-thumbnail"}):React.createElement("div",{className:"mwai-file-icon"},React.createElement("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},React.createElement("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),React.createElement("polyline",{points:"14 2 14 8 20 8"}))),React.createElement("div",{className:"mwai-file-info"},React.createElement("div",{className:"mwai-file-name"},i),s&&React.createElement("div",{className:"mwai-file-size"},s)),null!==e.uploadProgress&&e.uploadProgress<100?React.createElement("div",{className:"mwai-file-progress"},React.createElement("div",{className:"mwai-file-progress-bar",style:{width:`${e.uploadProgress}%`}})):React.createElement("button",{className:"mwai-file-remove",onClick:()=>l(t),"aria-label":"Remove file"},React.createElement(ar.A,{size:20}))))})(e,t))))},{useState:rr,useEffect:or,useRef:ir,useMemo:sr}=wp.element,cr=({conversationRef:e,onScroll:t,jsxShortcuts:a,jsxBlocks:n,inputClassNames:l,handleDrop:r,handleDrag:o,needsFooter:i,needTools:s,uploadIconPosition:c})=>{const{state:d,actions:m}=(0,Ya.o)(),{debugMode:u,eventLogs:p,messages:E,isRealtime:g,textCompliance:h,chatbotInputRef:R,isWindow:y,fullscreen:v,windowed:b,messagesType:f,inputType:w,theme:_}=d,[C,T]=rr([]),[A,N]=rr(new Set),O=ir([]),[I,S]=(ir(0),rr([]));or((()=>{(0===E.length||1===E.length&&"assistant"===E[0].role)&&N(new Set)}),[E]),or((()=>{const e=[];[...E,...I].forEach((t=>{t.streamEvents&&(u||p)&&!A.has(t.id)&&t.streamEvents.forEach((a=>{e.push({...a,messageId:t.id})}))})),g||(O.current=e,T(e))}),[E,I,u,p,g,A]);return React.createElement("div",{className:"mwai-body"},!g&&React.createElement(React.Fragment,null,v&&!b?React.createElement(React.Fragment,null,"none"!==f&&(()=>{const l=al("messages",f);if(!l){console.warn(`Messages component '${f}' not found, falling back to standard`);const l=al("messages","standard");return React.createElement(l,{messages:E,conversationRef:e,onScroll:t,shortcuts:a,blocks:n})}return React.createElement(l,{messages:E,conversationRef:e,onScroll:t,shortcuts:a,blocks:n})})(),React.createElement("div",{className:"mwai-fullscreen-spacer"}),React.createElement(lr,null)):React.createElement(React.Fragment,null,"none"!==f&&(()=>{const l=al("messages",f);if(!l){console.warn(`Messages component '${f}' not found, falling back to standard`);const l=al("messages","standard");return React.createElement(l,{messages:E,conversationRef:e,onScroll:t,shortcuts:a,blocks:n})}return React.createElement(l,{messages:E,conversationRef:e,onScroll:t,shortcuts:a,blocks:n})})(),React.createElement(lr,null)),"none"!==w&&(()=>{const e=al("input",w);if(!e){console.warn(`Input component '${w}' not found, falling back to standard`);const e=al("input","standard");return React.createElement(e,{inputClassNames:l,chatbotInputRef:R,handleDrop:r,handleDrag:o})}return React.createElement(e,{inputClassNames:l,chatbotInputRef:R,handleDrop:r,handleDrag:o})})()),g&&React.createElement("div",{className:"mwai-realtime"},React.createElement(Gl,{onMessagesUpdate:S,onStreamEvent:e=>{T((t=>[...t,e]))}})),i&&React.createElement("div",{className:"mwai-footer"},(()=>{const e=("mwai-tools"===c||"none"===w)&&s,t="none"===w||"chatgpt"!==(null==_?void 0:_.themeId)&&"timeless"!==(null==_?void 0:_.themeId)&&"messages"!==(null==_?void 0:_.themeId),a=E&&E.length>0;return e&&s||t&&a?React.createElement("div",{className:"mwai-tools"},e&&React.createElement($n,null),t&&React.createElement(dl,null)):null})(),h&&React.createElement("div",{className:"mwai-compliance",dangerouslySetInnerHTML:{__html:h}})),p&&React.createElement(tr,{allStreamData:C,debugMode:u,onClear:()=>{T([]),O.current=[];const e=new Set;[...E,...I].forEach((t=>{t.streamEvents&&e.add(t.id)})),N(e)},hasData:C.length>0,isWindow:y}))},{useState:dr,useMemo:mr,useLayoutEffect:ur,useCallback:pr,useEffect:Er,useRef:gr}=wp.element,hr=e=>e.type.startsWith("image/"),Rr=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),yr=e=>{const t=(0,Xa.gR)(),{style:a,isAdminPreview:n}=e,[l,r]=dr(!0),[o,i]=dr(!1),{state:s,actions:c}=(0,Ya.o)(),{theme:d,botId:m,customId:u,messages:p,textCompliance:E,isWindow:g,fullscreen:h,iconPosition:R,centerOpen:y,width:v,openDelay:b,iconBubble:f,windowAnimation:w,shortcuts:_,blocks:C,imageUpload:T,fileSearch:A,fileUpload:N,multiUpload:O,draggingType:I,isBlocked:S,windowed:M,cssVariables:k,conversationRef:x,open:P,opening:L,closing:D,busy:F,uploadIconPosition:U,containerType:B,headerType:H,messagesType:j,inputType:G,footerType:$,popupTitle:W,aiName:z}=s,{onSubmit:V,setIsBlocked:q,setDraggingType:K,onUploadFile:Y,onMultiFileUpload:X,setOpen:Q,setClosing:J}=c,Z=mr((()=>"css"===(null==d?void 0:d.type)?(null==d?void 0:d.style)||null:null!=d&&d.customCSS?d.customCSS:null),[d]),ee=T||A||N,te="none"!==$&&(ee||E&&E.trim()),ae=gr(null);Er((()=>{const e=()=>{i(window.innerWidth<=760)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)}),[]);const ne=mr((()=>`chatbot-${m||u||Math.random().toString(36).substr(2,9)}`),[m,u]);Er((()=>{let e=!1;return h&&!M?e=!g||P:o&&g&&P&&(e=!0),Ja.updateLock(ne,e),()=>{Ja.removeLock(ne)}}),[P,h,M,o,g,ne]);const le=pr(((e,t)=>{if(e.preventDefault(),!T&&!N)return;if(!t)return q(!1),void K(!1);const a=e.dataTransfer.items;let n=!1,l=!1;if(a&&a.length>0)for(let e=0;e<a.length;e++){const t=a[e];if("file"===t.kind){const e=t.type;e?T&&e.startsWith("image/")?n=!0:N&&(e.startsWith("text/")||"application/pdf"===e||e.includes("document")||e.includes("sheet")||e.includes("presentation"))&&(l=!0):(T||N)&&(T?n=!0:l=!0)}}const r=n||l;q(!r),K(!!r&&(n?"image":"document"))}),[T,N,K,q]),re=pr((e=>{e.preventDefault();const t=e.dataTransfer.files;if(O){const e=Array.from(t).filter((e=>T&&hr(e)||N&&Rr(e)));e.length>0&&X(e)}else{const e=Array.from(t).find((e=>T&&hr(e)||N&&Rr(e)));e&&Y(e)}K(!1),q(!1)}),[T,N,O,Y,X,K,q]),oe=gr(!1);Er((()=>{if(!oe.current&&g&&b&&b>0&&!P){oe.current=!0;const e=setTimeout((()=>{Q(!0)}),1e3*b);return ae.current=e,()=>{ae.current&&clearTimeout(ae.current)}}}),[g,b,P,Q]),ur((()=>{l&&x.current&&(x.current.scrollTop=x.current.scrollHeight)}),[p,l,x,F]);const ie=t("mwai-input",{"mwai-active":!F}),[se,ce]=dr(!1),[de,me]=dr(null),ue="undefined"==typeof window||window.matchMedia("(min-width: 761px)").matches,pe=pr((e=>{if(!g||!P||h&&!M||!ue||n)return;const t=e.target;if(t.closest&&(t.closest(".mwai-close-button")||t.closest(".mwai-resize-button")||t.closest("button")))return;const a=document.getElementById(`mwai-chatbot-${u||m}`);if(!a)return;const l=a.getBoundingClientRect(),r=e.clientX,o=e.clientY,i=l.top,s=l.left;ce(!0),me({top:i,left:s});const c=document.body.style.cursor;document.body.style.cursor="move";const d=e=>{const t=i+(e.clientY-o),a=s+(e.clientX-r);me({top:t,left:a})},p=()=>{ce(!1),document.body.style.cursor=c||"",document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",p)};document.addEventListener("mousemove",d),document.addEventListener("mouseup",p)}),[g,P,h,M,ue,u,m,n]),Ee=mr((()=>de?{top:`${Math.max(0,de.top)}px`,left:`${Math.max(0,de.left)}px`,right:"auto",bottom:"auto",transform:"none"}:{}),[de]);Er((()=>{P||D||!de||me(null)}),[P,D,de]);const ge=mr((()=>({...a,...k,maxWidth:h?null:v,maxHeight:h?null:"calc(100% - 20px)",...de?Ee:{}})),[a,k,h,v,de,Ee]),he=new Set(["zoom","slide","fade"]),Re=w&&he.has(w)?w:"none",ye=t("mwai-chat",{[`mwai-${R}`]:g,"mwai-window":g,"mwai-center-open":g&&y,"mwai-bubble":(!0===f||1===f||"1"===f||"true"===f)&&g,"mwai-open":P||!g&&h,"mwai-opening":L,"mwai-closing":D,"mwai-top-left":"top-left"===R,"mwai-top-right":"top-right"===R,"mwai-fullscreen":h&&!M,"mwai-bottom-left":"bottom-left"===R,"mwai-bottom-right":"bottom-right"===R,[`mwai-animation-${Re}`]:g&&Re&&"none"!==Re}),ve=t(ye,{"mwai-dragging":I,"mwai-blocked":S,"mwai-window-dragging":se,[`mwai-${null==d?void 0:d.themeId}-theme`]:!0,[`mwai-container-${B}`]:B&&"standard"!==B}),be=mr((()=>{if(!_||0===_.length)return null;const e=e=>e&&(e.startsWith("http://")||e.startsWith("https://")),a=e=>{if(!e)return!1;return/^[\u{1F300}-\u{1F9FF}\u{1F600}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F1E6}-\u{1F1FF}\u{1F191}-\u{1F251}\u{1F004}\u{1F0CF}\u{1F170}-\u{1F171}\u{1F17E}-\u{1F17F}\u{1F18E}\u{3030}\u{2B50}\u{2B55}\u{2934}-\u{2935}\u{2B05}-\u{2B07}\u{2B1B}-\u{2B1C}\u{3297}\u{3299}\u{303D}\u{00A9}\u{00AE}\u{2122}\u{23F3}\u{24C2}\u{23E9}-\u{23EF}\u{25AA}-\u{25AB}\u{25B6}\u{25C0}\u{25FB}-\u{25FE}\u{00A9}\u{00AE}\u{2122}\u{2139}\u{23E9}-\u{23F3}\u{24C2}\u{23F8}-\u{23FA}\u{231A}-\u{231B}\u{2328}\u{23CF}\u{2388}\u{23E9}-\u{23F0}\u{23F3}\u{23F8}-\u{23FA}]+$/u.test(e)};return React.createElement("div",{className:"mwai-shortcuts"},_.map(((n,l)=>{const{type:r,data:o}=n,{label:i,variant:s,icon:d,className:m}=o??{};let u=t("mwai-shortcut",{"mwai-success":"success"===s,"mwai-danger":"danger"===s,"mwai-warning":"warning"===s,"mwai-info":"info"===s});switch(m&&(u+=` ${m}`),r){case"action":{const{action:t,message:n}=o??{},r=()=>{"clear"===t?c.onClear():"message"===t&&n?V(n):console.warn(`This action is not supported: ${t}.`)};return React.createElement("button",{className:u,key:l,onClick:r},(e(d)||a(d))&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},e(d)&&React.createElement("img",{src:d,alt:i||"AI Shortcut"}),a(d)&&React.createElement("span",{role:"img","aria-label":"AI Shortcut"},d)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-label"},i||"N/A"))}case"callback":{const{onClick:t}=o,n=()=>{if("function"==typeof t)t();else if("string"==typeof t){const e=t.replace(/actions\.([\w]+)/g,"actions.$1").replace(/state\.([\w]+)/g,"state.$1"),a=new Function(`return (${e});`)();o.onClick=a,a()}else console.warn("No valid callback function provided in data.onClick.")};return React.createElement("button",{className:u,key:l,onClick:n},(e(d)||a(d))&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},e(d)&&React.createElement("img",{src:d,alt:i||"AI Shortcut"}),a(d)&&React.createElement("span",{role:"img","aria-label":"AI Shortcut"},d)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-label"},i||"N/A"))}case"message":{const{message:t}=o??{},n=()=>{t?V(t):console.warn("No message provided for message shortcut.")};return React.createElement("button",{className:u,key:l,onClick:n},(e(d)||a(d))&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},e(d)&&React.createElement("img",{src:d,alt:i||"AI Shortcut"}),a(d)&&React.createElement("span",{role:"img","aria-label":"AI Shortcut"},d)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-label"},i||"N/A"))}default:return console.warn(`This shortcut type is not supported: ${r}.`),null}})))}),[_,c,t,V]);Er((()=>{C&&C.length>0&&C.forEach((e=>{var t;if("content"===e.type&&null!==(t=e.data)&&void 0!==t&&t.script)try{const t=document.createElement("script");t.textContent=e.data.script,document.body.appendChild(t),setTimeout((()=>{t.parentNode&&t.parentNode.removeChild(t)}),0)}catch(e){console.error("Error executing block script:",e)}}))}),[C]);const fe=mr((()=>C&&0!==C.length?React.createElement("div",{className:"mwai-blocks"},C.map(((e,t)=>{const{type:a,data:n}=e,{html:l}=n??{};return"content"===a?React.createElement("div",{key:t,dangerouslySetInnerHTML:{__html:l}}):(console.warn(`This block type is not supported: ${a}.`),null)}))):null),[C]);return React.createElement(Xa.bE,{dir:"auto",id:`mwai-chatbot-${u||m}`,className:ve,style:ge,if:!0,disableTransition:!g},Z&&React.createElement("style",null,Z),g&&Re&&"none"!==Re&&React.createElement("style",null,`\n @media (max-width: 760px) {\n .mwai-chat.mwai-window.mwai-animation-${Re} .mwai-header {\n display: none !important;\n }\n /* Also hide during opening state */\n .mwai-chat.mwai-window.mwai-animation-${Re}.mwai-opening .mwai-header {\n display: none !important;\n }\n }\n `),"osx"===B&&React.createElement("style",null,"\n /* MacOS Container Styles - apply to window-box for proper animation */\n .mwai-chat.mwai-container-osx .mwai-window-box {\n border-radius: 10px !important;\n box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4) !important;\n overflow: hidden !important;\n border: 1px solid var(--mwai-borderColor) !important;\n }\n \n /* Remove container-level styles to prevent border remnants */\n .mwai-chat.mwai-container-osx {\n border: none !important;\n box-shadow: none !important;\n background: transparent !important;\n }\n\n /* Fix visibility when minimized */\n .mwai-chat.mwai-window:not(.mwai-open) {\n display: flex !important;\n }\n .mwai-chat.mwai-window:not(.mwai-open) .mwai-header,\n .mwai-chat.mwai-window:not(.mwai-open) .mwai-body {\n display: none !important;\n }\n\n /* Timeless: keep overflow contained in window-box */\n .mwai-timeless-theme.mwai-chat.mwai-container-osx .mwai-window-box { overflow: hidden !important; }\n .mwai-timeless-theme.mwai-chat.mwai-container-osx.mwai-open:not(.mwai-fullscreen) .mwai-input-submit { position: relative !important; z-index: 2 !important; }\n "),"osx"===H&&React.createElement("style",null,'\n /* MacOS Header Styles */\n .mwai-chat .mwai-header.mwai-header-osx {\n display: flex !important; flex-direction: column !important; align-items: stretch !important; justify-content: flex-start !important;\n padding: 0 !important;\n background: var(--mwai-backgroundHeaderColor) !important;\n border-radius: 10px 10px 0 0 !important; position: relative !important;\n }\n\n /* Hide header and body when minimized (standard container + macOS header) */\n .mwai-chat.mwai-window:not(.mwai-open) { display: flex !important; }\n .mwai-chat.mwai-window:not(.mwai-open) .mwai-header,\n .mwai-chat.mwai-window:not(.mwai-open) .mwai-body { display: none !important; }\n\n /* Top bar: traffic lights with centered title */\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-bar {\n display: flex !important; align-items: center !important; justify-content: flex-start !important;\n position: relative !important; padding: 8px 12px !important;\n background: #0000001c;\n }\n\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-controls { display: flex !important; align-items: center !important; gap: 8px !important; z-index: 1 !important; }\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-controls button {\n all: unset !important; display: flex !important; justify-content: center !important; align-items: center !important;\n width: 14px !important; height: 14px !important; min-width: 14px !important; min-height: 14px !important; border-radius: 50% !important;\n position: relative !important; cursor: pointer !important; border: none !important; padding: 0 !important; margin: 0 !important; box-shadow: none !important; transition: opacity 0.2s !important;\n }\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-controls button:hover { background-color: initial !important; }\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-controls button.mwai-osx-close { background-color: #ec6a5e !important; }\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-controls button.mwai-osx-minimize { background-color: #f4be4f !important; }\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-controls button.mwai-osx-maximize { background-color: #61c554 !important; }\n\n /* Icons inside buttons */\n .mwai-chat .mwai-header.mwai-header-osx .mwai-lucide-icon { width: 9px !important; height: 9px !important; stroke: rgba(0,0,0,0.5) !important; stroke-width: 2.5 !important; opacity: 0 !important; transition: none !important; }\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-controls:hover .mwai-lucide-icon { opacity: 1 !important; }\n\n /* Centered title, like macOS */\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-bar .mwai-osx-title {\n position: absolute !important;\n left: 50% !important;\n top: 50% !important;\n transform: translate(-50%, -50%) !important;\n margin: 0 !important; padding: 0 !important; text-align: center !important;\n white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important;\n max-width: calc(100% - 160px) !important; z-index: 0 !important; font-weight: 500 !important;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif !important;\n font-size: 13px !important;\n color: var(--mwai-headerColor) !important;\n }\n\n /* Optional merged content area for Timeless */\n .mwai-chat .mwai-header.mwai-header-osx .mwai-osx-content { padding: var(--mwai-spacing) !important; display: flex !important; align-items: center !important; }\n\n /* Timeless: let header height be dynamic under macOS */\n .mwai-timeless-theme.mwai-window .mwai-header.mwai-header-osx { height: auto !important; }\n\n /* ChatGPT dark adjustments */\n .mwai-chatgpt-theme .mwai-header.mwai-header-osx .mwai-osx-title { color: #d1d1d1 !important; }\n .mwai-chatgpt-theme .mwai-header.mwai-header-osx .mwai-lucide-icon { stroke: rgba(77,77,77,0.8) !important; }\n\n /* Hide standard buttons for MacOS header */\n .mwai-chat .mwai-header.mwai-header-osx .mwai-buttons { display: none !important; }\n\n /* Indicate draggable header on macOS style only when open and not transitioning */\n .mwai-chat.mwai-window.mwai-open:not(.mwai-opening):not(.mwai-closing) .mwai-header.mwai-header-osx .mwai-osx-bar { cursor: move; }\n '),React.createElement("style",null,"\n .mwai-chat.mwai-window.mwai-open:not(.mwai-opening):not(.mwai-closing) .mwai-header:not(.mwai-header-osx) {\n cursor: move;\n }\n "),React.createElement(sl,null),React.createElement("div",{className:"mwai-window-box"},o&&g&&P&&React.createElement("div",{className:"mwai-mobile-header"},React.createElement("div",{className:"mwai-mobile-header-title"},W||z||"AI Engine"),React.createElement("button",{className:"mwai-mobile-header-close",onClick:()=>{!D&&P&&(w&&"none"!==w?(J(!0),setTimeout((()=>{Q(!1),setTimeout((()=>{J(!1)}),150)}),180)):Q(!1))},"aria-label":"Close chatbot",type:"button"},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none"},React.createElement("path",{d:"M18 6L6 18M6 6l12 12",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})))),!(o&&g&&P)&&React.createElement(rl,{onDragStart:pe}),React.createElement(cr,{conversationRef:x,onScroll:()=>{if(x.current){const{scrollTop:e,scrollHeight:t,clientHeight:a}=x.current;r(t-e<=a+1)}},jsxShortcuts:be,jsxBlocks:fe,inputClassNames:ie,handleDrop:re,handleDrag:le,needsFooter:te,needTools:ee,uploadIconPosition:U})))},vr=e=>React.createElement(Ya.G,e,React.createElement(yr,e)),{useMemo:br,useState:fr,useEffect:wr}=wp.element,_r=e=>{e?localStorage.setItem("mwai-admin-chatbotKey",e):localStorage.removeItem("mwai-admin-chatbotKey")},Cr=e=>{const t=(0,l.jE)(),{options:a,updateOption:n,busy:i}=e,[s,c]=fr("chatbots"),[d,m]=fr(!1),[u,p]=fr((()=>localStorage.getItem("mwai-admin-chatbotKey")||"chatbot-key-0")),R=null==a?void 0:a.chatbot_defaults,{colors:y}=(0,r.z)(),{data:b}=(0,o.I)({queryKey:["chatbots"],queryFn:qe,initialData:v.N6}),{data:f}=(0,o.I)({queryKey:["themes"],queryFn:ze,initialData:v.Zj}),w=(null==a?void 0:a.botId)??"none",_=(null==a?void 0:a.chatbot_select)??"tabs",C=i||d,[T,A]=fr({});wr((()=>{if(b){const e={};if(b.forEach(((t,a)=>{e[`chatbot-key-${a}`]=t.botId})),A(e),!u||!(u in e)){const t=Object.keys(e)[0];p(t),_r(t)}}}),[b,u]);const N=br((()=>{if(b){return b.find((e=>"default"===e.botId))}}),[b]),O=br((()=>{if(b&&u&&T[u]){const e=T[u];return b.find((t=>t.botId===e))}return null}),[b,u,T]),I=br((()=>{let e=null;var t;if((f&&O&&(e=f.find((e=>e.themeId===(null==O?void 0:O.themeId)))),e||(e=f.find((e=>"chatgpt"===e.themeId))),e)&&(e={...e},delete e.customCSS,null!==(t=e.settings)&&void 0!==t&&t.customCSS&&""!==e.settings.customCSS.trim())){let t=e.settings.customCSS;const a=`.mwai-${e.themeId}-theme`,n=t.split("\n");let l="";for(const e of n){const t=e.trim();if(t&&!t.startsWith("/*"))if(e.includes("{")&&!e.includes("}")){const t=e.split("{");let n=t[0].trim();if(!n.startsWith(a)){const e=n.split(",").map((e=>(e=e.trim()).startsWith("@")||"from"===e||"to"===e||/^\d+%/.test(e)?e:a+" "+e));n=e.join(", ")}l+=n+" {"+(t[1]||"")+"\n"}else l+=e+"\n";else l+=e+"\n"}t=l,"css"===e.type?e.style=(e.style||"")+"\n\n/* Custom CSS */\n"+t:e.customCSS=t}return e}),[O,f]),S=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&&b.find((t=>t.botId===e)))return void alert("This chatbot ID is already in use. Please choose another ID.");m(!0);const n={...O,[a]:e};let l=[...b];if(O){const r=l.findIndex((e=>e.botId===O.botId));-1!==r&&(l[r]=n,l=await Ke(l),t.setQueryData(["chatbots"],l),"botId"===a&&A((t=>({...t,[u]:e}))))}m(!1)},M=async(e=R)=>{m(!0);const a="chatbot-"+pe(),n={...e,botId:a,name:"New Chatbot"};delete n.functions;const l=await Ke([...b,n]);t.setQueryData(["chatbots"],l);const r=`chatbot-key-${Object.keys(T).length}`;A((e=>({...e,[r]:a}))),p(r),_r(r),m(!1)},k=async()=>{m(!0);const e=T[u],a=Object.keys(T),n=a.indexOf(u);let l;l=n>0?a[n-1]:a.length>1?a[n+1]:null,p(l),_r(l);let r=b.filter((t=>t.botId!==e));r=await Ke(r),t.setQueryData(["chatbots"],r);const o={...T};delete o[u],A(o),m(!1)},x=async()=>{m(!0);let e=[...b];const a=e.findIndex((e=>e.botId===O.botId));e[a]={...R,botId:O.botId,name:O.name},e=await Ke(e),t.setQueryData(["chatbots"],e),m(!1)},P=async()=>{M(O)};return React.createElement(React.Fragment,null,React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,fullWidth:!0,style:{margin:10}},React.createElement(Le.V,null,React.createElement(wa,{currentChatbot:O}),React.createElement("label",{style:{marginLeft:5}},J.A.COMMON.CHATBOTS),React.createElement(De.S,{style:{marginLeft:5},disabled:C,onLabel:"",offLabel:"",width:42,offValue:"chatbots",onValue:"themes",offBackgroundColor:y.blue,onBackgroundColor:y.purple,checked:"themes"===s,onChange:c}),React.createElement("label",{style:{marginLeft:5}},J.A.COMMON.THEMES),React.createElement("div",{style:{flex:"auto"}}),React.createElement("label",null,J.A.COMMON.SITE_WIDE_CHATBOT,":"),React.createElement(j.u,{scrolldown:!0,name:"botId",disabled:C,style:{minWidth:160},value:w,onChange:n},React.createElement(j.j,{value:"none",label:"None"}),null==b?void 0:b.map((e=>React.createElement(j.j,{key:e.botId,value:e.botId,label:e.name})))))),React.createElement(E.Y,{minimal:!0,style:{margin:10,maxWidth:"50%"}},"chatbots"===s&&React.createElement(React.Fragment,null,"dropdown"===_&&React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",alignItems:"center",marginBottom:10}},React.createElement(j.u,{scrolldown:!0,textFiltering:!0,name:"botId",disabled:C,style:{flex:"auto",marginRight:10},value:u,onChange:p},null==b?void 0:b.map(((e,t)=>React.createElement(j.j,{key:e.botId,value:`chatbot-key-${t}`,label:e.name})))),React.createElement(h.M,{rounded:!0,small:!0,className:"success",icon:"plus",disabled:C,onClick:()=>M()})),O&&React.createElement(W.L,{style:{borderRadius:10}},React.createElement(xa,{style:{margin:"-10px -10px"},options:a,themes:f,defaultChatbot:N,deleteCurrentChatbot:k,resetCurrentChatbot:x,duplicateCurrentChatbot:P,shortcodeParams:O,updateShortcodeParams:S}))),"tabs"===_&&React.createElement(React.Fragment,null,React.createElement(g._,{inversed:!0,onChange:(e,t)=>{p(t.key),_r(t.key)},currentTab:u,action:React.createElement(h.M,{rounded:!0,small:!0,className:"success",icon:"plus",disabled:C,onClick:()=>M()})},Object.entries(T).map((([e,t])=>{const n=b.find((e=>e.botId===t));return React.createElement(g.V,{key:e,title:n.name,busy:d},React.createElement(xa,{options:a,themes:f,defaultChatbot:N,deleteCurrentChatbot:k,resetCurrentChatbot:x,duplicateCurrentChatbot:P,shortcodeParams:n,updateShortcodeParams:S}))}))))),"themes"===s&&React.createElement(Ka,{themes:f,options:a,updateOption:n,currentTheme:I,onSwitchTheme:e=>{S(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==O?void 0:O.name)," - Theme: ",React.createElement("b",null,null==I?void 0:I.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%)"}},!!O&&React.createElement(vr,{system:{botId:O.botId,userData:v.sw,sessionId:v.dZ,restNonce:v.ok,pluginUrl:v.Hm,restUrl:v.gh,stream:v.Td,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:O,theme:I,isAdminPreview:!0,style:O.window||O.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 Tr=a(421);const{useMemo:Ar,useState:Nr,useEffect:Or}=wp.element,Ir=[{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"}],Sr=async(e=[])=>await(0,y.IU)(`${v.y0}/system/logs/delete`,{nonce:v.ok,method:"POST",json:{logIds:e}}),Mr=({selectedLogIds:e,setSelectedLogIds:t,onDataFetched:a,isSidebarCollapsed:n,onToggleSidebar:r})=>{const i=(0,l.jE)(),[s,c]=Nr(!1),{getModelName:d}=ie(v.fF,null,!0),[m,u]=Nr((()=>Ir.filter((e=>e.filters)).map((e=>({accessor:e.accessor,value:[]}))))),[p,E]=Nr({filters:m,sort:{accessor:"time",by:"desc"},page:1,limit:20}),{isFetching:g,data:b,error:f}=(0,o.I)({queryKey:["logs",JSON.stringify(p)],queryFn:()=>(async e=>{const t={...e,offset:(e.page-1)*e.limit},a=await(0,y.IU)(`${v.y0}/system/logs/list`,{nonce:v.ok,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:[]}})(p)});Or((()=>{E({...p,filters:m})}),[m]),Or((()=>{null!=b&&b.logs&&a&&a(b.logs)}),[null==b?void 0:b.logs,a]);const w=Ar((()=>(null==b?void 0:b.total)||0),[b]),_=Ar((()=>null!=b&&b.logs?b.logs.sort(((e,t)=>t.created_at-e.created_at)).map((e=>{var t;const a=me(e.time),n=ue(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===v.fF||void 0===v.fF||null===(t=v.fF.ai_envs)||void 0===t||null===(t=t.find((t=>t.id===e.envId)))||void 0===t?void 0:t.name)||e.envId,c=React.createElement("div",null,React.createElement("span",{title:e.model},d(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:c,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}})):[]),[b]),C=async()=>{if(c(!0),e.length)await Sr(e),t([]);else{if(!window.confirm(J.A.ALERTS.ARE_YOU_SURE))return void c(!1);await Sr()}await i.invalidateQueries({queryKey:["logs"]}),c(!1)},T=Ar((()=>null!=f&&f.message?React.createElement(q.X,{variant:"danger",style:{margin:"5px 5px"}},React.createElement("b",null,f.message),React.createElement("br",null),React.createElement("small",null,"Check your Console Logs and PHP Error Logs for more information.")):null),[f]);return React.createElement(React.Fragment,null,React.createElement(R.z,{className:"primary",title:J.A.COMMON.QUERY_LOGS,action:React.createElement("div",{style:{display:"flex",alignItems:"center",gap:5}},React.createElement(h.M,{className:"secondary",disabled:g,onClick:async()=>{try{await i.invalidateQueries({queryKey:["logs"]})}catch(e){}}},J.A.COMMON.REFRESH),e.length>0&&React.createElement(h.M,{className:"danger",onClick:C},J.A.COMMON.DELETE),React.createElement(Rt.A,{isCollapsed:n,onClick:r,border:"left",direction:"right"}))},React.createElement(Pe.o,{busy:g||s,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:p.sort,onSortChange:(e,t)=>{E({...p,sort:{accessor:e,by:t}})},emptyMessage:T,filters:m,onFilterChange:(e,t)=>{const a=[...m.filter((t=>t.accessor!==e)),{accessor:e,value:t}];u(a)},data:f?[]:_,columns:Ir}),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginTop:10,marginBottom:-5}},React.createElement(h.M,{className:"danger",disabled:e.length>0,onClick:C},J.A.COMMON.DELETE_ALL),React.createElement("div",{style:{flex:"auto"}}),React.createElement(Be.Q,{currentPage:p.page,limit:p.limit,onCurrentPageChanged:e=>E({...p,page:e}),total:w,onClick:e=>E({...p,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:kr,useState:xr,useEffect:Pr}=wp.element;jt.t1.register(jt.PP,jt.kc,jt.E8,jt.m_,jt.s$);const Lr=()=>{const e=localStorage.getItem("mwai-admin-insights");try{const t=JSON.parse(e);return{isSidebarCollapsed:(null==t?void 0:t.isSidebarCollapsed)||!1}}catch(e){return{isSidebarCollapsed:!1}}},Dr=({options:e,updateOption:t,busy:a})=>{var n;const[l,i]=xr([]),[s,c]=xr([]),[d,u]=xr((()=>Lr().isSidebarCollapsed)),[p,E]=xr("users"),b=null==e?void 0:e.limits,f=null==e?void 0:e.default_limits;Pr((()=>{(({isSidebarCollapsed:e})=>{const t=Lr(),a={isSidebarCollapsed:void 0!==e?e:t.isSidebarCollapsed};localStorage.setItem("mwai-admin-insights",(0,y.F1)(a))})({isSidebarCollapsed:d})}),[d]);const w=kr((()=>1===s.length?s[0]:null),[s]),_=kr((()=>{const e=l.find((e=>e.id===w));if(e&&e.stats&&"string"==typeof e.stats)try{e.stats=JSON.parse(e.stats)}catch(t){e.stats={}}return e}),[l,w]),{isFetching:C,data:T}=(0,o.I)({queryKey:["logsMeta",w],queryFn:()=>(async e=>e?(await(0,y.IU)(`${v.y0}/system/logs/meta`,{nonce:v.ok,method:"POST",json:{logId:e,metaKeys:["query","reply","fields"]}})).data:null)(w),enabled:!!w,staleTime:864e5}),{colors:A}=(0,r.z)(),{models:N,getModel:O}=ie(e,null,!0),{data:I}=(0,o.I)({queryKey:["logsActivityDailyByModel"],queryFn:()=>(async(e=31,t=!1)=>{const a=await le(`${v.y0}/system/logs/activity_daily`,{nonce:(0,v.c3)(),method:"POST",json:{days:e,byModel:t}});return null!=a&&a.data?a.data:[]})(31,!0),staleTime:36e5}),S=kr((()=>{if(!I||0===I.length)return null;const e=I.map(((e,t)=>{const a=new Date;return a.setDate(a.getDate()-(I.length-1-t)),a.toLocaleDateString("en-US",{month:"short",day:"numeric"})}));if(!N||0===N.length){return{labels:e,datasets:[{label:"Queries",data:I.map((e=>Object.values(e).reduce(((e,t)=>e+t),0))),backgroundColor:A.blue}]}}const t={},a=new Set;I.forEach((e=>{Object.keys(e).forEach((e=>{if(!t[e]){const n=O(e),l=(null==n?void 0:n.family)||"Unknown";t[e]=l,a.add(l)}}))}));const n=[A.blue,A.green,A.yellow,A.orange,A.red,A.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=I.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]}}))}}),[I,A,N,O]),M=kr((()=>null!=b&&b[p]?b[p]:{credits:1,creditType:"price",timeFrame:"month",isAbsolute:!1,overLimitMessage:"You have reached the limit.",ignoredUsers:""}),[b,p]),k=async(e,a)=>{"credits"===a&&(e=Math.max(0,e));const n={...M,[a]:e},l={...b,[p]:n};await t(l,"limits")},x=kr((()=>Array.isArray(T)?null:T),[T]);return React.createElement(React.Fragment,null,React.createElement(ht.J,{mainFlex:2.5,sidebarFlex:1,minimal:!0,isCollapsed:d,onToggle:()=>u(!d),showToggle:!1},React.createElement(ht.J.Main,null,React.createElement(Mr,{selectedLogIds:s,setSelectedLogIds:c,onDataFetched:i,isSidebarCollapsed:d,onToggleSidebar:()=>u(!d)})),React.createElement(ht.J.Sidebar,null,w&&React.createElement(React.Fragment,null,React.createElement($.g,{large:!0}),React.createElement(g._,{inversed:!0,style:{marginRight:10,marginLeft:10}},React.createElement(g.V,{title:J.A.COMMON.QUERY},React.createElement("div",{style:{height:380,overflow:"auto",maxHeight:380}},C&&React.createElement("i",{style:{color:"gray"}},"Loading..."),!C&&!x&&React.createElement("i",{style:{color:"gray"}},J.A.COMMON.DATA_NOT_AVAILABLE),!C&&x&&React.createElement(Tr.p2,{value:x.query,rootName:"query",indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}))),React.createElement(g.V,{title:J.A.COMMON.REPLY},React.createElement("div",{style:{height:380,overflow:"auto",maxHeight:380}},C&&React.createElement("i",{style:{color:"gray"}},"Loading..."),!C&&!x&&React.createElement("i",{style:{color:"gray"}},J.A.COMMON.DATA_NOT_AVAILABLE),!C&&x&&React.createElement(Tr.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}},C&&React.createElement("i",{style:{color:"gray"}},"Loading..."),!C&&!x&&React.createElement("i",{style:{color:"gray"}},J.A.COMMON.DATA_NOT_AVAILABLE),!C&&x&&React.createElement(Tr.p2,{value:x.fields,rootName:"fields",indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}))),(null==_?void 0:_.stats)&&React.createElement(g.V,{title:"Stats"},React.createElement("div",{style:{height:380,overflow:"auto",maxHeight:380}},React.createElement(Tr.p2,{value:_.stats,rootName:"stats",indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}))))),S&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(R.z,{className:"primary",title:J.A.COMMON.ACTIVITY,style:{flex:1}},React.createElement("div",null,React.createElement(Gt.yP,{options:{responsive:!0,plugins:{legend:{display:!1}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:S})))),React.createElement(ga,{style:{marginTop:-25}},React.createElement(R.z,{className:"primary",busy:a,title:J.A.COMMON.LIMITS,style:{flex:1}},React.createElement(m.R,{name:"enabled",label:J.A.STATISTICS.ENABLE_LIMITS,checked:null==b?void 0:b.enabled,value:"1",onChange:async(e,a)=>{const n={...b,[a]:e};await t(n,"limits")}}),(null==b?void 0:b.enabled)&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(z.o,{value:p,busy:a,onChange:e=>E(e)},React.createElement(z.K,{title:J.A.COMMON.USERS,value:"users",disabled:!(null!=b&&b.enabled)}),React.createElement(z.K,{title:J.A.COMMON.GUESTS,value:"guests"}),React.createElement(z.K,{title:J.A.COMMON.SYSTEM,value:"system"})),"userId"===(null==b?void 0:b.target)&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,"Message for Guests:"),React.createElement(G.A,{id:"guestMessage",name:"guestMessage",disabled:!(null!=b&&b.enabled),value:null==b?void 0:b.guestMessage,onEnter:k,onBlur:k}))),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.CREDITS,":"),React.createElement(G.A,{id:"credits",name:"credits",type:"number",min:"0",max:"1000000",disabled:!(null!=b&&b.enabled),value:M.credits,onEnter:k,onBlur:k})),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.TYPE,":"),React.createElement(j.u,{scrolldown:!0,id:"creditType",name:"creditType",disabled:!(null!=b&&b.enabled),value:M.creditType,onChange:k},React.createElement(j.j,{key:"queries",id:"queries",value:"queries",label:"Queries"}),React.createElement(j.j,{key:"units",id:"units",value:"units",label:"Tokens"}),React.createElement(j.j,{key:"price",id:"price",value:"price",label:"Dollars"})))),0!==M.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!==M.credits&&"price"===M.creditType&&React.createElement("p",null,"The dollars represent the budget you spent through OpenAI."),0===M.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,J.A.COMMON.TIMEFRAME,":"),React.createElement(j.u,{scrolldown:!0,id:"timeFrame",name:"timeFrame",disabled:!(null!=b&&b.enabled),value:M.timeFrame,onChange:k},React.createElement(j.j,{key:"second",id:"second",value:"second",label:"Second"}),React.createElement(j.j,{key:"minute",id:"minute",value:"minute",label:"Minute"}),React.createElement(j.j,{key:"hour",id:"hour",value:"hour",label:"Hour"}),React.createElement(j.j,{key:"day",id:"day",value:"day",label:"Day"}),React.createElement(j.j,{key:"week",id:"week",value:"week",label:"Week"}),React.createElement(j.j,{key:"month",id:"month",value:"month",label:"Month"}),React.createElement(j.j,{key:"year",id:"year",value:"year",label:"Year"}))),React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.COMMON.ABSOLUTE,":"),React.createElement(m.R,{name:"isAbsolute",label:"Yes",disabled:!(null!=b&&b.enabled),checked:M.isAbsolute,value:"1",onChange:k}))),M.isAbsolute&&React.createElement("p",null,(0,y.FE)(J.A.STATISTICS.ABSOLUTE_HELP)),React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.STATISTICS.NO_CREDITS_MESSAGE,":"),React.createElement(G.A,{id:"overLimitMessage",name:"overLimitMessage",disabled:!(null!=b&&b.enabled),value:M.overLimitMessage,onEnter:k,onBlur:k}))),"users"===p&&React.createElement("div",{className:"mwai-builder-row"},React.createElement("div",{className:"mwai-builder-col"},React.createElement("label",null,J.A.STATISTICS.FULL_ACCESS_USERS,":"),React.createElement(j.u,{scrolldown:!0,id:"ignoredUsers",name:"ignoredUsers",disabled:!(null!=b&&b.enabled),value:null==b||null===(n=b.users)||void 0===n?void 0:n.ignoredUsers,description:"",onChange:k},React.createElement(j.j,{key:"none",id:"none",value:"",label:J.A.COMMON.NONE}),React.createElement(j.j,{key:"editor",id:"editor",value:"administrator,editor",label:J.A.COMMON.EDITORS_ADMINS}),React.createElement(j.j,{key:"admin",id:"admin",value:"administrator",label:J.A.COMMON.ADMINS_ONLY})))),React.createElement($.g,null),React.createElement(h.M,{fullWidth:!0,className:"danger",onClick:async()=>{confirm(J.A.ALERTS.ARE_YOU_SURE)&&await t(f,"limits")}},J.A.COMMON.RESET_LIMITS)))))))};var Fr=a(7392);const Ur=({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,s=null==e?void 0:e.queries_debug_mode,d=null==e?void 0:e.dev_mode,u=React.createElement(c.d,{title:J.A.COMMON.DEV_MODE},React.createElement(m.R,{name:"dev_mode",label:J.A.COMMON.ENABLE,value:"1",checked:d,description:J.A.COMMON.DEV_MODE_HELP,onChange:t})),p=React.createElement(c.d,{title:J.A.COMMON.CLIENT_DEBUG},React.createElement(m.R,{name:"debug_mode",label:J.A.COMMON.ENABLE,value:"1",checked:l,description:J.A.COMMON.CLIENT_DEBUG_HELP,onChange:t})),g=React.createElement(c.d,{title:J.A.COMMON.SERVER_DEBUG},React.createElement(m.R,{name:"server_debug_mode",label:J.A.COMMON.ENABLE,value:"1",checked:o,description:J.A.COMMON.SERVER_DEBUG_HELP,onChange:t})),b=r?React.createElement(c.d,{title:J.A.COMMON.MCP_DEBUG},React.createElement(m.R,{name:"mcp_debug_mode",label:J.A.COMMON.ENABLE,value:"1",checked:i,description:J.A.COMMON.MCP_DEBUG_HELP,onChange:t})):null,f=React.createElement(c.d,{title:J.A.COMMON.QUERIES_DEBUG},React.createElement(m.R,{name:"queries_debug_mode",label:J.A.COMMON.ENABLE,value:"1",checked:s,description:J.A.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 le(`${v.y0}/helpers/post_content?postType=${e}&postStatus=${n}&offset=${t}&postId=${a}`,{nonce:(0,v.c3)()}))(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 le(`${v.y0}/helpers/run_tasks`,{nonce:(0,v.c3)(),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"),b,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 Ge(`${v.y0}/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(Fr.k,{refreshQuery:Xe,clearQuery:Qe,i18n:J.A}))))},{useMemo:Br,useState:Hr}=wp.element,jr=({env:e,updateEnvironment:t,deleteEnvironment:a,ai_envs:n,options:l})=>{const{embeddingsModels:r}=ie(l,null==e?void 0:e.ai_embeddings_env),[o,i]=Hr(!1),[s,d]=Hr(null),u=Br((()=>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=Br((()=>r.find((t=>t.model===e.ai_embeddings_model))),[r,e.ai_embeddings_model]),E=Br((()=>{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=Br((()=>!!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):!("chroma"!==e.type||!e.chroma_dimensions)&&parseInt(e.chroma_dimensions)!==parseInt(e.ai_embeddings_dimensions))),[e.pinecone_dimensions,e.qdrant_dimensions,e.chroma_dimensions,e.ai_embeddings_dimensions,e.type]);return React.createElement(React.Fragment,null,React.createElement(c.d,{title:J.A.COMMON.NAME},React.createElement(G.A,{name:"name",value:e.name,onFinalChange:a=>t(e.id,{name:a})})),React.createElement(c.d,{title:J.A.COMMON.TYPE},React.createElement(j.u,{scrolldown:!0,name:"type",value:e.type,description:"qdrant"===e.type?be(J.A.HELP.QDRANT,J.A.HELP.QDRANT_URL,J.A.HELP.QDRANT_LINK_TEXT):null,onChange:a=>t(e.id,{type:a})},React.createElement(j.j,{value:"pinecone",label:"Pinecone"}),React.createElement(j.j,{value:"qdrant",label:"Qdrant"}),React.createElement(j.j,{value:"openai-vector-store",label:"OpenAI Vector Store"}),React.createElement(j.j,{value:"chroma",label:"Chroma"}))),"openai-vector-store"!==e.type&&React.createElement(c.d,{title:J.A.COMMON.API_KEY},React.createElement(G.A,{name:"apikey",value:e.apikey,placeholder:"chroma"===e.type?"Your API key":"",description:(0,y.FE)("chroma"===e.type?"Your Chroma API key. For Chroma Cloud, find this in your <a href='https://www.trychroma.com' target='_blank' rel='noopener noreferrer'>Chroma Cloud dashboard</a>. For self-hosted instances, leave empty unless authentication is configured.":"pinecone"===e.type?J.A.COMMON.PINECONE_APIKEY_HELP:J.A.COMMON.QDRANT_APIKEY_HELP),onFinalChange:a=>t(e.id,{apikey:a})})),"openai-vector-store"!==e.type&&React.createElement(c.d,{title:J.A.COMMON.SERVER},React.createElement(G.A,{name:"server",value:e.server,placeholder:"chroma"===e.type?"https://api.trychroma.com":"",description:(0,y.FE)("chroma"===e.type?"Your Chroma server URL. For self-hosted instances, enter the full URL (e.g., http://localhost:8000). Leave empty to use Chroma Cloud (defaults to https://api.trychroma.com).":"qdrant"===e.type?J.A.COMMON.QDRANT_SERVER_HELP:J.A.COMMON.PINECONE_SERVER_HELP),onFinalChange:a=>t(e.id,{server:a})})),"pinecone"===e.type&&React.createElement(React.Fragment,null,React.createElement(c.d,{title:J.A.COMMON.NAMESPACE},React.createElement(G.A,{name:"namespace",value:e.namespace,description:(0,y.FE)(J.A.COMMON.PINECONE_NAMESPACE_HELP),onFinalChange:a=>t(e.id,{namespace:a})})),React.createElement(c.d,{title:J.A.COMMON.DIMENSIONS},React.createElement(G.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(c.d,{title:J.A.COMMON.QDRANT_COLLECTION},React.createElement(G.A,{name:"collection",value:e.collection,description:(0,y.FE)(J.A.COMMON.QDRANT_COLLECTION_HELP),onFinalChange:a=>t(e.id,{collection:a})})),React.createElement(c.d,{title:J.A.COMMON.DIMENSIONS},React.createElement(G.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(c.d,{title:"OpenAI Environment"},React.createElement(j.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(j.j,{key:null,value:null,label:"Select an environment"}),n.filter((e=>"openai"===e.type)).map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))))),React.createElement(c.d,{title:"Vector Store ID"},React.createElement(G.A,{name:"store_id",value:e.store_id||"",placeholder:"vs_abc123...",description:e.store_id?(0,y.FE)(`The ID of your OpenAI vector store. <a href="https://platform.openai.com/storage/vector_stores/${e.store_id}" target="_blank" rel="noopener noreferrer">View in OpenAI Platform ↗</a>`):(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})}))),"chroma"===e.type&&React.createElement(React.Fragment,null,React.createElement(c.d,{title:"Tenant ID"},React.createElement(G.A,{name:"tenant",value:e.tenant||"",placeholder:"your-tenant-id",description:(0,y.FE)("Your Chroma tenant ID. For Chroma Cloud, enter your workspace identifier. For self-hosted instances, leave empty (defaults to 'default_tenant')."),onFinalChange:a=>t(e.id,{tenant:a})})),React.createElement(c.d,{title:"Database"},React.createElement(G.A,{name:"database",value:e.database||"default_database",placeholder:"default_database",description:(0,y.FE)("Your Chroma database name. For most setups, leave as 'default_database'. Only change if you have multiple databases configured."),onFinalChange:a=>t(e.id,{database:a})})),React.createElement(c.d,{title:"Collection"},React.createElement(G.A,{name:"collection",value:e.collection||"mwai",description:(0,y.FE)("Your Chroma collection name for storing vectors. This will be created automatically if it doesn't exist. Default is 'mwai'."),onFinalChange:a=>t(e.id,{collection:a})}))),React.createElement(c.d,{title:"Env ID"},React.createElement(G.A,{name:"env_id",value:e.id,readOnly:!0,description:"The unique identifier for this environment"})),React.createElement(Ue.Zc,{keepState:"embeddingsEnvs"},"openai-vector-store"!==e.type&&React.createElement(Ue.y2,{title:"Score"},React.createElement("div",{style:{marginTop:10}},React.createElement(c.d,{title:J.A.COMMON.MIN_SCORE},React.createElement(G.A,{name:"min_score",value:e.min_score||35,type:"number",min:"0",max:"100",step:"1",description:(0,y.FE)(J.A.HELP.MIN_SCORE),onFinalChange:a=>t(e.id,{min_score:a})})),React.createElement(c.d,{title:J.A.COMMON.MAX_SELECT},React.createElement(G.A,{name:"max_select",value:e.max_select||10,type:"number",min:"1",max:"100",step:"1",description:(0,y.FE)(J.A.HELP.MAX_SELECT),onFinalChange:a=>t(e.id,{max_select:a})})))),"openai-vector-store"!==e.type&&React.createElement(Ue.y2,{title:React.createElement("div",{style:{display:"flex",alignItems:"center",gap:"8px"}},React.createElement("span",null,J.A.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(c.d,{title:J.A.COMMON.OVERRIDE_DEFAULTS},React.createElement(m.R,{label:J.A.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(c.d,{title:J.A.COMMON.ENVIRONMENT},React.createElement(j.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(j.j,{key:null,value:null,label:"None"}),u.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))))),React.createElement(c.d,{title:J.A.COMMON.MODEL},React.createElement(j.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(j.j,{key:e.model,value:e.model,label:e.name}))))),React.createElement(c.d,{title:J.A.COMMON.DIMENSIONS},React.createElement(j.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(j.j,{key:e,value:e,label:0===t?`${e} (Native)`:e}))),React.createElement(j.j,{key:null,value:null,label:"Not Set"}))),g&&React.createElement(q.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(Ue.y2,{title:J.A.COMMON.ACTIONS},React.createElement("div",{style:{display:"flex",marginTop:10,justifyContent:"flex-end"}},("pinecone"===e.type||"chroma"===e.type)&&React.createElement(h.M,{className:"primary",onClick:async()=>{i(!0);try{const a="chroma"===e.type?"test_chroma":"test_pinecone",n=await fetch(`${v.y0}/embeddings/${a}`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":v.ok},body:JSON.stringify({env_id:e.id})}),l=await n.json();console.log("Test Response:",l),d(l),l.success&&l.dimension&&("pinecone"===e.type?t(e.id,{pinecone_dimensions:l.dimension}):"chroma"===e.type&&t(e.id,{chroma_dimensions:l.dimension}))}catch(t){console.error("Quick Test Error:",t),d({success:!1,error:t.message||`Failed to test ${"chroma"===e.type?"Chroma":"Pinecone"} connection`})}finally{i(!1)}},isBusy:o},"Quick Test"),React.createElement(h.M,{className:"danger",onClick:()=>a(e.id)},J.A.COMMON.DELETE)))),s&&React.createElement(V.n,{title:("chroma"===e.type?"Chroma":"Pinecone")+" Connection Test",isOpen:!!s,onRequestClose:()=>d(null),okButton:{label:"Close",onClick:()=>d(null)},content:React.createElement("div",null,s.success?React.createElement(React.Fragment,null,React.createElement(q.X,{variant:"success",style:{marginBottom:15}},"Connection successful!"),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Status:")," ",s.ready?React.createElement("span",{style:{color:"green"}},"Ready"):React.createElement("span",{style:{color:"orange"}},"Not Ready")),"pinecone"===e.type&&React.createElement(React.Fragment,null,React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Name:")," ",s.index_name),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Metric:")," ",s.metric,"cosine"===s.metric?React.createElement("span",{style:{color:"green"}}," ✓"):React.createElement("span",{style:{color:"orange"}}," (expected: cosine)"))),"chroma"===e.type&&React.createElement(React.Fragment,null,React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Collection:")," ",s.collection_name,s.collection_exists?React.createElement("span",{style:{color:"green"}}," ✓ (exists)"):React.createElement("span",{style:{color:"orange"}}," (will be created on first use)")),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Server:")," ",s.server),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Collections Count:")," ",s.collections_count)),React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Dimensions:")," ",s.dimension,s.dimension_match?React.createElement("span",{style:{color:"green"}}," ✓ (matches configuration)"):React.createElement("span",{style:{color:"red"}}," ✗ (expected: ",s.expected_dimension,")")),s.host&&React.createElement("div",{style:{marginBottom:10}},React.createElement("strong",null,"Host:")," ",s.host)):React.createElement(React.Fragment,null,React.createElement(q.X,{variant:"danger",style:{marginBottom:15}},"Connection failed"),React.createElement("div",null,React.createElement("strong",null,"Error:")," ",s.error)))}))};const Gr=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(s.s,{h2:!0,style:{color:"white"}},"Environments for Embeddings"),React.createElement(g._,{inversed:!0,style:{marginTop:-5},action:React.createElement(h.M,{rounded:!0,small:!0,className:"success",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(jr,{env:e,updateEnvironment:t,deleteEnvironment:r,ai_envs:(null==n?void 0:n.ai_envs)||[],options:n}))))))},{useCallback:$r,useMemo:Wr,useState:zr}=wp.element,Vr=({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=Wr((()=>{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(c.d,{title:J.A.COMMON.OPENAI_AZURE_DEPLOYMENTS,style:{marginTop:10}},a.map(((n,o)=>React.createElement("div",{key:o,style:{display:"flex",marginBottom:10}},React.createElement(G.A,{style:{flex:1},value:n.name,placeholder:J.A.COMMON.OPENAI_AZURE_DEPLOYMENT_NAME,onBlur:e=>l(o,"name",e),onEnter:e=>l(o,"name",e)}),React.createElement(j.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(j.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,{className:"success",fullWidth:!0,icon:"plus",onClick:()=>{const n=[...a,{name:"",model:""}];e(t,{deployments:n})}}))},qr=({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(c.d,{title:J.A.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(G.A,{style:{flex:1},value:l.name,placeholder:J.A.COMMON.HUGGINGFACE_MODEL_NAME,onBlur:e=>n(r,"name",e),onEnter:e=>n(r,"name",e)}),React.createElement(G.A,{style:{flex:2,marginLeft:5},value:l.apiUrl,placeholder:J.A.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,{className:"success",fullWidth:!0,icon:"plus",onClick:()=>{const n=[...a,{name:"",apiUrl:"",tags:["core","chat"]}];e(t,{customModels:n})}}))};const Kr=function({options:e,environments:t,updateEnvironment:a,updateOption:n,busy:l}){const[r,o]=zr(!1),[i,d]=zr(!1),[m,u]=zr(null),p=(null==e?void 0:e.ai_engines)??[],E=$r((e=>{switch(e.type){case"openai":return be(J.A.HELP.OPENAI_API_KEY,J.A.HELP.OPENAI_API_KEY_URL,J.A.HELP.OPENAI_API_KEY_LINK_TEXT);case"azure":return be(J.A.HELP.AZURE_API_KEY,J.A.HELP.AZURE_API_KEY_URL,J.A.HELP.AZURE_API_KEY_LINK_TEXT);case"openrouter":return be(J.A.HELP.OPENROUTER_API_KEY,J.A.HELP.OPENROUTER_API_KEY_URL,J.A.HELP.OPENROUTER_API_KEY_LINK_TEXT);case"anthropic":return be(J.A.HELP.ANTHROPIC_API_KEY,J.A.HELP.ANTHROPIC_API_KEY_URL,J.A.HELP.ANTHROPIC_API_KEY_LINK_TEXT);default:return""}}),[]),R=$r((async(t,a)=>{try{o(!0);const l=await(0,y.IU)(`${v.y0}/ai/models`,{method:"POST",nonce:v.ok,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]),b=$r((async e=>{d(!0);try{const t=await(0,y.IU)(`${v.y0}/ai/test_connection`,{method:"POST",nonce:v.ok,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(s.s,{h2:!0,style:{color:"white",marginBottom:15}},J.A.COMMON.ENVIRONMENTS_FOR_AI),React.createElement(g._,{inversed:!0,style:{marginTop:-5},action:React.createElement(h.M,{rounded:!0,small:!0,className:"success",icon:"plus",onClick:()=>{const e=[...t,{name:"New Environment",type:"openai",apikey:""}];n(e,"ai_envs")}})},t.map((o=>{var s;let d=0;const m=p.find((e=>e.type===o.type))||{},u=null===(s=m.inputs)||void 0===s?void 0:s.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(c.d,{title:J.A.COMMON.NAME},React.createElement(G.A,{name:"name",value:o.name,onFinalChange:e=>a(o.id,{name:e})})),React.createElement(c.d,{title:J.A.COMMON.TYPE},React.createElement(j.u,{scrolldown:!0,name:"type",value:o.type,onChange:e=>a(o.id,{type:e})},p.map((e=>React.createElement(j.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(c.d,{title:J.A.COMMON.API_KEY},React.createElement(G.A,{name:"apikey",value:e.apikey,description:E(e),onFinalChange:t=>a(e.id,{apikey:t})})),t.includes("organizationId")&&React.createElement(c.d,{title:J.A.COMMON.OPENAI_ORGANIZATION_ID},React.createElement(G.A,{name:"organizationId",value:e.organizationId,description:be(J.A.HELP.OPENAI_ORGANIZATION_ID,J.A.HELP.OPENAI_ORGANIZATION_URL,J.A.HELP.OPENAI_ORGANIZATION_LINK_TEXT),onFinalChange:t=>a(e.id,{organizationId:t})})),t.includes("endpoint")&&React.createElement(c.d,{title:J.A.COMMON.ENDPOINT},React.createElement(G.A,{name:"endpoint",value:e.endpoint,description:"azure"===e.type?(0,y.FE)(J.A.HELP.AZURE_ENDPOINT):void 0,onFinalChange:t=>a(e.id,{endpoint:t})})),t.includes("region")&&React.createElement(c.d,{title:J.A.COMMON.REGION},React.createElement(G.A,{name:"region",value:e.region,onFinalChange:t=>a(e.id,{region:t})})),t.includes("projectId")&&React.createElement(c.d,{title:J.A.COMMON.PROJECT_ID},React.createElement(G.A,{name:"projectId",value:e.projectId,onFinalChange:t=>a(e.id,{projectId:t})})))})(o),"azure"===o.type&&o.endpoint&&(()=>{const e=o.endpoint.replace(/^https?:\/\//,"").includes("/"),t=o.endpoint.includes("?");return e||t})()&&React.createElement(React.Fragment,null,React.createElement(q.X,{variant:"warning",style:{marginBottom:10}},React.createElement("strong",null,"Important:")," Please enter only your Azure resource domain (e.g., ",React.createElement("code",null,"myresource.openai.azure.com"),"), not the full URL. AI Engine will automatically construct the appropriate endpoint based on the model type.")),"google"===o.type&&React.createElement(React.Fragment,null,(""===o.apikey||!o.apikey)&&React.createElement(q.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(q.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($.g,null)),"huggingface"===o.type&&React.createElement(React.Fragment,null,React.createElement(q.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($.g,null)),"perplexity"===o.type&&(""===o.apikey||!o.apikey)&&React.createElement(React.Fragment,null,React.createElement(q.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($.g,null)),React.createElement(Ue.Zc,{keepState:"environmentCategories"},u&&React.createElement(Ue.y2,{title:J.A.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 (experimental models are automatically excluded). 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)},J.A.COMMON.REFRESH_MODELS)),"azure"===o.type&&React.createElement(React.Fragment,null,React.createElement("p",null,J.A.HELP.AZURE_DEPLOYMENTS),React.createElement(Ue.y2,{title:J.A.COMMON.OPENAI_AZURE_DEPLOYMENTS},React.createElement(Vr,{deployments:o.deployments??[],environmentId:o.id,updateEnvironment:a,options:e}))),"huggingface"===o.type&&React.createElement(Ue.y2,{title:J.A.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(qr,{customModels:o.customModels??[],environmentId:o.id,updateEnvironment:a,options:e})),React.createElement(Ue.y2,{title:J.A.COMMON.ENVIRONMENT_ID},React.createElement("p",null,'The EnvID is "',React.createElement("b",null,o.id),'".')),React.createElement(Ue.y2,{title:J.A.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:()=>b(o)},J.A.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)},J.A.COMMON.DELETE)))))}))),React.createElement(V.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(q.X,{variant:"success"},"Connection successful!"),React.createElement($.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(q.X,{variant:"danger"},React.createElement("strong",null,"Connection failed!"),React.createElement("br",null),m.error))}))},{useCallback:Yr,useState:Xr}=wp.element;const Qr=function({options:e,mcpServers:t,updateMCPServer:a,updateOption:n,busy:l}){const[r,o]=Xr({}),i=Yr(((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=Yr(((e,t)=>{a(e,{url:t})}),[a]),m=Yr(((e,t)=>{a(e,{token:t})}),[a]);return React.createElement("div",{style:{padding:"0px 10px 5px 10px",marginTop:13,marginBottom:5}},React.createElement(s.s,{h2:!0,style:{color:"white",marginBottom:15}},J.A.COMMON.MCP_SERVERS),React.createElement(g._,{inversed:!0,style:{marginTop:-5},action:React.createElement(h.M,{rounded:!0,small:!0,className:"success",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(c.d,{title:J.A.COMMON.NAME},React.createElement(G.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(c.d,{title:J.A.COMMON.URL},React.createElement(G.A,{name:"url",value:e.url,placeholder:"https://example.com/mcp-server",description:(0,y.FE)(J.A.HELP.MCP_SERVER_URL),onFinalChange:t=>d(e.id,t)})),React.createElement(c.d,{title:J.A.COMMON.TOKEN},React.createElement(G.A,{name:"token",value:e.token,placeholder:"Bearer token for authentication",description:(0,y.FE)(J.A.HELP.MCP_SERVER_TOKEN),onFinalChange:t=>m(e.id,t)})),React.createElement(Ue.Zc,{keepState:"mcpServerCategories"},React.createElement(Ue.y2,{title:J.A.COMMON.SERVER_ID},React.createElement("p",null,'The Server ID is "',React.createElement("b",null,e.id),'".')),React.createElement(Ue.y2,{title:J.A.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)},J.A.COMMON.DELETE)))))))))},{useState:Jr}=wp.element;const Zr=function({options:e}){const[t,a]=Jr({}),{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}),c=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($.g,null),React.createElement(R.z,{className:"primary",title:J.A.COMMON.MCP_FUNCTIONS||"MCP Functions",action:c},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,J.A.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(s.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(Ue.Zc,{keepState:`mcpFunctionDetails-${n}`},e[n].map(((e,t)=>React.createElement(Ue.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:eo}=wp.element,to=f.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;
}
`,ao=({children:e,value:t,...a})=>{const[n,l]=eo(null);return React.createElement(to,a,React.createElement("pre",{onClick:async()=>{navigator.clipboard?(await navigator.clipboard.writeText(t),l(J.A.COMMON.COPIED),setTimeout((()=>{l(null)}),2e3)):alert(J.A.COMMON.CLIPBOARD_ERROR)}},!n&&e,n&&React.createElement("span",null,n)))},{useState:no,useEffect:lo}=wp.element,ro=()=>{const[e,t]=no(""),[a,n]=no(""),[l,r]=no(""),[o,i]=no(!1),[s,c]=no("imageToText"),[d,m]=no(null);lo((()=>{t(""),n(""),r("")}),[s]);const u=async(t="imageToText")=>{let a="";if("textToJSON"===t)a=`${v.y0}/ai/json`;else if("imageToText"===t)a=`${v.y0}/ai/transcribe_image`;else{if("audioToText"!==t)return void alert(`Unknown transcription type: ${t}`);a=`${v.y0}/ai/transcribe_audio`}i(t),m(Date.now());try{var r;let t=(await(0,y.IU)(a,{method:"POST",nonce:v.ok,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)=>{c(t.key)}},React.createElement(g.V,{title:J.A.COMMON.IMAGE_TO_TEXT,key:"imageToText"},React.createElement("label",null,"Image URL:"),React.createElement($.g,{tiny:!0}),React.createElement(xe.m,{name:"url",rows:2,value:e,onChange:t}),React.createElement($.g,null),React.createElement("label",null,"Prompt:"),React.createElement($.g,{tiny:!0}),React.createElement(xe.m,{rows:2,value:l,onChange:r}),React.createElement($.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($.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:J.A.COMMON.AUDIO_TO_TEXT,key:"audioToText"},React.createElement("label",null,"Audio URL:"),React.createElement($.g,{tiny:!0}),React.createElement(xe.m,{name:"url",rows:2,value:e,onChange:t}),React.createElement($.g,null),React.createElement("label",null,"Prompt:"),React.createElement($.g,{tiny:!0}),React.createElement(xe.m,{rows:2,value:l,onChange:r}),React.createElement($.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:J.A.COMMON.PROMPT_TO_JSON,key:"textToJSON"},React.createElement("label",null,"Prompt:"),React.createElement($.g,{tiny:!0}),React.createElement(xe.m,{rows:2,value:l,onChange:r}),React.createElement($.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($.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($.g,null))))),React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{title:"Transcription",className:"primary"},React.createElement($.g,{tiny:!0}),"textToJSON"===s&&React.createElement(Tr.p2,{value:a,indentWidth:2,displayDataTypes:!1,displayObjectSize:!1,displayArrayKey:!1,enableClipboard:!1,style:{fontSize:12}}),"textToJSON"!==s&&React.createElement(xe.m,{name:"context",rows:21,value:a,disabled:!a}))))},{useState:oo,useMemo:io,useEffect:so}=wp.element,co=({options:e,updateOption:t,busy:a})=>{const[n,l]=oo(""),[r,o]=oo(null),[i,s]=oo(null),[c,d]=oo(!1),m=null==e?void 0:e.module_embeddings,u=(null==e?void 0:e.embeddings_envs)||[],p=async t=>{d(!0),o(null),s(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)(`${v.gh}/mwai-ui/v1/search`,{method:"POST",nonce:v.ok,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)}},b=io((()=>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=io((()=>{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=io((()=>{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(G.A,{name:"query",value:n,onChange:l,onEnter:()=>p((null==e?void 0:e.search_frontend_method)||"wordpress"),placeholder:"Enter your search query...",disabled:c,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||c,isBusy:c,style:{flex:1}},"Search")),React.createElement("div",{style:{display:"flex",gap:8}},React.createElement(h.M,{className:"secondary",onClick:()=>p("wordpress"),disabled:!n||c,style:{flex:1}},"WordPress"),React.createElement(h.M,{className:"secondary",onClick:()=>p("keywords"),disabled:!n||c,style:{flex:1}},"AI Keywords"),React.createElement(h.M,{className:"secondary",onClick:()=>p("embeddings"),disabled:!n||c||!m||0===u.length,style:{flex:1}},"Embeddings"),React.createElement(h.M,{className:"secondary",onClick:async()=>{d(!0),o(null),s(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)(`${v.gh}/mwai-ui/v1/search`,{method:"POST",nonce:v.ok,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`}}s(a)}finally{d(!1)}},disabled:!n||c,style:{flex:1}},"Multi-Method"))),r&&React.createElement(R.z,{title:"Results",className:"primary"},!1===r.success&&React.createElement(q.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,b.length>0?React.createElement(Pe.o,{data:b,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(q.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(Pe.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($.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(j.u,{name:"search_frontend_method",value:(null==e?void 0:e.search_frontend_method)||"wordpress",onChange:t,fullWidth:!0},React.createElement(j.j,{value:"wordpress",label:"WordPress"}),React.createElement(j.j,{value:"keywords",label:"AI Keywords"}),React.createElement(j.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(xe.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(j.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(j.j,{key:e.id,value:e.id,label:e.name})))):React.createElement(q.X,{variant:"info",style:{fontSize:13}},"No embeddings environments configured. Please configure one in the Knowledge tab."):React.createElement(q.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:mo,useMemo:uo,useEffect:po}=wp.element,Eo=[{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"}],go=[{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"}],ho=({options:e,refreshOptions:t})=>{var a;const n=(0,l.jE)(),[i,s]=mo(null),[c,d]=mo(!1),[m,u]=mo(null==e||null===(a=e.ai_envs)||void 0===a||null===(a=a[0])||void 0===a?void 0:a.id),[p,E]=mo("assistants"),[R,b]=mo([]),{colors:f}=(0,r.z)(),w=uo((()=>{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]),_=uo((()=>w.find((e=>e.id===m))),[m,w]),C=uo((()=>(null==_?void 0:_.assistants)||[]),[_]),[T,A]=mo({userId:null,purpose:["assistant-in","assistant-out"],metadata:null,envId:m,page:1,limit:10}),N=(0,y.F1)(T);po((()=>{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&&u(t)}),[]),po((()=>{(({envId:e})=>{const t={envId:e||null};localStorage.setItem("mwai-admin-assistants",(0,y.F1)(t))})({envId:m})}),[m]),po((()=>{A({...T,envId:m})}),[m]);const{isFetching:O,data:I}=(0,o.I)({queryKey:["assistants-files",N],enabled:"files"===p,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 Ge(`${v.gh}/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})(T)}),S=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=C.find((t=>t.id===e));return(null==t?void 0:t.name)||"N/A"})(e[t])})`:""))))):null,M=(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)),k=async e=>{d(!0);try{await(async e=>{const t=await Ge(`${v.gh}/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"),b([])}catch(e){s(e)}d(!1)},x=uo((()=>null==I?void 0:I.files.map((e=>{return{...e,file:M(e.url,e.refId),purpose:(t=e.purpose,"assistant-out"===t?"Generated":"assistant-in"===t?"Uploaded":t),metadata:S(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:c,onClick:()=>k([e.id])}))};var t}))),[I]),P=uo((()=>(null==I?void 0:I.total)||0),[I]),L=uo((()=>C.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(ke.z,{icon:"check",width:16,color:f.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(ke.z,{icon:e.has_file_search?"check":"close",width:16,color:e.has_file_search?f.green:f.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(ke.z,{icon:e.has_code_interpreter?"check":"close",width:16,color:e.has_code_interpreter?f.green:f.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()}}))),[C,f.gray,f.green]),D=c,F=uo((()=>React.createElement(j.u,{scrolldown:!0,value:m,onChange:u,style:{marginLeft:5}},w.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))))),[m,w]),U=uo((()=>React.createElement("div",null,React.createElement("div",{style:{display:"flex",flexDirection:"row"}},React.createElement(Be.Q,{currentPage:T.page,limit:T.limit,total:P,onClick:e=>{A({...T,page:e})}})))),[T,P]);return React.createElement(React.Fragment,null,React.createElement("div",{style:{width:"100%",margin:0,padding:0}},React.createElement(g._,{inversed:!0,style:{marginTop:-5,width:"100%"},currentTab:p,onChange:(e,t)=>{E(t.key)},action:React.createElement(React.Fragment,null,React.createElement("div",{style:{flex:"auto"}}),R.length>0&&"files"===p&&React.createElement(React.Fragment,null,React.createElement(h.M,{className:"danger",disabled:!1,onClick:()=>k(R)},J.A.COMMON.DELETE)),"files"===p&&React.createElement(h.M,{disabled:D||!_,busy:D,onClick:async()=>{await n.invalidateQueries("assistants-files")},className:"secondary"},J.A.COMMON.REFRESH),"assistants"===p&&React.createElement(h.M,{disabled:D||!_,busy:D,onClick:async()=>{d(!0);try{await(async e=>{const t=await Ge(`${v.y0}/openai/assistants/list?envId=${e}`);if(!t.success)throw new Error(t.message);return null==t?void 0:t.assistants})(m),await t()}catch(e){s(e)}d(!1)},className:"secondary"},J.A.COMMON.REFRESH),F)},React.createElement(g.V,{title:J.A.COMMON.ASSISTANTS,key:"assistants"},React.createElement(Pe.o,{busy:D,data:L,columns:Eo,emptyMessage:J.A.NO_ASSISTANTS_YET})),React.createElement(g.V,{title:J.A.COMMON.FILES,key:"files"},React.createElement(Pe.o,{busy:O||D,data:x,columns:go,selectedItems:R,onSelect:e=>{b([...R,...e])},onUnselect:e=>{b([...R.filter((t=>!e.includes(t)))])},emptyMessage:J.A.NO_FILES_YET}),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",marginTop:10}},React.createElement("div",{style:{flex:"auto"}}),U)))),React.createElement("div",{style:{width:"100%",margin:0,padding:0}},React.createElement(q.X,{variant:"danger",style:{marginTop:12}},"OpenAI will be deprecating the Assistants API with a planned shutdown date of August 26, 2026. You can continue using the Assistants API until that date, but no new features or model support will be added. Consider using Prompts instead (a new Mode in Chatbot)."),i&&React.createElement(V.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)})))},{useEffect:Ro,useState:yo,useCallback:vo}=wp.element,{Popover:bo,SlotFillProvider:fo}=wp.components,{useSelect:wo,useDispatch:_o}=wp.data,{BlockEditorProvider:Co,BlockList:To,WritingFlow:Ao,ObserveTyping:No,BlockInspector:Oo,BlockTools:Io,BlockEditorKeyboardShortcuts:So,Inserter:Mo,BlockNavigationDropdown:ko}=wp.blockEditor||{},{parse:xo,serialize:Po,createBlock:Lo}=wp.blocks||{},Do=({editingId:e,editingTitle:t,setEditingTitle:a,onCloseEditor:n,onSaveForm:l,busySave:r,canSave:o})=>{const{clearSelectedBlock:i}=_o("core/block-editor"),c=wo((e=>e("core/block-editor").getSelectedBlockClientId()),[]),d=vo((()=>{try{i()}catch(e){}}),[i]);return React.createElement(Le.V,{style:{display:"flex",alignItems:"center"}},React.createElement(ao,{value:`[mwai_form id="${e}"]`},React.createElement("span",null,"[mwai_form ",React.createElement("span",{className:"highlight"},'id="',e,'"'),"]")),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,marginLeft:10}},React.createElement(Mo,{rootClientId:void 0}),React.createElement(ko,null)),React.createElement("div",{style:{flex:1}}),React.createElement(s.s,{style:{marginRight:8}},"Title:"),React.createElement(G.A,{value:t,placeholder:"Enter form title",onChange:a,style:{width:260}}),c&&React.createElement(h.M,{className:"secondary",onClick:d,style:{marginLeft:6}},"Unselect Block"),React.createElement(h.M,{className:"primary",onClick:l,busy:r,disabled:!o||r,style:{marginLeft:6}},"Save"),React.createElement(h.M,{className:"secondary",onClick:n,disabled:r,style:{marginLeft:6}},"Close"))},Fo=()=>{const e=(0,l.jE)(),{clearSelectedBlock:t}=_o("core/block-editor"),[a,n]=yo(null),[r,i]=yo(""),[c,d]=yo([]),[m,u]=yo(!1),[p,g]=yo(!1),[y,b]=yo(""),[f,w]=yo(""),{data:_=[],isLoading:C,error:T}=(0,o.I)({queryKey:["forms"],queryFn:Je});Ro((()=>{try{var e;!!!wp.blocks.getBlockType("core/paragraph")&&null!==(e=wp.blockLibrary)&&void 0!==e&&e.registerCoreBlocks&&wp.blockLibrary.registerCoreBlocks()}catch(e){console.warn("Could not register core blocks:",e)}}),[]);const A=()=>{if(!Lo)return[];const e=()=>"mwai-"+Math.random().toString(36).substr(2,9),t=e(),a=Lo("ai-engine/form-field",{id:e(),type:"input",label:"English Word",name:"WORD",placeholder:"Enter an English word",required:!0}),n=Lo("ai-engine/form-output",{id:t,copyButton:!0}),l=Lo("ai-engine/form-submit",{id:e(),label:"Translate",message:"Translate the following English word to Japanese. Only reply with the translated word.\n\nWord: {WORD}",outputElement:`#${t}`,scope:"form"});return[Lo("ai-engine/form-container",{id:e(),theme:"ChatGPT"},[a,l,n])]},N=async e=>{u(!0);try{var t,a,l,r;const o=await(async e=>{const t=await Ge(`${v.y0}/forms/get?id=${e}`);if(!t.success)throw new Error(t.message);return t.form})(e),s=(null==o||null===(t=o.content)||void 0===t?void 0:t.raw)||(null==o||null===(a=o.content)||void 0===a?void 0:a.rendered)||"",c=s&&xo?xo(s):[];n(e);const m=(null==o||null===(l=o.title)||void 0===l?void 0:l.raw)||(null==o||null===(r=o.title)||void 0===r?void 0:r.rendered)||"";i(m);const u=c.length?c:A();d(u),b(m||""),w(Po?Po(u):"")}catch(e){console.error(e),alert("Could not load the form for editing.")}finally{u(!1)}};Ro((()=>{const e=()=>{try{t()}catch(e){}try{const e=window.getSelection();null!=e&&e.removeAllRanges&&e.removeAllRanges()}catch(e){}try{var e;null!==(e=document.activeElement)&&void 0!==e&&e.blur&&document.activeElement.blur()}catch(e){}setTimeout((()=>{try{t()}catch(e){}}),0)},a=t=>{try{const a=document.getElementById("mwai-forms-editor-canvas"),n=document.getElementById("mwai-forms-editor-inspector"),l=Array.from(document.querySelectorAll(".components-popover")),r=t.target,o=a&&a.contains(r),i=n&&n.contains(r),s=l.some((e=>e.contains(r)));o||i||s||e()}catch(t){}};document.addEventListener("mousedown",a,!0);const n=t=>{"Escape"===t.key&&(t.stopPropagation(),e())};return document.addEventListener("keydown",n,!0),()=>{document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",n,!0)}}),[t]);const O=async t=>{if(confirm("Delete this form? This cannot be undone.")){g(!0);try{await(async e=>{const t=await Ge(`${v.y0}/forms/delete`,{method:"POST",json:{id:e}});if(!t.success)throw new Error(t.message);return t})(t),await e.invalidateQueries(["forms"])}catch(e){alert("Error while deleting form. Check console."),console.error(e)}finally{g(!1)}}};return React.createElement(E.N,null,React.createElement("style",null,"\n .neko-toolbar pre,\n .neko-table pre {\n margin: 0 !important;\n }\n "),!a&&React.createElement(E.Y,{minimal:!0,fullWidth:!0},React.createElement(R.z,{className:"primary",title:"Forms (Beta)",action:React.createElement("div",{style:{display:"flex",alignItems:"center"}},React.createElement(h.M,{className:"primary",onClick:async()=>{u(!0);try{var t,a;const l=await(async(e="Untitled Form")=>{const t=await Ge(`${v.y0}/forms/create`,{method:"POST",json:{title:e}});if(!t.success)throw new Error(t.message);return t.form})("Untitled Form"),r=null==l?void 0:l.id;await e.invalidateQueries(["forms"]),n(r);const o=(null==l||null===(t=l.title)||void 0===t?void 0:t.raw)||(null==l||null===(a=l.title)||void 0===a?void 0:a.rendered)||"Untitled Form";i(o);const s=A();d(s),b(o||""),w("")}catch(e){console.error(e),alert("Could not create form.")}finally{u(!1)}},busy:m},"New Form"))},T&&React.createElement(q.X,{variant:"danger"},(null==T?void 0:T.message)||T),!C&&!T&&0===_.length&&React.createElement(s.s,{p:!0},"No forms yet. Create one to get started."),(C||_.length>0)&&React.createElement(Pe.o,{busy:C,data:_.map((e=>({id:e.id,title:e.title,shortcode:React.createElement(ao,{value:`[mwai_form id="${e.id}"]`},"[mwai_form ",React.createElement("span",{className:"highlight"},'id="',e.id,'"'),"]"),actions:React.createElement("div",null,React.createElement(h.M,{className:"primary",rounded:!0,icon:"pencil",onClick:()=>N(e.id)}),React.createElement(h.M,{className:"danger",rounded:!0,icon:"trash",onClick:()=>O(e.id),busy:p}))}))),columns:[{accessor:"title",title:"Title",width:"55%"},{accessor:"shortcode",title:"Shortcode",width:"35%"},{accessor:"actions",title:"",width:"10%"}]}))),a&&React.createElement(E.Y,{minimal:!0,fullWidth:!0},React.createElement(R.z,{className:"primary",title:`Edit Form #${a}`},Co&&xo&&Po&&Lo?React.createElement(fo,null,React.createElement(bo.Slot,null),React.createElement(Co,{value:c,onInput:d,onChange:d,settings:{allowedBlockTypes:!0,hasFixedToolbar:!1,mediaUpload:!1,__experimentalBlockPatterns:[],__experimentalFeatures:{spacing:{blockGap:!0}},canLockBlocks:!1,__unstableIsPreviewMode:!1,lockBlocks:!1,dragAndDrop:!1,__experimentalBlockMoverMode:"arrows"}},React.createElement(So,null),React.createElement(Do,{editingId:a,editingTitle:r,setEditingTitle:i,onCloseEditor:()=>{n(null),i(""),d([]),b(""),w("")},onSaveForm:async()=>{if(a){u(!0);try{const t=Po?Po(c):"",n={title:r||"Untitled Form",content:t,status:"publish"};await(async(e,t)=>{const a=await Ge(`${v.y0}/forms/update`,{method:"POST",json:{id:e,...t}});if(!a.success)throw new Error(a.message);return a.form})(a,n),await e.invalidateQueries(["forms"]),b(r||""),w(t)}catch(e){console.error(e),alert("Error while saving form.")}finally{u(!1)}}},busySave:m,canSave:(r||"").trim()!==(y||"").trim()||(Po?Po(c):"")!==f}),React.createElement($.g,null),React.createElement("div",{style:{display:"grid",gridTemplateColumns:"2fr 1fr",gap:18}},React.createElement(W.L,{style:{minHeight:420,border:"2px solid var(--neko-input-border)",borderRadius:10}},React.createElement("style",null,"\n .block-editor-block-mover__drag-handle,\n .block-editor-block-draggable-chip,\n .components-draggable__invisible-drag-handle,\n .block-editor-block-toolbar__drag-handle {\n display: none !important;\n }\n .block-editor-block-list__block.is-dragging {\n cursor: default !important;\n }\n "),React.createElement(Io,null,React.createElement(Ao,null,React.createElement(No,null,React.createElement(To,null))))),React.createElement(W.L,{style:{minHeight:420,border:"2px solid var(--neko-input-border)",borderRadius:10}},React.createElement("div",{style:{margin:-20}},React.createElement(Oo,null)))))):React.createElement(q.X,{variant:"warning",style:{margin:"20px"}},"The Block Editor is not available in this context. Please ensure you are in the WordPress admin area."))))};var Uo=a(9491);const{useState:Bo,useMemo:Ho}=wp.element,jo=f.Ay.div`
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 20px;
`,Go=({addons:e})=>{const t=e.some((e=>e.enabled))?"enabled":"all",[a,n]=Bo(t),l=Ho((()=>"enabled"===a?e.filter((e=>e.enabled)):"disabled"===a?e.filter((e=>!e.enabled)):e),[e,a]);return React.createElement(React.Fragment,null,React.createElement(Le.V,null,React.createElement(z.o,{name:"filter",value:a,onChange:e=>n(e)},React.createElement(z.K,{title:"All",value:"all"}),React.createElement(z.K,{title:"Enabled",value:"enabled"}),React.createElement(z.K,{title:"Disabled",value:"disabled"}))),React.createElement($.g,null),React.createElement(jo,null,l.map((e=>React.createElement(W.L,{key:e.id,style:{marginBottom:0,borderRadius:8,overflow:"auto"},footer:React.createElement("div",{style:{display:"flex",width:"100%",alignItems:"center",marginLeft:10,minHeight:30}},React.createElement("span",{style:{fontSize:"12px",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(Uo.r,null)),React.createElement(s.s,{h3:!0,style:{margin:0,marginLeft:8,fontWeight:"bold"}},e.name),React.createElement("div",{style:{marginLeft:5,marginTop:2,fontSize:15,color:"#fec74c"}},Array.from({length:e.stars},((e,t)=>React.createElement("span",{key:t},"★"))))),React.createElement("div",{className:"addon-description"},e.description))))))},{useMemo:$o,useState:Wo,useEffect:zo,useCallback:Vo}=wp.element,qo=[{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"}],Ko=["module_forms","module_statistics","module_embeddings","module_assistants","module_orchestration","module_cross_site"],Yo=()=>{var e,t,a,n,l,r,o,i,p,b,f;const[w,_]=Wo(v.fF),C=v.gh.replace("/wp-json",""),[T,A]=Wo((()=>{const e=localStorage.getItem("mwai_settings_section");return e||"ai"})),[N,O]=Wo(null),[I,S]=Wo(!1),[M,k]=Wo(!1),x=null==w?void 0:w.module_suggestions,P=null==w?void 0:w.module_advisor,L=null==w?void 0:w.module_forms,D=null==w?void 0:w.module_finetunes,F=null==w?void 0:w.module_statistics,U=null==w?void 0:w.module_playground,B=null==w?void 0:w.module_generator_content,H=null==w?void 0:w.module_generator_images,q=null==w?void 0:w.module_moderation,K=null==w?void 0:w.module_embeddings,Y=null==w?void 0:w.module_assistants,X=null==w?void 0:w.module_transcription,Z=null==w?void 0:w.module_devtools,ee=null==w?void 0:w.module_chatbots,te=null==w?void 0:w.module_search,ae=null==w?void 0:w.module_orchestration,ne=null==w?void 0:w.module_cross_site,le=null==w?void 0:w.forms_editor,re=$o((()=>null!=w&&w.ai_envs?null==w?void 0:w.ai_envs:[]),[w]),se=$o((()=>null!=w&&w.mcp_envs?null==w?void 0:w.mcp_envs:[]),[w]),ce=null==w?void 0:w.ai_fast_default_env,de=null==w?void 0:w.ai_fast_default_model,me=null==w?void 0:w.ai_default_env,ue=null==w?void 0:w.ai_default_model,pe=null==w?void 0:w.ai_vision_default_env,ge=null==w?void 0:w.ai_vision_default_model,he=null==w?void 0:w.ai_embeddings_default_env,Re=null==w?void 0:w.ai_embeddings_default_model,ye=null==w?void 0:w.ai_images_default_env,ve=null==w?void 0:w.ai_images_default_model,fe=null==w?void 0:w.ai_audio_default_env,we=null==w?void 0:w.ai_audio_default_model,_e=null==w?void 0:w.ai_json_default_env,Ce=null==w?void 0:w.ai_json_default_model,Te=null==w?void 0:w.ai_streaming,Ae=null==w?void 0:w.ai_responses_api,Oe=null==w?void 0:w.privacy_first,Ie=null!=w&&w.embeddings_envs?null==w?void 0:w.embeddings_envs:[],Se=null==w?void 0:w.embeddings_default_env,Me=null==w?void 0:w.syntax_highlight,ke=null==w?void 0:w.event_logs,xe=null==w?void 0:w.chatbot_discussions,Pe=null==w?void 0:w.chatbot_gdpr_consent,Le=null==w?void 0:w.chatbot_gdpr_text,De=null==w?void 0:w.chatbot_gdpr_button,Fe=null==w?void 0:w.speech_recognition,Ue=null==w?void 0:w.speech_synthesis,Be=null==w?void 0:w.public_api,He=null==w?void 0:w.statistics_data,je=null==w?void 0:w.statistics_forms_data,Ge=null==w?void 0:w.intro_message,$e=null==w?void 0:w.context_max_length,We=null==w?void 0:w.banned_ips,Xe=null==w?void 0:w.banned_words,Qe=null==w?void 0:w.ignore_word_boundaries,Je=(null==w?void 0:w.custom_languages)||[],Ze=(null==w?void 0:w.admin_bar)??["settings"],et=null==w?void 0:w.resolve_shortcodes,tt=null==w?void 0:w.clean_uninstall,{completionModels:at}=ie(w),{visionModels:nt}=ie(w,null==w?void 0:w.ai_vision_default_env),{audioModels:lt}=ie(w,null==w?void 0:w.ai_audio_default_env),{jsonModels:rt}=ie(w,null==w?void 0:w.ai_json_default_env),{imageModels:ot}=ie(w,null==w?void 0:w.ai_images_default_env),{embeddingsModels:it}=ie(w,null==w?void 0:w.ai_embeddings_default_env),st=$o((()=>re&&null!=w&&w.ai_engines?re.filter((e=>{if("azure"===e.type){var t;return null===(t=e.deployments)||void 0===t?void 0:t.some((e=>{var t,a;return(null===(t=e.model)||void 0===t?void 0:t.includes("embedding"))||(null===(a=e.model)||void 0===a?void 0:a.includes("ada"))}))}const a=w.ai_engines.find((t=>t.type===e.type));if(!a||!a.models)return!1;return a.models.some((e=>{var t;return null==e||null===(t=e.tags)||void 0===t?void 0:t.includes("embedding")}))})):[]),[re,w]),ct=$o((()=>it.find((e=>e.model===Re))),[it,Re]),dt=$o((()=>{var e,t;if(!ct)return[];if((null==ct||null===(e=ct.tags)||void 0===e?void 0:e.includes("matryoshka"))&&(null==ct||null===(t=ct.dimensions)||void 0===t?void 0:t.length)>0){const e=ct.dimensions[0];return[3072,2048,1536,1024,768,512].filter((t=>t<=e))}return(null==ct?void 0:ct.dimensions)||[]}),[ct]),mt=I,ut=Vo((async e=>{try{if((0,y.F1)(e)===(0,y.F1)(w))return;S(!0);const t=await(0,y.IU)(`${v.y0}/settings/update`,{method:"POST",nonce:v.ok,json:{options:e}});_(t.options)}catch(t){console.error(J.A.ERROR.UPDATING_OPTIONS,null!=t&&t.message?{message:t.message,options:w,newOptions:e}:{err:t,options:w,newOptions:e}),t.message&&O(React.createElement(React.Fragment,null,React.createElement("div",null,J.A.ERROR.UPDATING_OPTIONS),React.createElement("small",null,(0,y.FE)(J.A.ERROR.CHECK_YOUR_CONSOLE))))}finally{S(!1)}}),[w]);zo((()=>{(async()=>{let e=!1;const t={...w};qo.forEach((({envKey:a,modelKey:n,defaultModel:l})=>{let r=!1;if(w[a]&&(r=!!re.find((e=>e.id===w[a]))),!r){const r=re.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=it.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 ut(t)})()}),[re,w,ut,it]);const Et=async()=>{S(!0);try{const e=await Ye();_(e)}catch(e){console.error(J.A.ERROR.GETTING_OPTIONS,null!=e&&e.message?{message:e.message}:{err:e}),e.message&&O(React.createElement(React.Fragment,null,React.createElement("div",null,J.A.ERROR.GETTING_OPTIONS),React.createElement("small",null,(0,y.FE)(J.A.ERROR.CHECK_YOUR_CONSOLE))))}finally{S(!1)}},ht=async(e,t)=>{const a={...w,[t]:e};await ut(a)},Rt=async e=>{k(!0);try{await ht(e,"embeddings_settings")}finally{k(!1)}},yt=async(e,t)=>{const a=Ie.map((a=>a.id===e?{...a,...t}:a));ht(a,"embeddings_envs")};zo((()=>{if(!v.zN){const e={...w};let t=!1;Ko.forEach((a=>{e[a]&&(e[a]=!1,console.warn(`Resetting ${a}`),t=!0)})),t&&(0,y.F1)(e)!==(0,y.F1)(w)&&ut(e)}}),[]),zo((()=>{localStorage.setItem("mwai_settings_section",T)}),[T]),zo((()=>{!Te&&ke&&ht(!1,"event_logs")}),[Te,ke,ht]),zo((()=>{"ai"===T||"files"===T||"remote"===T||"others"===T||"addons"===T||"chatbot"===T&&ee||"knowledge"===T&&K||"orchestration"===T&&ae||"assistants"===T&&Y||A("ai")}),[T,ee,K,ae,Y]);const vt=React.createElement(c.d,{title:J.A.COMMON.UTILITIES},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_suggestions",label:J.A.COMMON.POSTS_SUGGESTIONS,value:"1",checked:x,description:J.A.COMMON.POSTS_SUGGESTIONS_HELP,onChange:ht}))),bt=React.createElement(c.d,{title:J.A.COMMON.ADVISOR},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_advisor",label:J.A.COMMON.ENABLE,value:"1",checked:P,description:J.A.HELP.ADVISOR,onChange:ht}))),ft=React.createElement(c.d,{title:J.A.COMMON.GENERATORS},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_generator_content",label:J.A.COMMON.CONTENT_GENERATOR,value:"1",checked:B,description:J.A.COMMON.CONTENT_GENERATOR_HELP,onChange:ht}),React.createElement(m.R,{name:"module_generator_images",label:J.A.COMMON.IMAGES_GENERATOR,value:"1",checked:H,description:J.A.COMMON.IMAGES_GENERATOR_HELP,onChange:ht}))),wt=React.createElement(c.d,{title:J.A.COMMON.PLAYGROUND},React.createElement(m.R,{name:"module_playground",label:J.A.COMMON.ENABLE,value:"1",checked:U,description:J.A.COMMON.PLAYGROUND_HELP,onChange:ht})),_t=React.createElement(c.d,{title:J.A.COMMON.FORMS},React.createElement(m.R,{name:"module_forms",label:J.A.COMMON.ENABLE,value:"1",checked:L,requirePro:!0,isPro:v.zN,description:J.A.COMMON.FORMS_HELP,onChange:ht})),Ct=React.createElement(c.d,{title:J.A.COMMON.SEARCH},React.createElement(m.R,{name:"module_search",label:J.A.COMMON.ENABLE,value:"1",checked:te,description:J.A.COMMON.SEARCH_HELP,onChange:ht})),Tt=React.createElement(c.d,{title:J.A.COMMON.FINETUNES},React.createElement(m.R,{name:"module_finetunes",label:J.A.COMMON.ENABLE,value:"1",checked:D,description:React.createElement(React.Fragment,null,React.createElement(Ee,{disabled:!D,style:{marginRight:3}}),J.A.HELP.FINETUNES),onChange:ht})),At=React.createElement(c.d,{title:React.createElement(React.Fragment,null,J.A.COMMON.INSIGHTS)},React.createElement(m.R,{name:"module_statistics",label:J.A.COMMON.ENABLE,value:"1",checked:F,requirePro:!0,isPro:v.zN,description:J.A.COMMON.INSIGHTS_HELP,onChange:ht})),Nt=React.createElement(c.d,{title:React.createElement(React.Fragment,null,J.A.COMMON.MODERATION)},React.createElement(m.R,{name:"module_moderation",label:J.A.COMMON.ENABLE,value:"1",checked:q,description:React.createElement(React.Fragment,null,React.createElement(Ee,{disabled:!q,style:{marginRight:3}}),J.A.COMMON.MODERATION_HELP),onChange:ht})),Ot=React.createElement(c.d,{title:React.createElement(React.Fragment,null,J.A.COMMON.TRANSCRIPTION)},React.createElement(m.R,{name:"module_transcription",label:J.A.COMMON.ENABLE,value:"1",checked:X,description:J.A.COMMON.TRANSCRIPTION_HELP,onChange:ht})),It=React.createElement(c.d,{title:React.createElement(React.Fragment,null,J.A.COMMON.KNOWLEDGE)},React.createElement(m.R,{name:"module_embeddings",label:J.A.COMMON.ENABLE,value:"1",checked:K,requirePro:!0,isPro:v.zN,description:(0,y.FE)(J.A.COMMON.KNOWLEDGE_HELP),onChange:ht})),St=React.createElement(c.d,{title:React.createElement(React.Fragment,null,J.A.COMMON.ASSISTANTS,React.createElement("small",{style:{position:"relative",top:-3,fontSize:8}}," BETA"))},React.createElement(m.R,{name:"module_assistants",label:J.A.COMMON.ENABLE,value:"1",checked:Y,requirePro:!0,isPro:v.zN,description:React.createElement(React.Fragment,null,React.createElement(Ee,{disabled:!Y,style:{marginRight:3}}),J.A.HELP.ASSISTANTS),onChange:ht})),Mt=React.createElement(c.d,{title:J.A.COMMON.ORCHESTRATION},React.createElement(m.R,{name:"module_orchestration",label:J.A.COMMON.ENABLE,value:"1",checked:ae,requirePro:!0,isPro:v.zN,description:J.A.COMMON.ORCHESTRATION_HELP,onChange:ht})),kt=React.createElement(c.d,{title:J.A.COMMON.CHATBOT},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"module_chatbots",label:J.A.COMMON.ENABLE,value:"1",checked:ee,description:J.A.COMMON.CHATBOT_HELP,onChange:ht}))),xt=React.createElement(c.d,{title:"Cross-Site"},React.createElement(m.R,{name:"module_cross_site",label:J.A.COMMON.ENABLE,value:"1",checked:ne,requirePro:!0,isPro:v.zN,description:"Enable chatbots to be embedded on external websites with domain-based access control.",onChange:ht})),Pt=React.createElement(c.d,{title:J.A.COMMON.QUERIES_DATA},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"statistics_data",label:J.A.COMMON.ENABLE,value:"1",checked:He,description:J.A.HELP.QUERIES_DATA,onChange:ht}))),Lt=React.createElement(c.d,{title:J.A.COMMON.QUERIES_FORMS_DATA},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"statistics_forms_data",label:J.A.COMMON.ENABLE,value:"1",checked:je,description:J.A.HELP.QUERIES_FORMS_DATA,onChange:ht}))),Dt=React.createElement(c.d,{title:J.A.COMMON.INTRO_MESSAGE},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"intro_message",label:J.A.COMMON.ENABLE,value:"1",checked:Ge,description:J.A.HELP.INTRO_MESSAGE,onChange:ht}))),Ft=React.createElement(c.d,{title:"Forms Editor"},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"forms_editor",label:J.A.COMMON.ENABLE,value:"1",checked:!!L&&!!le,disabled:!L,description:L?"Enable the Forms Editor (adds a new tab). Build forms with blocks and shortcodes.":"Enable the Forms module to use the Forms Editor.",onChange:ht}))),Ut=React.createElement(c.d,{title:J.A.COMMON.CHATBOT_SELECT},React.createElement(j.u,{scrolldown:!0,name:"chatbot_select",value:null==w?void 0:w.chatbot_select,onChange:ht,description:J.A.HELP.CHATBOT_SELECT},React.createElement(j.j,{key:"tabs",value:"tabs",label:J.A.COMMON.TABS}),React.createElement(j.j,{key:"dropdown",value:"dropdown",label:J.A.COMMON.DROPDOWN}))),Bt=React.createElement(c.d,{title:J.A.COMMON.WEBSPEECH_API},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"speech_recognition",label:J.A.COMMON.SPEECH_RECOGNITION,value:"1",checked:Fe,description:J.A.HELP.SPEECH_RECOGNITION,onChange:ht})),React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"speech_synthesis",label:J.A.COMMON.SPEECH_SYNTHESIS+" (SOON)",value:"1",disabled:!0,checked:Ue,description:J.A.HELP.SPEECH_SYNTHESIS,onChange:ht}))),jt=React.createElement(c.d,{title:J.A.COMMON.GDPR_CONSENT},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"chatbot_gdpr_consent",label:J.A.COMMON.ENABLE,value:"1",checked:Pe,description:J.A.HELP.GDPR_CONSENT,onChange:ht}))),Gt=React.createElement(c.d,{title:J.A.COMMON.GDPR_TEXT},React.createElement(G.A,{name:"chatbot_gdpr_text",value:Le,onBlur:ht})),$t=React.createElement(c.d,{title:J.A.COMMON.GDPR_BUTTON},React.createElement(G.A,{name:"chatbot_gdpr_button",value:De,onBlur:ht})),Wt=React.createElement(c.d,{title:J.A.COMMON.STREAMING},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"ai_streaming",label:J.A.COMMON.ENABLE,value:"1",checked:Te,description:J.A.HELP.STREAMING,onChange:ht}))),zt=React.createElement(c.d,{title:"Responses API"},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"ai_responses_api",label:J.A.COMMON.ENABLE,value:"1",checked:Ae,description:"Use OpenAI's new Responses API for improved performance and features. This is recommended, but can be disabled if you experience issues.",onChange:ht}))),Vt=React.createElement(c.d,{title:J.A.COMMON.PRIVACY_FIRST},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"privacy_first",label:J.A.COMMON.ENABLE,value:"1",checked:Oe,description:J.A.HELP.PRIVACY_FIRST,onChange:ht}))),Kt=React.createElement(c.d,{title:J.A.COMMON.DISCUSSIONS},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"chatbot_discussions",label:J.A.COMMON.ENABLE,value:"1",checked:xe,description:J.A.HELP.DISCUSSIONS,onChange:ht}))),Yt=React.createElement(c.d,{title:J.A.COMMON.SUMMARIZE},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"chatbot_discussions_titling",label:J.A.COMMON.ENABLE,value:"1",checked:null==w?void 0:w.chatbot_discussions_titling,description:J.A.HELP.DISCUSSION_SUMMARY,onChange:ht}))),Xt=React.createElement(c.d,{title:J.A.COMMON.PAGING||"Paging"},React.createElement(j.u,{scrolldown:!0,name:"chatbot_discussions_paging",value:(null==w?void 0:w.chatbot_discussions_paging)||10,onChange:ht,description:J.A.HELP.DISCUSSIONS_PAGING||"Number of discussions to display per page"},React.createElement(j.j,{value:"None",label:"None"}),React.createElement(j.j,{value:5,label:"5 per Page"}),React.createElement(j.j,{value:10,label:"10 per Page"}),React.createElement(j.j,{value:15,label:"15 per Page"}),React.createElement(j.j,{value:20,label:"20 per Page"}),React.createElement(j.j,{value:30,label:"30 per Page"}),React.createElement(j.j,{value:50,label:"50 per Page"}))),Qt=React.createElement(c.d,{title:J.A.COMMON.REFRESH_INTERVAL||"Refresh Interval"},React.createElement(j.u,{scrolldown:!0,name:"chatbot_discussions_refresh_interval",value:(null==w?void 0:w.chatbot_discussions_refresh_interval)||5,onChange:ht,description:J.A.HELP.DISCUSSIONS_REFRESH_INTERVAL||"How often to refresh the discussions list (in seconds)"},React.createElement(j.j,{value:1,label:"1 second"}),React.createElement(j.j,{value:2,label:"2 seconds"}),React.createElement(j.j,{value:5,label:"5 seconds"}),React.createElement(j.j,{value:10,label:"10 seconds"}),React.createElement(j.j,{value:30,label:"30 seconds"}),React.createElement(j.j,{value:60,label:"60 seconds"}),React.createElement(j.j,{value:120,label:"120 seconds"}),React.createElement(j.j,{value:"Manual",label:"Manually"}),React.createElement(j.j,{value:"Never",label:"Never"}))),Jt=React.createElement(c.d,{title:"Metadata Bar"},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"chatbot_discussions_metadata_enabled",label:J.A.COMMON.ENABLE,value:"1",checked:null==w?void 0:w.chatbot_discussions_metadata_enabled,description:"Display a metadata bar under discussion titles.",onChange:ht}))),Zt=null!=w&&w.chatbot_discussions_metadata_enabled?React.createElement(c.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==w?void 0:w.chatbot_discussions_metadata_start_date,description:"Show when the discussion was created.",onChange:ht}),React.createElement(m.R,{name:"chatbot_discussions_metadata_last_update",label:"Last Update",value:"1",checked:null==w?void 0:w.chatbot_discussions_metadata_last_update,description:"Show when the discussion was last modified.",onChange:ht}),React.createElement(m.R,{name:"chatbot_discussions_metadata_message_count",label:"Message Count",value:"1",checked:null==w?void 0:w.chatbot_discussions_metadata_message_count,description:"Show the number of messages in the discussion.",onChange:ht}))):null,ea=React.createElement(c.d,{title:J.A.COMMON.SYNTAX_HIGHLIGHT},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"syntax_highlight",label:J.A.COMMON.ENABLE,value:"1",checked:Me,description:J.A.HELP.SYNTAX_HIGHLIGHT,onChange:ht}))),ta=React.createElement(c.d,{title:J.A.COMMON.EVENT_LOGS},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"event_logs",label:J.A.COMMON.ENABLE,value:"1",checked:ke,disabled:!Te,description:J.A.HELP.EVENT_LOGS,onChange:ht}))),aa=React.createElement(c.d,{title:J.A.COMMON.PUBLIC_API},React.createElement(m.R,{name:"public_api",label:J.A.COMMON.ENABLE,value:"1",checked:Be,description:J.A.HELP.PUBLIC_API,onChange:ht}),Be&&React.createElement(ao,{value:`${v.gh}/mwai/v1/`},React.createElement("span",null,C,React.createElement("span",{className:"highlight"},"/wp-json/mwai/v1/")))),na=React.createElement(c.d,{title:J.A.COMMON.BEARER_TOKEN},React.createElement(G.A,{name:"public_api_bearer_token",value:null==w?void 0:w.public_api_bearer_token,description:be(J.A.HELP.BEARER_TOKEN,J.A.HELP.BEARER_TOKEN_URL,J.A.HELP.BEARER_TOKEN_LINK_TEXT),onBlur:ht})),la=React.createElement(c.d,{title:"SSE Endpoint"},React.createElement(m.R,{name:"module_mcp",label:J.A.COMMON.ENABLE,value:"1",checked:null==w?void 0:w.module_mcp,description:"Enable the /wp-json/mcp/v1/sse endpoint. Check the labs/mcp.md for more information.",onChange:ht}),(null==w?void 0:w.module_mcp)&&React.createElement(React.Fragment,null,React.createElement(ao,{value:`${v.gh}/mcp/v1/sse`},React.createElement("span",null,C,React.createElement("span",{className:"highlight"},"/wp-json/mcp/v1/sse"))))),ra=React.createElement(c.d,{title:J.A.COMMON.BEARER_TOKEN},React.createElement(G.A,{name:"mcp_bearer_token",value:null==w?void 0:w.mcp_bearer_token,description:(0,y.FE)(J.A.HELP.MCP_BEARER_TOKEN),onBlur:ht})),oa=React.createElement(c.d,{title:"No-Auth URL"},React.createElement(m.R,{name:"mcp_noauth_url",label:J.A.COMMON.ENABLE,value:"1",checked:null==w?void 0:w.mcp_noauth_url,disabled:!(null!=w&&w.module_mcp&&null!=w&&w.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:ht}),(null==w?void 0:w.mcp_noauth_url)&&(null==w?void 0:w.module_mcp)&&(null==w?void 0:w.mcp_bearer_token)&&React.createElement(ao,{value:`${v.gh}/mcp/v1/${w.mcp_bearer_token}/sse`},React.createElement("span",null,C,"/wp-json/mcp/v1/",React.createElement("span",{className:"highlight"},w.mcp_bearer_token),"/sse"))),ia=React.createElement(c.d,{title:"Tuned Core"},React.createElement(m.R,{name:"mcp_core",label:"Enable (Recommended)",value:"1",checked:null==w?void 0:w.mcp_core,description:"A highly-optimized MCP integration providing a streamlined, AI-focused layer tailored specifically for ease-of-use, performance, and clarity.",onChange:ht})),sa=React.createElement(c.d,{title:"Tuned Plugins"},React.createElement(m.R,{name:"mcp_plugins",label:J.A.COMMON.ENABLE,value:"1",checked:null==w?void 0:w.mcp_plugins,requirePro:!0,isPro:v.zN,description:"Create, fork, edit, and manage plugins directly through MCP.",onChange:ht})),ca=React.createElement(c.d,{title:"Tuned Themes"},React.createElement(m.R,{name:"mcp_themes",label:J.A.COMMON.ENABLE,value:"1",checked:null==w?void 0:w.mcp_themes,requirePro:!0,isPro:v.zN,description:"Enables theme management, editing, and the ability to fork existing themes into new ones to effortlessly integrate additional features.",onChange:ht})),da=React.createElement(c.d,{title:"Dynamic REST"},React.createElement(m.R,{name:"mcp_dynamic_rest",label:J.A.COMMON.ENABLE,value:"1",checked:null==w?void 0:w.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:ht})),ua=React.createElement(c.d,{title:"Local Upload"},React.createElement(j.u,{scrolldown:!0,name:"image_local_upload",value:null==w?void 0:w.image_local_upload,onChange:ht,description:"Files can be stored either in the filesystem or the Media Library."},React.createElement(j.j,{key:"uploads",value:"uploads",label:"Filesystem"}),React.createElement(j.j,{key:"library",value:"library",label:"Media Library"}))),pa=React.createElement(c.d,{title:"Remote Upload"},React.createElement(j.u,{scrolldown:!0,name:"image_remote_upload",value:null==w?void 0:w.image_remote_upload,onChange:ht,description:"Select Upload Data for private sites; Share URLs requires your WordPress to be online and reachable."},React.createElement(j.j,{key:"data",value:"data",label:"Upload Data"}),React.createElement(j.j,{key:"url",value:"url",label:"Share URLs"}))),Ea=React.createElement(c.d,{title:"Expiration"},React.createElement(j.u,{scrolldown:!0,name:"image_expires",value:(null==w?void 0:w.image_expires)??"never",onChange:ht,description:"Uploaded files will be deleted after a certain amount of time. This also affects files uploaded to OpenAI via the Assistants."},React.createElement(j.j,{key:300,value:300,label:"5 minutes"}),React.createElement(j.j,{key:3600,value:3600,label:"1 hour"}),React.createElement(j.j,{key:21600,value:21600,label:"6 hours"}),React.createElement(j.j,{key:86400,value:86400,label:"1 day"}),React.createElement(j.j,{key:604800,value:604800,label:"1 week"}),React.createElement(j.j,{key:2592e3,value:2592e3,label:"1 month"}),React.createElement(j.j,{key:"Never",value:"never",label:"Never"}))),ga=React.createElement(c.d,{title:"Local Download"},React.createElement(j.u,{scrolldown:!0,name:"image_local_download",value:(null==w?void 0:w.image_local_download)??null,onChange:ht,description:"Files can be stored either in the filesystem or the Media Library."},React.createElement(j.j,{key:null,value:null,label:"None"}),React.createElement(j.j,{key:"uploads",value:"uploads",label:"Filesystem"}),React.createElement(j.j,{key:"library",value:"library",label:"Media Library"}))),ha=React.createElement(c.d,{title:"Expiration"},React.createElement(j.u,{scrolldown:!0,name:"image_expires_download",value:(null==w?void 0:w.image_expires_download)??"never",onChange:ht,description:"Downloaded files will be deleted after a certain amount of time."},React.createElement(j.j,{key:300,value:300,label:"5 minutes"}),React.createElement(j.j,{key:3600,value:3600,label:"1 hour"}),React.createElement(j.j,{key:21600,value:21600,label:"6 hours"}),React.createElement(j.j,{key:86400,value:86400,label:"1 day"}),React.createElement(j.j,{key:604800,value:604800,label:"1 week"}),React.createElement(j.j,{key:2592e3,value:2592e3,label:"1 month"}),React.createElement(j.j,{key:"Never",value:"never",label:"Never"}))),Ra=React.createElement(c.d,{title:J.A.COMMON.DEV_TOOLS},React.createElement(m.R,{name:"module_devtools",label:J.A.COMMON.ENABLE,value:"1",checked:Z,description:J.A.HELP.DEV_TOOLS,onChange:ht})),ya=React.createElement(c.d,{title:J.A.COMMON.SHORTCODES},React.createElement(m.R,{name:"resolve_shortcodes",label:J.A.COMMON.RESOLVE,value:"1",checked:et,description:J.A.HELP.RESOLVE_SHORTCODE,onChange:ht})),va=React.createElement(c.d,{title:J.A.COMMON.CONTEXT_MAX_LENGTH},React.createElement(G.A,{name:"context_max_length",value:$e,type:"number",step:"1",description:J.A.HELP.CONTEXT_MAX_LENGTH,onBlur:ht})),ba=React.createElement(c.d,{title:J.A.COMMON.BANNED_WORDS},React.createElement(G.A,{id:"banned_words",name:"banned_words",value:Xe,isCommaSeparatedArray:!0,description:J.A.HELP.BANNED_WORDS,onBlur:ht})),fa=React.createElement(c.d,{title:J.A.COMMON.WORD_BOUNDARIES},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"ignore_word_boundaries",label:J.A.COMMON.IGNORE,value:"1",checked:Qe,description:J.A.HELP.WORD_BOUNDARIES,onChange:ht}))),wa=React.createElement(c.d,{title:J.A.COMMON.MODEL},React.createElement(j.u,{scrolldown:!0,name:"ai_default_model",value:ue,onChange:ht},at.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name}))))),_a=React.createElement(c.d,{title:J.A.COMMON.MODEL},React.createElement(j.u,{scrolldown:!0,name:"ai_fast_default_model",value:de,onChange:ht},at.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name}))))),Ca=React.createElement(c.d,{title:J.A.COMMON.MODEL},React.createElement(j.u,{scrolldown:!0,name:"ai_embeddings_default_model",value:Re,onChange:ht},it.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name}))))),Ta=React.createElement(c.d,{title:J.A.COMMON.DIMENSIONS},React.createElement(j.u,{scrolldown:!0,name:"ai_embeddings_default_dimensions",value:null!=w&&w.ai_embeddings_default_dimensions?parseInt(w.ai_embeddings_default_dimensions):null,onChange:ht},dt.map(((e,t)=>React.createElement(j.j,{key:e,value:e,label:0===t?`${e} (Native)`:e}))),React.createElement(j.j,{key:null,value:null,label:"Not Set"}))),Aa=React.createElement(c.d,{title:J.A.COMMON.MODEL},React.createElement(j.u,{scrolldown:!0,name:"ai_vision_default_model",value:ge,onChange:ht},nt.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name}))))),Na=React.createElement(c.d,{title:J.A.COMMON.MODEL},React.createElement(j.u,{scrolldown:!0,name:"ai_audio_default_model",value:we,onChange:ht},lt.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name}))))),Oa=React.createElement(c.d,{title:J.A.COMMON.MODEL},React.createElement(j.u,{scrolldown:!0,name:"ai_json_default_model",value:Ce,onChange:ht},rt.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name}))))),Ia=React.createElement(c.d,{title:J.A.COMMON.MODEL},React.createElement(j.u,{scrolldown:!0,name:"ai_images_default_model",value:ve,onChange:ht},ot.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name}))))),Sa=React.createElement(c.d,{title:J.A.COMMON.BANNED_IPS},React.createElement(G.A,{id:"banned_ips",name:"banned_ips",value:We,isCommaSeparatedArray:!0,description:J.A.HELP.BANNED_IPS,onBlur:ht})),Ma=React.createElement(c.d,{title:"Available Languages"},React.createElement(G.A,{id:"custom_languages",name:"custom_languages",value:Je,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:ht})),ka=React.createElement(c.d,{title:J.A.COMMON.PLAYGROUND},React.createElement(m.R,{label:J.A.COMMON.ENABLE,value:"1",checked:null==Ze?void 0:Ze.playground,onChange:e=>{const t={...Ze,playground:e};ht(t,"admin_bar")}})),xa=React.createElement(c.d,{title:J.A.COMMON.GENERATE_CONTENT},React.createElement(m.R,{label:J.A.COMMON.ENABLE,value:"1",checked:null==Ze?void 0:Ze.content_generator,onChange:e=>{const t={...Ze,content_generator:e};ht(t,"admin_bar")}})),Pa=React.createElement(c.d,{title:J.A.COMMON.GENERATE_IMAGES},React.createElement(m.R,{label:J.A.COMMON.ENABLE,value:"1",checked:null==Ze?void 0:Ze.images_generator,onChange:e=>{const t={...Ze,images_generator:e};ht(t,"admin_bar")}})),La=React.createElement(c.d,{title:"AI Engine"},React.createElement(m.R,{label:J.A.COMMON.ENABLE,value:"1",checked:null==Ze?void 0:Ze.settings,onChange:e=>{const t={...Ze,settings:e};ht(t,"admin_bar")}})),Da=React.createElement("div",null,React.createElement(qt,{options:w})),Fa=React.createElement(React.Fragment,null,React.createElement($.g,{height:5}),React.createElement(c.d,{title:J.A.COMMON.ENVIRONMENT},React.createElement(j.u,{scrolldown:!0,name:"ai_default_env",value:me,onChange:ht},re.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name})))))),Ua=React.createElement(React.Fragment,null,React.createElement($.g,{height:5}),React.createElement(c.d,{title:J.A.COMMON.ENVIRONMENT},React.createElement(j.u,{scrolldown:!0,name:"ai_fast_default_env",value:ce,onChange:ht},re.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name})))))),Ba=React.createElement(React.Fragment,null,React.createElement($.g,{height:5}),React.createElement(c.d,{title:J.A.COMMON.ENVIRONMENT},React.createElement(j.u,{scrolldown:!0,name:"ai_embeddings_default_env",value:he,onChange:ht},st.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name})))))),Ha=React.createElement(React.Fragment,null,React.createElement($.g,{height:5}),React.createElement(c.d,{title:J.A.COMMON.ENVIRONMENT},React.createElement(j.u,{scrolldown:!0,name:"ai_vision_default_env",value:pe,onChange:ht},re.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name})))))),ja=React.createElement(React.Fragment,null,React.createElement($.g,{height:5}),React.createElement(c.d,{title:J.A.COMMON.ENVIRONMENT},React.createElement(j.u,{scrolldown:!0,name:"ai_audio_default_env",value:fe,onChange:ht},re.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name})))))),Ga=React.createElement(React.Fragment,null,React.createElement($.g,{height:5}),React.createElement(c.d,{title:J.A.COMMON.ENVIRONMENT},React.createElement(j.u,{scrolldown:!0,name:"ai_json_default_env",value:_e,onChange:ht},re.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name})))))),$a=React.createElement(React.Fragment,null,React.createElement($.g,{height:5}),React.createElement(c.d,{title:J.A.COMMON.ENVIRONMENT},React.createElement(j.u,{scrolldown:!0,name:"ai_images_default_env",value:ye,onChange:ht},re.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name})))))),Wa=React.createElement(j.u,{scrolldown:!0,name:"embeddings_default_env",value:Se,onChange:ht},Ie.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name})))),za=React.createElement(c.d,{title:J.A.COMMON.PLUGIN_DATA},React.createElement(d.E,{max:"1"},React.createElement(m.R,{name:"clean_uninstall",label:J.A.COMMON.DELETE_ALL,description:J.A.COMMON.PLUGIN_DATA_DESCRIPTION,value:"1",checked:tt,onChange:ht})));return React.createElement(u.z,null,React.createElement(Ne,{options:w}),React.createElement(E.N,null,React.createElement(E.Y,{fullWidth:!0},React.createElement(oe,{options:w}),Ge&&React.createElement(W.L,null,((e,t)=>{const{sprintf:a}=wp.i18n,n=t.map((({url:e,text:t,target:a="_blank"})=>`<a href="${e}" target="${a}">${t}</a>`));return(0,y.FE)(a(e,...n))})(J.A.SETTINGS.INTRO,[{url:J.A.SETTINGS.INTRO_TUTORIAL_URL,text:J.A.SETTINGS.INTRO_TUTORIAL_TEXT},{url:J.A.SETTINGS.INTRO_DOCS_URL,text:J.A.SETTINGS.INTRO_DOCS_TEXT},{url:J.A.SETTINGS.INTRO_ADDONS_URL,text:J.A.SETTINGS.INTRO_ADDONS_TEXT},{url:J.A.SETTINGS.INTRO_DISCLAIMER_URL,text:J.A.SETTINGS.INTRO_DISCLAIMER_TEXT}])),React.createElement(g._,{keepTabOnReload:!0},React.createElement(g.V,{key:"dashboard",title:J.A.COMMON.DASHBOARD},React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{busy:mt,title:J.A.COMMON.CLIENT_MODULES,className:"primary"},kt,_t,Ct),React.createElement(R.z,{busy:mt,title:J.A.COMMON.SERVER_MODULES,className:"primary"},At,It,Mt,Tt,Nt,St),React.createElement(R.z,{busy:mt,title:J.A.COMMON.BACKEND_MODULES,className:"primary"},bt,ft,wt,vt,Ot)),React.createElement(E.Y,{minimal:!0},React.createElement(R.z,{busy:mt,title:J.A.COMMON.USAGE,className:"primary"},Da)))),ee&&React.createElement(g.V,{key:"chatbots",title:J.A.COMMON.CHATBOTS},React.createElement(Cr,{options:w,updateOption:ht,busy:mt})),te&&React.createElement(g.V,{key:"search",title:J.A.COMMON.SEARCH},React.createElement(co,{options:w,updateOption:ht,busy:mt})),ee&&xe&&React.createElement(g.V,{key:"discussions",title:J.A.COMMON.DISCUSSIONS},React.createElement(ma,null)),L&&le&&React.createElement(g.V,{key:"forms",title:J.A.COMMON.FORMS},React.createElement(Fo,null)),F&&React.createElement(g.V,{key:"insights",title:J.A.COMMON.INSIGHTS},React.createElement(Dr,{options:w,updateOption:ht,busy:mt})),K&&React.createElement(g.V,{key:"knowledge",title:J.A.COMMON.KNOWLEDGE},React.createElement(Ht,{options:w,updateEnvironment:yt,updateOption:ht})),D&&React.createElement(g.V,{key:"finetunes",title:J.A.COMMON.FINETUNES},React.createElement(pt,{options:w,updateOption:ht,refreshOptions:Et})),q&&React.createElement(g.V,{key:"moderation",title:J.A.COMMON.MODERATION},React.createElement(gt,{options:w,updateOption:ht,busy:mt})),X&&React.createElement(g.V,{key:"transcription",title:J.A.COMMON.TRANSCRIPTION},React.createElement(ro,{options:w,updateOption:ht})),React.createElement(g.V,{key:"settings",title:J.A.COMMON.SETTINGS},React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,fullWidth:!0,style:{paddingLeft:10,paddingTop:10}},React.createElement(z.o,{inversed:!0,name:"quicklinks",value:T,onChange:A},React.createElement(z.K,{title:"AI",value:"ai"}),ee&&React.createElement(z.K,{title:"Chatbot",value:"chatbot"}),K&&React.createElement(z.K,{title:"Knowledge",value:"knowledge"}),ae&&React.createElement(z.K,{title:"Orchestration",value:"orchestration"}),Y&&React.createElement(z.K,{title:J.A.COMMON.ASSISTANTS,value:"assistants"}),React.createElement(z.K,{title:"Files & Media",value:"files"}),React.createElement(z.K,{title:J.A.COMMON.REMOTE_ACCESS,value:"remote"}),React.createElement(z.K,{title:"Add-ons",value:"addons"}),React.createElement(z.K,{title:J.A.COMMON.OTHERS,value:"others"}))),React.createElement(E.Y,{minimal:!0,fullWidth:!0},React.createElement(E.N,null,React.createElement(E.Y,{minimal:!0,fullWidth:"assistants"===T},"ai"===T&&React.createElement(React.Fragment,null,React.createElement(Kr,{busy:mt,options:w,environments:re,updateEnvironment:async(e,t)=>{const a=re.map((a=>a.id===e?{...a,...t}:a));ht(a,"ai_envs")},updateOption:ht}),React.createElement("div",{style:{padding:"0px 10px 15px 10px",marginTop:13,marginBottom:5}},React.createElement(s.s,{h2:!0,style:{color:"white",marginBottom:15}},J.A.COMMON.AI_ENVIRONMENT_DEFAULTS),React.createElement(g._,{inversed:!0},React.createElement(g.V,{key:"ai",title:J.A.COMMON.DEFAULT,busy:mt},Fa,wa,React.createElement($.g,{height:15}),React.createElement(s.s,{p:!0,style:{margin:0}},"The default environment for general AI queries and content generation.")),React.createElement(g.V,{key:"fast",title:J.A.COMMON.DEFAULT_FAST,busy:mt},Ua,_a,React.createElement($.g,{height:15}),React.createElement(s.s,{p:!0,style:{margin:0}},"Used for quick tasks like generating discussion titles and optimizing search queries.")),React.createElement(g.V,{key:"vision",title:J.A.COMMON.VISION,busy:mt},Ha,Aa,React.createElement($.g,{height:15}),React.createElement(s.s,{p:!0,style:{margin:0}},"For analyzing and understanding images, including image-to-text capabilities.")),React.createElement(g.V,{key:"images",title:J.A.COMMON.IMAGES,busy:mt},$a,Ia,React.createElement($.g,{height:15}),React.createElement(s.s,{p:!0,style:{margin:0}},"For generating images using AI models like DALL-E.")),React.createElement(g.V,{key:"embeddings",title:J.A.COMMON.EMBEDDINGS,busy:mt},Ba,Ca,Ta,React.createElement($.g,{height:15}),React.createElement(s.s,{p:!0,style:{margin:0}},"For creating text embeddings used in semantic search and similarity matching.")),React.createElement(g.V,{key:"audio",title:J.A.COMMON.AUDIO,busy:mt},ja,Na,React.createElement($.g,{height:15}),React.createElement(s.s,{p:!0,style:{margin:0}},"For audio transcription and speech-to-text processing.")),React.createElement(g.V,{key:"json",title:J.A.COMMON.JSON,busy:mt},Ga,Oa,React.createElement($.g,{height:15}),React.createElement(s.s,{p:!0,style:{margin:0}},"For structured data generation and JSON output formatting."))))),"knowledge"===T&&K&&React.createElement(React.Fragment,null,React.createElement(Gr,{busy:mt,options:w,environments:Ie,updateEnvironment:yt,updateOption:ht}),React.createElement(R.z,{busy:mt,title:J.A.COMMON.EMBEDDINGS_ENVIRONMENT_DEFAULT,className:"primary"},Wa)),"chatbot"===T&&React.createElement(React.Fragment,null,React.createElement(R.z,{busy:mt,title:J.A.COMMON.CHATBOT,className:"primary"},Kt,xt,ea,Bt,jt,Pe&&React.createElement(React.Fragment,null,Gt,$t))),"assistants"===T&&Y&&React.createElement(React.Fragment,null),"orchestration"===T&&React.createElement(React.Fragment,null,React.createElement(Qr,{busy:mt,options:w,mcpServers:se,updateMCPServer:async(e,t)=>{const a=se.map((a=>a.id===e?{...a,...t}:a));ht(a,"mcp_envs")},updateOption:ht})),"files"===T&&React.createElement(R.z,{busy:mt,title:"Uploaded by Users",className:"primary"},ua,pa,Ea),"others"===T&&React.createElement(R.z,{busy:mt,title:J.A.COMMON.USER_INTERFACE,className:"primary"},Dt,Ft),"others"===T&&F&&React.createElement(R.z,{busy:mt,title:J.A.COMMON.INSIGHTS,className:"primary"},React.createElement("p",null,J.A.HELP.STATISTICS),Pt,Lt),"others"===T&&React.createElement(R.z,{busy:mt,title:J.A.COMMON.ADMIN_BAR,className:"primary"},La,ka,xa,Pa),"others"===T&&React.createElement(R.z,{busy:mt,title:J.A.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()=>{S("exportSettings");try{const e=await qe(),t=await ze(),a={chatbots:e,themes:t,options:await Ye()},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{S(!1)}},style:{flex:2}},"Export Settings"),React.createElement(h.M,{className:"danger",onClick:async()=>{S("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 Ke(a),await Ve(n),await ut(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{S(!1)}},style:{flex:1}},"Import Settings"),React.createElement(h.M,{className:"danger",onClick:async()=>{if(window.confirm(J.A.ALERTS.ARE_YOU_SURE)){S(!0);try{await(0,y.IU)(`${v.y0}/settings/reset`,{method:"POST",nonce:v.ok}),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{S(!1)}}},style:{flex:1}},"Reset Settings")),React.createElement(h.M,{className:"danger",onClick:async()=>{if(window.confirm(J.A.COMMON.RESET_USAGE_SURE)){S(!0);try{await ht([],"ai_usage"),await ht([],"ai_usage_daily");const e=await(0,y.IU)(`${v.y0}/settings/options`,{method:"GET",headers:{"X-WP-Nonce":v.ok}});e.success&&e.options&&(ut(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{S(!1)}}},disabled:mt,fullWidth:!0},J.A.COMMON.RESET," ",J.A.COMMON.USAGE)),"remote"===T&&React.createElement(React.Fragment,null,React.createElement(R.z,{busy:mt,title:"Model Context Protocol (MCP)",className:"primary"},React.createElement("p",null,be(J.A.HELP.MCP_INTRO,J.A.HELP.MCP_TUTORIAL_URL,J.A.HELP.MCP_TUTORIAL_TEXT)),React.createElement($.g,null),la,ra,oa,(null==w?void 0:w.module_mcp)&&React.createElement(React.Fragment,null,ia,sa,ca,da)),(null==w?void 0:w.module_mcp)&&React.createElement(Zr,{options:w}))),React.createElement(E.Y,{minimal:!0},"ai"===T&&React.createElement(React.Fragment,null,React.createElement(R.z,{busy:mt,title:J.A.COMMON.GENERAL,className:"primary"},Wt,ta,zt)),"knowledge"===T&&K&&React.createElement(React.Fragment,null,React.createElement(R.z,{className:"primary",title:J.A.COMMON.DEFAULTS},React.createElement("p",null,React.createElement("strong",null,J.A.COMMON.AI_ENVIRONMENT,":")," ",null!=w&&w.ai_embeddings_default_env?null==w||null===(e=w.ai_envs)||void 0===e||null===(e=e.find((e=>e.id===w.ai_embeddings_default_env)))||void 0===e?void 0:e.name:(null==w||null===(t=w.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,J.A.COMMON.EMBEDDINGS_MODEL,":")," ",(null==w?void 0:w.ai_embeddings_default_model)||"text-embedding-3-small",React.createElement("br",null),React.createElement("strong",null,J.A.COMMON.DIMENSIONS,":")," ",(null==w?void 0:w.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:M},React.createElement(c.d,{title:"Method"},React.createElement(j.u,{scrolldown:!0,value:(null==w||null===(a=w.embeddings_settings)||void 0===a?void 0:a.search_method)||"simple",onChange:e=>Rt({...w.embeddings_settings,search_method:e}),description:"Choose how to build search queries from conversations."},React.createElement(j.j,{value:"simple",label:"Simple"}),React.createElement(j.j,{value:"context_aware",label:"Context-Aware"}),React.createElement(j.j,{value:"smart_search",label:"Smart Search"}))),("context_aware"===(null==w||null===(n=w.embeddings_settings)||void 0===n?void 0:n.search_method)||"smart_search"===(null==w||null===(l=w.embeddings_settings)||void 0===l?void 0:l.search_method)||"user_messages"===(null==w||null===(r=w.embeddings_settings)||void 0===r?void 0:r.search_method)||"ai_optimized"===(null==w||null===(o=w.embeddings_settings)||void 0===o?void 0:o.search_method))&&React.createElement(c.d,{title:"Messages"},React.createElement(G.A,{type:"number",value:(null==w||null===(i=w.embeddings_settings)||void 0===i?void 0:i.context_messages)||10,min:1,max:20,onFinalChange:e=>Rt({...w.embeddings_settings,context_messages:parseInt(e)||10}),description:"Number of recent messages to consider for context."})),("smart_search"===(null==w||null===(p=w.embeddings_settings)||void 0===p?void 0:p.search_method)||"ai_optimized"===(null==w||null===(b=w.embeddings_settings)||void 0===b?void 0:b.search_method))&&React.createElement(c.d,{title:"Instructions"},React.createElement(m.R,{name:"include_instructions",label:"Enable",value:"1",checked:(null==w||null===(f=w.embeddings_settings)||void 0===f?void 0:f.include_instructions)||!1,onChange:()=>{var e;return Rt({...w.embeddings_settings,include_instructions:!(null!=w&&null!==(e=w.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,"Simple:")," Uses only the last message for context (default, fastest)."),React.createElement("li",null,React.createElement("strong",null,"Context-Aware:")," Includes more conversation history for better context."),React.createElement("li",null,React.createElement("strong",null,"Smart Search:")," 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",rel:"noreferrer"},"documentation")," or join the ",React.createElement("a",{href:"https://discord.gg/bHDGh38",target:"_blank",rel:"noreferrer"},"Discord Server")," to discuss embeddings with other users.")))),"chatbot"===T&&React.createElement(React.Fragment,null,xe&&React.createElement(R.z,{busy:mt,title:J.A.COMMON.DISCUSSIONS,className:"primary"},Yt,Xt,Qt,Jt,Zt),React.createElement(R.z,{busy:mt,title:J.A.COMMON.USER_INTERFACE,className:"primary"},Ut)),"orchestration"===T&&React.createElement(R.z,{className:"primary",title:"Information"},React.createElement("p",null,(0,y.FE)(J.A.SETTINGS.ORCHESTRATION_INFO))),"remote"===T&&React.createElement(R.z,{busy:mt,title:J.A.COMMON.REST_API,className:"primary"},React.createElement("p",null,be(J.A.HELP.REST_API_INTRO,J.A.HELP.REST_API_MAKE_URL,J.A.HELP.REST_API_MAKE_TEXT)),React.createElement($.g,null),aa,na),"remote"===T&&React.createElement(R.z,{className:"primary",title:"Information",style:{marginTop:10}},React.createElement("div",{style:{marginBottom:20}},React.createElement("p",null,"AI Engine provides two ways to integrate with external systems: REST API and Model Context Protocol (MCP)."),React.createElement("p",{style:{marginTop:15}},React.createElement("strong",null,"REST API")),React.createElement("p",{style:{marginTop:5}},"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."),React.createElement("p",{style:{marginTop:15}},React.createElement("strong",null,"MCP (Model Context Protocol)")),React.createElement("p",{style:{marginTop:10,marginBottom:5}},React.createElement("em",null,"How to Use:")),React.createElement("ul",{style:{marginTop:5,marginLeft:20}},React.createElement("li",null,React.createElement("strong",null,"Claude Desktop App:")," Use the ",React.createElement("code",null,"mcp.js")," relay. Check ",React.createElement("code",null,"/labs/mcp.md")," for setup instructions."),React.createElement("li",null,React.createElement("strong",null,"OpenAI/ChatGPT:")," Limited to Deep Research mode with only ",React.createElement("code",null,"search")," and ",React.createElement("code",null,"fetch")," tools (requires Tuned Core enabled)."),React.createElement("li",null,React.createElement("strong",null,"Claude.ai:")," Currently not supported.")),React.createElement("p",{style:{marginTop:10,marginBottom:5}},React.createElement("em",null,"Available Tools:")),React.createElement("ul",{style:{marginTop:5,marginLeft:20}},React.createElement("li",null,React.createElement("strong",null,"Full access (Claude Desktop):")," WordPress management, plugin/theme development, SEO Engine, Code Engine snippets"),React.createElement("li",null,React.createElement("strong",null,"Limited access (OpenAI):")," Only search and fetch WordPress posts/pages")),React.createElement("p",{style:{marginTop:10,marginBottom:5}},React.createElement("em",null,"For Developers:")),React.createElement("p",{style:{marginTop:5}},"Extend functionality using ",React.createElement("code",null,"mwai_mcp_tools")," and ",React.createElement("code",null,"mwai_mcp_callback")," filters. See ",React.createElement("code",null,"dev-notes.md")," for details."),React.createElement("p",{style:{marginTop:15}},React.createElement("strong",null,"Note:")," This makes WordPress an MCP server. For connecting TO external MCP servers, use the Orchestration module."))),"files"===T&&React.createElement(R.z,{busy:mt,title:"Generated by AI",className:"primary"},ga,null!==(null==w?void 0:w.image_local_download)&&ha),"others"===T&&React.createElement(R.z,{busy:mt,title:J.A.COMMON.ADVANCED,className:"primary"},ya,va,Ra,za),"others"===T&&React.createElement(R.z,{busy:mt,title:"Languages",className:"primary"},Ma),"others"===T&&React.createElement(R.z,{busy:mt,title:J.A.COMMON.SECURITY,className:"primary"},Vt,ba,(null==Xe?void 0:Xe.length)>0&&fa,Sa)))),"addons"===T&&React.createElement(E.Y,{minimal:!0,fullWidth:!0,style:{paddingLeft:10,paddingRight:10,marginTop:-20}},React.createElement(Go,{addons:null==w?void 0:w.addons,updateOption:ht})),"assistants"===T&&Y&&React.createElement(E.Y,{minimal:!0,fullWidth:!0,style:{paddingLeft:10,paddingRight:10,marginTop:-20}},React.createElement(s.s,{h2:!0,style:{color:"white"}},J.A.COMMON.ASSISTANTS),React.createElement(ho,{options:w,refreshOptions:Et})))),Z&&React.createElement(g.V,{key:"devtools",title:J.A.COMMON.DEV_TOOLS},React.createElement(Ur,{options:w,setOptions:_,updateOption:ht,busy:mt})),React.createElement(g.V,{key:"license",title:J.A.COMMON.LICENSE_TAB},React.createElement(Q,{domain:v.bl,prefix:v.Pl,isPro:v.am,isRegistered:v.zN}))))),React.createElement(V.n,{isOpen:N,title:J.A.COMMON.ERROR,content:N,onRequestClose:()=>O(!1),okButton:{label:"Close",onClick:()=>O(!1)}}))};var Xo=a(6087);const Qo=[{value:"informative",label:J.A.WRITING_STYLES.INFORMATIVE},{value:"descriptive",label:J.A.WRITING_STYLES.DESCRIPTIVE},{value:"creative",label:J.A.WRITING_STYLES.CREATIVE},{value:"narrative",label:J.A.WRITING_STYLES.NARRATIVE},{value:"persuasive",label:J.A.WRITING_STYLES.PERSUASIVE},{value:"reflective",label:J.A.WRITING_STYLES.REFLECTIVE},{value:"argumentative",label:J.A.WRITING_STYLES.ARGUMENTATIVE},{value:"analytical",label:J.A.WRITING_STYLES.ANALYTICAL},{value:"evaluative",label:J.A.WRITING_STYLES.EVALUATIVE},{value:"journalistic",label:J.A.WRITING_STYLES.JOURNALISTIC},{value:"technical",label:J.A.WRITING_STYLES.TECHNICAL}],Jo=[{value:"neutral",label:J.A.WRITING_TONES.NEUTRAL},{value:"formal",label:J.A.WRITING_TONES.FORMAL},{value:"assertive",label:J.A.WRITING_TONES.ASSERTIVE},{value:"cheerful",label:J.A.WRITING_TONES.CHEERFUL},{value:"humorous",label:J.A.WRITING_TONES.HUMOROUS},{value:"informal",label:J.A.WRITING_TONES.INFORMAL},{value:"inspirational",label:J.A.WRITING_TONES.INSPIRATIONAL},{value:"professional",label:J.A.WRITING_TONES.PROFESSIONAL},{value:"confluent",label:J.A.WRITING_TONES.CONFLUENT},{value:"emotional",label:J.A.WRITING_TONES.EMOTIONAL},{value:"persuasive",label:J.A.WRITING_TONES.PERSUASIVE},{value:"supportive",label:J.A.WRITING_TONES.SUPPORTIVE},{value:"sarcastic",label:J.A.WRITING_TONES.SARCASTIC},{value:"condescending",label:J.A.WRITING_TONES.CONDESCENDING},{value:"skeptical",label:J.A.WRITING_TONES.SKEPTICAL},{value:"narrative",label:J.A.WRITING_TONES.NARRATIVE},{value:"journalistic",label:J.A.WRITING_TONES.JOURNALISTIC}],Zo="",ei="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.",ti='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.',ai='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.',ni='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.',li=[{id:"default",name:"Default Template",mode:"query",model:Zo,envId:"",temperature:.8,stopSequence:"",maxTokens:2048,prompt:""},{id:"article_translator",name:"Text Translator",mode:"query",model:Zo,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:Zo,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:Zo,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:Zo,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."}],ri=[{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."}],oi=[{id:"default",name:"Default Template",mode:"single",topic:"",topics:"",context:"",topicsAreTitles:!1,title:"",sections:"",model:Zo,envId:"",temperature:.8,maxTokens:2048,sectionsCount:2,paragraphsCount:3,language:"en",customLanguage:"",writingStyle:"creative",writingTone:"cheerful",titlePromptFormat:ei,sectionsPromptFormat:ti,contentPromptFormat:ai,excerptPromptFormat:ni},{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:Zo,envId:"",temperature:.8,maxTokens:2048,sectionsCount:5,paragraphsCount:2,language:"en",customLanguage:"",writingStyle:"informative",writingTone:"informal",titlePromptFormat:ei,sectionsPromptFormat:ti,contentPromptFormat:ai,excerptPromptFormat:ni},{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:Zo,envId:"",temperature:.7,maxTokens:2048,sectionsCount:4,paragraphsCount:3,language:"en",customLanguage:"",writingStyle:"informative",writingTone:"cheerful",titlePromptFormat:ei,sectionsPromptFormat:ti,contentPromptFormat:ai,excerptPromptFormat:ni}],{useState:ii,useEffect:si,useMemo:ci}=wp.element;function di(){return(new Date).getTime().toString(36)+Math.random().toString(36).substr(2,9)}const mi="mwai_last_template_",ui=e=>{const t=[...e];return t.sort(((e,t)=>e.name.localeCompare(t.name))),t},pi=(e="playground")=>{const[t,a]=ii(),[n,l]=ii(!1),[r,i]=ii([]),{isLoading:s,data:c}=(0,o.I)({queryKey:[`templates-${e}`],queryFn:()=>(async e=>{try{const t=await(0,y.IU)(`${v.y0}/system/templates?category=${e}`,{nonce:v.ok});let a=[];"imagesGenerator"===e?a=ri:"playground"===e?a=li:"contentGenerator"===e&&(a=oi);const n=a.find((e=>"default"===e.id));return null!=t&&t.templates&&t.templates.length>0&&(a=ui(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)});si((()=>{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===v.fF||void 0===v.fF?void 0:v.fF.ai_default_env)||null;let l=(null===v.fF||void 0===v.fF?void 0:v.fF.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]),si((()=>{if(c){i(c);const t=(e=>{try{const t=`${mi}${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=c.find((e=>e.id===t))),!n){n=c.find((e=>"default"===e.id))||c[0]}a(n)}}),[c,e]);const d=async t=>{t=ui(t),i(t);try{return await(0,y.IU)(`${v.y0}/system/templates`,{method:"POST",nonce:v.ok,json:{category:e,templates:t}})}catch(e){console.error(e),alert(e.message)}},m=ci((()=>{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=`${mi}${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(J.A.COMMON.NAME,t.name||J.A.TEMPLATES.NEW_TEMPLATE_NAME);if(!e)return!1;const a={...t,id:di(),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:di(),name:e};d([...r,a]),u({...a})},b=()=>{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(J.A.TEMPLATES.DELETE_ALL_CONFIRM))return;let t=[];"imagesGenerator"===e?t=[...ri]:"playground"===e?t=[...li]:"contentGenerator"===e&&(t=[...oi]),d(t),u({...t[0]})},w=ci((()=>m&&!!t),[m,t]),_=ci((()=>t&&"default"!==t.id),[t]),C=ci((()=>t&&"default"!==t.id),[t]),T=ci((()=>React.createElement("div",{style:{margin:"0"}},React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"12px"}},React.createElement("h3",{style:{margin:0,fontSize:"14px",fontWeight:600}},J.A.TEMPLATES.TEMPLATE),React.createElement(De.S,{small:!0,onLabel:J.A.TEMPLATES.EDIT,offLabel:J.A.TEMPLATES.EDIT,width:60,onChange:l,checked:n})),s&&React.createElement("div",{style:{display:"flex",marginTop:30,justifyContent:"center"}},React.createElement(Xo.X,{type:"icon",size:"24px",color:"#2271b1"})),!s&&React.createElement(React.Fragment,null,React.createElement(j.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(j.j,{key:e.id,value:e.id,label:e.name})))),m&&React.createElement("div",{style:{display:"flex",gap:"4px",marginTop:"8px"}},React.createElement(h.M,{className:"secondary",style:{flex:1},icon:"undo",disabled:!w,onClick:p},"Undo"),React.createElement(h.M,{className:"primary",style:{flex:1},icon:"save",disabled:!w,onClick:g},"Save")),n&&React.createElement("div",{style:{marginTop:"8px"}},React.createElement("div",{style:{display:"flex",gap:"4px",justifyContent:"center"}},React.createElement(h.M,{className:"primary",rounded:!0,icon:"plus",onClick:R}),React.createElement(h.M,{className:"primary",rounded:!0,icon:"duplicate",onClick:E}),React.createElement("div",{style:{width:"12px"}}),React.createElement(h.M,{className:"secondary",rounded:!0,icon:"rename",disabled:!_,onClick:b}),React.createElement(h.M,{className:"danger",rounded:!0,icon:"delete",disabled:!C,onClick:()=>(e=>{if(!confirm(J.A.TEMPLATES.DELETE_CONFIRM))return;const t=r.filter((t=>t.id!==e.id));d([...t]),u({...t[0]})})(t)})))),n&&React.createElement("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:"1px solid #e0e0e0"}},React.createElement(h.M,{className:"danger",small:!0,style:{width:"100%"},onClick:f},"Reset All Templates")))),[r,t,n,m,w,s]);return{template:t,templates:r,clearTemplate:p,setTemplate:u,jsxTemplates:T,isEdit:n}},{useState:Ei,useMemo:gi}=wp.element,hi=e=>{const[t,a]=Ei(0),[n,l]=Ei(0),r=()=>{a(0),l(0)};return{addUsage:(n,r,o)=>{const i=e(n,r,o);l(i),a(t+i)},jsxUsageCosts:gi((()=>{let e=(0,y.FE)(J.A.COMMON.USAGE_HELP);if(!v.zN){const t=be(J.A.COMMON.USAGE_PRO_HELP,J.A.COMMON.USAGE_PRO_HELP_URL,J.A.COMMON.USAGE_PRO_HELP_LINK_TEXT);e=React.createElement(React.Fragment,null,e," ",t)}return React.createElement(React.Fragment,null,React.createElement("div",null,J.A.COMMON.SESSION,": ",React.createElement("span",{style:{float:"right"}},"$",t.toFixed(4))),React.createElement("div",null,J.A.COMMON.LAST_REQUEST,": ",React.createElement("span",{style:{float:"right"}},"$",n.toFixed(4))),React.createElement($.g,{height:15}),React.createElement("p",{style:{fontSize:11,lineHeight:1.4,opacity:.6,margin:0}},e),React.createElement($.g,{height:15}),React.createElement(h.M,{fullWidth:!0,onClick:r},J.A.COMMON.RESET_USAGE))}),[t,n])}},{useState:Ri,useEffect:yi,useRef:vi}=wp.element,bi=(0,f.Ay)(xe.m)`
.neko-textarea-container {
textarea {
color: white;
font-size: 13px;
padding: 10px;
font-family: monospace;
background: #333d4e;
border: none;
&:focus {
background-color: #333d4e;
}
}
}
`,fi=()=>{const{template:e,setTemplate:t,jsxTemplates:a}=pi("playground"),[n,l]=Ri(""),[r,o]=Ri(!1),[i,c]=Ri(""),[d,m]=Ri(),[p,g]=Ri(),[R,b]=Ri(!0),f=vi(),w=(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,A=(null==e?void 0:e.envId)??"",{calculatePrice:N,completionModels:O}=(null==e||e.stopSequence,null==e||e.maxTokens,ie(v.fF,A||null)),{addUsage:I,jsxUsageCosts:S}=hi(N),M=(null===v.fF||void 0===v.fF?void 0:v.fF.ai_envs)||[],k=(a,n)=>{const l={...e,[n]:a};"envId"===n&&""===a&&(l.model=""),t(l)},x=a=>{t({...e,prompt:a})};yi((()=>{e&&l("")}),[e]);const P=async(e=w)=>{f.current=new AbortController,o(!0),m(new Date);try{var t,a;const n=v.Td?e=>{l(e)}:null,r=await(0,_a.ti)(`${v.y0}/ai/completions`,{scope:"playground",session:v.dZ,message:e,temperature:T,envId:A,model:_,stream:v.Td},v.ok,v.Td,f.current.signal),o=!1,i=await(0,_a.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?x(e+"\n"+i.data+"\n"):l(i.data),I(_,(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(Ne,{title:J.A.COMMON.PLAYGROUND}),React.createElement(E.N,null,React.createElement(oe,{options:v.fF}),(null===v.fF||void 0===v.fF?void 0:v.fF.intro_message)&&React.createElement(E.Y,{fullWidth:!0},React.createElement(W.L,{style:{marginBottom:0}},React.createElement(s.s,{p:!0},(0,y.FE)(J.A.PLAYGROUND.INTRO)))),React.createElement(E.Y,null,React.createElement(pa,null,a),React.createElement($.g,null),React.createElement(pa,null,React.createElement(h.M,{fullWidth:!0,ai:!0,onClick:P,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}},J.A.COMMON.GENERATE))),React.createElement(E.Y,{style:{flex:3}},React.createElement(pa,null,"continuous"!==C&&React.createElement(React.Fragment,null,React.createElement(bi,{rows:12,onChange:x,value:w})),"continuous"===C&&React.createElement(React.Fragment,null,React.createElement(bi,{rows:18,onChange:x,value:w}),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(Ea,{name:"continuousEntry",value:i,onChange:c,onEnter:()=>{const e=w+"Human: "+i;x(e),c(""),P(e)},disabled:r})))),React.createElement($.g,null),(n||r)&&React.createElement(pa,null,React.createElement(_a.CI,{content:n,isStreaming:v.Td&&r}))),React.createElement(E.Y,null,React.createElement(pa,null,React.createElement(Oe,{onClick:()=>b(!R),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginTop:0,marginBottom:0}},J.A.COMMON.SETTINGS),React.createElement(ke.z,{icon:R?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),R&&React.createElement(React.Fragment,null,React.createElement($.g,{tiny:!0}),React.createElement("label",null,J.A.COMMON.ENVIRONMENT,":"),React.createElement(j.u,{scrolldown:!0,name:"envId",value:A??"",onChange:k},M.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(j.j,{value:"",label:"Default"})),React.createElement("label",null,J.A.COMMON.MODEL,":"),React.createElement(j.u,{name:"model",value:_||"",scrolldown:!0,disabled:!A,onChange:k},React.createElement(j.j,{value:"",label:A?"None":"Default"}),O.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name})))),React.createElement("label",null,J.A.COMMON.TEMPERATURE,":"),React.createElement(G.A,{name:"temperature",value:T,type:"number",onChange:e=>k(parseFloat(e),"temperature"),description:React.createElement("span",{style:{fontSize:11,opacity:.6}},J.A.HELP.TEMPERATURE)}))),React.createElement($.g,null),React.createElement(pa,null,React.createElement(Oe,null,React.createElement("h2",{style:{marginTop:0,marginBottom:0}},J.A.COMMON.USAGE)),React.createElement($.g,{tiny:!0}),S))),React.createElement(V.n,{isOpen:p,onRequestClose:()=>{g()},okButton:{onClick:()=>{g()}},title:"Error",content:React.createElement("p",null,p)}))},wi=f.Ay.div`
margin-bottom: 5px;
`,_i=f.Ay.div`
margin-top: 5px;
padding: 10px;
font-size: 14px;
cursor: pointer;
background: #dbf2ff;
&:hover {
background: #037cba;
color: white;
}
`,{useState:Ci,useEffect:Ti,useMemo:Ai}=wp.element,Ni=e=>{const{post:t,onTitleClick:a={},onClose:n={}}=e,[l,r]=Ci([]),[o,i]=Ci(!1),[s,c]=Ci(!1);Ti((()=>{t&&d(t)}),[t]);const d=async({postId:e,postTitle:t})=>{i(!0);try{var a;const t=await(0,y.IU)(`${v.y0}/ai/magic_wand`,{method:"POST",nonce:v.ok,json:{action:"suggestTitles",data:{postId:e}}});r(null===(a=t.data)||void 0===a?void 0:a.results)}catch(e){console.error(e),c(e.message)}i(!1)},m=async()=>{n(),r([]),c(),i(!1)},u=Ai((()=>o?React.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100px"}},React.createElement(Xo.X,{type:"icon",size:"32px",color:"#2271b1"})):s?React.createElement(React.Fragment,null,"Error: ",s):(null==l?void 0:l.length)>0?React.createElement(React.Fragment,null,"Pick a new title by clicking on it.",React.createElement(wi,null,l.map((e=>React.createElement(_i,{key:e,onClick:()=>{(async e=>{i(!0);try{await a(e),m()}catch(e){c(e.message)}i(!1)})(e)}},e))))):React.createElement(React.Fragment,null,"Nothing to display.")),[o,l,s]),p=Ai((()=>{const e=[];return e.push({label:"Close",onClick:m}),!o&&(null==l?void 0:l.length)>0&&e.push({label:"Try Again",onClick:()=>d(t),variant:"primary"}),e}),[o,l,t]);return React.createElement(E.N,null,React.createElement(V.n,{isOpen:t,onRequestClose:m,title:`New title for "${null==t?void 0:t.postTitle}"`,content:u,okButton:p[0],cancelButton:p[1]}))},{useState:Oi,useEffect:Ii,useMemo:Si}=wp.element,Mi=e=>{const{post:t,onExcerptClick:a={},onClose:n={}}=e,[l,r]=Oi([]),[o,i]=Oi(!1),[s,c]=Oi(!1);Ii((()=>{t&&d(t)}),[t]);const d=async({postId:e})=>{i(!0);try{var t;const a=await(0,y.IU)(`${v.y0}/ai/magic_wand`,{method:"POST",nonce:v.ok,json:{action:"suggestExcerpts",data:{postId:e}}});r(null===(t=a.data)||void 0===t?void 0:t.results)}catch(e){console.error(e),c(e.message)}i(!1)},m=async()=>{n(),r([]),c(),i(!1)},u=Si((()=>o?React.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100px"}},React.createElement(Xo.X,{type:"icon",size:"32px",color:"#2271b1"})):s?React.createElement(React.Fragment,null,"Error: ",s):(null==l?void 0:l.length)>0?React.createElement(React.Fragment,null,"Pick a new excerpt by clicking on it.",React.createElement(wi,null,l.map((e=>React.createElement(_i,{key:e,onClick:()=>{(async e=>{i(!0);try{await a(e),m()}catch(e){c(e.message)}i(!1)})(e)}},e))))):React.createElement(React.Fragment,null,"Nothing to display.")),[o,l,s]),p=Si((()=>{const e=[];return e.push({label:"Close",onClick:m}),!o&&(null==l?void 0:l.length)>0&&e.push({label:"Try Again",onClick:()=>d(t),variant:"primary"}),e}),[o,l,t]);return React.createElement(E.N,null,React.createElement(V.n,{isOpen:t,onRequestClose:m,title:`New excerpt for "${null==t?void 0:t.postTitle}"`,content:u,okButton:p[0],cancelButton:p[1]}))},{useState:ki,useEffect:xi}=wp.element,Pi=()=>{const[e,t]=ki();xi((()=>{setTimeout((()=>{document.querySelectorAll(".mwai-magic-wand-action").forEach((e=>{const t=e.querySelector(".mwai-magic-wand-trigger"),a=e.querySelector(".mwai-magic-wand-dropdown");let n;e.addEventListener("mouseenter",(()=>{clearTimeout(n),a.style.display="block"})),e.addEventListener("mouseleave",(()=>{n=setTimeout((()=>{a.style.display="none"}),200)})),t.addEventListener("click",(e=>{e.preventDefault(),e.stopPropagation()}))})),document.addEventListener("click",(e=>{if(e.target.closest(".mwai-link-title")){e.preventDefault(),e.stopPropagation();const a=e.target.closest(".mwai-link-title"),n=a.getAttribute("data-id"),l=a.getAttribute("data-title");console.log("Title click:",n,l),t({postId:n,postTitle:l,mode:"title"})}if(e.target.closest(".mwai-link-excerpt")){e.preventDefault(),e.stopPropagation();const a=e.target.closest(".mwai-link-excerpt"),n=a.getAttribute("data-id"),l=a.getAttribute("data-title");console.log("Excerpt click:",n,l),t({postId:n,postTitle:l,mode:"excerpt"})}}))}),100)}),[]);return React.createElement(r.A,null,React.createElement(E.N,null,React.createElement(Ni,{post:"title"===(null==e?void 0:e.mode)?e:null,onTitleClick:async a=>{const n=await(0,y.IU)(`${v.y0}/helpers/update_post_title`,{method:"POST",nonce:v.ok,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(Mi,{post:"excerpt"===(null==e?void 0:e.mode)?e:null,onExcerptClick:async a=>{const n=await(0,y.IU)(`${v.y0}/helpers/update_post_excerpt`,{method:"POST",nonce:v.ok,json:{postId:e.postId,excerpt:a}});if(!n.success)throw new Error(n.message);t()},onClose:()=>{t()}})))},{useState:Li,useEffect:Di,useMemo:Fi,useRef:Ui}=wp.element,Bi=()=>{const[e,t]=Li(""),[a,n]=Li(""),{template:l,setTemplate:r,clearTemplate:i,jsxTemplates:c}=pi("contentGenerator"),d=(0,je.XS)(),[p,g]=Li(!1),[R,b]=Li(),[f,w]=Li(!1),[_,C]=Li(!1),[T,A]=Li(!1),[N,O]=Li(!1),[I,S]=Li(),[M,k]=Li("post"),[x,P]=Li([]),[L,D]=Li([]),[F,U]=Li({}),B=Ui(),{isLoading:H,data:q}=(0,o.I)({queryKey:["postTypes"],queryFn:$e}),K=d.busy||p,Y=(null==l?void 0:l.title)??"",X=(null==l?void 0:l.sections)??"",Q=(null==l?void 0:l.mode)??"single",Z=(null==l?void 0:l.topic)??"",ne=(null==l?void 0:l.topics)??"",le=(null==l?void 0:l.context)??"",re=(null==l?void 0:l.model)??(null===v.fF||void 0===v.fF?void 0:v.fF.ai_default_model)??null,se=(null==l?void 0:l.sectionsCount)??2,ce=(null==l?void 0:l.paragraphsCount)??3,de=(null==l?void 0:l.writingStyle)??"creative",me=(null==l?void 0:l.writingTone)??"cheerful",ue=(null==l?void 0:l.titlePromptFormat)??"",pe=(null==l?void 0:l.sectionsPromptFormat)??"",Ee=(null==l?void 0:l.contentPromptFormat)??"",ge=(null==l?void 0:l.excerptPromptFormat)??"",he=(null==l?void 0:l.envId)??"",Re=(null==l?void 0:l.temperature)??.6,ye=(null==l||l.maxTokens,(null==l?void 0:l.topicsAreTitles)??!1),ve=!pe||!se,{completionModels:be,calculatePrice:fe}=(null==l||l.useMaxTokens,ie(v.fF,he||null)),{addUsage:we,jsxUsageCosts:_e}=hi(fe),Ce=(null===v.fF||void 0===v.fF?void 0:v.fF.ai_envs)||[],{jsxLanguageSelector:Te,currentLanguage:Ae,isCustom:Ie,currentHumanLanguage:Se}=(({disabled:e,options:t,language:a})=>{const[n,l]=te(a??"en"),r=(null==t?void 0:t.languages)||[],o=ee((()=>Object.keys(r).map((e=>({value:e,label:r[e]})))),[r]);ae((()=>{l(a)}),[a]),ae((()=>{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=ee((()=>{const e=o.find((e=>e.value===n));return e?e.label:(console.warn("A system language should be set."),"English")}),[n,o]),s=(e,t)=>{l(e,t),localStorage.setItem("mwai_preferred_language",e)};return{jsxLanguageSelector:ee((()=>React.createElement(j.u,{scrolldown:!0,name:"language",disabled:e,description:(0,y.FE)(J.A.CONTENT_GENERATOR.CUSTOM_LANGUAGE_HELP),value:n,onChange:s},o.map((e=>React.createElement(j.j,{key:e.value,value:e.value,label:e.label}))))),[n,i,o]),currentLanguage:n,currentHumanLanguage:i}})({options:v.fF,language:null==l?void 0:l.language,customLanguage:null==l?void 0:l.customLanguage}),Me=Fi((()=>(e=>{if(!e)return null;const t=e.split(" ").length,a=e.length,n=[];return a?(t<3?n.push(J.A.CONTENT_GENERATOR.TITLE_TOO_SHORT):t>8?n.push(J.A.CONTENT_GENERATOR.TITLE_TOO_LONG):a<40?n.push(J.A.CONTENT_GENERATOR.TITLE_TOO_SHORT):a>70&&n.push(J.A.CONTENT_GENERATOR.TITLE_TOO_LONG_2),n.join(" ")):void 0})(Y)),[Y]),Pe=(e,t)=>{r((a=>{const n={...a,[t]:e};return"envId"===t&&""===e&&(n.model=""),n}))};Di((()=>{const e=ne.split("\n").map((e=>e.trim())).filter((e=>!!e));P(e)}),[ne]),Di((()=>{l&&Pe("","sections")}),[Y,se]),Di((()=>{t(""),n(""),S()}),[X,ce]),Di((()=>{l&&(!Ie&&l.customLanguage&&Pe(null,"customLanguage"),Ie&&l.customLanguage!==Se&&Pe(Se,"customLanguage"),l.language!==Ae&&Pe(Ae,"language"))}),[Ie,Ae,Se]);const Le=(e,t=le)=>{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}",Se).replace("{WRITING_STYLE}",de).replace("{WRITING_TONE}",me).replace("{PARAGRAPHS_PER_SECTION}",ce).replace("{SECTIONS_COUNT}",se).replace("{CONTEXT}",a)},De=Fi((()=>{const e=(e,t)=>!!t.find((t=>t.includes(e))),t=[ue,pe,Ee,ge];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)}}),[ue,pe,Ee,ge,se,ce]),Fe=async(e,t=!1)=>{B.current||(B.current=new AbortController);try{var a,n;const t={scope:"admin-tools",envId:he||null,model:re||null,session:v.dZ,message:e,temperature:Re},l=await(0,y.IU)(`${v.y0}/ai/completions`,{method:"POST",nonce:v.ok,signal:B.current.signal,json:t});we(re,(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),b(e.message)),null}},Ue=async(e=Z,t=Y,a=!1)=>{if(!t)return void alert(J.A.CONTENT_GENERATOR.TITLE_MISSING);g(!0),U({...F,sections:new Date}),Pe("","sections");let n=pe.replace("{TITLE}",t).replace("{TOPIC}",e);n=Le(n);let l=await Fe(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&&Pe(l,"sections"),g(!1),U({...F,sections:null}),l},Be=async(e=Z,a=Y,n=X,l=!1)=>{if(!a)return void alert(J.A.CONTENT_GENERATOR.TITLE_MISSING);if(!ve&&!n)return void alert(J.A.CONTENT_GENERATOR.SECTIONS_MISSING);g(!0),U({...F,content:new Date}),t((()=>""));let r=Ee.replace("{TITLE}",a).replace("{SECTIONS}",n).replace("{TOPIC}",e);r=Le(r);let o=await Fe(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),U({...F,content:null}),o},Ge=async(e=Z,t=Y,a=!1)=>{if(!t)return void alert(J.A.CONTENT_GENERATOR.TITLE_MISSING);g(!0),U({...F,excerpt:new Date}),n((()=>""));let l=ge.replace("{TITLE}",t).replace("{TOPIC}",e);l=Le(l);const r=await Fe(l,a);return r&&n((()=>r)),g(!1),U({...F,excerpt:null}),r},We=async(e=Z,t=!1)=>{g(!0),B.current=new AbortController,U({...F,all:new Date});try{let a=e;if(!ye||!t){const n=Le(ue.replace("{TOPIC}",e));a=await Fe(n,t)}let n=null,l=null,r=null;return g(!1),a&&(Pe(a,"title"),ve||(U((e=>({...e,sections:new Date}))),n=await Ue(e,a,t),U((e=>({...e,sections:null})))),(n||ve)&&(U((e=>({...e,content:new Date}))),l=await Be(e,a,n,t),U((e=>({...e,content:null}))),l&&(U((e=>({...e,excerpt:new Date}))),r=await Ge(e,a,t),U((e=>({...e,excerpt:null})))))),{title:a,heads:n,content:l,excerpt:r}}catch(e){throw console.error(e),g(!1),U({}),e}},ze=async(t=Y,n=e,l=a,r=!1)=>{g(!0),B.current=new AbortController;try{const e=await(0,y.IU)(`${v.y0}/helpers/create_post`,{method:"POST",nonce:v.ok,signal:B.current.signal,json:{title:t,content:n,excerpt:l,postType:M}});return r||S(e.postId),e.postId}catch(e){return"AbortError"!==e.name&&(console.error(e),b(e.message)),null}finally{g(!1)}};return React.createElement(u.z,{nekoErrors:[]},React.createElement(Ne,{title:J.A.COMMON.CONTENT_GENERATOR}),React.createElement(E.N,null,React.createElement(oe,{options:v.fF}),(null===v.fF||void 0===v.fF?void 0:v.fF.intro_message)&&React.createElement(E.Y,{fullWidth:!0},React.createElement(W.L,{style:{marginBottom:0}},React.createElement(s.s,{p:!0},(0,y.FE)(J.A.CONTENT_GENERATOR.INTRO)))),React.createElement(E.Y,{style:{flex:1}},React.createElement(pa,null,c),React.createElement($.g,null),React.createElement(pa,null,React.createElement("h2",{style:{marginTop:0}},"bulk"===Q?J.A.COMMON.CONTEXT||"Context":J.A.COMMON.TOPIC),"bulk"===Q?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(xe.m,{name:"context",disabled:K||H,rows:14,value:le,onChange:Pe,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(xe.m,{name:"topic",disabled:K||H,rows:16,value:Z,onChange:Pe,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($.g,null),React.createElement(h.M,{fullWidth:!0,ai:!0,disabled:!Z||"bulk"===Q||H,isBusy:K,onClick:()=>We(),onStopClick:()=>{var e;null===(e=B.current)||void 0===e||e.abort(),g(!1),U({})},startTime:null==F?void 0:F.all,style:{height:50,fontSize:16,flex:4}},J.A.COMMON.GENERATE))),React.createElement(E.Y,{style:{flex:2}},React.createElement(z.o,{name:"mode",value:Q,disabled:K,onChange:Pe},React.createElement(z.K,{title:J.A.CONTENT_GENERATOR.SINGLE_GENERATE,value:"single"}),React.createElement(z.K,{title:J.A.CONTENT_GENERATOR.BULK_GENERATE,value:"bulk",count:x.length})),React.createElement($.g,null),"bulk"===Q&&React.createElement(pa,null,React.createElement("p",{style:{marginTop:0,marginBottom:20}},(0,y.FE)(J.A.CONTENT_GENERATOR.TOPICS_HELP)),React.createElement("div",{style:{display:"flex"}},React.createElement(h.M,{ai:!0,disabled:K||!x.length,onClick:async()=>{D([]);const e=x.map(((e,t)=>async()=>{console.log("Topic "+t);try{const{title:t,content:a,excerpt:n}=await We(e,!0);if(t&&a&&n){const l=await ze(t,a,n,!0);D((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(J.A.CONTENT_GENERATOR.BULK_ERROR_CONFIRM.replace("{MESSAGE}",e.message))||(d.stop(),d.reset(),g(!1))}return{success:!0}}));await d.start(e),d.reset()}},J.A.COMMON.GENERATE),React.createElement(He.j,{busy:d.busy,style:{marginLeft:10,flex:"auto"},value:d.value,max:d.max,onStopClick:d.stop})),React.createElement($.g,null),React.createElement("h3",null,J.A.COMMON.TOPICS),React.createElement(xe.m,{name:"topics",rows:10,value:ne,onChange:Pe,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:J.A.CONTENT_GENERATOR.USE_TOPICS_AS_TITLES,value:"1",checked:ye,onChange:Pe}),React.createElement("h3",null,J.A.CONTENT_GENERATOR.GENERATED_POSTS),!L.length&&React.createElement("i",null,J.A.CONTENT_GENERATOR.NOTHING_YET),L.length>0&&React.createElement("ul",null,L.map((e=>React.createElement("li",{key:e.postId},e.title," ",React.createElement("a",{target:"_blank",href:`/?p=${e.postId}`,rel:"noreferrer"},J.A.COMMON.VIEW)," ","or"," ",React.createElement("a",{target:"_blank",href:`/wp-admin/post.php?post=${e.postId}&action=edit`,rel:"noreferrer"},J.A.COMMON.EDIT)))))),"single"===Q&&React.createElement(pa,null,React.createElement("h2",{style:{marginTop:0}},J.A.COMMON.TITLE),React.createElement(G.A,{name:"title",disabled:K,value:Y,onChange:Pe,placeholder:"The title will appear here after clicking 'Generate'"}),Me&&React.createElement("div",{className:"information"},J.A.CONTENT_GENERATOR.ADVICE,": ",Me),pe&&React.createElement(React.Fragment,null,React.createElement($.g,null),React.createElement(Oe,null,React.createElement("h2",{style:{marginBottom:0}},J.A.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"}},J.A.CONTENT_GENERATOR.NUMBER_OF_SECTIONS,":"," "),React.createElement(j.u,{scrolldown:!0,name:"sectionsCount",disabled:K,style:{marginRight:10},value:se,description:"",onChange:Pe},[2,3,4,5,6,8,10,12].map((e=>React.createElement(j.j,{key:e,value:e,label:e}))))),se>0&&React.createElement(h.M,{ai:!0,disabled:!Y,isBusy:K,startTime:null==F?void 0:F.sections,onClick:()=>Ue()},J.A.CONTENT_GENERATOR.GENERATE_SECTIONS))),se>0&&React.createElement(React.Fragment,null,React.createElement($.g,{tiny:!0}),React.createElement(xe.m,{name:"sections",disabled:K,rows:4,value:X,description:J.A.CONTENT_GENERATOR.SECTIONS_HELP,onChange:Pe,placeholder:"Sections will appear here after clicking 'Generate'"}))),React.createElement($.g,null),React.createElement(Oe,null,React.createElement("h2",{style:{marginBottom:0}},J.A.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"}},J.A.CONTENT_GENERATOR.PARAGRAPHS_PER_SECTION,": "),React.createElement(j.u,{scrolldown:!0,name:"paragraphsCount",disabled:K,style:{marginRight:10},value:ce,description:"",onChange:Pe},[1,2,3,4,6,8,10].map((e=>React.createElement(j.j,{key:e,value:e,label:e}))))),React.createElement(h.M,{ai:!0,disabled:!Y,isBusy:K,startTime:null==F?void 0:F.content,onClick:()=>Be()},J.A.CONTENT_GENERATOR.GENERATE_CONTENT))),React.createElement($.g,{tiny:!0}),React.createElement(xe.m,{countable:"words",disabled:K,rows:12,value:e,description:J.A.CONTENT_GENERATOR.CONTENT_HELP,onChange:t,placeholder:"Your article content will appear here after clicking 'Generate'"}),React.createElement($.g,null),React.createElement(Oe,null,React.createElement("h2",{style:{marginBottom:0}},J.A.COMMON.EXCERPT),React.createElement(h.M,{ai:!0,disabled:!Y,isBusy:K,startTime:null==F?void 0:F.excerpt,onClick:()=>Ge()},J.A.CONTENT_GENERATOR.GENERATE_EXCERPT)),React.createElement($.g,{tiny:!0}),React.createElement(xe.m,{disabled:K,value:a,onBlur:n,rows:3,placeholder:"The excerpt will appear here after clicking 'Generate'"}),React.createElement($.g,null),React.createElement(h.M,{fullWidth:!0,style:{height:60,fontSize:16},onClick:()=>ze(),isBusy:K,disabled:!Y||!e},J.A.CONTENT_GENERATOR.CREATE_POST))),React.createElement(E.Y,{style:{flex:1}},React.createElement(pa,null,React.createElement("h2",{style:{marginTop:0}},J.A.COMMON.CONTENT),!De.language&&!De.writingStyle&&!De.writingTone&&!M&&React.createElement("div",{style:{fontSize:11,lineHeight:"14px"}},J.A.CONTENT_GENERATOR.CONTENT_PARAMS_INTRO),De.language&&React.createElement(React.Fragment,null,React.createElement("label",null,J.A.COMMON.LANGUAGE,":"),Te),De.writingStyle&&React.createElement(React.Fragment,null,React.createElement("label",null,J.A.CONTENT_GENERATOR.WRITING_STYLE,":"),React.createElement(j.u,{scrolldown:!0,name:"writingStyle",disabled:K,value:de,description:"",onChange:Pe},Qo.map((e=>React.createElement(j.j,{key:e.value,value:e.value,label:e.label}))))),De.writingTone&&React.createElement(React.Fragment,null,React.createElement("label",null,J.A.CONTENT_GENERATOR.WRITING_TONE,":"),React.createElement(j.u,{scrolldown:!0,name:"writingTone",disabled:K,value:me,description:"",onChange:Pe},Jo.map((e=>React.createElement(j.j,{key:e.value,value:e.value,label:e.label}))))),React.createElement(React.Fragment,null,React.createElement("label",null,J.A.COMMON.POST_TYPE,":"),React.createElement(j.u,{scrolldown:!0,disabled:K,name:"postType",onChange:k,value:M},null==q?void 0:q.map((e=>React.createElement(j.j,{key:e.type,value:e.type,label:e.name})))))),React.createElement($.g,null),React.createElement(pa,null,React.createElement(Oe,{onClick:()=>w(!f),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginBottom:0}},J.A.COMMON.MODEL),React.createElement(ke.z,{icon:f?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),f&&React.createElement(React.Fragment,null,React.createElement("label",null,J.A.COMMON.ENVIRONMENT,":"),React.createElement(j.u,{scrolldown:!0,name:"envId",value:he??"",onChange:Pe},Ce.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(j.j,{value:"",label:"Default"})),React.createElement("label",null,J.A.COMMON.MODEL,":"),React.createElement(j.u,{name:"model",value:re||"",scrolldown:!0,disabled:!he,onChange:Pe},React.createElement(j.j,{value:"",label:he?"None":"Default"}),be.map((e=>React.createElement(j.j,{key:e,value:e.model,label:e.name})))),React.createElement("label",null,J.A.COMMON.TEMPERATURE,":"),React.createElement(G.A,{name:"temperature",value:Re,type:"number",onChange:Pe,onBlur:Pe,description:J.A.HELP.TEMPERATURE}))),React.createElement($.g,null),React.createElement(pa,null,React.createElement(Oe,{onClick:()=>A(!T),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginBottom:0}},(0,y.FE)(J.A.COMMON.PROMPTS)),React.createElement(ke.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}},J.A.CONTENT_GENERATOR.PROMPTS_INTRO),React.createElement("label",null,(0,y.FE)(J.A.CONTENT_GENERATOR.PROMPT_TITLE)),React.createElement(xe.m,{disabled:K||"default"===(null==l?void 0:l.id),name:"titlePromptFormat",value:ue,onChange:Pe}),React.createElement("label",null,(0,y.FE)(J.A.CONTENT_GENERATOR.PROMPT_SECTIONS)),React.createElement(xe.m,{disabled:K||"default"===(null==l?void 0:l.id),name:"sectionsPromptFormat",value:pe,onChange:Pe}),React.createElement("label",null,(0,y.FE)(J.A.CONTENT_GENERATOR.PROMPT_CONTENT)),React.createElement(xe.m,{disabled:K||"default"===(null==l?void 0:l.id),name:"contentPromptFormat",value:Ee,onChange:Pe}),React.createElement("label",null,(0,y.FE)(J.A.CONTENT_GENERATOR.PROMPT_EXCERPT)),React.createElement(xe.m,{disabled:K||"default"===(null==l?void 0:l.id),name:"excerptPromptFormat",value:ge,onChange:Pe}))),React.createElement($.g,null),React.createElement(pa,null,React.createElement(Oe,{onClick:()=>O(!N),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginBottom:0}},J.A.COMMON.USAGE),React.createElement(ke.z,{icon:N?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),N&&React.createElement(React.Fragment,null,React.createElement($.g,{tiny:!0}),_e)))),React.createElement(V.n,{isOpen:I,onRequestClose:()=>S(),okButton:{label:J.A.CONTENT_GENERATOR.EDIT_POST,onClick:()=>{window.open(`/wp-admin/post.php?post=${I}&action=edit`,"_blank"),i(),S()}},cancelButton:{label:J.A.COMMON.CLOSE,onClick:()=>{S()}},title:J.A.CONTENT_GENERATOR.POST_CREATED,content:React.createElement("p",null,J.A.CONTENT_GENERATOR.POST_CREATED_AS_DRAFT)}),React.createElement(V.n,{isOpen:R,onRequestClose:()=>{b()},okButton:{onClick:()=>{b()}},title:J.A.COMMON.ERROR,content:React.createElement("p",null,R)}))},{useState:Hi,useEffect:ji,useMemo:Gi,useRef:$i}=wp.element,Wi=[1,2,3,4,5,6,7,8,9,10,12,14,16,18,20,40,60,80,100];const zi=f.Ay.div`
margin-bottom: 5px;
label {
margin-bottom: 5px;
display: block;
}
`,Vi=f.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"};
}
`,qi=f.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;
`,Ki=()=>{var e,t,a;const{template:n,setTemplate:l,jsxTemplates:r}=pi("imagesGenerator"),[o,i]=Hi(),c=new URLSearchParams(window.location.search).get("editId"),[d,p]=Hi(c?"edit":"generate"),[g,R]=Hi(!1),[b,f]=Hi(),[w,_]=Hi(!0),[C,T]=Hi(!1),[A,N]=Hi(!1),[O,I]=Hi(!1),[S,M]=Hi(!1),k=(null===v.fF||void 0===v.fF?void 0:v.fF.ai_envs)||[],{imageModels:x,getModel:P}=ie(v.fF,(null==n?void 0:n.envId)||null),L=P(null==n?void 0:n.model),[D,F]=Hi([]),[U,B]=Hi([]),[H,q]=Hi(),[K,Y]=Hi(""),[X,Q]=Hi(""),[Z,ee]=Hi(""),[te,ae]=Hi(""),[ne,le]=Hi(""),[re,se]=Hi([]),[ce,de]=Hi(!1),[me,ue]=Hi(null),[pe,Ee]=Hi(30),[ge,he]=Hi(!0),[Re,ye]=Hi(!0),[ve,be]=Hi({x:0,y:0,visible:!1}),fe=$i(),we=$i(),_e=$i(),Ce=($i([]),null==n?void 0:n.prompt),[Te,Ae]=Hi(1),[Se,Me]=Hi(0),[Pe,Le]=Hi(0),De=$i(),Fe=()=>{var e;null===(e=De.current)||void 0===e||e.abort(),F([]),Me(0),Le(0),T(!1)},Ue=(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}))};ji((()=>{if(H){const e=U.indexOf(H)+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}(Ce).toLowerCase()||"image")+".png";le(t),Y(`Untitled Image #${e||1}`),Q(Ce||""),ee(""),ae("")}}),[H]),ji((()=>{c&&fetch(`${v.gh}/wp/v2/media/${c}`).then((e=>e.json())).then((e=>f(e.source_url)))}),[c]),ji((()=>{if(b&&we.current&&fe.current){const e=we.current,t=fe.current;e.onload=()=>{t.width=e.naturalWidth,t.height=e.naturalHeight;t.getContext("2d").clearRect(0,0,t.width,t.height),_e.current||(_e.current=document.createElement("canvas")),_e.current.width=t.width,_e.current.height=t.height}}}),[b]),ji((()=>{if(!ce)return;const e=e=>{"["===e.key?(e.preventDefault(),Ee((e=>Math.max(5,e-5)))):"]"===e.key&&(e.preventDefault(),Ee((e=>Math.min(200,e+5))))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)}),[ce]);const je=$i();ji((()=>{if(b&&we.current&&je.current){const e=we.current,t=je.current;e.onload=()=>{t.width=e.naturalWidth,t.height=e.naturalHeight}}}),[b]);const Ge=(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()},$e=()=>{var e;if(Ce)if("edit"!==d||null!=L&&null!==(e=L.tags)&&void 0!==e&&e.includes("image-edit")){for(let e=0;e<Te;e++){const e={prompt:Ce,envId:n.envId,model:n.model,resolution:n.resolution,style:n.style};F((t=>[...t,e]))}Me((e=>e+Te))}else i("This model does not support image editing.");else console.error("Prompt is empty, cannot add to queue.")};ji((()=>{D.length>0&&!C&&(async()=>{if(0===D.length||C)return;T(!0),De.current=new AbortController;const e=D[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:v.dZ,message:e.prompt,maxResults:1,mediaId:c,local_download:null};let n;if(console.log("Image Edit Request:",{mode:d,endpoint:t,hasMask:!!me,editId:c,requestData:a}),"edit"===d&&me){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",me,"mask.png"),console.log("FormData contents:");for(let[t,a]of e.entries())console.log(t,a);if(n=await fetch(`${v.y0}/ai/${t}`,{method:"POST",headers:{"X-WP-Nonce":v.ok},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)(`${v.y0}/ai/${t}`,{method:"POST",nonce:v.ok,signal:De.current.signal,json:a});n.data&&n.data.length>0&&B((e=>[...e,n.data[0]])),F((e=>e.slice(1))),Le((e=>e+1)),1===D.length&&(Me(0),Le(0))}catch(e){"AbortError"===e.name||/aborted/i.test(e.message)||(console.error(e),i(e.message+(D.length>1?" The other tasks will continue.":"")),F((e=>e.slice(1))),Me((e=>e-1)))}finally{T(!1)}})()}),[D,C]);const We=async(e=!1)=>{N(!0);try{const t=await(0,y.IU)(`${v.y0}/helpers/create_image`,{method:"POST",nonce:v.ok,json:{url:H,title:K,description:X,caption:Z,alt:te,filename:ne}});se([...re,{id:t.attachmentId,url:H}]),e&&(window.location.href=`edit.php?page=mwai_images_generator&editId=${t.attachmentId}`),q()}catch(e){"AbortError"===e.name||/aborted/i.test(e.message)||(console.error(e),i(e.message))}finally{N(!1)}};return React.createElement(u.z,{nekoErrors:[]},React.createElement(Ne,{title:J.A.COMMON.IMAGES_GENERATOR}),React.createElement(E.N,null,React.createElement(oe,{options:v.fF}),(null===v.fF||void 0===v.fF?void 0:v.fF.intro_message)&&React.createElement(E.Y,{fullWidth:!0},React.createElement(W.L,{style:{marginBottom:0}},React.createElement(s.s,{p:!0},(0,y.FE)(J.A.COMMON.IMAGES_GENERATOR_INTRO)))),React.createElement(E.Y,{style:{flex:1}},React.createElement(pa,null,"edit"===d&&b&&React.createElement(React.Fragment,null,React.createElement(Vi,{maskMode:ce,onMouseMove:e=>{if(ce){const t=e.currentTarget.getBoundingClientRect();be({x:e.clientX-t.left,y:e.clientY-t.top,visible:!0})}},onMouseLeave:()=>be((e=>({...e,visible:!1})))},React.createElement("img",{ref:we,src:b}),React.createElement("canvas",{ref:fe,onMouseDown:e=>{if(!ce)return;const t=fe.current,a=t.getBoundingClientRect(),n=t.getContext("2d"),l=t.width/a.width,r=t.height/a.height,o=pe*l;let i=!0,s=(e.clientX-a.left)*l,c=(e.clientY-a.top)*r;const d=.5;let m=null;const u=e=>{n.save(),n.globalAlpha=e,Ge(n,s,c,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-s,g=m-c,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=s+u*a,r=c+g*a;n.save(),n.globalAlpha=.15,Ge(n,l,r,o,.5),n.restore()}s=t,c=m,p=d,E=!0}},R=()=>{i=!1,m&&cancelAnimationFrame(m),(e=>{const t=fe.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=>{ue(e)})),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",R)};document.addEventListener("mousemove",h),document.addEventListener("mouseup",R)}}),React.createElement(qi,{visible:ve.visible&&ce,style:{left:ve.x,top:ve.y,width:pe,height:pe}})),React.createElement("div",{style:{display:"flex",gap:5,marginBottom:5}},React.createElement(h.M,{onClick:()=>{if(ce){const e=fe.current;e.getContext("2d").clearRect(0,0,e.width,e.height),ue(null),de(!1)}else de(!0)},style:{flex:2}},ce?"Remove Mask":"Create Mask"),ce&&React.createElement(React.Fragment,null,React.createElement(h.M,{onClick:()=>Ee((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}},pe),React.createElement(h.M,{onClick:()=>Ee((e=>Math.min(200,e+5))),style:{flex:1},title:"Increase brush size"},"+"))),ce&&React.createElement("div",{style:{fontSize:11,opacity:.6,marginBottom:10,textAlign:"center"}},"Use [ and ] keys to adjust brush size")),"edit"!==d&&r),React.createElement($.g,null),React.createElement(pa,null,!H&&React.createElement(React.Fragment,null,React.createElement("h2",{style:{marginTop:0}},(0,y.FE)(J.A.COMMON.PROMPT)),React.createElement(xe.m,{value:Ce,onChange:e=>{l({...n,prompt:e})},rows:10,placeholder:"Enter your prompt here..."}),React.createElement($.g,{tiny:!0}),React.createElement(Oe,null,React.createElement("div",{style:{display:"flex",flexDirection:"column",flex:1}},React.createElement("div",{style:{display:"flex",gap:5}},C&&React.createElement(h.M,{disabled:!Ce,onClick:$e,style:{flex:1}},"Add to Queue"),U.length>0&&React.createElement(h.M,{onClick:()=>{B([])},style:{flex:1}},"Clear")),React.createElement("div",{style:{marginTop:5}},React.createElement(j.u,{scrolldown:!0,id:"totalImagesToGenerate",name:"totalImagesToGenerate",style:{width:"100%"},value:Te,onChange:e=>Ae(e)},Wi.map((e=>React.createElement(j.j,{key:e,id:e,value:e,label:`${e} ${e>1?"Images":"Image"}`}))))))))),React.createElement($.g,null),React.createElement(pa,null,React.createElement(h.M,{fullWidth:!0,disabled:!Ce,ai:!0,onClick:$e,onStopClick:Fe,isBusy:C,style:{height:50,fontSize:16,flex:4}},J.A.COMMON.GENERATE))),React.createElement(E.Y,{style:{flex:2}},React.createElement(z.o,{value:d,onChange:e=>{"generate"===e?location.href="edit.php?page=mwai_images_generator":"edit"===e&&(c?p("edit"):R(!0))}},React.createElement(z.K,{title:"Create",value:"generate"}),React.createElement(z.K,{title:"Editor",value:"edit"})),React.createElement($.g,null),React.createElement(He.j,{busy:C,value:Pe,max:Se,onStopClick:Fe,status:()=>`${Pe} / ${Se}`}),React.createElement($.g,null),React.createElement("div",null,React.createElement(V.n,{isOpen:!!H,title:K||"Image Preview",size:"larger",onRequestClose:()=>q(),hideButtons:!0,content:H&&React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",marginBottom:20}},React.createElement("div",{style:{flex:2}},React.createElement("a",{href:H,target:"_blank",rel:"noreferrer"},React.createElement("img",{src:H,style:{maxWidth:"100%",maxHeight:"60vh",objectFit:"contain"}}))),React.createElement("div",{style:{flex:1,marginLeft:10,display:"flex",flexDirection:"column"}},React.createElement(zi,null,React.createElement("label",null,"Title:"),React.createElement(G.A,{value:K,onChange:Y})),React.createElement(zi,null,React.createElement("label",null,"Caption:"),React.createElement(xe.m,{value:Z,onBlur:ee,rows:2})),React.createElement(zi,null,React.createElement("label",null,"Description:"),React.createElement(xe.m,{value:X,onBlur:Q,rows:2})),React.createElement(zi,null,React.createElement("label",null,"Alternative Text:"),React.createElement(xe.m,{value:te,onBlur:ae,rows:2})),React.createElement(zi,null,React.createElement("label",null,"Filename:"),React.createElement(G.A,{value:ne,onChange:le})),React.createElement($.g,{tiny:!0}),React.createElement(h.M,{ai:!0,onClick:async()=>{M(!0);try{const e=await(0,y.IU)(`${v.y0}/helpers/generate_image_meta`,{method:"POST",nonce:v.ok,json:{url:H}});null!=e&&e.data&&(Y(e.data.title||""),Q(e.data.description||""),ee(e.data.description||""),ae(e.data.description||""),e.data.filename&&le(e.data.filename))}catch(e){"AbortError"===e.name||/aborted/i.test(e.message)||(console.error(e),i(e.message))}finally{M(!1)}},isBusy:S},"Generate Meta"),React.createElement($.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:()=>q(),secondary:!0},"Close"),React.createElement(h.M,{onClick:()=>{I(!0),We(!0).finally((()=>I(!1)))},isBusy:O,secondary:!0},"Add to Media Library & Edit"),React.createElement(h.M,{onClick:()=>We(!1),isBusy:A},"Add to Media Library")))}),!H&&React.createElement(React.Fragment,null,React.createElement(Ie,null,U.map((e=>{const t=re.find((t=>t.url===e));return React.createElement("div",{key:e,className:"image-wrapper",onClick:()=>q(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(),B(U.filter((t=>t!==e))),se(re.filter((t=>t.url!==e)))}},"×"))})),[...Array(Math.max(3-U.length,0)).keys()].map(((e,t)=>React.createElement("div",{key:t,className:"empty-image"}))))))),React.createElement(E.Y,{style:{flex:1}},React.createElement(pa,{style:{marginBottom:25}},React.createElement(Oe,{onClick:()=>he(!ge),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginTop:0,marginBottom:0}},J.A.COMMON.MODEL),React.createElement(ke.z,{icon:ge?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),ge&&React.createElement(React.Fragment,null,React.createElement($.g,{tiny:!0}),React.createElement("label",null,J.A.COMMON.ENVIRONMENT,":"),React.createElement(j.u,{scrolldown:!0,name:"envId",value:(null==n?void 0:n.envId)??"",onChange:Be},k.map((e=>React.createElement(j.j,{key:e.id,value:e.id,label:e.name}))),React.createElement(j.j,{value:"",label:"Default"})),React.createElement("label",null,J.A.COMMON.MODEL,":"),React.createElement(j.u,{scrolldown:!0,name:"model",value:(null==n?void 0:n.model)||"",disabled:!(null!=n&&n.envId),onChange:Be},React.createElement(j.j,{value:"",label:null!=n&&n.envId?"None":"Default"}),x.map((e=>React.createElement(j.j,{key:e.model,value:e.model,label:e.name})))),(null==L||null===(e=L.resolutions)||void 0===e?void 0:e.length)>0&&React.createElement(React.Fragment,null,React.createElement("label",null,J.A.COMMON.RESOLUTION,":"),React.createElement(j.u,{scrolldown:!0,name:"resolution",value:(null==n?void 0:n.resolution)||"",onChange:Be},React.createElement(j.j,{value:"",label:"Default"}),null==L||null===(t=L.resolutions)||void 0===t?void 0:t.map((e=>React.createElement(j.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(G.A,{name:"customResolution",value:null==n?void 0:n.customResolution,onChange:e=>Be(e,"customResolution")})),(null==L||null===(a=L.model)||void 0===a?void 0:a.startsWith("dall-e-3"))&&React.createElement(React.Fragment,null,React.createElement("label",null,J.A.COMMON.STYLE,":"),React.createElement(j.u,{scrolldown:!0,name:"style",value:Ue,onChange:Be},React.createElement(j.j,{key:"none",value:null,label:"None"}),React.createElement(j.j,{key:"natural",value:"natural",label:"Natural"}),React.createElement(j.j,{key:"vivid",value:"vivid",label:"Vivid"}))))),React.createElement(pa,{style:{marginBottom:25}},React.createElement(Oe,{onClick:()=>ye(!Re),style:{cursor:"pointer"}},React.createElement("h2",{style:{marginTop:0,marginBottom:0}},J.A.COMMON.SETTINGS),React.createElement(ke.z,{icon:Re?"chevron-up":"chevron-down",height:"20",style:{opacity:.7}})),Re&&React.createElement(React.Fragment,null,React.createElement($.g,{tiny:!0}),React.createElement(m.R,{id:"continuous_mode ",label:"Continuous",value:"1",checked:w,description:React.createElement("span",{style:{fontSize:11,opacity:.6}},"New images will be added to the already generated images."),onChange:_}))))),React.createElement(V.n,{isOpen:o,onRequestClose:()=>{i()},okButton:{onClick:()=>{i()}},title:"Error",content:React.createElement("p",null,o)}),React.createElement(V.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:Yi,useEffect:Xi,useMemo:Qi}=wp.element,Ji=e=>{const{isOpen:t=!1,title:a,error:n,results:l,busy:o=!1,onClick:i=(()=>{})}=e,s=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},c=Qi((()=>o?React.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100px"}},React.createElement(Xo.X,{type:"icon",size:"32px",color:"#2271b1"})):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(wi,null,l.map((e=>React.createElement(_i,{key:s(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(V.n,{isOpen:t,title:a??"Results",content:c,onRequestClose:()=>i(),okButton:{label:"Close",onClick:()=>i()}})))},{useState:Zi,useEffect:es,Fragment:ts}=wp.element,{__:as}=wp.i18n,{registerPlugin:ns}=wp.plugins,{Button:ls,ToolbarDropdownMenu:rs,ToolbarGroup:os,Spinner:is,MenuGroup:ss,MenuItem:cs}=wp.components,{BlockControls:ds}=wp.blockEditor||{},{PluginDocumentSettingPanel:ms}=wp.editor||{},{addFilter:us}=wp.hooks,{createHigherOrderComponent:ps}=wp.compose,{registerFormatType:Es}=wp.richText,{useSelect:gs}=wp.data;function hs(){const[e,t]=Zi(!1),[a,n]=Zi([]),[l,r]=Zi(""),o=gs((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"},s=e=>{e.style.opacity=1,e.style.pointerEvents="auto",e.style.userSelect="auto",e.style.animation="none"};es((()=>{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):s(t):console.warn("AI Engine: Could not find block element for",o.name,o.clientId)}),[e,o]);const c=()=>{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?s(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 s=e.attributes.content;if(s&&"object"==typeof s&&s.originalHTML){const e=document.createElement("div");return e.innerHTML=s.originalHTML,e.textContent||e.innerText||""}return s||""}},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:s}=wp.data.select("core/editor"),u=l(a()),{id:p}=s();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 b={postId:p};E?(b.json=g,b.blockType=o.name):(b.text=h,b.selectedText=R);try{const a=await(0,y.IU)(`${v.y0}/ai/magic_wand`,{method:"POST",nonce:v.ok,json:{action:e,data:b}});c(),t(!1);const{mode:l,result:r,results:i,type:s}=a.data;if("replace"===l)"json"===s&&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"!==s&&E?(console.error("AI Wand: Unexpected response type:",s),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){c(),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 ds?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(ds,null,React.createElement(os,null,React.createElement(rs,{icon:e?React.createElement(is,null):React.createElement(Ae,{icon:"wand",style:{marginRight:0}}),label:as("AI Wand")},(()=>React.createElement(React.Fragment,null,React.createElement(ss,null,React.createElement(cs,{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(cs,{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(cs,{onClick:()=>u("longerText")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Longer Text"),React.createElement("small",null,"Readibility"))),React.createElement(cs,{onClick:()=>u("shorterText")},React.createElement("div",{style:{display:"flex",flexDirection:"column"}},React.createElement("b",null,"Shorter Text"),React.createElement("small",null,"Readibility"))),React.createElement(cs,{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(ss,null,React.createElement(cs,{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(ss,null,React.createElement(cs,{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(Ji,{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([])})):null}const Rs=async(e,t)=>{if(!e)return e;const{getCurrentPost:a}=wp.data.select("core/editor"),{id:n}=a();return(await(0,y.IU)(`${v.y0}/ai/magic_wand`,{method:"POST",nonce:v.ok,json:{action:"translateSection",data:{postId:n,context:t,text:e}}})).data.result},ys=()=>{const e=null===v.fF||void 0===v.fF?void 0:v.fF.module_suggestions,[t,a]=Zi(),[n,l]=Zi();return e&&ms?React.createElement(r.A,null,React.createElement(ms,{name:"mwai-document-settings",title:React.createElement(React.Fragment,null,React.createElement(Ae,null)," AI Engine"),className:"mwai-document-settings"},React.createElement("p",null,"Suggest:"),React.createElement("div",{style:{display:"flex"}},React.createElement(ls,{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(Ae,{icon:"wand",style:{marginRight:8}})," Titles"),React.createElement(ls,{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(Ae,{icon:"wand",style:{marginRight:8}})," Excerpts")),React.createElement("div",{style:{display:"flex"}},React.createElement(ls,{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"),s="mwai-translation-progress-notice",c=e(),d=i("title"),m=ve(),u=async e=>{r(`Translating content... ${e}%`,{id:s,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"};c.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=c.length+2;let R=0,y="";try{y=await Rs(d,m),R++,n({title:y}),g&&E(g),await u(Math.round(R/h*100));for(const e of c){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 Rs(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 Rs(e,m)})}finally{c.forEach((e=>{const t=document.querySelector(`[data-block="${e.clientId}"]`);t&&E(t)})),o(s)}})()},style:{flex:1,marginTop:10,textAlign:"center"}},React.createElement(Ae,{icon:"wand",style:{marginRight:8}})," Translate Post")),React.createElement(r.A,null,React.createElement(E.N,null,React.createElement(Ni,{post:t,onTitleClick:async e=>{wp.data.dispatch("core/editor").editPost({title:e})},onClose:a}),React.createElement(Mi,{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(`${v.y0}/ai/magic_wand`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":v.ok},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 vs=()=>{ns("ai-engine-document-settings",{render:ys});const e=ps((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=gs((e=>e("core/block-editor").getSelectedBlock()),[]);return e&&e.clientId===t.clientId?React.createElement(hs,null):null};return React.createElement(ts,null,React.createElement(e,t),React.createElement(a,null))}),"withAIWand");us("editor.BlockEdit","ai-engine/ai-wand",e)};function bs(){return bs=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},bs.apply(this,arguments)}const{addFilter:fs}=wp.hooks,{useState:ws,useRef:_s,useEffect:Cs}=wp.element,{TextControl:Ts,Spinner:As,ProgressBar:Ns,ToggleControl:Os,Card:Is,CardBody:Ss}=wp.components,{dispatch:Ms}=wp.data,ks="mwai-copilot/prevent-new-block",xs=()=>{const e=e=>{const t=_s(),[a,n]=ws(!1),[l,r]=ws(""),[o,i]=ws(!1),[s,c]=ws(!1),[d,m]=ws(!1),u=wp.data.select("core/editor").getCurrentPostId(),p=async t=>{s||("Enter"===t.key?(t.preventDefault(),t.stopPropagation(),await(async t=>{const a=ve("[== CURRENT BLOCK ==]");try{i(!0);const n=await(0,y.IU)(`${v.y0}/ai/copilot`,{method:"POST",nonce:v.ok,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),Ms("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 Cs((()=>{a&&t.current&&t.current.focus()}),[a]),Cs((()=>{const e=e=>{if(a&&"Enter"===e.key)return e.preventDefault(),!1};return Ms("core/keyboard-shortcuts").registerShortcut({name:ks,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),Ms("core/keyboard-shortcuts").unregisterShortcut(ks)}}),[a]),a?React.createElement(Is,null,React.createElement(Ss,null,o?React.createElement("div",{style:{textAlign:"center",padding:20}},React.createElement(Ns,null)):React.createElement(React.Fragment,null,React.createElement(Ts,{ref:t,label:React.createElement(React.Fragment,null,React.createElement(Ae,{icon:"wand",style:{marginBottom:-4}}),"AI Copilot"),value:l,placeholder:d?"Describe the image...":"Write about...",onChange:e=>r(e),onKeyDown:p,onCompositionStart:()=>c(!0),onCompositionEnd:()=>c(!1)}),React.createElement("div",{style:{display:"flex",justifyContent:"end",marginBottom:-12}},React.createElement(Os,{label:"Image Mode",checked:d,onChange:m}))))):React.createElement("div",{onCompositionStart:()=>c(!0),onCompositionEnd:()=>c(!1),onKeyDown:e=>{var t,a;if(s)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))};fs("editor.BlockEdit","mwai-copilot/module",(t=>a=>"core/paragraph"===a.name?React.createElement(e,bs({BlockEdit:t},a)):React.createElement(t,a)));fs("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 Ps(){return Ps=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},Ps.apply(this,arguments)}const Ls=React.createElement(Ae,{icon:"ai",style:{width:20,height:20}}),Ds=({children:e,variant:t="default"})=>{const a={display:"inline-block",padding:"4px 10px",borderRadius:"8px",fontSize:"10px",lineHeight:"1.4",backgroundColor:"purple"===t?"#9b51e0":"red"===t?"#cf2e2e":"#0693e3",color:"#fff"};return React.createElement("span",{style:a},e)},Fs=f.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-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 {
}
`,Us=({children:e,type:t="",title:a="",hint:n="",isSelected:l,isDisplayed:r,...o})=>{const i=(0,je.gR)("mwai-block-container",`mwai-${t}`,{"is-selected":l,"is-meow":!0});return React.createElement(Fs,Ps({className:i},o),React.createElement("div",{className:"mwai-title-container"},React.createElement(Ae,{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))},Bs=(null===v.fF||void 0===v.fF?void 0:v.fF.chatbot_defaults)||{},{registerBlockType:Hs}=wp.blocks||{},{useMemo:js,useState:Gs,useEffect:$s}=wp.element,{PanelBody:Ws,SelectControl:zs,ToggleControl:Vs}=wp.components,{InspectorControls:qs,useBlockProps:Ks}=wp.blockEditor||{},Ys=e=>e.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`)),Xs=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=Ys(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} ${Ys(t)}="${encodeURIComponent(a)}"`),"[mwai_chatbot")}]`}},Qs=e=>{const{attributes:{chatbotId:t,isCustomChatbot:a,shortcodeParams:n},setAttributes:l,isSelected:r}=e,[o,i]=Gs((()=>Object.keys(n||{}).length?n:Bs));$s((()=>{!a||n&&Object.keys(n).length||(i(Bs),l({shortcodeParams:Bs}))}),[a]);const s=Ks(),c=js((()=>{const e=v.N6.map((e=>({label:e.name,value:e.botId})));return e.unshift({label:"None",value:null}),e}),[v.N6]),d=js((()=>v.N6.find((e=>e.botId===t))),[t]),m=js((()=>a?"Custom Chatbot":d?`Chatbot (${d.name})`:"Chatbot"),[a,t,d]);return React.createElement(React.Fragment,null,React.createElement("div",s,React.createElement(Us,{title:m,type:"chatbot",isSelected:r},a&&React.createElement(React.Fragment,null,React.createElement(xa,{shortcodeParams:o,updateShortcodeParams:(e,t)=>{const a={...o};a[t]=e,i(a),l({shortcodeParams:a})},options:v.fF,blockMode:!0})),!a&&React.createElement("p",null,"Selected chatbot: ",d?d.name:"None"))),React.createElement(qs,null,React.createElement(Ws,{title:J.A.COMMON.CHATBOT},React.createElement(Vs,{label:"Custom Chatbot",checked:a,onChange:e=>l({isCustomChatbot:e})}),!a&&c&&c.length>0&&React.createElement(zs,{label:J.A.COMMON.CHATBOT,value:t,options:c,onChange:e=>l({chatbotId:e})})),!a&&React.createElement(Ws,{title:J.A.COMMON.SETTINGS})))},Js=()=>{Hs&&Hs("ai-engine/chatbot",{title:"AI Chatbot",description:"Embed an AI Engine Chatbot in your content.",icon:Ls,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:Bs}},edit:Qs,save:Xs})},{registerBlockType:Zs}=wp.blocks||{},{useMemo:ec}=wp.element,{PanelBody:tc,SelectControl:ac,ToggleControl:nc,TextControl:lc}=wp.components,{InspectorControls:rc,useBlockProps:oc}=wp.blockEditor||{},ic=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")}]`},sc=e=>{const{attributes:{isCustomChatbot:t,chatbotId:a,customId:n,textNewChat:l},setAttributes:r,isSelected:o}=e,i=oc(),s=ec((()=>{const e=v.N6.map((e=>({label:e.name,value:e.botId})));return e.unshift({label:"None",value:""}),e}),[v.N6]),c=ec((()=>v.N6.find((e=>e.botId===a))),[a]),d=ec((()=>t?"Discussions (Custom Chatbot)":c?`Discussions (${c.name})`:"Discussions"),[t,c]);return React.createElement(React.Fragment,null,React.createElement("div",i,React.createElement(Us,{title:d,type:"discussions",isSelected:o},React.createElement("span",null,t?`Custom ID: ${n||"None"}`:`Selected chatbot: ${c?c.name:"None"}`),React.createElement("span",null,"New Chat: ",l||"Default"))),React.createElement(rc,null,React.createElement(tc,{title:"Discussions Settings"},React.createElement(nc,{label:"Custom Chatbot",checked:t,onChange:e=>r({isCustomChatbot:e})}),t?React.createElement(lc,{label:"Custom Chatbot ID",value:n,onChange:e=>r({customId:e})}):React.createElement(ac,{label:"Select Chatbot",value:a,options:s,onChange:e=>r({chatbotId:e})}),React.createElement(lc,{label:"Text for New Chat Button",value:l,onChange:e=>r({textNewChat:e})}))))},cc=()=>{Zs&&Zs("ai-engine/discussions",{title:"AI Discussions",description:"Embed AI Engine Discussions in your content.",icon:Ls,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:sc,save:ic})};function dc(){return dc=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},dc.apply(this,arguments)}const{__:mc}=wp.i18n,{registerBlockType:uc,createBlock:pc}=wp.blocks||{},{useEffect:Ec}=wp.element,{PanelBody:gc,SelectControl:hc,TextControl:Rc,Button:yc}=wp.components,{InspectorControls:vc,InnerBlocks:bc,useBlockProps:fc}=wp.blockEditor||{},{useSelect:wc,dispatch:_c}=wp.data,Cc=e=>{const t=fc.save(),{attributes:{id:a,theme:n}}=e,l=n&&"none"!==n?`mwai-${n.toLowerCase()}-theme`:"";return React.createElement("div",dc({},t,{id:`mwai-form-container-${a}`,className:`mwai-form-container ${l}`.trim(),"data-mwai-form-container":!0,"data-theme":n}),React.createElement(bc.Content,null))},Tc=e=>{const{attributes:{id:t,theme:a},setAttributes:n,clientId:l}=e,r=fc();Ec((()=>{if(!t){const e=Math.random().toString(36).substr(2,9);n({id:e})}}),[t]);const o=wc((e=>{const t=e("core/block-editor").getBlock(l);return!t||0===(t.innerBlocks||[]).length}),[l]),i=()=>"mwai-"+Math.random().toString(36).substr(2,9);return React.createElement(React.Fragment,null,React.createElement("div",r,React.createElement(Us,{title:"Container",type:"container",isDisplayed:!0},o&&React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8}},React.createElement("p",{style:{margin:0}},"This container is empty."," ",React.createElement("a",{href:"#",onClick:e=>{e&&e.preventDefault&&(e.preventDefault(),e.stopPropagation());const t=i(),a=i(),n=i(),r=pc("ai-engine/form-field",{id:t,type:"input",label:"English Word",name:"WORD",placeholder:"Enter an English word",required:!0}),o=pc("ai-engine/form-output",{id:a,copyButton:!0}),s=pc("ai-engine/form-submit",{id:n,label:"Translate",message:"Translate the following English word to Japanese. Only reply with the translated word.\n\nWord: {WORD}",outputElement:`#${a}`,scope:"form"});_c("core/block-editor").insertBlocks([r,s,o],0,l)},style:{textDecoration:"underline"}},"Click here")," ","to create a Quick Start Form to test AI Forms.")),React.createElement(bc,null))),React.createElement(vc,null,React.createElement(gc,{title:J.A.COMMON.STYLE},React.createElement("p",null,"The theme will be applied to all the AI elements in this container."),React.createElement(hc,{label:"Theme",value:a,onChange:e=>n({theme:e}),options:[{label:"None",value:"none"},{label:"ChatGPT",value:"ChatGPT"},{label:"Timeless",value:"Timeless"}]}),React.createElement(Rc,{label:"ID",value:t,onChange:e=>n({id:e})}))))},Ac=()=>{uc&&uc("ai-engine/form-container",{title:"AI Form Container",description:"Container to embed the blocks relative to a specific AI Form.",icon:Ls,category:"layout",keywords:[mc("ai"),mc("openai"),mc("form")],attributes:{id:{type:"string",default:""},theme:{type:"string",default:"ChatGPT"}},edit:Tc,save:Cc,deprecated:[{attributes:{id:{type:"string",default:""},theme:{type:"string",default:"ChatGPT"}},save:e=>{const t=fc.save(),{attributes:{id:a,theme:n}}=e,l=`[mwai-form-container id="${a}" theme="${n}"]`;return React.createElement("div",dc({},t,{id:`mwai-form-container-${a}`,className:"mwai-form-container"}),l,React.createElement(bc.Content,null))}}]})},{__:Nc}=wp.i18n,{registerBlockType:Oc}=wp.blocks||{},{useEffect:Ic}=wp.element,{Button:Sc,PanelBody:Mc,TextControl:kc,SelectControl:xc,CheckboxControl:Pc}=wp.components,{useBlockProps:Lc,InspectorControls:Dc}=wp.blockEditor||{};const Fc=e=>{const{attributes:{id:t,label:a,type:n,name:l,options:r=[],placeholder:o,rows:i,defaultValue:s,maxlength:c,required:d}}=e,m=encodeURIComponent((0,y.F1)(r)),u=Lc.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}"`),s&&(p+=` default="${s}"`),c&&(p+=` maxlength="${c}"`),d&&(p+=` required="${d}"`),p+="]",React.createElement("div",u,p)},Uc=e=>{const{attributes:{id:t,type:a,name:n,options:l=[],label:r,placeholder:o,rows:i,defaultValue:s,maxlength:c,required:d},setAttributes:m,isSelected:u}=e,p=Lc();Ic((()=>{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(Us,{title:`${E=a,E.charAt(0).toUpperCase()+E.slice(1)}`,type:"field",isSelected:u,hint:React.createElement(Ds,null,"{",n,"}")},React.createElement("div",null,r),React.createElement("div",{style:{flex:"auto"}}),React.createElement("div",null,n))),React.createElement(Dc,null,React.createElement(Mc,{title:Nc("Field")},React.createElement(kc,{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(kc,{label:"Field Name",value:n,onChange:e=>m({name:e})}),React.createElement(xc,{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(kc,{label:"Placeholder",value:o,onChange:e=>m({placeholder:e})}),("input"===a||"textarea"===a)&&React.createElement(kc,{label:"Default Value",value:s,onChange:e=>m({defaultValue:e})}),("input"===a||"textarea"===a)&&React.createElement(kc,{label:"Max Length",value:c,onChange:e=>m({maxlength:e})}),"textarea"===a&&React.createElement(kc,{label:J.A.COMMON.ROWS,value:i,onChange:e=>m({rows:e}),type:"number",step:"1",min:"1",max:"100"}),React.createElement(Pc,{label:"Required",checked:d,onChange:e=>m({required:e})})),("select"===a||"radio"===a||"checkbox"===a)&&React.createElement(Mc,{title:React.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"}},React.createElement("div",null,Nc("Options")))},l.map(((e,t)=>React.createElement("div",{key:t,style:{display:"flex",marginBottom:-25}},React.createElement("div",{style:{marginRight:5}},React.createElement(kc,{style:{marginRight:10},label:"Label",isInline:!0,value:e.label,onChange:e=>{const a=[...l];a[t].label=e,m({options:a})}})),React.createElement(kc,{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(Sc,{style:{height:30},isDestructive:!0,icon:"trash",isSmall:!0,onClick:()=>{const e=[...l];e.splice(t,1),m({options:e})}}))))),React.createElement(Sc,{isPrimary:!0,style:{width:"100%",marginTop:10},onClick:()=>{const e=[...l];e.push({label:"",value:""}),m({options:e})}},"Add Option")),React.createElement(Mc,{title:J.A.COMMON.SYSTEM},React.createElement(kc,{label:"ID",value:t,onChange:e=>m({id:e})}))));var E},Bc=()=>{Oc&&Oc("ai-engine/form-field",{apiVersion:3,title:"AI Form Field",description:"An AI Field for your AI Form.",icon:Ls,category:"layout",keywords:[Nc("ai"),Nc("openai"),Nc("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:Uc,save:Fc})},{__:Hc}=wp.i18n,{registerBlockType:jc}=wp.blocks||{},{useEffect:Gc}=wp.element,{Button:$c,PanelBody:Wc,TextControl:zc,SelectControl:Vc,CheckboxControl:qc}=wp.components,{useBlockProps:Kc,InspectorControls:Yc}=wp.blockEditor||{};const Xc=e=>{const{attributes:{id:t,label:a,name:n,required:l,accept:r,customAccept:o,multiple:i}}=e,s=Kc.save(),c=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}"`),""!==c&&(d+=` accept="${c}"`),i&&(d+=' multiple="true"'),l&&(d+=' required="true"'),d+="]",React.createElement("div",s,d)},Qc=e=>{const{attributes:{id:t,label:a,name:n,required:l,accept:r,customAccept:o,multiple:i},setAttributes:s,isSelected:c}=e,d=Kc();Gc((()=>{if(!t){const e=Math.random().toString(36).substr(2,9);s({id:"mwai-"+e})}}),[t]);return React.createElement(React.Fragment,null,React.createElement("div",d,React.createElement(Us,{title:"Upload Field",type:"field",isSelected:c,hint:React.createElement(Ds,null,"{"+n+"}")},React.createElement("div",null,a),React.createElement("div",{style:{flex:"auto"}}),React.createElement("div",null,n))),React.createElement(Yc,null,React.createElement(Wc,{title:Hc("Upload Field Settings")},React.createElement(zc,{label:"Label Text",value:a,onChange:e=>{if(s({label:e}),!n||"LABEL"===n){const t=e.trim().replace(/ /g,"_").replace(/[^\w-]+/g,"").toUpperCase();t&&s({name:t})}}}),React.createElement(zc,{label:"Field Name",value:n,onChange:e=>s({name:e})}),React.createElement(Vc,{label:"Accept",value:r,onChange:e=>s({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(zc,{label:"Custom MIME Types",help:"Comma-separated list (e.g. .png,.jpg)",value:o,onChange:e=>s({customAccept:e})}),React.createElement(qc,{label:"Multiple",checked:i,onChange:e=>s({multiple:e})}),React.createElement(qc,{label:"Required",checked:l,onChange:e=>s({required:e})})),React.createElement(Wc,{title:J.A.COMMON.SYSTEM},React.createElement(zc,{label:"ID",value:t,onChange:e=>s({id:e})}))))},Jc=()=>{jc&&jc("ai-engine/upload-field",{apiVersion:3,title:"AI Upload Field",description:"A File Upload field for your AI Form.",icon:Ls,category:"layout",keywords:[Hc("ai"),Hc("openai"),Hc("form"),Hc("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:Qc,save:Xc})},{__:Zc}=wp.i18n,{registerBlockType:ed}=wp.blocks||{},{useEffect:td}=wp.element,{PanelBody:ad,TextControl:nd,CheckboxControl:ld}=wp.components,{InspectorControls:rd,useBlockProps:od}=wp.blockEditor||{},id=e=>{const{attributes:{id:t,copyButton:a}}=e,n=od.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)},sd=e=>{const{attributes:{id:t,copyButton:a},setAttributes:n,isSelected:l}=e,r=od();return td((()=>{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(Us,{title:"Output",type:"output",isSelected:l,hint:React.createElement(Ds,{variant:"purple"},"#",t)},React.createElement("div",null),React.createElement("div",{style:{flex:"auto"}}),React.createElement("div",null,"#",t))),React.createElement(rd,null,React.createElement(ad,{title:J.A.FORMS.OUTPUT},React.createElement(ld,{label:"Copy Button",checked:a,onChange:e=>n({copyButton:e})}),React.createElement(nd,{label:"ID",value:t,onChange:e=>n({id:e})}))))},cd=()=>{ed&&ed("ai-engine/form-output",{title:"AI Form Output",description:"An Output Field for your AI Form.",icon:Ls,category:"layout",keywords:[Zc("ai"),Zc("openai"),Zc("form")],supports:{dimensions:{minHeight:!0}},attributes:{id:{type:"string",default:""},copyButton:{type:"boolean",default:!0}},edit:sd,save:id})},{__:dd}=wp.i18n,{registerBlockType:md}=wp.blocks||{},{useMemo:ud,useEffect:pd,useState:Ed}=wp.element,{PanelBody:gd,TextControl:hd,TextareaControl:Rd,SelectControl:yd,CheckboxControl:vd}=wp.components,{InspectorControls:bd,useBlockProps:fd}=wp.blockEditor||{},wd=e=>{const{attributes:{id:t,scope:a,label:n,prompt:l,message:r,outputElement:o,aiEnvId:i,embeddingsEnvId:s,index:c,namespace:d,localMemory:m,model:u,temperature:p,maxTokens:E,isAssistant:g,assistantId:h,resolution:R,mcpServers:y}}=e,v=encodeURIComponent(l),b=encodeURIComponent(r),f=fd.save(),w={id:{value:t,insertIfNull:!0},scope:{value:a,insertIfNull:!1},local_memory:{value:m,insertIfNull:!1},label:{value:n,insertIfNull:!0},prompt:{value:v,insertIfNull:!1},message:{value:b,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:s,insertIfNull:!1},embeddings_index:{value:c,insertIfNull:!1},embeddings_namespace:{value:d,insertIfNull:!1},assistant_id:{value:h,insertIfNull:!1},resolution:{value:R,insertIfNull:!1},mcp_servers:{value:y&&y.length>0?encodeURIComponent(JSON.stringify(y)):null,insertIfNull:!1}};let _=Object.entries(w).filter((([,{value:e,insertIfNull:t}])=>!!e||t)).reduce(((e,[t,{value:a}])=>`${e} ${t}="${a}"`),"[mwai-form-submit");return _=`${_}]`,React.createElement("div",f,_)},_d=e=>{var t;const a=fd(),{attributes:{id:n,scope:l,label:r,message:o,model:i,temperature:s,maxTokens:c,aiEnvId:d,embeddingsEnvId:m,index:u,namespace:p,assistantId:E,resolution:g,isAssistant:h,localMemory:R,outputElement:y,placeholders:b=[],mcpServers:f=[]},setAttributes:w,isSelected:_}=e,C=ud((()=>v.fF.embeddings_envs||[]),[]),T=ud((()=>C.find((e=>e.id===m))||null),[C,m]),A=ud((()=>(null==T?void 0:T.indexes)||[]),[T]),N=ud((()=>(null==T?void 0:T.namespaces)||[]),[T]),O=ud((()=>v.fF.ai_envs||[]),[]),I=ud((()=>d||((null===v.fF||void 0===v.fF?void 0:v.fF.ai_default_env)||null)),[d,null===v.fF||void 0===v.fF?void 0:v.fF.ai_default_env]),S=ud((()=>i||((null===v.fF||void 0===v.fF?void 0:v.fF.ai_default_model)||null)),[i,null===v.fF||void 0===v.fF?void 0:v.fF.ai_default_model]),{models:M,getModel:k}=ie(v.fF,I),x=k(S),P=null==x||null===(t=x.features)||void 0===t?void 0:t.includes("text-to-image"),L=ud((()=>{var e;return(null==x||null===(e=x.tags)||void 0===e?void 0:e.includes("mcp"))||!1}),[x]),D=(null===v.fF||void 0===v.fF||v.fF.module_orchestration,ud((()=>(null===v.fF||void 0===v.fF?void 0:v.fF.mcp_envs)||[]),[])),F=ud((()=>O.find((e=>e.id===I))||null),[O,I]),U=ud((()=>(null==F?void 0:F.assistants)||[]),[F]),B=ud((()=>U.find((e=>e.id===E))||null),[U,E]);pd((()=>{!d&&!i||F||w({aiEnvId:null,model:null})}),[d]),pd((()=>{(m||u||p)&&!T&&w({embeddingsEnvId:null,index:null,namespace:null})}),[m]),pd((()=>{B&&B.model&&B.model!==i&&w({model:B.model})}),[B]),pd((()=>{l||w({scope:"form"})}),[l]),pd((()=>{h||w({assistantId:""})}),[h]),pd((()=>{if(!n){const e=Math.random().toString(36).substr(2,9);w({id:"mwai-"+e})}}),[n]),pd((()=>{d||""===i||w({model:""})}),[d]),pd((()=>{const e=o.match(/{([^}]+)}/g);if(e){const t=e.map((e=>e.replace("{","").replace("}","")));t.join(",")!==b.join(",")&&w({placeholders:t})}else w({placeholders:[]})}),[o]);const H=ud((()=>b?b.length:0),[b]),j=ud((()=>{const e=U.map((e=>({label:e.name,value:e.id})));return e.unshift({label:"None",value:""}),e}),[U]),G=ud((()=>{const e=M.map((e=>({label:e.rawName,value:e.model})));return e.unshift({label:"Default",value:""}),e}),[M]),$=ud((()=>{var e;if(!x||!P)return[];const t=(null==x||null===(e=x.resolutions)||void 0===e?void 0:e.map((e=>({label:e.label,value:e.name}))))||[];return t.unshift({label:"None",value:""}),t}),[x,P]),W=ud((()=>{const e=A.map((e=>({label:e.name,value:e.name})));return e.unshift({label:"None",value:""}),e}),[A]),z=ud((()=>{const e=O.map((e=>({label:e.name,value:e.id})));return e.unshift({label:"Default",value:""}),e}),[O]),V=ud((()=>{const e=C.map((e=>({label:e.name,value:e.id})));return e.unshift({label:"None",value:""}),e}),[C]),q=ud((()=>{const e=N.map((e=>({label:e,value:e})));return e.unshift({label:"None",value:""}),e}),[N]),K=ud((()=>0===H?"N/A":React.createElement(Ds,null,H," field",H>1?"s":"")),[H]);return React.createElement(React.Fragment,null,React.createElement("div",a,React.createElement(Us,{title:"Submit",type:"submit",isSelected:_,hint:React.createElement(React.Fragment,null,"IN:"," ",K," ","OUT:"," ",React.createElement(Ds,{variant:"purple"},y||"N/A"))},"Input Fields: ",b.join(", "),React.createElement("br",null),"Prompt: ",o,React.createElement("br",null),"Output Element: ",y)),React.createElement(bd,null,React.createElement(gd,{title:J.A.COMMON.OUTPUT},React.createElement(hd,{label:J.A.COMMON.LABEL,value:r,onChange:e=>w({label:e})}),React.createElement(Rd,{label:J.A.COMMON.PROMPT,value:o,onChange:e=>w({message:e}),help:J.A.FORMS.PROMPT_INFO}),React.createElement(hd,{label:J.A.FORMS.OUTPUT_ELEMENT,value:y,onChange:e=>w({outputElement:e}),help:J.A.FORMS.OUTPUT_ELEMENT_INFO})),React.createElement(gd,{title:J.A.COMMON.MODEL_PARAMS},O&&O.length>0&&React.createElement(yd,{label:J.A.COMMON.ENVIRONMENT,value:d,options:z,onChange:e=>w({aiEnvId:e}),help:!d&&I?(()=>{const e=O.find((e=>e.id===I));return e?`→ ${e.name}`:null})():null}),O&&O.length>0&&React.createElement(vd,{label:"Assistant Mode",checked:h,onChange:e=>w({isAssistant:e})}),h&&U&&U.length>0&&React.createElement(React.Fragment,null,React.createElement(yd,{label:J.A.COMMON.ASSISTANT,value:E,options:j,onChange:e=>w({assistantId:e})})),!h&&React.createElement(React.Fragment,null,M&&M.length>0&&React.createElement(yd,{label:J.A.COMMON.MODEL,value:i,options:G,disabled:!d,onChange:e=>w({model:e}),help:!i&&""===d&&S?`→ ${S}`:null}),!P&&React.createElement(React.Fragment,null,React.createElement(hd,{label:J.A.COMMON.TEMPERATURE,value:s,onChange:e=>w({temperature:parseFloat(e)}),type:"number",step:"0.1",min:"0",max:"1",help:J.A.HELP.TEMPERATURE}),React.createElement(hd,{label:J.A.COMMON.MAX_TOKENS,value:c,onChange:e=>w({maxTokens:parseInt(e)}),type:"number",step:"16",min:"32",max:"4096",help:React.createElement(Ra,{model:x,maxTokens:c,onRecommendedClick:e=>w({maxTokens:e})})})),P&&React.createElement(React.Fragment,null,React.createElement(yd,{label:J.A.COMMON.RESOLUTION,value:g,options:$,onChange:e=>w({resolution:e})})))),!P&&React.createElement(React.Fragment,null,React.createElement(gd,{title:J.A.COMMON.CONTEXT_PARAMS},C&&C.length>0&&React.createElement(yd,{label:J.A.COMMON.EMBEDDINGS_ENV,value:m,options:V,disabled:!(null!=V&&V.length),onChange:e=>w({embeddingsEnvId:e})}),A&&A.length>0&&React.createElement(yd,{label:J.A.COMMON.EMBEDDINGS_INDEX,value:u,options:W,disabled:!(null!=V&&V.length),onChange:e=>w({index:e})}),"pinecone"===(null==T?void 0:T.type)&&N&&N.length>0&&React.createElement(yd,{label:J.A.COMMON.NAMESPACE,value:p,options:q,disabled:!(null!=V&&V.length),onChange:e=>w({namespace:e})}))),(L||f.length>0)&&D.length>0&&React.createElement(gd,{title:J.A.COMMON.MCP_SERVERS||"MCP Servers"},D.map((e=>React.createElement(vd,{key:e.id,label:React.createElement(React.Fragment,null,React.createElement("span",null,e.name),e.description&&React.createElement("small",{style:{marginLeft:10,opacity:.7}},e.description)),checked:f.some((t=>t.id===e.id)),onChange:t=>{const a=t?[...f,{id:e.id}]:f.filter((t=>t.id!==e.id));w({mcpServers:a})}}))),!L&&f.length>0&&React.createElement("p",{style:{color:"#ff6b6b",marginTop:10,fontWeight:"bold"}},"Note: The selected model does not support MCP servers.")),React.createElement(gd,{title:J.A.COMMON.SYSTEM},React.createElement(hd,{label:"ID",value:n,onChange:e=>w({id:e})}),React.createElement(vd,{label:"Local Memory",checked:R,onChange:e=>w({localMemory:e}),help:"Store the forms data in the browser's local storage for 12 hours."}),React.createElement(hd,{label:"Scope",value:l,onChange:e=>w({scope:e}),help:"The scope of the form. Different forms can have the same scope."}))))},Cd=()=>{md&&md("ai-engine/form-submit",{title:"AI Form Submit",description:"The Submit Button for your AI Form.",icon:Ls,category:"layout",keywords:[dd("ai"),dd("openai"),dd("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},mcpServers:{type:"array",default:[]}},edit:_d,save:wd})},{__:Td}=wp.i18n,{registerBlockType:Ad}=wp.blocks||{},{useMemo:Nd,useEffect:Od}=wp.element,{PanelBody:Id,TextControl:Sd,CheckboxControl:Md}=wp.components,{InspectorControls:kd,useBlockProps:xd}=wp.blockEditor||{},Pd=e=>{const{attributes:{id:t,label:a,localMemory:n}}=e,l=xd.save();let r=`[mwai-form-reset id="${t}" label="${a}"`;return n&&(r+=' local_memory="true"'),r+="]",React.createElement("div",l,r)},Ld=e=>{const t=xd(),{attributes:{id:a,label:n,localMemory:l},setAttributes:r,isSelected:o}=e;return Od((()=>{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(Us,{title:"Reset",type:"reset",isSelected:o,hint:React.createElement(React.Fragment,null,Td("This block resets the AI form fields","ai-engine"))},Td("ID:","ai-engine")," ",a,React.createElement("br",null),Td("Label:","ai-engine")," ",n)),React.createElement(kd,null,React.createElement(Id,{title:Td("Reset Button Settings","ai-engine")},React.createElement(Sd,{label:Td("ID","ai-engine"),value:a,onChange:e=>r({id:e}),help:Td("Unique identifier. If omitted, one is auto-generated.","ai-engine")}),React.createElement(Sd,{label:Td("Label","ai-engine"),value:n,onChange:e=>r({label:e}),help:Td("Text on the reset button.","ai-engine")}),React.createElement(Md,{label:Td("Local Memory","ai-engine"),checked:l,onChange:e=>r({localMemory:e}),help:Td("Clear local storage for this form’s key when resetting.","ai-engine")}))))},Dd=()=>{Ad&&Ad("ai-engine/form-reset",{title:"AI Form Reset",description:"A reset button for your AI Form.",icon:Ls,category:"layout",keywords:[Td("ai"),Td("openai"),Td("form"),Td("reset")],supports:{dimensions:{minHeight:!1}},attributes:{id:{type:"string",default:""},label:{type:"string",default:"Reset"},localMemory:{type:"boolean",default:!1}},edit:Ld,save:Pd})};function Fd(){return Fd=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},Fd.apply(this,arguments)}const{__:Ud}=wp.i18n,{registerBlockType:Bd}=wp.blocks||{},{useEffect:Hd,useMemo:jd}=wp.element,{PanelBody:Gd,TextControl:$d,SelectControl:Wd,Button:zd}=wp.components,{InspectorControls:Vd,InnerBlocks:qd,useBlockProps:Kd}=wp.blockEditor||{},{useSelect:Yd}=wp.data,Xd=e=>{const{attributes:{id:t,conditions:a=[],logic:n="AND",conditionField:l,conditionValue:r}}=e,o=Kd.save();let i=`[mwai-form-conditional id="${t}"`;const s=a.length?a:l?[{field:l,operator:"eq",value:r}]:[];return s.length&&(i+=` conditions="${encodeURIComponent(JSON.stringify(s))}" logic="${n}"`),i+="]",React.createElement("div",Fd({},o,{id:`mwai-form-conditional-${t}`,className:"mwai-form-conditional",style:{display:"none"}}),i,React.createElement(qd.Content,null))},Qd=[{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"}],Jd=[{label:"AND",value:"AND"},{label:"OR",value:"OR"}],Zd=e=>{const{attributes:{id:t,conditions:a=[],logic:n="AND",conditionField:l,conditionValue:r},setAttributes:o,clientId:i}=e,s=Kd();Hd((()=>{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 c=Yd((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=jd((()=>{const e=c.map((e=>({label:e,value:e})));return e.unshift({label:"[N/A]",value:""}),e}),[c]);Hd((()=>{if(1===c.length&&a.some((e=>!e.field))){const e=c[0],t=a.map((t=>t.field?t:{...t,field:e}));o({conditions:t})}}),[c,a]);const m=jd((()=>0===a.length||a.some((e=>!e.field))?React.createElement(Ds,{variant:"red"},"[N/A]"):React.createElement(Ds,null,a.length," condition",a.length>1?"s":"")),[a]),u=jd((()=>{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",s,React.createElement(Us,{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(qd,null))),React.createElement(Vd,null,React.createElement(Gd,{title:J.A.COMMON.CONDITIONS},a.map(((e,t)=>React.createElement("div",{key:t,style:{marginBottom:"8px"},className:"mwai-condition-panel"},React.createElement(Gd,{title:`${J.A.COMMON.CONDITION} ${t+1}`,initialOpen:!0},React.createElement(Wd,{label:"Field",value:e.field,options:d,onChange:e=>{const n=[...a];n[t].field=e,o({conditions:n})}}),React.createElement(Wd,{label:"Operator",value:e.operator,options:Qd,onChange:e=>{const n=[...a];n[t].operator=e,o({conditions:n})}}),"empty"!==e.operator&&"not_empty"!==e.operator&&React.createElement($d,{label:"Value",value:e.value,onChange:e=>{const n=[...a];n[t].value=e,o({conditions:n})}}),React.createElement(zd,{isSecondary:!0,isDestructive:!0,icon:"trash",style:{width:"100%"},onClick:()=>{const e=a.filter(((e,a)=>a!==t));o({conditions:e})}},J.A.COMMON.REMOVE)),t<a.length-1&&React.createElement(Wd,{label:"",value:n,options:Jd,onChange:e=>o({logic:e})})))),React.createElement(zd,{isPrimary:!0,style:{width:"100%",marginBottom:"8px"},icon:"plus",onClick:()=>{const e=1===c.length?c[0]:"";o({conditions:[...a,{field:e,operator:"eq",value:""}]})}},J.A.COMMON.ADD_CONDITION),React.createElement($d,{label:"ID",value:t,onChange:e=>o({id:e})}))))},em=()=>{Bd&&Bd("ai-engine/form-conditional",{title:"AI Form Conditional",description:"Display inner blocks only when a condition is met.",icon:Ls,category:"layout",keywords:[Ud("ai"),Ud("openai"),Ud("form")],attributes:{id:{type:"string",default:""},conditions:{type:"array",default:[]},logic:{type:"string",default:"AND"},conditionField:{type:"string",default:""},conditionValue:{type:"string",default:""}},edit:Zd,save:Xd})};var tm,am;if(null!==(tm=window.mwai)&&void 0!==tm&&tm.plugin_url&&null!==(am=window.mwai)&&void 0!==am&&am.cache_buster){const e=window.mwai.plugin_url.replace(/\/$/,"")+"/app/",t=window.mwai.cache_buster;if(a.p=e,a.p){const e=a.l;a.l=function(a,n,l,r){return a&&a.includes(".js")&&!a.includes("?")&&(a=a+"?ver="+t),e.call(this,a,n,l,r)}}}const{render:nm}=wp.element,lm=new n.E({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnMount:!1,retry:!1,placeholderData:e=>e}}}),rm=v.fF.module_chatbots,om=v.fF.module_suggestions,im=v.fF.module_forms;v.fF.forms_editor;rm&&(Js(),cc()),im&&(Bc(),Jc(),cd(),Cd(),Dd(),Ac(),em()),om&&(vs(),xs()),document.addEventListener("DOMContentLoaded",(function(){const e=document.getElementById("mwai-admin-settings");e&&nm(React.createElement(l.Ht,{client:lm},React.createElement(r.A,null,React.createElement(Yo,null))),e);const t=document.getElementById("mwai-content-generator");t&&nm(React.createElement(l.Ht,{client:lm},React.createElement(r.A,null,React.createElement(Bi,null))),t);const a=document.getElementById("mwai-image-generator");a&&nm(React.createElement(l.Ht,{client:lm},React.createElement(r.A,null,React.createElement(Ki,null))),a);const n=document.getElementById("mwai-playground");if(n&&nm(React.createElement(l.Ht,{client:lm},React.createElement(r.A,null,React.createElement(fi,null))),n),om){const e=document.getElementById("mwai-admin-postsList");e&&nm(React.createElement(r.A,null,React.createElement(Pi,null)),e)}const o=document.getElementById("meow-common-dashboard");o&&nm(React.createElement(l.Ht,{client:lm},React.createElement(r.A,null,React.createElement(H,null))),o)}))},2714:(e,t,a)=>{a.d(t,{Hm:()=>i,N6:()=>h,Pl:()=>n,Td:()=>g,Zj:()=>E,am:()=>c,bl:()=>l,c3:()=>y,dZ:()=>p,fF:()=>u,gh:()=>r,ok:()=>m,pK:()=>R,sw:()=>s,y0:()=>o,zN:()=>d});const n=mwai.prefix,l=mwai.domain,r=mwai.rest_url.replace(/\/+$/,""),o=mwai.api_url.replace(/\/+$/,""),i=mwai.plugin_url.replace(/\/+$/,""),s=mwai.user_data,c=!0===mwai.is_pro||1===mwai.is_pro||"1"===mwai.is_pro,d=c&&(!0===mwai.is_registered||1===mwai.is_registered||"1"===mwai.is_registered);let m=mwai.rest_nonce;const u=mwai.options,p=mwai.session,E=mwai.themes,g=!!mwai.stream,h=mwai.chatbots,R=e=>{m=e,"undefined"!=typeof mwai&&(mwai.rest_nonce=e)},y=()=>m},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(s=0;s<deferred.length;s++){for(var[t,a,n]=deferred[s],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(s--,1);var i=a();void 0!==i&&(e=i)}}return e}n=n||0;for(var s=deferred.length;s>0&&deferred[s-1][2]>n;s--)deferred[s]=deferred[s-1];deferred[s]=[t,a,n]},__webpack_require__.F={},__webpack_require__.E=e=>{Object.keys(__webpack_require__.F).map((t=>{__webpack_require__.F[t](e)}))},__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=>({115:"premium-pdf-import",546:"premium-pdfjs"}[e]+".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 s=o[i];if(s.getAttribute("src")==e||s.getAttribute("data-webpack")==dataWebpackPrefix+a){l=s;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 c=(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(c.bind(null,void 0,{type:"timeout",target:l}),12e4);l.onerror=c.bind(null,l.onerror),l.onload=c.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__.F.j=t=>{if(!__webpack_require__.o(e,t)||void 0===e[t]){e[t]=null;var a=document.createElement("link");__webpack_require__.nc&&a.setAttribute("nonce",__webpack_require__.nc),a.rel="prefetch",a.as="script",a.href=__webpack_require__.p+__webpack_require__.u(t),document.head.appendChild(a)}},__webpack_require__.O.j=t=>0===e[t];var t=(t,a)=>{var n,l,[r,o,i]=a,s=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 c=i(__webpack_require__)}for(t&&t(a);s<r.length;s++)l=r[s],__webpack_require__.o(e,l)&&e[l]&&e[l][0](),e[l]=0;return __webpack_require__.O(c)},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,__webpack_require__.O(0,[57],(()=>{__webpack_require__.E(121),__webpack_require__.E(115)}),5);var __webpack_exports__=__webpack_require__.O(void 0,[121],(()=>__webpack_require__(1253)));__webpack_exports__=__webpack_require__.O(__webpack_exports__)})();