Current File : /home/mdkeenpw/www/wp-content/plugins/ai-engine/app/chatbot.js |
/*! For license information please see chatbot.js.LICENSE.txt */
(()=>{var __webpack_modules__={233:(e,t,n)=>{"use strict";n.d(t,{A:()=>s});const{__:a,sprintf:i}=wp.i18n,r={};r.COMMON={GENERAL:a("General","ai-engine"),MODULES:a("Modules","ai-engine"),CLIENT_MODULES:a("Client Modules","ai-engine"),BACKEND_MODULES:a("Admin Modules","ai-engine"),SERVER_MODULES:a("Server Modules","ai-engine"),ADVISOR:a("Advisor","ai-engine"),SETTINGS:a("Settings","ai-engine"),CHATBOT:a("Chatbot","ai-engine"),CHATBOTS:a("Chatbots","ai-engine"),CHATBOT_HELP:a("Build intelligent conversational experiences with fully customizable AI-powered chatbots.","ai-engine"),INSIGHTS:a("Insights","ai-engine"),STYLE:a("Style","ai-engine"),ENABLE:a("Enable","ai-engine"),NAME:a("Name","ai-engine"),SUBMIT:a("Submit","ai-engine"),MODEL:a("Model","ai-engine"),AI_MODEL:a("AI Model","ai-engine"),TEMPERATURE:a("Temperature","ai-engine"),MAX_TOKENS:a("Max Tokens","ai-engine"),CONTEXT_MAX_LENGTH:a("Context Max Length","ai-engine"),STOP_SEQUENCE:a("Stop Sequence","ai-engine"),MODE:a("Mode","ai-engine"),CONTEXT:a("Context","ai-engine"),IMAGES_NUMBER:a("Number of Images","ai-engine"),AVATAR:a("Avatar","ai-engine"),AI_NAME:a("AI Name","ai-engine"),GUEST_NAME:a("Guest Name","ai-engine"),USER_NAME:a("User Name","ai-engine"),PLACEHOLDER:a("Placeholder","ai-engine"),START_SENTENCE:a("Start Sentence","ai-engine"),SEND:a("Send","ai-engine"),CLEAR:a("Clear","ai-engine"),CLOSE:a("Close","ai-engine"),VIEW:a("View","ai-engine"),EDIT:a("Edit","ai-engine"),SYSTEM_NAME:a("System Name","ai-engine"),ID:a("ID","ai-engine"),SCOPE:a("Scope","ai-engine"),POPUP:a("Popup","ai-engine"),POSITION:a("Position","ai-engine"),CENTER:a("Center","ai-engine"),OPEN_DELAY:a("Open Delay","ai-engine"),WINDOW_ANIMATION:a("Window Animation","ai-engine"),ZOOM:a("Zoom","ai-engine"),SLIDE:a("Slide","ai-engine"),FADE:a("Fade","ai-engine"),VOICE:a("Voice","ai-engine"),ICON:a("Icon","ai-engine"),ICON_TEXT:a("Icon Text","ai-engine"),ICON_TEXT_DELAY:a("Icon Text Delay","ai-engine"),FULL_SCREEN:a("Full Screen","ai-engine"),CASUALLY_FINE_TUNED:a("Casually Fine-Tuned","ai-engine"),CONTENT_AWARE:a("Content Aware","ai-engine"),TITLE:a("Title","ai-engine"),TOPIC:a("Topic","ai-engine"),TOPICS:a("Topics","ai-engine"),SPACING:a("Spacing","ai-engine"),BORDER_RADIUS:a("Border Radius","ai-engine"),FONT_SIZE:a("Font Size","ai-engine"),FONT_COLOR:a("Font Color","ai-engine"),BORDER_COLOR:a("Border Color","ai-engine"),BACK_PRIMARY_COLOR:a("Back Primary Color","ai-engine"),BACK_SECONDARY_COLOR:a("Back 2nd Color","ai-engine"),HEADER_COLOR:a("Header Color","ai-engine"),HEADER_BACKGROUND_COLOR:a("Header Back Color","ai-engine"),HEADER_SUBTITLE:a("Header Subtitle","ai-engine"),BUBBLE_COLOR:a("Bubble Color","ai-engine"),BACK_USER_COLOR:a("Back User Color","ai-engine"),BACK_AI_COLOR:a("Back AI Color","ai-engine"),BACK_AI_SECONDARY_COLOR:a("Back AI 2nd Color","ai-engine"),AVATAR_MESSAGE_BACKGROUND_COLOR:a("Message Back","ai-engine"),AVATAR_MESSAGE_FONT_COLOR:a("Message Color","ai-engine"),POPUP_ICON:a("Popup Icon","ai-engine"),CUSTOM_ICON:a("Custom Icon (URL or Emoticon)","ai-engine"),FEATURES:a("Features","ai-engine"),TIMEFRAME:a("Timeframe","ai-engine"),ABSOLUTE:a("Absolute","ai-engine"),NONE:a("None","ai-engine"),EDITORS_ADMINS:a("Editors & Admins","ai-engine"),ADMINS_ONLY:a("Admins Only","ai-engine"),MAINTENANCE:a("Maintenance","ai-engine"),CREDITS:a("Credits","ai-engine"),TYPE:a("Type","ai-engine"),LIMITS:a("Limits","ai-engine"),USERS:a("Users","ai-engine"),USER:a("User","ai-engine"),GUESTS:a("Guests","ai-engine"),GUEST:a("Guest","ai-engine"),OPENAI:a("Open AI","ai-engine"),LICENSE_TAB:a("License","ai-engine"),FINETUNES:a("Finetunes","ai-engine"),MODELS:a("Models","ai-engine"),FILES:a("Files","ai-engine"),ASSISTANT:a("Assistant","ai-engine"),ASSISTANTS:a("Assistants","ai-engine"),UTILITIES:a("Utilities","ai-engine"),POSTS_SUGGESTIONS:a("AI Copilot, AI Suggestions, Magic Wands","ai-engine"),POSTS_SUGGESTIONS_HELP:a("Tools to brainstorm/write faster and better.","ai-engine"),GENERATORS:a("Generators","ai-engine"),CONTENT_GENERATOR:a("Content Generator","ai-engine"),CONTENT_GENERATOR_HELP:a("Transform ideas into polished articles with AI-powered content creation.","ai-engine"),IMAGES_GENERATOR:a("Images Generator","ai-engine"),IMAGES_GENERATOR_HELP:a("Bring your vision to life with stunning AI-generated visuals.","ai-engine"),IMAGES_GENERATOR_INTRO:a("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:a("Playground","ai-engine"),PLAYGROUND_HELP:a("Experiment with AI models and unlock endless creative possibilities.","ai-engine"),FORMS:a("Forms","ai-engine"),FORMS_HELP:a("Create dynamic, intelligent forms that adapt and respond based on user input with conditional logic.","ai-engine"),SEARCH:a("Search","ai-engine"),SEARCH_HELP:a("Override the default WordPress search with AI powered keywords or embeddings.","ai-engine"),INSIGHTS_HELP:a("Enable Query Logs, Usage and Limits.","ai-engine"),CLIENT_DEBUG:a("Client Debug","ai-engine"),CLIENT_DEBUG_HELP:a("Debugging information for Chatbots and Forms will be displayed in the Browser Console.","ai-engine"),SERVER_DEBUG:a("Server Debug","ai-engine"),SERVER_DEBUG_HELP:a("API calls and server events will be logged and displayed in the Logs Console.","ai-engine"),MCP_DEBUG:a("MCP Debug","ai-engine"),MCP_DEBUG_HELP:a("Debugging information from MCP will be written directly to the PHP error logs using error_log().","ai-engine"),QUERIES_DEBUG:a("Queries Debug","ai-engine"),QUERIES_DEBUG_HELP:a("Full queries and responses will be written directly to the PHP error logs using error_log().","ai-engine"),DEV_MODE:a("Dev Mode","ai-engine"),DEV_MODE_HELP:a("Run tasks frequently for debugging.","ai-engine"),CLEAR_LOGS:a("Clear Logs","ai-engine"),REFRESH_LOGS:a("Refresh Logs","ai-engine"),API_KEY:a("API Key","ai-engine"),USAGE_HELP:a("Estimates only. Check your AI service for actual costs. Insights module provides better accuracy.","ai-engine"),RESET_USAGE_SURE:a("Are you sure you want to reset the usage data?","ai-engine"),USAGE_PRO_HELP:a("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:a("AI Engine Pro ↗","ai-engine"),LANGUAGE:a("Language","ai-engine"),HIDE:a("Hide","ai-engine"),SHOW:a("Show","ai-engine"),CONTENT:a("Content","ai-engine"),IMAGES:a("Images","ai-engine"),IMAGES_AND_FILES:a("Images & Files","ai-engine"),EXCERPT:a("Excerpt","ai-engine"),GENERATE:a("Generate","ai-engine"),MODEL_PARAMS:a("Model Params","ai-engine"),CONTEXT_PARAMS:a("Context Params","ai-engine"),PROMPT:a("Prompt","ai-engine"),PROMPTS:a("Prompts","ai-engine"),LABEL:a("Label","ai-engine"),SYSTEM:a("System","ai-engine"),SHORTCODE:a("Shortcode","ai-engine"),SHORTCODES:a("Shortcodes","ai-engine"),RESOLVE:a("Resolve","ai-engine"),MAX_MESSAGES:a("Max Messages","ai-engine"),INPUT_MAX_LENGTH:a("Input Max Length","ai-engine"),COMPLIANCE_TEXT:a("Compliance Text","ai-engine"),MODERATION:a("Moderation","ai-engine"),MODERATION_HELP:a("Moderation features with AI.","ai-engine"),FORMATTING:a("Formatting","ai-engine"),FORMATTING_HELP:a("Format the reply from AI into HTML. This is already done automatically if Markdown is detected in the reply.","ai-engine"),LOGS:a("Logs","ai-engine"),QUERY:a("Query","ai-engine"),REPLY:a("Reply","ai-engine"),CODE:a("Code","ai-engine"),EMBEDDINGS:a("Embeddings","ai-engine"),QUERY_LOGS:a("Query Logs","ai-engine"),KNOWLEDGE:a("Knowledge","ai-engine"),KNOWLEDGE_HELP:a("Searchable data for AI. Powered by <b>embeddings</b> for now, alternatives will come later.","ai-engine"),REMOTE_ACCESS:a("Remote Access","ai-engine"),OTHERS:a("Others","ai-engine"),PINECONE_APIKEY_HELP:a("You can get your API Keys in your %s.","ai-engine"),PINECONE_APIKEY_URL:"https://app.pinecone.io/organizations/keys",PINECONE_APIKEY_LINK_TEXT:a("Pinecone Account ↗","ai-engine"),QDRANT_APIKEY_HELP:a("You can get your API Keys in your %s.","ai-engine"),QDRANT_APIKEY_URL:"https://cloud.qdrant.io/accounts/",QDRANT_APIKEY_LINK_TEXT:a("Qdrant Account ↗","ai-engine"),SERVER:a("Server","ai-engine"),PINECONE_SERVER_HELP:a("The URL of your host (check your Indexes).","ai-engine"),PINECONE_NAMESPACE_HELP:a("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:a("The URL of your cluster (known as Cluster URL).","ai-engine"),QDRANT_COLLECTION_HELP:a("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:a("Cost","ai-engine"),USAGE:a("Usage","ai-engine"),USAGE_ESTIMATES_NOTE:a("Costs and tokens are estimates. For accurate data and detailed analytics, visit the Insights tab.","ai-engine"),ACTIVITY:a("Activity","ai-engine"),TRANSCRIPTION:a("Transcription","ai-engine"),TRANSCRIPTION_HELP:a("Introduces a 'Transcribe' tab to easily transform audio/images into text and get AI answers in JSON format.","ai-engine"),AUDIO_TRANSCRIPTION:a("Audio-to-Text","ai-engine"),IMAGE_TRANSCRIPTION:a("Image-to-Text","ai-engine"),AUDIO_TO_TEXT:a("Audio ➡ Text","ai-engine"),IMAGE_TO_TEXT:a("Image ➡ Text","ai-engine"),EMBEDDINGS_ENV:a("Environment","ai-engine"),EMBEDDINGS_INDEX:a("Index","ai-engine"),NAMESPACE:a("Namespace","ai-engine"),NAMESPACES:a("Namespaces","ai-engine"),NAMESPACE_HELP:a("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:a("Enter the namespaces you would like to use on this site, separated by commas.","ai-engine"),ERROR:a("Error","ai-engine"),RETRY:a("Retry","ai-engine"),AUTO_RETRY:a("Auto Retry","ai-engine"),SKIP:a("Skip","ai-engine"),AUTO_SKIP:a("Auto Skip","ai-engine"),STOP:a("Stop","ai-engine"),AUTO_RETRY_DESCRIPTION:a("Auto Retry retries actions up to 10 times with increasing delay to avoid timeouts.","ai-engine"),WIDTH:a("Width","ai-engine"),MAX_HEIGHT:a("Max Height","ai-engine"),APPEARANCE:a("Appearance","ai-engine"),THRESHOLDS:a("Thresholds","ai-engine"),DASHBOARD:a("Dashboard","ai-engine"),ADVANCED:a("Advanced","ai-engine"),DISCUSSIONS:a("Discussions","ai-engine"),DISCUSSION_TITLES:a("Discussion Titles","ai-engine"),SUMMARIZE:a("Summarize","ai-engine"),ROWS:a("Rows","ai-engine"),POST_TYPE:a("Post Type","ai-engine"),GENERATE_CONTENT:a("Generate Content","ai-engine"),GENERATE_IMAGES:a("Generate Images","ai-engine"),REST_API:a("REST API","ai-engine"),ADMIN_BAR:a("Admin Bar","ai-engine"),REFRESH:a("Refresh","ai-engine"),DELETE:a("Delete","ai-engine"),DELETE_ALL:a("Delete All","ai-engine"),DELETE_SELECTED:a("Delete Selected","ai-engine"),OPENAI_ORGANIZATION_ID:a("Organization ID","ai-engine"),OPENAI_AZURE_API_KEY:a("API Key","ai-engine"),OPENAI_AZURE_DEPLOYMENT_NAME:a("Deployment Name","ai-engine"),OPENAI_AZURE_DEPLOYMENTS:a("Deployments","ai-engine"),ENDPOINT:a("Endpoint","ai-engine"),HUGGINGFACE_MODELS:a("Models","ai-engine"),HUGGINGFACE_MODEL_NAME:a("Name","ai-engine"),HUGGINGFACE_MODEL_URL:a("API URL","ai-engine"),THEME:a("Theme","ai-engine"),THEMES:a("Themes","ai-engine"),BANNED_WORDS:a("Banned Words","ai-engine"),WORD_BOUNDARIES:a("Word Boundaries","ai-engine"),IGNORE:a("Ignore","ai-engine"),BANNED_IPS:a("Banned IPs","ai-engine"),SECURITY:a("Security","ai-engine"),POST_TYPES:a("Post Types","ai-engine"),COPY_BUTTON:a("Copy Button","ai-engine"),AI_AVATAR:a("AI Avatar","ai-engine"),GUEST_AVATAR:a("Guest Avatar","ai-engine"),SITE_WIDE_CHATBOT:a("Site-Wide Chatbot","ai-engine"),QUERIES_DATA:a("Queries Data","ai-engine"),QUERIES_FORMS_DATA:a("Queries Form Data","ai-engine"),WEBSPEECH_API:a("Web Speech API","ai-engine"),GDPR_CONSENT:a("GDPR Consent","ai-engine"),GDPR_TEXT:a("GDPR Text","ai-engine"),GDPR_BUTTON:a("GDPR Button","ai-engine"),FIX:a("Fix","ai-engine"),SPEECH_RECOGNITION:a("Speech Recognition","ai-engine"),SPEECH_SYNTHESIS:a("Speech Synthesis","ai-engine"),QUERIES:a("Queries","ai-engine"),LOCAL_MEMORY:a("Local Memory","ai-engine"),ACTIONS:a("Actions","ai-engine"),RESET:a("Reset","ai-engine"),INCIDENTS_OPENAI:a("Incidents (OpenAI)","ai-engine"),PREVIEW:a("Preview","ai-engine"),LEGACY_FORMS:a("Legacy Forms","ai-engine"),LEGACY_FEATURES:a("Legacy Features","ai-engine"),DUPLICATE:a("Duplicate","ai-engine"),CHATBOT_EDITOR:a("Chatbot Editor","ai-engine"),THEME_EDITOR:a("Theme Editor","ai-engine"),STREAMING:a("Streaming","ai-engine"),SYNTAX_HIGHLIGHT:a("Syntax Highlight","ai-engine"),EVENT_LOGS:a("Event Logs","ai-engine"),PRIVACY_FIRST:a("Privacy First","ai-engine"),DATA_NOT_AVAILABLE:a("Data not available.","ai-engine"),EXPORT:a("Export","ai-engine"),IMPORT:a("Import","ai-engine"),MODIFY_EMBEDDING:a("Modify Embedding","ai-engine"),ADD_EMBEDDING:a("Add Embedding","ai-engine"),DEV_TOOLS:a("Dev Tools","ai-engine"),SINGLE_GENERATE:a("Single Generate","ai-engine"),PUBLIC_API:a("Public API","ai-engine"),USER_INTERFACE:a("User Interface","ai-engine"),INTRO_MESSAGE:a("Intro Message","ai-engine"),ADDONS:a("Add-ons","ai-engine"),AI_ENVIRONMENT_DEFAULTS:a("Default Environments for AI","ai-engine"),ENVIRONMENTS_FOR_AI:a("Environments for AI","ai-engine"),ENVIRONMENT_ID:a("Environment ID","ai-engine"),EMBEDDINGS_ENVIRONMENT_DEFAULT:a("Default Embeddings Environment","ai-engine"),ENVIRONMENT:a("Environment","ai-engine"),PLUGIN_DATA:a("Plugin Data","ai-engine"),PLUGIN_DATA_DESCRIPTION:a("The database and all the options of the plugin will be removed on uninstall.","ai-engine"),RESET_LIMITS:a("Reset Limits","ai-engine"),VISION:a("Vision","ai-engine"),FILE_SEARCH:a("File Search","ai-engine"),PROMPT_TO_JSON:a("Prompt ➡ JSON","ai-engine"),RESOLUTION:a("Resolution","ai-engine"),DEFAULT:a("Default","ai-engine"),DEFAULTS:a("Defaults","ai-engine"),DEFAULT_FAST:a("Fast","ai-engine"),REFRESH_MODELS:a("Refresh Models","ai-engine"),AUDIO:a("Audio","ai-engine"),JSON:a("JSON","ai-engine"),AI_ENVIRONMENT:a("AI Environment","ai-engine"),OVERRIDE_DEFAULTS:a("Override Defaults","ai-engine"),REGION:a("Region","ai-engine"),PROJECT_ID:a("Project ID","ai-engine"),BEARER_TOKEN:a("Bearer Token","ai-engine"),DIMENSIONS:a("Dimensions","ai-engine"),EMBEDDINGS_MODEL:a("Embeddings Model","ai-engine"),MIN_SCORE:a("Min Score","ai-engine"),MAX_SELECT:a("Max Results","ai-engine"),QDRANT_COLLECTION:a("Collection","ai-engine"),INSTRUCTIONS:a("Instructions","ai-engine"),FUNCTIONS:a("Functions","ai-engine"),TOOLS:a("Tools","ai-engine"),WEB_SEARCH:a("Web Search","ai-engine"),IMAGE_GENERATION:a("Image Generation","ai-engine"),CODE_INTERPRETER:a("Code Interpreter","ai-engine"),HISTORY_STRATEGY:a("History Strategy","ai-engine"),AUTOMATIC:a("Automatic","ai-engine"),FULL_HISTORY:a("Full History","ai-engine"),INCREMENTAL:a("Incremental","ai-engine"),BUBBLE:a("Bubble","ai-engine"),TABS:a("Tabs","ai-engine"),DROPDOWN:a("Dropdown","ai-engine"),CHATBOT_SELECT:a("Chatbot Select","ai-engine"),CONDITIONS:a("Conditions","ai-engine"),CONDITION:a("Condition","ai-engine"),ADD_CONDITION:a("Add Condition","ai-engine"),REMOVE:a("Remove","ai-engine"),MCP_NO_OPTIONS:a("MCP is enabled but no options are selected. Please enable at least one option.","ai-engine"),ORCHESTRATION:a("Orchestration","ai-engine"),ORCHESTRATION_HELP:a("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:a("MCP Servers","ai-engine"),MCP_FUNCTIONS:a("MCP Functions","ai-engine"),URL:a("URL","ai-engine"),TOKEN:a("Token","ai-engine"),SERVER_ID:a("Server ID","ai-engine"),PRICE:a("Price","ai-engine"),UNITS:a("Units","ai-engine"),FAMILY:a("Family","ai-engine"),DAILY:a("Daily","ai-engine"),MONTHLY:a("Monthly","ai-engine"),UNKNOWN_MODEL:a("Unknown Model","ai-engine"),CONTEXTUAL:a("Contextual","ai-engine"),COMPLETION:a("Completion","ai-engine"),TOTAL_MAX_TOKENS:a("Total Max Tokens","ai-engine"),RECOMMENDED:a("Recommended","ai-engine"),SESSION:a("Session","ai-engine"),LAST_REQUEST:a("Last Request","ai-engine"),RESET_USAGE:a("Reset Usage","ai-engine"),COPIED:a("Copied!","ai-engine"),CLIPBOARD_ERROR:a("Clipboard is not enabled (only works with https).","ai-engine"),VIEW_IN_PLATFORM:a("View in OpenAI Platform","ai-engine")},r.FORMS={PROMPT_INFO:a("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:a("Output","ai-engine"),OUTPUT_ELEMENT:a("Output Element","ai-engine"),OUTPUT_ELEMENT_INFO:a("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:a("Between 0 and 1. Higher values means the model will take more risks.","ai-engine"),MAX_TOKENS:a("The maximum number of tokens to generate. The model will stop generating once it hits this limit.","ai-engine"),STOP_SEQUENCE:a("The sequence of tokens that will cause the model to stop generating text. You absolutely need this with fine-tuned models.","ai-engine"),COST:a("Keeps track of the current costs.","ai-engine"),RESOLVE_SHORTCODE:a("Will resolve the shortcode in your content when needed (Content-Aware will use this, for instance).","ai-engine"),FINETUNES:a("Train your own AI models.","ai-engine"),DISCUSSIONS:a("Keep the conversations and enable browsing them via the Conversations tab.","ai-engine"),DISCUSSION_TITLES:a("Generate titles for the discussions automatically with AI.","ai-engine"),DISCUSSION_SUMMARY:a("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:a("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:a("Reject queries containing these words; separate with commas.","ai-engine"),WORD_BOUNDARIES:a("Ignore standard word separation (space) and match banned words anywhere in the text.","ai-engine"),BANNED_IPS:a("Block access from specified IP addresses or ranges using CIDR notation; separate with commas.","ai-engine"),GDPR_CONSENT:a("If enabled, the user will have to accept the conditions before using the chatbot.","ai-engine"),POST_TYPES:a("Enable for these post types; separate with commas.","ai-engine"),POST_STATUS:a("Enable for these post statuses (publish, draft, future, private, etc); separate with commas.","ai-engine"),POST_CATEGORIES:a("Enable for these categories (slugs); separate with commas. If none, it will be enabled for all.","ai-engine"),CONTEXT_MAX_LENGTH:a("Truncate the context (Content-Aware, Embeddings, etc) to make sure it is below this number of characters.","ai-engine"),MAX_MESSAGES:a("Maximum number of historical messages that is sent to the AI model.","ai-engine"),INPUT_MAX_LENGTH:a("Maximum number of characters that can be input by the user.","ai-engine"),STATISTICS:a(" 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:a("Record the queries and their replies.","ai-engine"),QUERIES_FORMS_DATA:a("Capture form data neatly for simple reuse.","ai-engine"),SPEECH_RECOGNITION:a("Enable speech-to-text. Depends on the browser and OS used by the user.","ai-engine"),SPEECH_SYNTHESIS:a("Enable text-to-speech.","ai-engine"),CUSTOM_SHORTCODE:a("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:a("Type an User ID, or an IP.","ai-engine"),STREAMING:a("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:a("Enable syntax highlighting for the code blocks.","ai-engine"),EVENT_LOGS:a("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:a("Only essential data is stored. IPs, conversations, and other private details are minimized and kept as anonymous as possible.","ai-engine"),DEV_TOOLS:a("Enable a new tab with debugging tools. For developers only.","ai-engine"),DEV_MODE:a("Run tasks very frequently for debugging.","ai-engine"),PUBLIC_API:a("Enable the Public REST API.","ai-engine"),INTRO_MESSAGE:a("Enable introduction messages on some modules.","ai-engine"),ADDONS:a("Enable the AI Addons section under the Meow Apps menu.","ai-engine"),OPENAI_API_KEY:a("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:a("OpenAI Account ↗","ai-engine"),OPENAI_ORGANIZATION_ID:a("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:a("Organization ↗","ai-engine"),AZURE_API_KEY:a("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:a("Azure Account ↗","ai-engine"),AZURE_ENDPOINT:a("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:a("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:a("Anthropic Account ↗","ai-engine"),OPENROUTER_API_KEY:a("You can get your API Keys in your %s.","ai-engine"),OPENROUTER_API_KEY_URL:"https://openrouter.ai/keys",OPENROUTER_API_KEY_LINK_TEXT:a("OpenRouter Account ↗","ai-engine"),QDRANT:a("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:a("Create a Qdrant Account ↗","ai-engine"),ASSISTANTS:a("The Assistants API is designed to help developers build powerful AI assistants capable of performing a variety of tasks.","ai-engine"),ASSISTANTS_INTRO:a("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:a("OpenAI Assistants ↗","ai-engine"),ASSISTANTS_WARNINGS:a("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:a("in beta ↗","ai-engine"),ASSISTANTS_PRICING_URL:"https://openai.com/pricing",ASSISTANTS_PRICING_TEXT:a("tricky ↗","ai-engine"),ASSISTANTS_DISCORD_URL:"https://discord.gg/bHDGh38",ASSISTANTS_DISCORD_TEXT:a("Meow Apps Discord Server ↗","ai-engine"),BEARER_TOKEN:a("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:a("build your own authentication ↗","ai-engine"),REST_API_INTRO:a("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:a("Make.com ↗","ai-engine"),MCP_BEARER_TOKEN:a("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:a("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:a("This tutorial is highly recommended ↗","ai-engine"),MCP_SERVER_URL:a("The URL of the MCP server. Must start with https://","ai-engine"),MCP_SERVER_TOKEN:a("Bearer token for authenticating with the MCP server.","ai-engine"),NO_EMBEDDINGS_RESULTS:a("No results for this search. Make sure the Minimum Score is not too high.","ai-engine"),NO_EMBEDDINGS_ROWS:a("No embeddings yet in this environment.","ai-engine"),MIN_SCORE:a("The minimum score the embeddings need to have to be returned. Between 0 and 100 and defaults to 35.","ai-engine"),MAX_SELECT:a("The maximum number of embeddings to return and to use as context. Between 1 and 100 and defaults to 10.","ai-engine"),FUNCTIONS:a("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:a("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:a("Code Engine ↗","ai-engine"),MCP_SERVERS:a("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:a("No MCP servers are available. Configure them in Settings > Orchestration.","ai-engine"),TOOLS:a("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:a("Allow the AI to search the web for current information","ai-engine"),IMAGE_GENERATION:a("Allow the AI to generate images based on text descriptions","ai-engine"),CODE_INTERPRETER:a("Allow the AI to write and run Python code to solve complex problems, process data, and generate visualizations","ai-engine"),HISTORY_STRATEGY:a("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:a("In your Dashboard will be displayed daily recommendations tailored to your WordPress setup. Admins only.","ai-engine"),BUBBLE:a("The popup will be displayed as a bubble.","ai-engine"),ICON_TEXT:a("If set, this text will appear next to the icon/bubble.","ai-engine"),ICON_TEXT_DELAY:a("Delay before text appears.","ai-engine"),WIDTH:a("Width of the chatbot when open.","ai-engine"),OPEN_DELAY:a("Auto-open after X seconds.","ai-engine"),CHATBOT_SELECT:a("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:a('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:a("OpenAI ↗","ai-engine"),PINECONE_SETUP:a("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:a("Pinecone ↗","ai-engine"),INTRO:a("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:a("tutorial ↗","ai-engine"),INTRO_DOCS_URL:"https://ai.thehiddendocs.com/",INTRO_DOCS_TEXT:a("documentation ↗","ai-engine"),INTRO_ADDONS_URL:"https://meowapps.com/products/category/ai-add-ons/",INTRO_ADDONS_TEXT:a("add-ons ↗","ai-engine"),INTRO_DISCLAIMER_URL:"https://meowapps.com/ai-engine/disclaimer/",INTRO_DISCLAIMER_TEXT:a("disclaimer ↗","ai-engine"),MODULES_INTRO:a("To avoid cluttering the UI and your WP, only enable the features you need.","ai-engine"),ALERT_INJECT_BUT_NO_POPUP:a("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:a("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:a("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:a("here ↗","ai-engine"),SET_AS_DEFAULT_PARAMETERS:a("Set as Default Parameters","ai-engine"),SET_AS_DEFAULT_PARAMETERS_HELP:a("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:a("Inject Default Chatbot in Entire Website","ai-engine"),INJECT_DEFAULT_CHATBOT_HELP:a("Inject the chatbot [mwai_chat] in the entire website.","ai-engine"),CHATGPT_STYLE_INTRO:a("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:a("here ↗","ai-engine"),CHATGPT_STYLE_FAQ_URL:"https://meowapps.com/ai-engine/faq",CHATGPT_STYLE_FAQ_TEXT:a("FAQ ↗","ai-engine"),TYPEWRITER_EFFECT:a("Typewriter Effect","ai-engine"),TYPEWRITER_EFFECT_HELP:a("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:a("If the conversation seems offensive, the chatbot will reject it.","ai-engine"),CUSTOM_URL:a("Custom URL","ai-engine"),ASSISTANT_NO_FILE_SEARCH:a("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:a("OpenAI Assistants ↗","ai-engine"),ASSISTANT_FILE_SEARCH:a("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:a("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:a("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:a("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:a("Pinecone ↗","ai-engine"),KNOWLEDGE_DISCORD_URL:"https://discord.gg/bHDGh38",KNOWLEDGE_DISCORD_TEXT:a("Meow Apps Discord Server ↗","ai-engine"),ORCHESTRATION_INFO:a("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:a("Chatbot Builder","ai-engine"),RESET_PARAMS:a("Reset Parameters","ai-engine")},r.STATISTICS={ABSOLUTE_HELP:a("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:a("Message for No Credits","ai-engine"),FULL_ACCESS_USERS:a("Full-Access Users","ai-engine"),ENABLE_LIMITS:a("Enable Limits","ai-engine")},r.CONTENT_GENERATOR={INTRO:a("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:a("Title is missing!","ai-engine"),SECTIONS_MISSING:a("Sections are missing!","ai-engine"),SINGLE_GENERATE:a("Single Generate","ai-engine"),BULK_GENERATE:a("Bulk Generate","ai-engine"),CONTENT_PARAMS:a("Content Params","ai-engine"),POST_PARAMS:a("Post Params","ai-engine"),CONTENT_PARAMS_INTRO:a("Input fields are displayed for certain placeholders used in prompts, such as {LANGUAGE} or {WRITING_TONE}","ai-engine"),CUSTOM_LANGUAGE:a("Custom Language","ai-engine"),WRITING_STYLE:a("Writing Style","ai-engine"),WRITING_TONE:a("Writing Tone","ai-engine"),CUSTOM_LANGUAGE_HELP:a("AI supports all languages with varying quality. %s.","ai-engine"),CUSTOM_LANGUAGE_URL:"https://meowapps.com/ai-engine/faq/#languages",CUSTOM_LANGUAGE_LINK_TEXT:a("Learn more ↗","ai-engine"),MODEL_HELP:a("It is recommended to use Turbo or GPT-4 to write texts.","ai-engine"),PROMPTS_INTRO:a("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:a("Prompt for <b>Title</b>","ai-engine"),PROMPT_SECTIONS:a("Prompt for <b>Sections</b>","ai-engine"),PROMPT_CONTENT:a("Prompt for <b>Content</b>","ai-engine"),PROMPT_EXCERPT:a("Prompt for <b>Excerpt</b>","ai-engine"),POST_CREATED:a("Post Created","ai-engine"),POST_CREATED_AS_DRAFT:a("The post was created as a draft.","ai-engine"),CONTENT_HELP:a('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:a('Add, rewrite, remove, or reorganize those sections as you wish before (re)clicking on "Generate Content". Markdown format is recommended.',"ai-engine"),GENERATE_EXCERPT:a("Generate Excerpt","ai-engine"),GENERATE_CONTENT:a("Generate Content","ai-engine"),GENERATE_SECTIONS:a("Generate Sections","ai-engine"),PARAGRAPHS_PER_SECTION:a("# of Paragraphs per Section","ai-engine"),NUMBER_OF_SECTIONS:a("# of Sections","ai-engine"),ADVICE:a("Advice","ai-engine"),SECTIONS:a("Sections","ai-engine"),USE_MAX_TOKENS:a("Use Max Tokens","ai-engine"),TOPICS_HELP:a("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:a("Generated Posts","ai-engine"),USE_TOPICS_AS_TITLES:a("Use Topics as Titles","ai-engine"),NOTHING_YET:a("Nothing yet.","ai-engine"),BULK_ERROR_CONFIRM:a("An error was caught ({MESSAGE}). Should we continue?","ai-engine"),GENERATE_ALL:a("Generate All","ai-engine"),EDIT_POST:a("Edit Post","ai-engine"),CREATE_POST:a("Create Post","ai-engine"),TITLE_TOO_SHORT:a("The title is too short. It should be at least 3 words.","ai-engine"),TITLE_TOO_SHORT_2:a("The title is too short. It should be at least 40 characters.","ai-engine"),TITLE_TOO_LONG:a("The title is too long. It should be less than 8 words.","ai-engine"),TITLE_TOO_LONG_2:a("The title is too long. It should be less than 70 characters.","ai-engine")},r.TEMPLATES={TEMPLATE:a("Template","ai-engine"),TEMPLATES:a("Templates","ai-engine"),DELETE_CONFIRM:a("Are you sure you want to delete this template?","ai-engine"),DELETE_ALL_CONFIRM:a("Are you sure you want to delete all the templates?","ai-engine"),NEW_TEMPLATE_NAME:a("New Template","ai-engine"),EDIT:a("EDIT","ai-engine")},r.PLAYGROUND={INTRO:a("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:a("Query / Prompt","ai-engine"),REPLY:a("Reply","ai-engine")},r.ALERTS={FINETUNING_STARTED:a("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:a("This will delete all the rows in the builder. Are you sure?","ai-engine"),DELETE_FINETUNE:a("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:a("This fine-tune was already deleted. It will be removed from the list.","ai-engine"),CHECK_CONSOLE:a("Error! Check your console for more details.","ai-engine"),DATASET_UPLOADED:a("Uploaded successfully! You can now train a model based on this dataset.","ai-engine"),ONLY_SUPPORTS_FILES:a("This only supports JSON, JSONL, and CSV files. Check the Instructions section below.","ai-engine"),EMPTY_LINES_DATASET:a("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:a("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:a("Are you sure?","ai-engine")},r.FINETUNING={MODELS_INTRO:a("The AI models you have fine-tuned. To create more, visit <b>Files</b>.","ai-engine"),LEGACY_MODELS_INTRO:a("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:a("announced by OpenAI ↗","ai-engine"),FILES_INTRO:a("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:a("Model Finetune","ai-engine"),MODELS_FILES:a("Models & Files","ai-engine"),DATASET_EDITOR:a("Dataset Editor","ai-engine"),EDITOR:a("Editor","ai-engine"),GENERATOR:a("Generator","ai-engine"),HUGE_DATASET_WARNING:a("Caution: The data is too large to be saved in your browser's local storage.","ai-engine"),NO_FINETUNES_YET:a("No fine-tunes found. Refresh the list, or create a new one (via a dataset).","ai-engine"),CLEAN_MODELS_LIST:a("Clean Models List","ai-engine"),DELETED_FINETUNE_ISSUE:a("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:a("New Chat","ai-engine"),NO_MESSAGES_YET:a("No messages yet","ai-engine"),RENAME:a("Rename","ai-engine"),DELETE:a("Delete","ai-engine"),UNTITLED:a("Untitled","ai-engine"),TITLE_GENERATION_PROMPT:a("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:a("Informative","ai-engine"),DESCRIPTIVE:a("Descriptive","ai-engine"),CREATIVE:a("Creative","ai-engine"),NARRATIVE:a("Narrative","ai-engine"),PERSUASIVE:a("Persuasive","ai-engine"),REFLECTIVE:a("Reflective","ai-engine"),ARGUMENTATIVE:a("Argumentative","ai-engine"),ANALYTICAL:a("Analytical","ai-engine"),EVALUATIVE:a("Evaluative","ai-engine"),JOURNALISTIC:a("Journalistic","ai-engine"),TECHNICAL:a("Technical","ai-engine")},r.WRITING_TONES={NEUTRAL:a("Neutral","ai-engine"),FORMAL:a("Formal","ai-engine"),ASSERTIVE:a("Assertive","ai-engine"),CHEERFUL:a("Cheerful","ai-engine"),HUMOROUS:a("Humorous","ai-engine"),INFORMAL:a("Informal","ai-engine"),INSPIRATIONAL:a("Inspirational","ai-engine"),PROFESSIONAL:a("Professional","ai-engine"),CONFLUENT:a("Confluent","ai-engine"),EMOTIONAL:a("Emotional","ai-engine"),PERSUASIVE:a("Persuasive","ai-engine"),SUPPORTIVE:a("Supportive","ai-engine"),SARCASTIC:a("Sarcastic","ai-engine"),CONDESCENDING:a("Condescending","ai-engine"),SKEPTICAL:a("Skeptical","ai-engine"),NARRATIVE:a("Narrative","ai-engine"),JOURNALISTIC:a("Journalistic","ai-engine")},r.EMBEDDINGS={EDIT:a("EDIT","ai-engine"),AI_SEARCH:a("AI SEARCH","ai-engine"),SYNC_POSTS:a("Sync Posts","ai-engine"),AUTO_SYNC_POSTS:a("Auto-Sync Posts","ai-engine"),AUTO_SYNC_POSTS_DESCRIPTION:a("Embeddings will be created, updated or removed based on the activity related to your posts.","ai-engine"),REWRITE_CONTENT:a("Rewrite Content","ai-engine"),REWRITE_CONTENT_DESCRIPTION:a("Shorten and improve the content for your embedding using the default model.","ai-engine"),FORCE_RECREATE:a("Force Recreate","ai-engine"),FORCE_RECREATE_DESCRIPTION:a("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:a("Delete All Embeddings","ai-engine"),DELETE_ALL_EMBEDDINGS_CONFIRM:a("Are you sure you want to delete all the embeddings in this environment?","ai-engine"),REWRITE_PROMPT_DESCRIPTION:a("Prompt for the rewrite. Supports {CONTENT}, {TITLE}, {URL}, {EXCERPT}, {LANGUAGE}, {ID}.","ai-engine"),SYNC_ALL:a("Sync All","ai-engine"),SYNC_ONE:a("Sync One","ai-engine"),ADD_INDEX:a("Add Index","ai-engine"),ADD_INDEX_DESCRIPTION:a("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:a("Note: This server does not support namespaces.","ai-engine")},r.ERROR={UPDATING_OPTIONS:a("An error occurred while updating the options."),GETTING_OPTIONS:a("An error occurred while getting the options."),CHECK_YOUR_CONSOLE:a('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:a("Your session has expired. Please refresh the page to continue using AI Engine.","ai-engine"),COULD_NOT_PARSE_ERROR_STREAM:a("Could not parse the 'error' stream.","ai-engine"),COULD_NOT_PARSE_END_STREAM:a("Could not parse the 'end' stream.","ai-engine"),INVALID_API_KEY:a("Invalid API key: Please check your OpenAI API key in settings.","ai-engine"),RATE_LIMIT_EXCEEDED:a("Rate limit exceeded: Too many requests. Please try again later.","ai-engine"),NETWORK_ERROR:a("Network error: Failed to establish connection to the AI service.","ai-engine"),AUTHENTICATION_FAILED:a("Authentication failed: Your session has expired. Please refresh the page.","ai-engine"),INTERNAL_SERVER_ERROR:a("Internal server error: An unexpected error occurred. Please try again.","ai-engine"),PROCESSING_ERROR:a("An error occurred while processing your request. Please try again.","ai-engine"),MEDIADEVICES_NOT_AVAILABLE:a("MediaDevices API not available. Please ensure you are using HTTPS and a modern browser.","ai-engine"),MICROPHONE_ACCESS_FAILED:a("Failed to access microphone. Please ensure microphone permissions are granted and try again.","ai-engine"),CONNECTION_FAILED:a("Failed to establish connection with OpenAI servers. Please try again.","ai-engine")},r.DEBUG={CRASH_IN_MARKDOWN:a("Crash in markdown-to-jsx! Reverting to plain text.","ai-engine"),AI_ENGINE_COULD_NOT_FIND_BLOCK:a("AI Engine: Could not find block element for","ai-engine"),AI_WAND_TABLE_REQUIRES_DATA:a("AI Wand: Table requires structured data for proper update","ai-engine"),AI_WAND_COULD_NOT_FIND_SELECTION:a("AI Wand: Could not find selection, replacing entire block content","ai-engine"),NEW_TOKEN_RECEIVED:a("[MWAI] 🔐 New token received","ai-engine"),NONCE_ERROR_DETECTED:a("[MWAI] Nonce error detected, attempting to refresh...","ai-engine")};const s=r},469:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.d(__webpack_exports__,{G:()=>ChatbotContextProvider,o:()=>useChatbotContext});var _app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(728),_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(137),_app_helpers__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(678),_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(213);const{useContext,createContext,useState,useMemo,useEffect,useCallback,useRef}=wp.element,__=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(),n=3===t.length?t.split("").map((e=>e+e)).join(""):t,a=parseInt(n,16);return Number.isNaN(a)||6!==n.length?null:{r:a>>16&255,g:a>>8&255,b:255&a}},rgbToHsl=({r:e,g:t,b:n})=>{e/=255,t/=255,n/=255;const a=Math.max(e,t,n),i=Math.min(e,t,n);let r=0,s=0,o=(a+i)/2;if(a!==i){const l=a-i;switch(s=o>.5?l/(2-a-i):l/(a+i),a){case e:r=(t-n)/l+(t<n?6:0);break;case t:r=(n-e)/l+2;break;case n:r=(e-t)/l+4}r/=6}return{h:r,s,l:o}},hslToRgb=({h:e,s:t,l:n})=>{const a=(e,t,n)=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e);let i,r,s;if(0===t)i=r=s=n;else{const o=n<.5?n*(1+t):n+t-n*t,l=2*n-o;i=a(l,o,e+1/3),r=a(l,o,e),s=a(l,o,e-1/3)}return{r:Math.round(255*i),g:Math.round(255*r),b:Math.round(255*s)}},rgbToHex=({r:e,g:t,b:n})=>`#${[e,t,n].map((e=>e.toString(16).padStart(2,"0"))).join("")}`,lightenHex=(e,t=.4)=>{const n=hexToRgb(e);if(!n)return e;const a=rgbToHsl(n);return a.l=clamp01(a.l+(1-a.l)*t),a.s=clamp01(1.05*a.s),rgbToHex(hslToRgb(a))},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`,n=e(processedParams.aiAvatarUrl),a=e(processedParams.userAvatarUrl),i=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:n,userAvatarUrl:a,guestAvatarUrl:i}}),[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`),n=await t.json();if(setRestNonce(n.restNonce),restNonceRef.current=n.restNonce,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.setToken(n.restNonce),n.sessionId&&"N/A"!==n.sessionId&&setSessionId(n.sessionId),n.new_token){if(n.token_expires_at){const e=new Date(1e3*n.token_expires_at);console.log(`[MWAI] 🔐 New token received - expires at ${e.toLocaleTimeString()} (in ${n.token_expires_in}s)`)}return setRestNonce(n.new_token),restNonceRef.current=n.new_token,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.setToken(n.new_token),n.new_token}return n.restNonce}catch(e){console.error("Error while fetching the restNonce.",e)}finally{setBusyNonce(!1)}}),[restNonce,setRestNonce,restUrl,setSessionId]),[isResumingConversation,setIsResumingConversation]=useState(!1),[isConversationLoaded,setIsConversationLoaded]=useState(!1);useEffect((()=>{isConversationLoaded&&(isResumingConversation||messages.length>1||1===messages.length&&messages[0].content!==startSentence||(initialActions.length>0&&handleActions(initialActions),initialShortcuts.length>0&&handleShortcuts(initialShortcuts),initialBlocks.length>0&&handleBlocks(initialBlocks)))}),[isConversationLoaded,isResumingConversation,messages,startSentence]),useEffect((()=>{chatbotTriggered&&!restNonce&&refreshRestNonce()}),[chatbotTriggered]),useEffect((()=>{inputText.length>0&&!chatbotTriggered&&setChatbotTriggered(!0)}),[chatbotTriggered,inputText]),useEffect((()=>{resetMessages()}),[startSentence]),useEffect((()=>{if(customId||botId){const e=_app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3__.HX.chatbots.findIndex((e=>e.internalId===internalId)),t={internalId,botId,chatId,customId,localStorageKey,open:()=>{setTasks((e=>[...e,{action:"open"}]))},close:()=>{setTasks((e=>[...e,{action:"close"}]))},clear:e=>{const{chatId:t=null}=e||{};setTasks((e=>[...e,{action:"clear",data:{chatId:t}}]))},toggle:()=>{setTasks((e=>[...e,{action:"toggle"}]))},ask:(e,t=!1)=>{setTasks((n=>[...n,{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:n})=>{console.warn("MwaiAPI: setContext is deprecated. Please use setConversation instead."),setTasks((a=>[...a,{action:"setContext",data:{chatId:e,messages:t,previousResponseId:n}}]))},setConversation:({chatId:e,messages:t,previousResponseId:n})=>{setTasks((a=>[...a,{action:"setContext",data:{chatId:e,messages:t,previousResponseId:n}}]))}};-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 n={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,n])),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 n=e.length-1;let a=null,i=null;if(n>=0&&"user"===e[n].role){const t=e[n].content,r=t.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);a=r?r[1]:t,r&&uploadedFile&&(i=uploadedFile)}return setMessages(e),saveMessages(e),void addErrorMessage(serverReply.message,a?{text:a,file:i}: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 n;const e=(new Date).getTime(),a=e-((null===(n=t.streamEvents[0])||void 0===n?void 0:n.timestamp)||e);let i;i=a<1e3?`${a}ms`:a<6e4?`${(a/1e3).toFixed(1)}s`:`${Math.floor(a/6e4)}m ${(a%6e4/1e3).toFixed(0)}s`,t.streamEvents.push({type:"event",subtype:"status",data:`Request completed in ${i}.`,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(),n=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)(n,null,null,null,debugMode)}),[botId,customId,contextId,chatId,restNonce,refreshRestNonce,restUrl]),onCommitStats=useCallback((async(e,t=null)=>{try{const n=restNonceRef.current??await refreshRestNonce(),a=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/stats`,{botId,session:sessionId,refId:t||chatId,stats:e},n),i=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(a,null,null,null,debugMode);return{success:i.success,message:i.message,overLimit:i.overLimit||!1,limitMessage:i.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(),n={botId,session:sessionId,chatId,messages:(e??[]).filter((e=>"error"!==e.role&&!e.isError))},a=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/openai/realtime/discussions`,n,t),i=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(a,null,null,null,debugMode);return{success:i.success,message:i.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),n=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(t,null,null,null,debugMode);return n}{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 n=uploadedFile,a=multiUpload?uploadedFiles:[],i=null==uploadedFile?void 0:uploadedFile.uploadedUrl,r=null==uploadedFile||null===(t=uploadedFile.localFile)||void 0===t?void 0:t.type,s=!!r&&r.startsWith("image");let o=e;multiUpload&&a.length>0?o=`${a.map((e=>{var t;const n=null===(t=e.localFile)||void 0===t?void 0:t.type;return n&&n.startsWith("image")?``:`[${(null===(a=e.localFile)||void 0===a?void 0:a.name)||"Uploaded File"}](${e.uploadedUrl})`;var a})).join("\n")}\n${e}`:i&&(o=s?`\n${e}`:`[Uploaded File](${i})\n${e}`),setBusy(!0),setInputText(""),setShortcuts([]),setBlocks([]),resetUploadedFile(),multiUpload&&resetUploadedFiles();const l=[...messages,{id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"user",content:o,who:rawUserName,timestamp:(new Date).getTime()}];saveMessages(l);const c=(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),u=[...l,{id:c,role:"assistant",content:stream?"":null,who:rawAiName,timestamp:null,isQuerying:!stream,isStreaming:!!stream,streamEvents:stream&&(debugMode||eventLogs)?[]:void 0}];if(setMessages(u),"[ERROR]"===e){setBusy(!1);const t=messages.slice(0,-1);setMessages(t);const a=[__("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.")],i=a[Math.floor(Math.random()*a.length)],r={id:(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.vx)(),role:"error",content:`[TEST ERROR] ${i}`,who:"Error",timestamp:(new Date).getTime(),isError:!0,failedQuery:{text:e,file:n}},s=[...l,r];return setMessages(s),saveMessages(s),void setLastFailedQuery({text:e,file:n})}const d={botId,customId,session:sessionId,chatId,contextId,messages:messages.filter((e=>"error"!==e.role&&!e.isError)),newMessage:e,newFileId:multiUpload?null:null==n?void 0:n.uploadedId,newFileIds:multiUpload?a.map((e=>e.uploadedId)).filter((e=>e)):null,stream,...atts};previousResponseId&&(d.previousResponseId=previousResponseId);try{debugMode&&console.log("[CHATBOT] OUT: ",d);const e=stream?(e,t)=>{debugMode&&t&&t.subtype&&console.log("[CHATBOT] STREAM EVENT:",t),setMessages((n=>{const a=[...n],i=a.length>0?a[a.length-1]:null;return i&&i.id===c&&(i.content=e,i.timestamp=(new Date).getTime(),t&&t.subtype&&(i.streamEvents||(i.streamEvents=[]),i.streamEvents.push({...t,timestamp:(new Date).getTime()}))),a}))}:null,t=restNonceRef.current??await refreshRestNonce();stream&&(debugMode||eventLogs)&&e&&e("",{type:"event",subtype:"status",data:"Request sent...",timestamp:(new Date).getTime()});const a=e=>{setRestNonce(e),restNonceRef.current=e,_app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1__.A.setToken(e)},i=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.ti)(`${restUrl}/mwai-ui/v1/chats/submit`,d,t,stream,void 0,a),r=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.Pn)(i,e,debugMode?"CHATBOT":null,a,debugMode);if(!r.success&&r.message){const e=[...u];e.pop();const t=e.length-1;let a=null,i=null;if(t>=0&&"user"===e[t].role){const r=e[t].content,s=r.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);a=s?s[1]:r,s&&(i=n)}return setMessages(e),saveMessages(e),addErrorMessage(r.message,a?{text:a,file:i}: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 a=null,i=null;if(t>=0&&"user"===u[t].role){const e=u[t].content,r=e.match(/^(?:\!\[.*?\]\(.*?\)|\[.*?\]\(.*?\))\n(.*)$/s);a=r?r[1]:e,r&&(i=n)}addErrorMessage(e.message||__("An error occurred while processing your request. Please try again."),a?{text:a,file:i}:null)}}),[busy,uploadedFile,messages,saveMessages,stream,botId,customId,sessionId,chatId,contextId,atts,inputText,debugMode,restNonce,refreshRestNonce,restUrl]),onSubmitAction=useCallback(((e=null)=>{var t;const n=!(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):(n||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",n="N/A")=>{try{if(null===e)return void resetUploadedFile();const a={type:t,purpose:n},i=`${restUrl}/mwai-ui/v1/files/upload`,r=restNonceRef.current??await refreshRestNonce(),s=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.uE)(i,e,r,(t=>{setUploadedFile({localFile:e,uploadedId:null,uploadedUrl:null,uploadProgress:t})}),a);setUploadedFile({localFile:e,uploadedId:s.data.id,uploadedUrl:s.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,n)=>n!==e))))},resetUploadedFiles=()=>{setUploadedFiles([])},onMultiFileUpload=async(e,t="N/A",n="N/A")=>{try{if(null===e)return;const a={type:t,purpose:n},i=`${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 s=uploadedFiles.length,o=restNonceRef.current??await refreshRestNonce(),l=await(0,_app_helpers__WEBPACK_IMPORTED_MODULE_2__.uE)(i,e,o,(e=>{setUploadedFiles((t=>t.map(((t,n)=>n===s?{...t,uploadProgress:e}:t))))}),a);setUploadedFiles((t=>t.map(((t,n)=>n===s?{localFile:e,uploadedId:l.data.id,uploadedUrl:l.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:n}=e.data;n?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:n,previousResponseId:a}=e.data;setChatId(t),setMessages(n),a&&setPreviousResponseId(a),setIsResumingConversation(!0),setIsConversationLoaded(!0),setShortcuts([]),saveMessages(n)}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)}},137:(e,t,n)=>{"use strict";n.d(t,{HX:()=>i,W5:()=>r});class a{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,n=10){this.filters[e]||(this.filters[e]=[]),this.filters[e].push({callback:t,priority:n}),this.filters[e].sort(((e,t)=>e.priority-t.priority))}applyFilters(e,t,...n){return this.filters[e]?this.filters[e].reduce(((e,t)=>t.callback(e,...n)),t):t}addAction(e,t,n=10){this.actions[e]||(this.actions[e]=[]),this.actions[e].push({callback:t,priority:n}),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 i=(()=>{if("undefined"!=typeof window&&window.MwaiAPI)return window.MwaiAPI;const e=new a;return"undefined"!=typeof window&&(window.MwaiAPI=e),e})(),r=(e,t,...n)=>i.applyFilters(e,t,...n)},728:(e,t,n)=>{"use strict";n.d(t,{tm:()=>u,bE:()=>f,Mc:()=>g,mv:()=>m,_$:()=>h,dh:()=>p,gR:()=>d,Vw:()=>E});const a=(0,n(407).A)("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},i.apply(this,arguments)}const{useState:r,useMemo:s,useEffect:o,useRef:l,useCallback:c}=wp.element,u=({active:e,disabled:t,...n})=>React.createElement("div",i({active:e?"true":"false",disabled:t},n),React.createElement(a,{size:"24"})),d=()=>s((()=>(e,t)=>(Array.isArray(e)||(e=[e]),t&&Object.entries(t).forEach((([t,n])=>{n&&e.push(t)})),e.join(" "))),[]);function m(e){return!(!e||"string"!=typeof e)&&0===e.indexOf("http")}function p(){const[e,t]=r(null),n=l(null);function a(e){return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`}return o((()=>()=>{clearInterval(n.current)}),[]),{timeElapsed:e,startChrono:function(){if(null!==n.current)return;const e=Date.now();t(a(0)),n.current=setInterval((()=>{const n=Math.floor((Date.now()-e)/1e3);t(a(n))}),500)},stopChrono:function(){clearInterval(n.current),n.current=null,t(null)}}}const g=(e,t)=>"string"==typeof e&&t?(Object.entries(t).forEach((([t,n])=>{e=e.replace(new RegExp(`{${t}}`,"g"),n)})),e):e,h=(e,t=[])=>{var n,a,i,r,s,o,l,c,u,d,m,p,h,E,f,y,_;const w=(null===(n=e.guestName)||void 0===n?void 0:n.trim())??"",v=(null===(a=e.textSend)||void 0===a?void 0:a.trim())??"",R=(null===(i=e.textClear)||void 0===i?void 0:i.trim())??"",T=parseInt(e.textInputMaxLength),I=(null===(r=e.textInputPlaceholder)||void 0===r?void 0:r.trim())??"";let b=(null===(s=e.textCompliance)||void 0===s?void 0:s.trim())??"",S="",A="";const C=Boolean(e.window),N=Boolean(e.copyButton),k=Boolean(e.fullscreen),O=(null===(o=e.icon)||void 0===o?void 0:o.trim())??"";let x=(null===(l=e.iconText)||void 0===l?void 0:l.trim())??"";const M=parseInt(e.iconTextDelay||1),P=(null===(c=e.iconAlt)||void 0===c?void 0:c.trim())??"",L=(null===(u=e.iconPosition)||void 0===u?void 0:u.trim())??"",D=Boolean(e.centerOpen),U=(null===(d=e.width)||void 0===d?void 0:d.trim())??"",F=e.openDelay?parseInt(e.openDelay):null,B=Boolean(e.iconBubble),G=(null===(m=e.windowAnimation)||void 0===m?void 0:m.trim())??"zoom",H=(null===(p=e.aiName)||void 0===p?void 0:p.trim())??"",$=(null===(h=e.userName)||void 0===h?void 0:h.trim())??"",z=Boolean(null==e?void 0:e.aiAvatar),W=Boolean(null==e?void 0:e.userAvatar),K=Boolean(null==e?void 0:e.guestAvatar),j=z?(null==e||null===(E=e.aiAvatarUrl)||void 0===E?void 0:E.trim())??"":null,Y=W?(null==e||null===(f=e.userAvatarUrl)||void 0===f?void 0:f.trim())??"":null,V=K?(null==e||null===(y=e.guestAvatarUrl)||void 0===y?void 0:y.trim())??"":null,q=Boolean(e.localMemory),X=Boolean(e.imageUpload),Q=Boolean(e.fileUpload),J=Boolean(e.multiUpload),Z=Boolean(e.fileSearch),ee=(null===(_=e.mode)||void 0===_?void 0:_.trim())??"chat";var te,ne;return S=null===e.headerSubtitle||void 0===e.headerSubtitle?"Discuss with":(null===(te=e.headerSubtitle)||void 0===te?void 0:te.trim())??"",A=null===e.popupTitle||void 0===e.popupTitle?"AI Engine":(null===(ne=e.popupTitle)||void 0===ne?void 0:ne.trim())??"",t&&(b=g(b,t),x=g(x,t)),{textSend:v,textClear:R,textInputMaxLength:T,textInputPlaceholder:I,textCompliance:b,mode:ee,window:C,copyButton:N,fullscreen:k,localMemory:q,imageUpload:X,fileUpload:Q,multiUpload:J,fileSearch:Z,icon:O,iconText:x,iconTextDelay:M,iconAlt:P,iconPosition:L,centerOpen:D,width:U,openDelay:F,iconBubble:B,windowAnimation:G,headerSubtitle:S,popupTitle:A,aiName:H,userName:$,guestName:w,aiAvatar:z,userAvatar:W,guestAvatar:K,aiAvatarUrl:j,userAvatarUrl:Y,guestAvatarUrl:V}},E=e=>{const[t,n]=r(!1),[a,i]=r(!1);return o((()=>{"undefined"!=typeof window&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)&&i(!0)}),[]),o((()=>{if(!a)return;const i=new(window.SpeechRecognition||window.webkitSpeechRecognition);let r=null;return navigator.userAgent.toLowerCase().indexOf("android")>-1?(i.interimResults=!1,i.continuous=!1,r=t=>{const a=Array.from(t.results).filter((e=>e.isFinal)).map((e=>e[0].transcript)).join("");e(a),n(!1)}):(i.interimResults=!0,i.continuous=!0,r=t=>{const n=Array.from(t.results).map((e=>e[0])).map((e=>e.transcript)).join("");e(n)}),t?(i.addEventListener("result",r),i.start()):(i.removeEventListener("result",r),i.abort()),()=>{i.abort()}}),[t,a]),{isListening:t,setIsListening:n,speechRecognitionAvailable:a}},f=({if:e,className:t,disableTransition:n=!1,children:a,...s})=>{const[l,c]=r(!1),[u,d]=r("mwai-transition");return o((()=>{n?c(e):e?(c(!0),setTimeout((()=>{d("mwai-transition mwai-transition-visible")}),150)):d("mwai-transition")}),[e,n]),l?React.createElement("div",i({className:`${t} ${n?"":u}`,onTransitionEnd:()=>{"mwai-transition"!==u||n||c(!1)}},s),a):null}},678:(e,t,n)=>{"use strict";n.d(t,{F1:()=>o,Pn:()=>l,Ve:()=>g,rn:()=>m,ti:()=>c,uE:()=>u,vx:()=>d});const{useMemo:a,useEffect:i,useState:r}=wp.element;let s=null;try{s=n(233).A}catch(e){s={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 o(e,t=null,n=!0){const a=[];return JSON.stringify(e,((e,t)=>{if("object"==typeof t&&null!==t){if(a.includes(t)){if(!n)throw console.warn("Circular reference found.",{key:e,value:t,cache:a,cacheIndex:a.indexOf(t)}),new Error("Circular reference found. Cancelled.");return}a.push(t)}return t}),t)}async function l(e,t,n=null,a=null,i=!1){if(!t)try{const t=await e.json();return n&&console.log(`[${n}] IN: `,t),t.new_token&&(i&&console.log("[MWAI] Token refreshed!"),a&&a(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 l="",c="";for(;;){const{value:e,done:u}=await r.read();if(l+=o.decode(e,{stream:!0}),u)break;const d=l.split("\n");for(let e=0;e<d.length-1;e++){if(0!==d[e].indexOf("data: "))continue;const r=JSON.parse(d[e].replace("data: ",""));if("live"===r.type)n&&console.log(`[${n} 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 n&&console.error(`[${n} 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:s.ERRORS.COULD_NOT_PARSE_ERROR_STREAM}}else if("end"===r.type)try{const e=JSON.parse(r.data);return n&&console.log(`[${n} STREAM] END: `,e),e.new_token&&(i&&console.log("[MWAI] Token refreshed!"),a&&a(e.new_token)),e}catch(e){return console.error("Could not parse the 'end' stream.",{err:e,data:r}),{success:!1,message:s.ERRORS.COULD_NOT_PARSE_END_STREAM}}}l=d[d.length-1]}try{const e=JSON.parse(l);return n&&console.log(`[${n} STREAM] IN: `,e),e}catch(e){return console.error("Could not parse the buffer.",{err:e,buffer:l}),{success:!1,message:"Could not parse the buffer."}}}async function c(e,t,n,a,i=void 0,r=null){const l={"Content-Type":"application/json"};n&&(l["X-WP-Nonce"]=n),a&&(l.Accept="text/event-stream");const c=await fetch(`${e}`,{method:"POST",headers:l,body:o(t),credentials:"same-origin",signal:i});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(s.ERRORS.SESSION_EXPIRED)}catch(e){if(e.message&&e.message.includes("session has expired"))throw e}if(!a&&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 u(e,t,n,a,i={}){return new Promise(((r,s)=>{const o=new FormData;o.append("file",t);for(const[e,t]of Object.entries(i))o.append(e,t);const l=new XMLHttpRequest;l.open("POST",e,!0),n&&l.setRequestHeader("X-WP-Nonce",n),l.upload.onprogress=function(e){if(e.lengthComputable&&a){const t=e.loaded/e.total*100;a(t)}},l.onload=function(){if(l.status>=200&&l.status<300)try{const e=JSON.parse(l.responseText);r(e)}catch(e){s({status:l.status,statusText:l.statusText,error:"The server response is not valid JSON"})}else{try{const e=JSON.parse(l.responseText);return void s({status:l.status,message:e.message})}catch(e){}s({status:l.status,statusText:l.statusText})}},l.onerror=function(){s({status:l.status,statusText:l.statusText})},l.send(o)}))}function d(){return Math.random().toString(36).substring(2)}const m=()=>{const[e,t]=r(!0);i((()=>{const e=setTimeout((()=>{const e=setInterval((()=>{t((e=>!e))}),500);return()=>clearInterval(e)}),200);return()=>clearTimeout(e)}),[]);const n={opacity:e?1:0,width:"1px",height:"1em",borderLeft:"8px solid",marginLeft:"2px"};return React.createElement("span",{style:n})},p=/([\u2700-\u27BF]|[\uE000-\uF8FF]|[\uD800-\uDFFF]|[\uFE00-\uFE0F]|[\u1F100-\u1F1FF]|[\u1F200-\u1F2FF]|[\u1F300-\u1F5FF]|[\u1F600-\u1F64F]|[\u1F680-\u1F6FF]|[\u1F700-\u1F77F]|[\u1F780-\u1F7FF]|[\u1F800-\u1F8FF]|[\u1F900-\u1F9FF]|[\u1FA00-\u1FA6F])/;function g(e){return e&&2===e.length&&p.test(e)}},213:(e,t,n)=>{"use strict";n.d(t,{A:()=>i});const a=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&&a.setToken(window.mwai.rest_nonce);const i=a},407:(e,t,n)=>{"use strict";n.d(t,{A:()=>o});var a=n(594);const i=(...e)=>e.filter(((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t)).join(" ").trim();var r={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const s=(0,a.forwardRef)((({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:s,className:o="",children:l,iconNode:c,...u},d)=>(0,a.createElement)("svg",{ref:d,...r,width:t,height:t,stroke:e,strokeWidth:s?24*Number(n)/Number(t):n,className:i("lucide",o),...u},[...c.map((([e,t])=>(0,a.createElement)(e,t))),...Array.isArray(l)?l:[l]]))),o=(e,t)=>{const n=(0,a.forwardRef)((({className:n,...r},o)=>{return(0,a.createElement)(s,{ref:o,iconNode:t,className:i(`lucide-${l=e,l.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,n),...r});var l}));return n.displayName=`${e}`,n}},833:e=>{e.exports=function(e,t,n,a){var i=n?n.call(a,e,t):void 0;if(void 0!==i)return!!i;if(e===t)return!0;if("object"!=typeof e||!e||"object"!=typeof t||!t)return!1;var r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(var o=Object.prototype.hasOwnProperty.bind(t),l=0;l<r.length;l++){var c=r[l];if(!o(c))return!1;var u=e[c],d=t[c];if(!1===(i=n?n.call(a,u,d,c):void 0)||void 0===i&&u!==d)return!1}return!0}},594:e=>{"use strict";e.exports=React}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}__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 n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.nc=void 0;var __webpack_exports__={};(()=>{"use strict";var e=__webpack_require__(469),t=__webpack_require__(728);const n=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(){return!(!document||!document.body)&&!!(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=n);const a=n;var i=__webpack_require__(678),r=__webpack_require__(594),s=__webpack_require__.n(r),o=function(){return o=Object.assign||function(e){for(var t,n=1,a=arguments.length;n<a;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function l(e,t,n){if(n||2===arguments.length)for(var a,i=0,r=t.length;i<r;i++)!a&&i in t||(a||(a=Array.prototype.slice.call(t,0,i)),a[i]=t[i]);return e.concat(a||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var c=__webpack_require__(833),u=__webpack_require__.n(c),d="-ms-",m="-moz-",p="-webkit-",g="comm",h="rule",E="decl",f="@import",y="@keyframes",_="@layer",w=Math.abs,v=String.fromCharCode,R=Object.assign;function T(e){return e.trim()}function I(e,t){return(e=t.exec(e))?e[0]:e}function b(e,t,n){return e.replace(t,n)}function S(e,t,n){return e.indexOf(t,n)}function A(e,t){return 0|e.charCodeAt(t)}function C(e,t,n){return e.slice(t,n)}function N(e){return e.length}function k(e){return e.length}function O(e,t){return t.push(e),e}function x(e,t){return e.filter((function(e){return!I(e,t)}))}var M=1,P=1,L=0,D=0,U=0,F="";function B(e,t,n,a,i,r,s,o){return{value:e,root:t,parent:n,type:a,props:i,children:r,line:M,column:P,length:s,return:"",siblings:o}}function G(e,t){return R(B("",null,null,"",null,null,0,e.siblings),e,{length:-e.length},t)}function H(e){for(;e.root;)e=G(e.root,{children:[e]});O(e,e.siblings)}function $(){return U=D>0?A(F,--D):0,P--,10===U&&(P=1,M--),U}function z(){return U=D<L?A(F,D++):0,P++,10===U&&(P=1,M++),U}function W(){return A(F,D)}function K(){return D}function j(e,t){return C(F,e,t)}function Y(e){switch(e){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function V(e){return T(j(D-1,Q(91===e?e+2:40===e?e+1:e)))}function q(e){for(;(U=W())&&U<33;)z();return Y(e)>2||Y(U)>3?"":" "}function X(e,t){for(;--t&&z()&&!(U<48||U>102||U>57&&U<65||U>70&&U<97););return j(e,K()+(t<6&&32==W()&&32==z()))}function Q(e){for(;z();)switch(U){case e:return D;case 34:case 39:34!==e&&39!==e&&Q(U);break;case 40:41===e&&Q(e);break;case 92:z()}return D}function J(e,t){for(;z()&&e+U!==57&&(e+U!==84||47!==W()););return"/*"+j(t,D-1)+"*"+v(47===e?e:z())}function Z(e){for(;!Y(W());)z();return j(e,D)}function ee(e,t){for(var n="",a=0;a<e.length;a++)n+=t(e[a],a,e,t)||"";return n}function te(e,t,n,a){switch(e.type){case _:if(e.children.length)break;case f:case E:return e.return=e.return||e.value;case g:return"";case y:return e.return=e.value+"{"+ee(e.children,a)+"}";case h:if(!N(e.value=e.props.join(",")))return""}return N(n=ee(e.children,a))?e.return=e.value+"{"+n+"}":""}function ne(e,t,n){switch(function(e,t){return 45^A(e,0)?(((t<<2^A(e,0))<<2^A(e,1))<<2^A(e,2))<<2^A(e,3):0}(e,t)){case 5103:return p+"print-"+e+e;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return p+e+e;case 4789:return m+e+e;case 5349:case 4246:case 4810:case 6968:case 2756:return p+e+m+e+d+e+e;case 5936:switch(A(e,t+11)){case 114:return p+e+d+b(e,/[svh]\w+-[tblr]{2}/,"tb")+e;case 108:return p+e+d+b(e,/[svh]\w+-[tblr]{2}/,"tb-rl")+e;case 45:return p+e+d+b(e,/[svh]\w+-[tblr]{2}/,"lr")+e}case 6828:case 4268:case 2903:return p+e+d+e+e;case 6165:return p+e+d+"flex-"+e+e;case 5187:return p+e+b(e,/(\w+).+(:[^]+)/,p+"box-$1$2"+d+"flex-$1$2")+e;case 5443:return p+e+d+"flex-item-"+b(e,/flex-|-self/g,"")+(I(e,/flex-|baseline/)?"":d+"grid-row-"+b(e,/flex-|-self/g,""))+e;case 4675:return p+e+d+"flex-line-pack"+b(e,/align-content|flex-|-self/g,"")+e;case 5548:return p+e+d+b(e,"shrink","negative")+e;case 5292:return p+e+d+b(e,"basis","preferred-size")+e;case 6060:return p+"box-"+b(e,"-grow","")+p+e+d+b(e,"grow","positive")+e;case 4554:return p+b(e,/([^-])(transform)/g,"$1"+p+"$2")+e;case 6187:return b(b(b(e,/(zoom-|grab)/,p+"$1"),/(image-set)/,p+"$1"),e,"")+e;case 5495:case 3959:return b(e,/(image-set\([^]*)/,p+"$1$`$1");case 4968:return b(b(e,/(.+:)(flex-)?(.*)/,p+"box-pack:$3"+d+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+p+e+e;case 4200:if(!I(e,/flex-|baseline/))return d+"grid-column-align"+C(e,t)+e;break;case 2592:case 3360:return d+b(e,"template-","")+e;case 4384:case 3616:return n&&n.some((function(e,n){return t=n,I(e.props,/grid-\w+-end/)}))?~S(e+(n=n[t].value),"span",0)?e:d+b(e,"-start","")+e+d+"grid-row-span:"+(~S(n,"span",0)?I(n,/\d+/):+I(n,/\d+/)-+I(e,/\d+/))+";":d+b(e,"-start","")+e;case 4896:case 4128:return n&&n.some((function(e){return I(e.props,/grid-\w+-start/)}))?e:d+b(b(e,"-end","-span"),"span ","")+e;case 4095:case 3583:case 4068:case 2532:return b(e,/(.+)-inline(.+)/,p+"$1$2")+e;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(N(e)-1-t>6)switch(A(e,t+1)){case 109:if(45!==A(e,t+4))break;case 102:return b(e,/(.+:)(.+)-([^]+)/,"$1"+p+"$2-$3$1"+m+(108==A(e,t+3)?"$3":"$2-$3"))+e;case 115:return~S(e,"stretch",0)?ne(b(e,"stretch","fill-available"),t,n)+e:e}break;case 5152:case 5920:return b(e,/(.+?):(\d+)(\s*\/\s*(span)?\s*(\d+))?(.*)/,(function(t,n,a,i,r,s,o){return d+n+":"+a+o+(i?d+n+"-span:"+(r?s:+s-+a)+o:"")+e}));case 4949:if(121===A(e,t+6))return b(e,":",":"+p)+e;break;case 6444:switch(A(e,45===A(e,14)?18:11)){case 120:return b(e,/(.+:)([^;\s!]+)(;|(\s+)?!.+)?/,"$1"+p+(45===A(e,14)?"inline-":"")+"box$3$1"+p+"$2$3$1"+d+"$2box$3")+e;case 100:return b(e,":",":"+d)+e}break;case 5719:case 2647:case 2135:case 3927:case 2391:return b(e,"scroll-","scroll-snap-")+e}return e}function ae(e,t,n,a){if(e.length>-1&&!e.return)switch(e.type){case E:return void(e.return=ne(e.value,e.length,n));case y:return ee([G(e,{value:b(e.value,"@","@"+p)})],a);case h:if(e.length)return function(e,t){return e.map(t).join("")}(n=e.props,(function(t){switch(I(t,a=/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":H(G(e,{props:[b(t,/:(read-\w+)/,":"+m+"$1")]})),H(G(e,{props:[t]})),R(e,{props:x(n,a)});break;case"::placeholder":H(G(e,{props:[b(t,/:(plac\w+)/,":"+p+"input-$1")]})),H(G(e,{props:[b(t,/:(plac\w+)/,":"+m+"$1")]})),H(G(e,{props:[b(t,/:(plac\w+)/,d+"input-$1")]})),H(G(e,{props:[t]})),R(e,{props:x(n,a)})}return""}))}}function ie(e){return function(e){return F="",e}(re("",null,null,null,[""],e=function(e){return M=P=1,L=N(F=e),D=0,[]}(e),0,[0],e))}function re(e,t,n,a,i,r,s,o,l){for(var c=0,u=0,d=s,m=0,p=0,g=0,h=1,E=1,f=1,y=0,_="",R=i,T=r,I=a,C=_;E;)switch(g=y,y=z()){case 40:if(108!=g&&58==A(C,d-1)){-1!=S(C+=b(V(y),"&","&\f"),"&\f",w(c?o[c-1]:0))&&(f=-1);break}case 34:case 39:case 91:C+=V(y);break;case 9:case 10:case 13:case 32:C+=q(g);break;case 92:C+=X(K()-1,7);continue;case 47:switch(W()){case 42:case 47:O(oe(J(z(),K()),t,n,l),l);break;default:C+="/"}break;case 123*h:o[c++]=N(C)*f;case 125*h:case 59:case 0:switch(y){case 0:case 125:E=0;case 59+u:-1==f&&(C=b(C,/\f/g,"")),p>0&&N(C)-d&&O(p>32?le(C+";",a,n,d-1,l):le(b(C," ","")+";",a,n,d-2,l),l);break;case 59:C+=";";default:if(O(I=se(C,t,n,c,u,i,o,_,R=[],T=[],d,r),r),123===y)if(0===u)re(C,t,I,I,R,r,d,o,T);else switch(99===m&&110===A(C,3)?100:m){case 100:case 108:case 109:case 115:re(e,I,I,a&&O(se(e,I,I,0,0,i,o,_,i,R=[],d,T),T),i,T,d,o,a?R:T);break;default:re(C,I,I,I,[""],T,0,o,T)}}c=u=p=0,h=f=1,_=C="",d=s;break;case 58:d=1+N(C),p=g;default:if(h<1)if(123==y)--h;else if(125==y&&0==h++&&125==$())continue;switch(C+=v(y),y*h){case 38:f=u>0?1:(C+="\f",-1);break;case 44:o[c++]=(N(C)-1)*f,f=1;break;case 64:45===W()&&(C+=V(z())),m=W(),u=d=N(_=C+=Z(K())),y++;break;case 45:45===g&&2==N(C)&&(h=0)}}return r}function se(e,t,n,a,i,r,s,o,l,c,u,d){for(var m=i-1,p=0===i?r:[""],g=k(p),E=0,f=0,y=0;E<a;++E)for(var _=0,v=C(e,m+1,m=w(f=s[E])),R=e;_<g;++_)(R=T(f>0?p[_]+" "+v:b(v,/&\f/g,p[_])))&&(l[y++]=R);return B(e,t,n,0===i?h:o,l,c,u,d)}function oe(e,t,n,a){return B(e,t,n,g,v(U),C(e,2,-2),0,a)}function le(e,t,n,a,i){return B(e,t,n,E,C(e,0,a),C(e,a+1,-1),a,i)}var ce={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},ue="undefined"!=typeof process&&void 0!==process.env&&(process.env.REACT_APP_SC_ATTR||process.env.SC_ATTR)||"data-styled",de="active",me="data-styled-version",pe="6.1.12",ge="/*!sc*/\n",he="undefined"!=typeof window&&"HTMLElement"in window,Ee=Boolean("boolean"==typeof SC_DISABLE_SPEEDY?SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env&&void 0!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&""!==process.env.REACT_APP_SC_DISABLE_SPEEDY?"false"!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&process.env.REACT_APP_SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env&&void 0!==process.env.SC_DISABLE_SPEEDY&&""!==process.env.SC_DISABLE_SPEEDY&&"false"!==process.env.SC_DISABLE_SPEEDY&&process.env.SC_DISABLE_SPEEDY),fe=(new Set,Object.freeze([])),ye=Object.freeze({});var _e=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","track","u","ul","use","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"]),we=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,ve=/(^-|-$)/g;function Re(e){return e.replace(we,"-").replace(ve,"")}var Te=/(a)(d)/gi,Ie=52,be=function(e){return String.fromCharCode(e+(e>25?39:97))};function Se(e){var t,n="";for(t=Math.abs(e);t>Ie;t=t/Ie|0)n=be(t%Ie)+n;return(be(t%Ie)+n).replace(Te,"$1-$2")}var Ae,Ce=5381,Ne=function(e,t){for(var n=t.length;n;)e=33*e^t.charCodeAt(--n);return e},ke=function(e){return Ne(Ce,e)};function Oe(e){return"string"==typeof e&&!0}var xe="function"==typeof Symbol&&Symbol.for,Me=xe?Symbol.for("react.memo"):60115,Pe=xe?Symbol.for("react.forward_ref"):60112,Le={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},De={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},Ue={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Fe=((Ae={})[Pe]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Ae[Me]=Ue,Ae);function Be(e){return("type"in(t=e)&&t.type.$$typeof)===Me?Ue:"$$typeof"in e?Fe[e.$$typeof]:Le;var t}var Ge=Object.defineProperty,He=Object.getOwnPropertyNames,$e=Object.getOwnPropertySymbols,ze=Object.getOwnPropertyDescriptor,We=Object.getPrototypeOf,Ke=Object.prototype;function je(e,t,n){if("string"!=typeof t){if(Ke){var a=We(t);a&&a!==Ke&&je(e,a,n)}var i=He(t);$e&&(i=i.concat($e(t)));for(var r=Be(e),s=Be(t),o=0;o<i.length;++o){var l=i[o];if(!(l in De||n&&n[l]||s&&l in s||r&&l in r)){var c=ze(t,l);try{Ge(e,l,c)}catch(e){}}}}return e}function Ye(e){return"function"==typeof e}function Ve(e){return"object"==typeof e&&"styledComponentId"in e}function qe(e,t){return e&&t?"".concat(e," ").concat(t):e||t||""}function Xe(e,t){if(0===e.length)return"";for(var n=e[0],a=1;a<e.length;a++)n+=t?t+e[a]:e[a];return n}function Qe(e){return null!==e&&"object"==typeof e&&e.constructor.name===Object.name&&!("props"in e&&e.$$typeof)}function Je(e,t,n){if(void 0===n&&(n=!1),!n&&!Qe(e)&&!Array.isArray(e))return t;if(Array.isArray(t))for(var a=0;a<t.length;a++)e[a]=Je(e[a],t[a]);else if(Qe(t))for(var a in t)e[a]=Je(e[a],t[a]);return e}function Ze(e,t){Object.defineProperty(e,"toString",{value:t})}function et(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return new Error("An error occurred. See https://github.com/styled-components/styled-components/blob/main/packages/styled-components/src/utils/errors.md#".concat(e," for more information.").concat(t.length>0?" Args: ".concat(t.join(", ")):""))}var tt=function(){function e(e){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=e}return e.prototype.indexOfGroup=function(e){for(var t=0,n=0;n<e;n++)t+=this.groupSizes[n];return t},e.prototype.insertRules=function(e,t){if(e>=this.groupSizes.length){for(var n=this.groupSizes,a=n.length,i=a;e>=i;)if((i<<=1)<0)throw et(16,"".concat(e));this.groupSizes=new Uint32Array(i),this.groupSizes.set(n),this.length=i;for(var r=a;r<i;r++)this.groupSizes[r]=0}for(var s=this.indexOfGroup(e+1),o=(r=0,t.length);r<o;r++)this.tag.insertRule(s,t[r])&&(this.groupSizes[e]++,s++)},e.prototype.clearGroup=function(e){if(e<this.length){var t=this.groupSizes[e],n=this.indexOfGroup(e),a=n+t;this.groupSizes[e]=0;for(var i=n;i<a;i++)this.tag.deleteRule(n)}},e.prototype.getGroup=function(e){var t="";if(e>=this.length||0===this.groupSizes[e])return t;for(var n=this.groupSizes[e],a=this.indexOfGroup(e),i=a+n,r=a;r<i;r++)t+="".concat(this.tag.getRule(r)).concat(ge);return t},e}(),nt=new Map,at=new Map,it=1,rt=function(e){if(nt.has(e))return nt.get(e);for(;at.has(it);)it++;var t=it++;return nt.set(e,t),at.set(t,e),t},st=function(e,t){it=t+1,nt.set(e,t),at.set(t,e)},ot="style[".concat(ue,"][").concat(me,'="').concat(pe,'"]'),lt=new RegExp("^".concat(ue,'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)')),ct=function(e,t,n){for(var a,i=n.split(","),r=0,s=i.length;r<s;r++)(a=i[r])&&e.registerName(t,a)},ut=function(e,t){for(var n,a=(null!==(n=t.textContent)&&void 0!==n?n:"").split(ge),i=[],r=0,s=a.length;r<s;r++){var o=a[r].trim();if(o){var l=o.match(lt);if(l){var c=0|parseInt(l[1],10),u=l[2];0!==c&&(st(u,c),ct(e,u,l[3]),e.getTag().insertRules(c,i)),i.length=0}else i.push(o)}}},dt=function(e){for(var t=document.querySelectorAll(ot),n=0,a=t.length;n<a;n++){var i=t[n];i&&i.getAttribute(ue)!==de&&(ut(e,i),i.parentNode&&i.parentNode.removeChild(i))}};function mt(){return __webpack_require__.nc}var pt=function(e){var t=document.head,n=e||t,a=document.createElement("style"),i=function(e){var t=Array.from(e.querySelectorAll("style[".concat(ue,"]")));return t[t.length-1]}(n),r=void 0!==i?i.nextSibling:null;a.setAttribute(ue,de),a.setAttribute(me,pe);var s=mt();return s&&a.setAttribute("nonce",s),n.insertBefore(a,r),a},gt=function(){function e(e){this.element=pt(e),this.element.appendChild(document.createTextNode("")),this.sheet=function(e){if(e.sheet)return e.sheet;for(var t=document.styleSheets,n=0,a=t.length;n<a;n++){var i=t[n];if(i.ownerNode===e)return i}throw et(17)}(this.element),this.length=0}return e.prototype.insertRule=function(e,t){try{return this.sheet.insertRule(t,e),this.length++,!0}catch(e){return!1}},e.prototype.deleteRule=function(e){this.sheet.deleteRule(e),this.length--},e.prototype.getRule=function(e){var t=this.sheet.cssRules[e];return t&&t.cssText?t.cssText:""},e}(),ht=function(){function e(e){this.element=pt(e),this.nodes=this.element.childNodes,this.length=0}return e.prototype.insertRule=function(e,t){if(e<=this.length&&e>=0){var n=document.createTextNode(t);return this.element.insertBefore(n,this.nodes[e]||null),this.length++,!0}return!1},e.prototype.deleteRule=function(e){this.element.removeChild(this.nodes[e]),this.length--},e.prototype.getRule=function(e){return e<this.length?this.nodes[e].textContent:""},e}(),Et=function(){function e(e){this.rules=[],this.length=0}return e.prototype.insertRule=function(e,t){return e<=this.length&&(this.rules.splice(e,0,t),this.length++,!0)},e.prototype.deleteRule=function(e){this.rules.splice(e,1),this.length--},e.prototype.getRule=function(e){return e<this.length?this.rules[e]:""},e}(),ft=he,yt={isServer:!he,useCSSOMInjection:!Ee},_t=function(){function e(e,t,n){void 0===e&&(e=ye),void 0===t&&(t={});var a=this;this.options=o(o({},yt),e),this.gs=t,this.names=new Map(n),this.server=!!e.isServer,!this.server&&he&&ft&&(ft=!1,dt(this)),Ze(this,(function(){return function(e){for(var t=e.getTag(),n=t.length,a="",i=function(n){var i=function(e){return at.get(e)}(n);if(void 0===i)return"continue";var r=e.names.get(i),s=t.getGroup(n);if(void 0===r||!r.size||0===s.length)return"continue";var o="".concat(ue,".g").concat(n,'[id="').concat(i,'"]'),l="";void 0!==r&&r.forEach((function(e){e.length>0&&(l+="".concat(e,","))})),a+="".concat(s).concat(o,'{content:"').concat(l,'"}').concat(ge)},r=0;r<n;r++)i(r);return a}(a)}))}return e.registerId=function(e){return rt(e)},e.prototype.rehydrate=function(){!this.server&&he&&dt(this)},e.prototype.reconstructWithOptions=function(t,n){return void 0===n&&(n=!0),new e(o(o({},this.options),t),this.gs,n&&this.names||void 0)},e.prototype.allocateGSInstance=function(e){return this.gs[e]=(this.gs[e]||0)+1},e.prototype.getTag=function(){return this.tag||(this.tag=(e=function(e){var t=e.useCSSOMInjection,n=e.target;return e.isServer?new Et(n):t?new gt(n):new ht(n)}(this.options),new tt(e)));var e},e.prototype.hasNameForId=function(e,t){return this.names.has(e)&&this.names.get(e).has(t)},e.prototype.registerName=function(e,t){if(rt(e),this.names.has(e))this.names.get(e).add(t);else{var n=new Set;n.add(t),this.names.set(e,n)}},e.prototype.insertRules=function(e,t,n){this.registerName(e,t),this.getTag().insertRules(rt(e),n)},e.prototype.clearNames=function(e){this.names.has(e)&&this.names.get(e).clear()},e.prototype.clearRules=function(e){this.getTag().clearGroup(rt(e)),this.clearNames(e)},e.prototype.clearTag=function(){this.tag=void 0},e}(),wt=/&/g,vt=/^\s*\/\/.*$/gm;function Rt(e,t){return e.map((function(e){return"rule"===e.type&&(e.value="".concat(t," ").concat(e.value),e.value=e.value.replaceAll(",",",".concat(t," ")),e.props=e.props.map((function(e){return"".concat(t," ").concat(e)}))),Array.isArray(e.children)&&"@keyframes"!==e.type&&(e.children=Rt(e.children,t)),e}))}function Tt(e){var t,n,a,i=void 0===e?ye:e,r=i.options,s=void 0===r?ye:r,o=i.plugins,l=void 0===o?fe:o,c=function(e,a,i){return i.startsWith(n)&&i.endsWith(n)&&i.replaceAll(n,"").length>0?".".concat(t):e},u=l.slice();u.push((function(e){e.type===h&&e.value.includes("&")&&(e.props[0]=e.props[0].replace(wt,n).replace(a,c))})),s.prefix&&u.push(ae),u.push(te);var d=function(e,i,r,o){void 0===i&&(i=""),void 0===r&&(r=""),void 0===o&&(o="&"),t=o,n=i,a=new RegExp("\\".concat(n,"\\b"),"g");var l=e.replace(vt,""),c=ie(r||i?"".concat(r," ").concat(i," { ").concat(l," }"):l);s.namespace&&(c=Rt(c,s.namespace));var d,m,p,g=[];return ee(c,(d=u.concat((p=function(e){return g.push(e)},function(e){e.root||(e=e.return)&&p(e)})),m=k(d),function(e,t,n,a){for(var i="",r=0;r<m;r++)i+=d[r](e,t,n,a)||"";return i})),g};return d.hash=l.length?l.reduce((function(e,t){return t.name||et(15),Ne(e,t.name)}),Ce).toString():"",d}var It=new _t,bt=Tt(),St=s().createContext({shouldForwardProp:void 0,styleSheet:It,stylis:bt}),At=(St.Consumer,s().createContext(void 0));function Ct(){return(0,r.useContext)(St)}function Nt(e){var t=(0,r.useState)(e.stylisPlugins),n=t[0],a=t[1],i=Ct().styleSheet,o=(0,r.useMemo)((function(){var t=i;return e.sheet?t=e.sheet:e.target&&(t=t.reconstructWithOptions({target:e.target},!1)),e.disableCSSOMInjection&&(t=t.reconstructWithOptions({useCSSOMInjection:!1})),t}),[e.disableCSSOMInjection,e.sheet,e.target,i]),l=(0,r.useMemo)((function(){return Tt({options:{namespace:e.namespace,prefix:e.enableVendorPrefixes},plugins:n})}),[e.enableVendorPrefixes,e.namespace,n]);(0,r.useEffect)((function(){u()(n,e.stylisPlugins)||a(e.stylisPlugins)}),[e.stylisPlugins]);var c=(0,r.useMemo)((function(){return{shouldForwardProp:e.shouldForwardProp,styleSheet:o,stylis:l}}),[e.shouldForwardProp,o,l]);return s().createElement(St.Provider,{value:c},s().createElement(At.Provider,{value:l},e.children))}var kt=function(){function e(e,t){var n=this;this.inject=function(e,t){void 0===t&&(t=bt);var a=n.name+t.hash;e.hasNameForId(n.id,a)||e.insertRules(n.id,a,t(n.rules,a,"@keyframes"))},this.name=e,this.id="sc-keyframes-".concat(e),this.rules=t,Ze(this,(function(){throw et(12,String(n.name))}))}return e.prototype.getName=function(e){return void 0===e&&(e=bt),this.name+e.hash},e}(),Ot=function(e){return e>="A"&&e<="Z"};function xt(e){for(var t="",n=0;n<e.length;n++){var a=e[n];if(1===n&&"-"===a&&"-"===e[0])return e;Ot(a)?t+="-"+a.toLowerCase():t+=a}return t.startsWith("ms-")?"-"+t:t}var Mt=function(e){return null==e||!1===e||""===e},Pt=function(e){var t,n,a=[];for(var i in e){var r=e[i];e.hasOwnProperty(i)&&!Mt(r)&&(Array.isArray(r)&&r.isCss||Ye(r)?a.push("".concat(xt(i),":"),r,";"):Qe(r)?a.push.apply(a,l(l(["".concat(i," {")],Pt(r),!1),["}"],!1)):a.push("".concat(xt(i),": ").concat((t=i,null==(n=r)||"boolean"==typeof n||""===n?"":"number"!=typeof n||0===n||t in ce||t.startsWith("--")?String(n).trim():"".concat(n,"px")),";")))}return a};function Lt(e,t,n,a){return Mt(e)?[]:Ve(e)?[".".concat(e.styledComponentId)]:Ye(e)?!Ye(i=e)||i.prototype&&i.prototype.isReactComponent||!t?[e]:Lt(e(t),t,n,a):e instanceof kt?n?(e.inject(n,a),[e.getName(a)]):[e]:Qe(e)?Pt(e):Array.isArray(e)?Array.prototype.concat.apply(fe,e.map((function(e){return Lt(e,t,n,a)}))):[e.toString()];var i}function Dt(e){for(var t=0;t<e.length;t+=1){var n=e[t];if(Ye(n)&&!Ve(n))return!1}return!0}var Ut=ke(pe),Ft=function(){function e(e,t,n){this.rules=e,this.staticRulesId="",this.isStatic=(void 0===n||n.isStatic)&&Dt(e),this.componentId=t,this.baseHash=Ne(Ut,t),this.baseStyle=n,_t.registerId(t)}return e.prototype.generateAndInjectStyles=function(e,t,n){var a=this.baseStyle?this.baseStyle.generateAndInjectStyles(e,t,n):"";if(this.isStatic&&!n.hash)if(this.staticRulesId&&t.hasNameForId(this.componentId,this.staticRulesId))a=qe(a,this.staticRulesId);else{var i=Xe(Lt(this.rules,e,t,n)),r=Se(Ne(this.baseHash,i)>>>0);if(!t.hasNameForId(this.componentId,r)){var s=n(i,".".concat(r),void 0,this.componentId);t.insertRules(this.componentId,r,s)}a=qe(a,r),this.staticRulesId=r}else{for(var o=Ne(this.baseHash,n.hash),l="",c=0;c<this.rules.length;c++){var u=this.rules[c];if("string"==typeof u)l+=u;else if(u){var d=Xe(Lt(u,e,t,n));o=Ne(o,d+c),l+=d}}if(l){var m=Se(o>>>0);t.hasNameForId(this.componentId,m)||t.insertRules(this.componentId,m,n(l,".".concat(m),void 0,this.componentId)),a=qe(a,m)}}return a},e}(),Bt=s().createContext(void 0);Bt.Consumer;var Gt={};function Ht(e,t,n){var a=Ve(e),i=e,l=!Oe(e),c=t.attrs,u=void 0===c?fe:c,d=t.componentId,m=void 0===d?function(e,t){var n="string"!=typeof e?"sc":Re(e);Gt[n]=(Gt[n]||0)+1;var a="".concat(n,"-").concat(function(e){return Se(ke(e)>>>0)}(pe+n+Gt[n]));return t?"".concat(t,"-").concat(a):a}(t.displayName,t.parentComponentId):d,p=t.displayName,g=void 0===p?function(e){return Oe(e)?"styled.".concat(e):"Styled(".concat(function(e){return e.displayName||e.name||"Component"}(e),")")}(e):p,h=t.displayName&&t.componentId?"".concat(Re(t.displayName),"-").concat(t.componentId):t.componentId||m,E=a&&i.attrs?i.attrs.concat(u).filter(Boolean):u,f=t.shouldForwardProp;if(a&&i.shouldForwardProp){var y=i.shouldForwardProp;if(t.shouldForwardProp){var _=t.shouldForwardProp;f=function(e,t){return y(e,t)&&_(e,t)}}else f=y}var w=new Ft(n,h,a?i.componentStyle:void 0);function v(e,t){return function(e,t,n){var a=e.attrs,i=e.componentStyle,l=e.defaultProps,c=e.foldedComponentIds,u=e.styledComponentId,d=e.target,m=s().useContext(Bt),p=Ct(),g=e.shouldForwardProp||p.shouldForwardProp,h=function(e,t,n){return void 0===n&&(n=ye),e.theme!==n.theme&&e.theme||t||n.theme}(t,m,l)||ye,E=function(e,t,n){for(var a,i=o(o({},t),{className:void 0,theme:n}),r=0;r<e.length;r+=1){var s=Ye(a=e[r])?a(i):a;for(var l in s)i[l]="className"===l?qe(i[l],s[l]):"style"===l?o(o({},i[l]),s[l]):s[l]}return t.className&&(i.className=qe(i.className,t.className)),i}(a,t,h),f=E.as||d,y={};for(var _ in E)void 0===E[_]||"$"===_[0]||"as"===_||"theme"===_&&E.theme===h||("forwardedAs"===_?y.as=E.forwardedAs:g&&!g(_,f)||(y[_]=E[_]));var w=function(e,t){var n=Ct();return e.generateAndInjectStyles(t,n.styleSheet,n.stylis)}(i,E),v=qe(c,u);return w&&(v+=" "+w),E.className&&(v+=" "+E.className),y[Oe(f)&&!_e.has(f)?"class":"className"]=v,y.ref=n,(0,r.createElement)(f,y)}(R,e,t)}v.displayName=g;var R=s().forwardRef(v);return R.attrs=E,R.componentStyle=w,R.displayName=g,R.shouldForwardProp=f,R.foldedComponentIds=a?qe(i.foldedComponentIds,i.styledComponentId):"",R.styledComponentId=h,R.target=a?i.target:e,Object.defineProperty(R,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(e){this._foldedDefaultProps=a?function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var a=0,i=t;a<i.length;a++)Je(e,i[a],!0);return e}({},i.defaultProps,e):e}}),Ze(R,(function(){return".".concat(R.styledComponentId)})),l&&je(R,e,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0}),R}function $t(e,t){for(var n=[e[0]],a=0,i=t.length;a<i;a+=1)n.push(t[a],e[a+1]);return n}new Set;var zt=function(e){return Object.assign(e,{isCss:!0})};function Wt(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(Ye(e)||Qe(e))return zt(Lt($t(fe,l([e],t,!0))));var a=e;return 0===t.length&&1===a.length&&"string"==typeof a[0]?Lt(a):zt(Lt($t(a,t)))}function Kt(e,t,n){if(void 0===n&&(n=ye),!t)throw et(1,t);var a=function(a){for(var i=[],r=1;r<arguments.length;r++)i[r-1]=arguments[r];return e(t,n,Wt.apply(void 0,l([a],i,!1)))};return a.attrs=function(a){return Kt(e,t,o(o({},n),{attrs:Array.prototype.concat(n.attrs,a).filter(Boolean)}))},a.withConfig=function(a){return Kt(e,t,o(o({},n),a))},a}var jt=function(e){return Kt(Ht,e)},Yt=jt;_e.forEach((function(e){Yt[e]=jt(e)})),function(){function e(e,t){this.rules=e,this.componentId=t,this.isStatic=Dt(e),_t.registerId(this.componentId+1)}e.prototype.createStyles=function(e,t,n,a){var i=a(Xe(Lt(this.rules,t,n,a)),""),r=this.componentId+e;n.insertRules(r,r,i)},e.prototype.removeStyles=function(e,t){t.clearRules(this.componentId+e)},e.prototype.renderStyles=function(e,t,n,a){e>2&&_t.registerId(this.componentId+e),this.removeStyles(e,n),this.createStyles(e,t,n,a)}}(),function(){function e(){var e=this;this._emitSheetCSS=function(){var t=e.instance.toString();if(!t)return"";var n=mt(),a=Xe([n&&'nonce="'.concat(n,'"'),"".concat(ue,'="true"'),"".concat(me,'="').concat(pe,'"')].filter(Boolean)," ");return"<style ".concat(a,">").concat(t,"</style>")},this.getStyleTags=function(){if(e.sealed)throw et(2);return e._emitSheetCSS()},this.getStyleElement=function(){var t;if(e.sealed)throw et(2);var n=e.instance.toString();if(!n)return[];var a=((t={})[ue]="",t[me]=pe,t.dangerouslySetInnerHTML={__html:n},t),i=mt();return i&&(a.nonce=i),[s().createElement("style",o({},a,{key:"sc-0-0"}))]},this.seal=function(){e.sealed=!0},this.instance=new _t({isServer:!0}),this.sealed=!1}e.prototype.collectStyles=function(e){if(this.sealed)throw et(2);return s().createElement(Nt,{sheet:this.instance},e)},e.prototype.interleaveWithNodeStream=function(e){throw et(3)}}(),"__sc-".concat(ue,"__");const Vt=Yt.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>');
}
}
}
`,qt=()=>{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,n)=>React.createElement("div",{key:n,style:{...e,animationDelay:t}})))))};function Xt(){return Xt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},Xt.apply(this,arguments)}const{useState:Qt,useEffect:Jt,useRef:Zt,useCallback:en}=wp.element,tn=({enabled:e,content:n,children:a,className:i,message:r,...s})=>{var o;const l=(0,t.gR)(),[c,u]=Qt("idle"),[d,m]=Qt(!0),[p,g]=Qt([]),h=Zt(null),E=Zt(!1),f=Zt(null),y=(null==r||null===(o=r.images)||void 0===o?void 0:o.filter((e=>e&&!e.includes("placehold.co")&&!e.includes("Expired+Image"))))||[],_=y.length>0,w=p.length>0,v=_||w;Jt((()=>{const e=()=>{if(f.current){const e=f.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?g(t):g([])}};e();const t=setTimeout(e,100);return()=>clearTimeout(t)}),[a]);const R=en((()=>{E.current||(E.current=!0,h.current=setTimeout((()=>{m(!1)}),500))}),[]),T=en((()=>{h.current&&clearTimeout(h.current),m(!0),E.current=!1}),[]);Jt((()=>()=>{h.current&&clearTimeout(h.current)}),[]);const I="success"===c?'<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"===c?'<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" />',b=!!e||v;return React.createElement("div",Xt({},s,{ref:f,onMouseLeave:T,onMouseEnter:R,onMouseOver:R}),React.createElement("span",{className:i},a),b&&React.createElement("div",{className:l("mwai-reply-actions",{"mwai-hidden":d})},e&&React.createElement("div",{className:"mwai-copy-button",onClick:()=>{try{navigator.clipboard.writeText(n),u("success")}catch(e){u("error"),console.warn("Not allowed to copy to clipboard. Make sure your website uses HTTPS.",{content:n})}finally{setTimeout((()=>{u("idle")}),2e3)}}},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:I}})),v&&React.createElement("div",{className:"mwai-download-button",onClick:async()=>{if(!v)return;const e=_?y:p;for(let t=0;t<e.length;t++){const n=e[t];try{const e=await fetch(n),a=await e.blob(),i=window.URL.createObjectURL(a),s=document.createElement("a");s.href=i;let o=`ai-image-${t+1}.png`;try{const e=n.split("/"),t=e[e.length-1];t&&!t.includes("?")&&(o=t)}catch(e){}s.download=o,document.body.appendChild(s),s.click(),document.body.removeChild(s),window.URL.revokeObjectURL(i),t<r.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:nn}=wp.element,an=({enabled:n,content:a,children:i,className:r,message:s,...o})=>{const l=(0,t.gR)(),{actions:c,state:u}=(0,e.o)(),{setMessages:d,saveMessages:m,retryLastQuery:p}=c,{messages:g}=u,[h,E]=nn("idle"),f=g.length>0&&g[g.length-1].id===s.id,y="success"===h?'<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"===h?'<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",o,React.createElement("span",{className:r},i),React.createElement("div",{className:l("mwai-reply-actions")},React.createElement("div",{className:"mwai-copy-button",onClick:()=>{try{navigator.clipboard.writeText(a),E("success")}catch(e){E("error"),console.warn("Not allowed to copy to clipboard. Make sure your website uses HTTPS.",{content:a})}finally{setTimeout((()=>{E("idle")}),2e3)}},title:"Copy"},React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",dangerouslySetInnerHTML:{__html:y}})),React.createElement("div",{className:"mwai-action-button",onClick:()=>{d((e=>{const t=e.findIndex((e=>e.id===s.id));let n;return n=t>0?e.filter(((e,n)=>n!==t&&n!==t-1)):e.filter((e=>e.id!==s.id)),m(n),n}))},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"/>'}})),s.failedQuery&&f&&React.createElement("div",{className:"mwai-action-button",onClick:()=>{s.failedQuery&&p&&(d((e=>{const t=e.findIndex((e=>e.id===s.id));let n;return n=t>0?e.filter(((e,n)=>n!==t&&n!==t-1)):e.filter((e=>e.id!==s.id)),m(n),n})),p())},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:rn}=wp.element,sn=({role:n="user"})=>{const{state:a}=(0,e.o)(),{pluginUrl:r,iconUrl:s,userData:o,userName:l,aiName:c,guestName:u,userAvatar:d,aiAvatar:m,guestAvatar:p,userAvatarUrl:g,aiAvatarUrl:h,guestAvatarUrl:E}=a,f=rn((()=>{const e="assistant"===n,a=!o&&!e,f=e=>React.createElement("div",{className:"mwai-name-text"},e),y=(e,n,a,s,o=!1)=>{if(!e)return null;if((0,i.Ve)(n))return l=n,React.createElement("div",{className:"mwai-avatar mwai-emoji",style:{fontSize:"32px",lineHeight:"32px"}},l);var l;const c=((e,n=!1)=>(0,t.mv)(e)?e:e&&!(0,i.Ve)(e)?n?e:`${r}/images/${e}`:(n||(0,i.Ve)(e)||console.warn("Invalid URL for avatar:",e),null))(n,o)||a;return c?((e,t)=>React.createElement("div",{className:"mwai-avatar"},React.createElement("img",{width:"32",height:"32",src:e,alt:t})))(c,s):null};if(e){const e=y(m,h,s,"AI Avatar");return e?(null===h&&s&&console.warn("Using iconUrl as a temporary fallback for AI avatar. Please set aiAvatarUrl."),e):f(c)}if(!a){return y(d,g,null==o?void 0:o.AVATAR_URL,"User Avatar",!0)||f(function(e,t,n){return n&&0!==Object.keys(n).length?Object.entries(n).reduce(((e,[t,n])=>{const a=`{${t}}`;return e.includes(a)?e.replace(a,n):e}),e):t||e||"Guest"}(l,u,o))}if(a){return y(p,E,null,"Guest Avatar")||f(u||"Guest")}}),[n,c,l,u,o,s,m,d,p,h,g,E,r]);return React.createElement("span",{className:"mwai-name"},f)};function on(){return on=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},on.apply(this,arguments)}const ln={blockQuote:"0",breakLine:"1",breakThematic:"2",codeBlock:"3",codeFenced:"4",codeInline:"5",footnote:"6",footnoteReference:"7",gfmTask:"8",heading:"9",headingSetext:"10",htmlBlock:"11",htmlComment:"12",htmlSelfClosing:"13",image:"14",link:"15",linkAngleBraceStyleDetector:"16",linkBareUrlDetector:"17",linkMailtoDetector:"18",newlineCoalescer:"19",orderedList:"20",paragraph:"21",ref:"22",refImage:"23",refLink:"24",table:"25",tableSeparator:"26",text:"27",textBolded:"28",textEmphasized:"29",textEscaped:"30",textMarked:"31",textStrikethroughed:"32",unorderedList:"33"};var cn,un;(un=cn||(cn={}))[un.MAX=0]="MAX",un[un.HIGH=1]="HIGH",un[un.MED=2]="MED",un[un.LOW=3]="LOW",un[un.MIN=4]="MIN";const dn=["allowFullScreen","allowTransparency","autoComplete","autoFocus","autoPlay","cellPadding","cellSpacing","charSet","className","classId","colSpan","contentEditable","contextMenu","crossOrigin","encType","formAction","formEncType","formMethod","formNoValidate","formTarget","frameBorder","hrefLang","inputMode","keyParams","keyType","marginHeight","marginWidth","maxLength","mediaGroup","minLength","noValidate","radioGroup","readOnly","rowSpan","spellCheck","srcDoc","srcLang","srcSet","tabIndex","useMap"].reduce(((e,t)=>(e[t.toLowerCase()]=t,e)),{for:"htmlFor"}),mn={amp:"&",apos:"'",gt:">",lt:"<",nbsp:" ",quot:"“"},pn=["style","script"],gn=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,hn=/mailto:/i,En=/\n{2,}$/,fn=/^(\s*>[\s\S]*?)(?=\n{2,})/,yn=/^ *> ?/gm,_n=/^ {2,}\n/,wn=/^(?:( *[-*_])){3,} *(?:\n *)+\n/,vn=/^\s*(`{3,}|~{3,}) *(\S+)?([^\n]*?)?\n([\s\S]+?)\s*\1 *(?:\n *)*\n?/,Rn=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,Tn=/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,In=/^(?:\n *)*\n/,bn=/\r\n?/g,Sn=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,An=/^\[\^([^\]]+)]/,Cn=/\f/g,Nn=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,kn=/^\s*?\[(x|\s)\]/,On=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,xn=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Mn=/^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/,Pn=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,Ln=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Dn=/^<!--[\s\S]*?(?:-->)/,Un=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,Fn=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,Bn=/^\{.*\}$/,Gn=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,Hn=/^<([^ >]+@[^ >]+)>/,$n=/^<([^ >]+:\/[^ >]+)>/,zn=/-([a-z])?/gi,Wn=/^(.*\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,Kn=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,jn=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,Yn=/^\[([^\]]*)\] ?\[([^\]]*)\]/,Vn=/(\[|\])/g,qn=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Xn=/\t/g,Qn=/(^ *\||\| *$)/g,Jn=/^ *:-+: *$/,Zn=/^ *:-+ *$/,ea=/^ *-+: *$/,ta="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|~~.*?~~|==.*?==|.|\\n)*?)",na=new RegExp(`^([*_])\\1${ta}\\1\\1(?!\\1)`),aa=new RegExp(`^([*_])${ta}\\1(?!\\1|\\w)`),ia=new RegExp(`^==${ta}==`),ra=new RegExp(`^~~${ta}~~`),sa=/^\\([^0-9A-Za-z\s])/,oa=/^[\s\S]+?(?=[^0-9A-Z\s\u00c0-\uffff&#;.()'"]|\d+\.|\n\n| {2,}\n|\w+:\S|$)/i,la=/^\n+/,ca=/^([ \t]*)/,ua=/\\([^\\])/g,da=/ *\n+$/,ma=/(?:^|\n)( *)$/,pa="(?:\\d+\\.)",ga="(?:[*+-])";function ha(e){return"( *)("+(1===e?pa:ga)+") +"}const Ea=ha(1),fa=ha(2);function ya(e){return new RegExp("^"+(1===e?Ea:fa))}const _a=ya(1),wa=ya(2);function va(e){return new RegExp("^"+(1===e?Ea:fa)+"[^\\n]*(?:\\n(?!\\1"+(1===e?pa:ga)+" )[^\\n]*)*(\\n|$)","gm")}const Ra=va(1),Ta=va(2);function Ia(e){const t=1===e?pa:ga;return new RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const ba=Ia(1),Sa=Ia(2);function Aa(e,t){const n=1===t,a=n?ba:Sa,i=n?Ra:Ta,r=n?_a:wa;return{match(e,t,n){const i=ma.exec(n);return i&&(t.list||!t.inline&&!t.simple)?a.exec(e=i[1]+e):null},order:1,parse(e,t,a){const s=n?+e[2]:void 0,o=e[0].replace(En,"\n").match(i);let l=!1;return{items:o.map((function(e,n){const i=r.exec(e)[0].length,s=new RegExp("^ {1,"+i+"}","gm"),c=e.replace(s,"").replace(r,""),u=n===o.length-1,d=-1!==c.indexOf("\n\n")||u&&l;l=d;const m=a.inline,p=a.list;let g;a.list=!0,d?(a.inline=!1,g=c.replace(da,"\n\n")):(a.inline=!0,g=c.replace(da,""));const h=t(g,a);return a.inline=m,a.list=p,h})),ordered:n,start:s}},render:(t,n,a)=>e(t.ordered?"ol":"ul",{key:a.key,start:t.type===ln.orderedList?t.start:void 0},t.items.map((function(t,i){return e("li",{key:i},n(t,a))})))}}const Ca=new RegExp("^\\[((?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*\\)"),Na=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/,ka=[fn,vn,Rn,On,Mn,xn,Dn,Wn,Ra,ba,Ta,Sa],Oa=[...ka,/^[^\n]+(?: \n|\n{2,})/,Pn,Fn];function xa(e){return e.replace(/[ÀÁÂÃÄÅàáâãä忯]/g,"a").replace(/[çÇ]/g,"c").replace(/[ðÐ]/g,"d").replace(/[ÈÉÊËéèêë]/g,"e").replace(/[ÏïÎîÍíÌì]/g,"i").replace(/[Ññ]/g,"n").replace(/[øØœŒÕõÔôÓóÒò]/g,"o").replace(/[ÜüÛûÚúÙù]/g,"u").replace(/[ŸÿÝý]/g,"y").replace(/[^a-z0-9- ]/gi,"").replace(/ /gi,"-").toLowerCase()}function Ma(e){return ea.test(e)?"right":Jn.test(e)?"center":Zn.test(e)?"left":null}function Pa(e,t,n,a){const i=n.inTable;n.inTable=!0;let r=e.trim().split(/( *(?:`[^`]*`|<.*?>.*?<\/.*?>(?!<\/.*?>)|\\\||\|) *)/).reduce(((e,i)=>("|"===i.trim()?e.push(a?{type:ln.tableSeparator}:{type:ln.text,text:i}):""!==i&&e.push.apply(e,t(i,n)),e)),[]);n.inTable=i;let s=[[]];return r.forEach((function(e,t){e.type===ln.tableSeparator?0!==t&&t!==r.length-1&&s.push([]):(e.type!==ln.text||null!=r[t+1]&&r[t+1].type!==ln.tableSeparator||(e.text=e.text.trimEnd()),s[s.length-1].push(e))})),s}function La(e,t,n){n.inline=!0;const a=e[2]?e[2].replace(Qn,"").split("|").map(Ma):[],i=e[3]?function(e,t,n){return e.trim().split("\n").map((function(e){return Pa(e,t,n,!0)}))}(e[3],t,n):[],r=Pa(e[1],t,n,!!i.length);return n.inline=!1,i.length?{align:a,cells:i,header:r,type:ln.table}:{children:r,type:ln.paragraph}}function Da(e,t){return null==e.align[t]?{}:{textAlign:e.align[t]}}function Ua(e){return function(t,n){return n.inline?e.exec(t):null}}function Fa(e){return function(t,n){return n.inline||n.simple?e.exec(t):null}}function Ba(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function Ga(e){return function(t){return e.exec(t)}}function Ha(e,t,n){if(t.inline||t.simple)return null;if(n&&!n.endsWith("\n"))return null;let a="";e.split("\n").every((e=>!ka.some((t=>t.test(e)))&&(a+=e+"\n",e.trim())));const i=a.trimEnd();return""==i?null:[a,i]}function $a(e){try{if(decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"").match(/^\s*(javascript|vbscript|data(?!:image)):/i))return null}catch(e){return null}return e}function za(e){return e.replace(ua,"$1")}function Wa(e,t,n){const a=n.inline||!1,i=n.simple||!1;n.inline=!0,n.simple=!0;const r=e(t,n);return n.inline=a,n.simple=i,r}function Ka(e,t,n){const a=n.inline||!1,i=n.simple||!1;n.inline=!1,n.simple=!0;const r=e(t,n);return n.inline=a,n.simple=i,r}function ja(e,t,n){const a=n.inline||!1;n.inline=!1;const i=e(t,n);return n.inline=a,i}const Ya=(e,t,n)=>({children:Wa(t,e[1],n)});function Va(){return{}}function qa(){return null}function Xa(...e){return e.filter(Boolean).join(" ")}function Qa(e,t,n){let a=e;const i=t.split(".");for(;i.length&&(a=a[i[0]],void 0!==a);)i.shift();return a||n}function Ja(e="",t={}){function n(e,n,...a){const i=Qa(t.overrides,`${e}.props`,{});return t.createElement(function(e,t){const n=Qa(t,e);return n?"function"==typeof n||"object"==typeof n&&"render"in n?n:Qa(t,`${e}.component`,e):e}(e,t.overrides),on({},n,i,{className:Xa(null==n?void 0:n.className,i.className)||void 0}),...a)}function a(e){e=e.replace(Nn,"");let a=!1;t.forceInline?a=!0:t.forceBlock||(a=!1===qn.test(e));const i=u(c(a?e:`${e.trimEnd().replace(la,"")}\n\n`,{inline:a}));for(;"string"==typeof i[i.length-1]&&!i[i.length-1].trim();)i.pop();if(null===t.wrapper)return i;const s=t.wrapper||(a?"span":"div");let o;if(i.length>1||t.forceWrapper)o=i;else{if(1===i.length)return o=i[0],"string"==typeof o?n("span",{key:"outer"},o):o;o=null}return r.createElement(s,{key:"outer"},o)}function i(e,n){const i=n.match(gn);return i?i.reduce((function(n,i,s){const o=i.indexOf("=");if(-1!==o){const l=function(e){return-1!==e.indexOf("-")&&null===e.match(Un)&&(e=e.replace(zn,(function(e,t){return t.toUpperCase()}))),e}(i.slice(0,o)).trim(),c=function(e){const t=e[0];return('"'===t||"'"===t)&&e.length>=2&&e[e.length-1]===t?e.slice(1,-1):e}(i.slice(o+1).trim()),u=dn[l]||l,d=n[u]=function(e,t,n,a){return"style"===t?n.split(/;\s?/).reduce((function(e,t){const n=t.slice(0,t.indexOf(":"));return e[n.trim().replace(/(-[a-z])/g,(e=>e[1].toUpperCase()))]=t.slice(n.length+1).trim(),e}),{}):"href"===t||"src"===t?a(n,e,t):(n.match(Bn)&&(n=n.slice(1,n.length-1)),"true"===n||"false"!==n&&n)}(e,l,c,t.sanitizer);"string"==typeof d&&(Pn.test(d)||Fn.test(d))&&(n[u]=r.cloneElement(a(d.trim()),{key:s}))}else"style"!==i&&(n[dn[i]||i]=!0);return n}),{}):null}t.overrides=t.overrides||{},t.sanitizer=t.sanitizer||$a,t.slugify=t.slugify||xa,t.namedCodesToUnicode=t.namedCodesToUnicode?on({},mn,t.namedCodesToUnicode):mn,t.createElement=t.createElement||r.createElement;const s=[],o={},l={[ln.blockQuote]:{match:Ba(fn),order:1,parse:(e,t,n)=>({children:t(e[0].replace(yn,""),n)}),render:(e,t,a)=>n("blockquote",{key:a.key},t(e.children,a))},[ln.breakLine]:{match:Ga(_n),order:1,parse:Va,render:(e,t,a)=>n("br",{key:a.key})},[ln.breakThematic]:{match:Ba(wn),order:1,parse:Va,render:(e,t,a)=>n("hr",{key:a.key})},[ln.codeBlock]:{match:Ba(Rn),order:0,parse:e=>({lang:void 0,text:e[0].replace(/^ {4}/gm,"").replace(/\n+$/,"")}),render:(e,t,a)=>n("pre",{key:a.key},n("code",on({},e.attrs,{className:e.lang?`lang-${e.lang}`:""}),e.text))},[ln.codeFenced]:{match:Ba(vn),order:0,parse:e=>({attrs:i("code",e[3]||""),lang:e[2]||void 0,text:e[4],type:ln.codeBlock})},[ln.codeInline]:{match:Fa(Tn),order:3,parse:e=>({text:e[2]}),render:(e,t,a)=>n("code",{key:a.key},e.text)},[ln.footnote]:{match:Ba(Sn),order:0,parse:e=>(s.push({footnote:e[2],identifier:e[1]}),{}),render:qa},[ln.footnoteReference]:{match:Ua(An),order:1,parse:e=>({target:`#${t.slugify(e[1],xa)}`,text:e[1]}),render:(e,a,i)=>n("a",{key:i.key,href:t.sanitizer(e.target,"a","href")},n("sup",{key:i.key},e.text))},[ln.gfmTask]:{match:Ua(kn),order:1,parse:e=>({completed:"x"===e[1].toLowerCase()}),render:(e,t,a)=>n("input",{checked:e.completed,key:a.key,readOnly:!0,type:"checkbox"})},[ln.heading]:{match:Ba(t.enforceAtxHeadings?xn:On),order:1,parse:(e,n,a)=>({children:Wa(n,e[2],a),id:t.slugify(e[2],xa),level:e[1].length}),render:(e,t,a)=>n(`h${e.level}`,{id:e.id,key:a.key},t(e.children,a))},[ln.headingSetext]:{match:Ba(Mn),order:0,parse:(e,t,n)=>({children:Wa(t,e[1],n),level:"="===e[2]?1:2,type:ln.heading})},[ln.htmlBlock]:{match:Ga(Pn),order:1,parse(e,t,n){const[,a]=e[3].match(ca),r=new RegExp(`^${a}`,"gm"),s=e[3].replace(r,""),o=(l=s,Oa.some((e=>e.test(l)))?ja:Wa);var l;const c=e[1].toLowerCase(),u=-1!==pn.indexOf(c),d=(u?c:e[1]).trim(),m={attrs:i(d,e[2]),noInnerParse:u,tag:d};return n.inAnchor=n.inAnchor||"a"===c,u?m.text=e[3]:m.children=o(t,s,n),n.inAnchor=!1,m},render:(e,t,a)=>n(e.tag,on({key:a.key},e.attrs),e.text||t(e.children,a))},[ln.htmlSelfClosing]:{match:Ga(Fn),order:1,parse(e){const t=e[1].trim();return{attrs:i(t,e[2]||""),tag:t}},render:(e,t,a)=>n(e.tag,on({},e.attrs,{key:a.key}))},[ln.htmlComment]:{match:Ga(Dn),order:1,parse:()=>({}),render:qa},[ln.image]:{match:Fa(Na),order:1,parse:e=>({alt:e[1],target:za(e[2]),title:e[3]}),render:(e,a,i)=>n("img",{key:i.key,alt:e.alt||void 0,title:e.title||void 0,src:t.sanitizer(e.target,"img","src")})},[ln.link]:{match:Ua(Ca),order:3,parse:(e,t,n)=>({children:Ka(t,e[1],n),target:za(e[2]),title:e[3]}),render:(e,a,i)=>n("a",{key:i.key,href:t.sanitizer(e.target,"a","href"),title:e.title},a(e.children,i))},[ln.linkAngleBraceStyleDetector]:{match:Ua($n),order:0,parse:e=>({children:[{text:e[1],type:ln.text}],target:e[1],type:ln.link})},[ln.linkBareUrlDetector]:{match:(e,t)=>t.inAnchor?null:Ua(Gn)(e,t),order:0,parse:e=>({children:[{text:e[1],type:ln.text}],target:e[1],title:void 0,type:ln.link})},[ln.linkMailtoDetector]:{match:Ua(Hn),order:0,parse(e){let t=e[1],n=e[1];return hn.test(n)||(n="mailto:"+n),{children:[{text:t.replace("mailto:",""),type:ln.text}],target:n,type:ln.link}}},[ln.orderedList]:Aa(n,1),[ln.unorderedList]:Aa(n,2),[ln.newlineCoalescer]:{match:Ba(In),order:3,parse:Va,render:()=>"\n"},[ln.paragraph]:{match:Ha,order:3,parse:Ya,render:(e,t,a)=>n("p",{key:a.key},t(e.children,a))},[ln.ref]:{match:Ua(Kn),order:0,parse:e=>(o[e[1]]={target:e[2],title:e[4]},{}),render:qa},[ln.refImage]:{match:Fa(jn),order:0,parse:e=>({alt:e[1]||void 0,ref:e[2]}),render:(e,a,i)=>o[e.ref]?n("img",{key:i.key,alt:e.alt,src:t.sanitizer(o[e.ref].target,"img","src"),title:o[e.ref].title}):null},[ln.refLink]:{match:Ua(Yn),order:0,parse:(e,t,n)=>({children:t(e[1],n),fallbackChildren:t(e[0].replace(Vn,"\\$1"),n),ref:e[2]}),render:(e,a,i)=>o[e.ref]?n("a",{key:i.key,href:t.sanitizer(o[e.ref].target,"a","href"),title:o[e.ref].title},a(e.children,i)):n("span",{key:i.key},a(e.fallbackChildren,i))},[ln.table]:{match:Ba(Wn),order:1,parse:La,render(e,t,a){const i=e;return n("table",{key:a.key},n("thead",null,n("tr",null,i.header.map((function(e,r){return n("th",{key:r,style:Da(i,r)},t(e,a))})))),n("tbody",null,i.cells.map((function(e,r){return n("tr",{key:r},e.map((function(e,r){return n("td",{key:r,style:Da(i,r)},t(e,a))})))}))))}},[ln.text]:{match:Ga(oa),order:4,parse:e=>({text:e[0].replace(Ln,((e,n)=>t.namedCodesToUnicode[n]?t.namedCodesToUnicode[n]:e))}),render:e=>e.text},[ln.textBolded]:{match:Fa(na),order:2,parse:(e,t,n)=>({children:t(e[2],n)}),render:(e,t,a)=>n("strong",{key:a.key},t(e.children,a))},[ln.textEmphasized]:{match:Fa(aa),order:3,parse:(e,t,n)=>({children:t(e[2],n)}),render:(e,t,a)=>n("em",{key:a.key},t(e.children,a))},[ln.textEscaped]:{match:Fa(sa),order:1,parse:e=>({text:e[1],type:ln.text})},[ln.textMarked]:{match:Fa(ia),order:3,parse:Ya,render:(e,t,a)=>n("mark",{key:a.key},t(e.children,a))},[ln.textStrikethroughed]:{match:Fa(ra),order:3,parse:Ya,render:(e,t,a)=>n("del",{key:a.key},t(e.children,a))}};!0===t.disableParsingRawHTML&&(delete l[ln.htmlBlock],delete l[ln.htmlSelfClosing]);const c=function(e){let t=Object.keys(e);function n(a,i){let r=[],s="";for(;a;){let o=0;for(;o<t.length;){const l=t[o],c=e[l],u=c.match(a,i,s);if(u){const e=u[0];a=a.substring(e.length);const t=c.parse(u,n,i);null==t.type&&(t.type=l),r.push(t),s=e;break}o++}}return r}return t.sort((function(t,n){let a=e[t].order,i=e[n].order;return a!==i?a-i:t<n?-1:1})),function(e,t){return n(function(e){return e.replace(bn,"\n").replace(Cn,"").replace(Xn," ")}(e),t)}}(l),u=(d=function(e,t){return function(n,a,i){const r=e[n.type].render;return t?t((()=>r(n,a,i)),n,a,i):r(n,a,i)}}(l,t.renderRule),function e(t,n={}){if(Array.isArray(t)){const a=n.key,i=[];let r=!1;for(let a=0;a<t.length;a++){n.key=a;const s=e(t[a],n),o="string"==typeof s;o&&r?i[i.length-1]+=s:null!==s&&i.push(s),r=o}return n.key=a,i}return d(t,e,n)});var d;const m=a(e);return s.length?n("div",null,m,n("footer",{key:"footer"},s.map((function(e){return n("div",{id:t.slugify(e.identifier,xa),key:e.identifier},e.identifier,u(c(e.footnote,{inline:!0})))})))):m}var Za=__webpack_require__(233);const{useMemo:ei}=wp.element,ti=({href:e,children:t})=>{if(!e)return React.createElement("span",null,t);const n="_blank";if("Uploaded File"===String(t)){const t=e.split("/").pop();return React.createElement("a",{href:e,target:n,rel:"noopener noreferrer",className:"mwai-filename"},React.createElement("span",null,"✓ ",t))}return React.createElement("a",{href:e,target:n,rel:"noopener noreferrer"},t)},ni=({message:e})=>{let t=e.content??"";const n=e.isError||"error"===e.role;(t.match(/```/g)||[]).length%2!=0&&(t+="\n```");const a=ei((()=>({forceBlock:!1,forceInline:!1,breaks:!0,overrides:{BlinkingCursor:{component:i.rn},a:{component:ti},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"}}}})),[]),r=ei((()=>{if(n)return t;let e="";try{let n=t;const i=[];n=n.replace(/```[\s\S]*?```/g,((e,t)=>(i.push(e),`__CODE_BLOCK_${i.length-1}__`)));const r=[];n=n.replace(/`[^`]+`/g,(e=>(r.push(e),`__INLINE_CODE_${r.length-1}__`))),n=n.replace(/(?<!\n)\n(?!\n)/g," \n"),i.forEach(((e,t)=>{n=n.replace(`__CODE_BLOCK_${t}__`,e)})),r.forEach(((e,t)=>{n=n.replace(`__INLINE_CODE_${t}__`,e)})),e=Ja(n,a)}catch(n){console.error(Za.A.DEBUG.CRASH_IN_MARKDOWN,{e:n,content:t}),e=t}return e}),[t,a,e.id,e.key,n]);return e.isStreaming?React.createElement(React.Fragment,null,n?React.createElement("span",{dangerouslySetInnerHTML:{__html:r}}):r,React.createElement(i.rn,null)):n?React.createElement("span",{dangerouslySetInnerHTML:{__html:r}}):r},{useState:ai,useMemo:ii,useEffect:ri,useRef:si}=wp.element,oi=({message:t,onRendered:n=(()=>{})})=>{const{state:a}=(0,e.o)(),{copyButton:i,debugMode:r}=a,[s]=ai(t.isQuerying||t.isStreaming),o=t.isQuerying,l=t.isStreaming;if(ri((()=>{s&&(!s||o||l)||n()}),[s,o,l]),o)return React.createElement(qt,null);const c=t.isError||"error"===t.role?an:tn;return React.createElement(React.Fragment,null,React.createElement(sn,{role:t.role}),React.createElement(c,{content:t.content,enabled:i,className:"mwai-text",message:t},React.createElement(ni,{message:t})))},li=({message:t,onRendered:n=(()=>{})})=>{const{state:a}=(0,e.o)(),{copyButton:i}=a,[r,s]=ai(null==t?void 0:t.images);if(ri((()=>{n()})),t.isQuerying)return React.createElement(qt,null);const o={...t,images:r};return React.createElement(React.Fragment,null,React.createElement(sn,{role:t.role}),React.createElement(tn,{content:"",enabled:!1,className:"mwai-text",message:o},React.createElement("div",{className:"mwai-gallery"},null==r?void 0:r.map(((e,t)=>React.createElement("a",{key:t,href:e,target:"_blank",rel:"noopener noreferrer"},React.createElement("img",{key:t,src:e,onError:()=>(e=>{s((t=>t.map(((t,n)=>n===e?"https://placehold.co/600x200?text=Expired+Image":t))))})(t)})))))))},ci=({message:n,conversationRef:a})=>{var i;const{state:r,actions:s}=(0,e.o)(),{typewriter:o}=r,{setMessages:l,retryLastQuery:c}=s,u=(0,t.gR)(),d=si(),m=u("mwai-reply",{"mwai-ai":"assistant"===n.role,"mwai-user":"user"===n.role,"mwai-system":"system"===n.role,"mwai-error":"error"===n.role||n.isError}),p=(null==n||null===(i=n.images)||void 0===i?void 0:i.length)>0,g="error"===n.role||n.isError,h=()=>{!d.current||n.isQuerying||d.current.classList.contains("mwai-rendered")||"undefined"==typeof hljs||(d.current.classList.add("mwai-rendered"),d.current.querySelectorAll("pre code").forEach((e=>{hljs.highlightElement(e)})))};return ii((()=>{if("user"===n.role)return React.createElement("div",{ref:d,className:m},React.createElement(oi,{message:n}));if("assistant"===n.role)return p?React.createElement("div",{ref:d,className:m},React.createElement(li,{message:n,conversationRef:a,onRendered:h})):React.createElement("div",{ref:d,className:m},React.createElement(oi,{message:n,conversationRef:a,onRendered:h}));if("system"===n.role&&!g)return React.createElement("div",{ref:d,className:m},React.createElement(oi,{message:n,conversationRef:a,onRendered:h}));if(g){const e={...n,role:"assistant"};return React.createElement("div",{ref:d,className:m},React.createElement(oi,{message:e,conversationRef:a,onRendered:h}))}return React.createElement("div",null,React.createElement("i",null,"Unhandled role."))}),[n,a,p,o])},{useRef:ui,useEffect:di}=wp.element;var mi=__webpack_require__(407);const pi=(0,mi.A)("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),{useMemo:gi,useRef:hi,useEffect:Ei,useImperativeHandle:fi,useCallback:yi,useState:_i}=wp.element,wi=({children:e,role:t="assistant"})=>{const n="user"===t?"mwai-terminal-user":"system"===t?"mwai-terminal-system":"mwai-terminal-assistant";return React.createElement("div",{className:`mwai-terminal-line ${n}`},e)};function vi(){return vi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},vi.apply(this,arguments)}const Ri=r.useLayoutEffect;var Ti=function(e,t){"function"!=typeof e?e.current=t:e(t)};var Ii={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0"},bi=function(e){Object.keys(Ii).forEach((function(t){e.style.setProperty(t,Ii[t],"important")}))},Si=null,Ai=function(e,t){var n=e.scrollHeight;return"border-box"===t.sizingStyle.boxSizing?n+t.borderSize:n-t.paddingSize},Ci=function(){},Ni=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak"],ki=!!document.documentElement.currentStyle;function Oi(e,t,n){var a,i,s=(a=n,i=r.useRef(a),Ri((function(){i.current=a})),i);r.useLayoutEffect((function(){var n=function(e){return s.current(e)};if(e)return e.addEventListener(t,n),function(){return e.removeEventListener(t,n)}}),[])}var xi=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Mi=function(e,t){var n,a=e.cacheMeasurements,i=e.maxRows,s=e.minRows,o=e.onChange,l=void 0===o?Ci:o,c=e.onHeightChange,u=void 0===c?Ci:c,d=function(e,t){if(null==e)return{};var n,a,i={},r=Object.keys(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,xi),m=void 0!==d.value,p=r.useRef(null),g=function(e,t){var n=(0,r.useRef)();return(0,r.useCallback)((function(a){e.current=a,n.current&&Ti(n.current,null),n.current=t,t&&Ti(t,a)}),[t])}(p,t),h=r.useRef(0),E=r.useRef(),f=function(){var e=p.current,t=a&&E.current?E.current:function(e){var t=window.getComputedStyle(e);if(null===t)return null;var n,a=(n=t,Ni.reduce((function(e,t){return e[t]=n[t],e}),{})),i=a.boxSizing;return""===i?null:(ki&&"border-box"===i&&(a.width=parseFloat(a.width)+parseFloat(a.borderRightWidth)+parseFloat(a.borderLeftWidth)+parseFloat(a.paddingRight)+parseFloat(a.paddingLeft)+"px"),{sizingStyle:a,paddingSize:parseFloat(a.paddingBottom)+parseFloat(a.paddingTop),borderSize:parseFloat(a.borderBottomWidth)+parseFloat(a.borderTopWidth)})}(e);if(t){E.current=t;var n=function(e,t,n,a){void 0===n&&(n=1),void 0===a&&(a=1/0),Si||((Si=document.createElement("textarea")).setAttribute("tabindex","-1"),Si.setAttribute("aria-hidden","true"),bi(Si)),null===Si.parentNode&&document.body.appendChild(Si);var i=e.paddingSize,r=e.borderSize,s=e.sizingStyle,o=s.boxSizing;Object.keys(s).forEach((function(e){var t=e;Si.style[t]=s[t]})),bi(Si),Si.value=t;var l=Ai(Si,e);Si.value=t,l=Ai(Si,e),Si.value="x";var c=Si.scrollHeight-i,u=c*n;"border-box"===o&&(u=u+i+r),l=Math.max(u,l);var d=c*a;return"border-box"===o&&(d=d+i+r),[l=Math.min(d,l),c]}(t,e.value||e.placeholder||"x",s,i),r=n[0],o=n[1];h.current!==r&&(h.current=r,e.style.setProperty("height",r+"px","important"),u(r,{rowHeight:o}))}};return r.useLayoutEffect(f),Oi(window,"resize",f),n=f,Oi(document.fonts,"loadingdone",n),r.createElement("textarea",vi({},d,{onChange:function(e){m||f(),l(e)},ref:g}))},Pi=r.forwardRef(Mi);const Li=(0,mi.A)("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]),{useState:Di,useMemo:Ui,useRef:Fi}=wp.element,Bi=()=>{var n;const a=(0,t.gR)(),{state:i,actions:r}=(0,e.o)(),{uploadedFile:s,uploadedFiles:o,multiUpload:l,busy:c,imageUpload:u,fileUpload:d,fileSearch:m,draggingType:p}=i,{onUploadFile:g,onMultiFileUpload:h,resetUploadedFiles:E}=r,[f,y]=Di(!1),_=Fi(),w=l?o.length>0:null==s?void 0:s.uploadedId,v=u||m||d,R=()=>g(null),T=s,I=Ui((()=>null!=T&&T.localFile?T.localFile.type.startsWith("image/")?"image":"document":p),[T,p]),b=Ui((()=>{let e="idle";return null!=T&&T.uploadProgress?e="up":p?e="add":f&&w?e="del":w?e="ok":f&&!w&&(e="add"),`mwai-file-upload-icon mwai-${I?I.toLowerCase():"idle"}-${e}`}),[I,T,p,f,w]),S=Ui((()=>null!=T&&T.uploadProgress?T.uploadProgress>99?99:Math.round(T.uploadProgress):""),[T]),A=Ui((()=>l?(o||[]).length||0:w?1:0),[l,o,w]);if(!v)return null;const C="timeless"===(null==i||null===(n=i.theme)||void 0===n?void 0:n.themeId),N="none"===(null==i?void 0:i.inputType),k=C||N,O=a("mwai-file-upload",{"mwai-enabled":null==s?void 0:s.uploadedId,"mwai-busy":(null==s?void 0:s.localFile)&&!(null!=s&&s.uploadedId)});return React.createElement("div",{disabled:c,onClick:()=>{w?l?E():R():c||_.current.click()},onMouseEnter:()=>y(!0),onMouseLeave:()=>y(!1),className:O,style:{cursor:c?"default":"pointer"}},React.createElement("div",{className:`${b}${k?" mwai-lucide":""}${k&&f&&w?" mwai-hover":""}`},k&&React.createElement(Li,{size:16}),k&&A>0&&React.createElement("span",{className:"mwai-upload-count","data-count":A,onClick:e=>{e.stopPropagation(),l?E():R()}}),!k&&React.createElement("span",{className:"mwai-file-upload-progress"},S)),React.createElement("input",{type:"file",ref:_,onChange:e=>{const t=e.target.files;if(t&&t.length>0)if(l){for(let e=0;e<t.length;e++)h(t[e]);e.target.value=""}else g(t[0])},multiple:l,style:{display:"none"}}))},{useRef:Gi,useState:Hi,useEffect:$i,useImperativeHandle:zi}=wp.element,Wi=()=>{const n=(0,t.gR)(),{state:a,actions:i}=(0,e.o)(),{inputText:r,textInputMaxLength:s,textInputPlaceholder:o,error:l,speechRecognitionAvailable:c,isMobile:u,conversationRef:d,open:m,uploadIconPosition:p,locked:g,isListening:h,busy:E,speechRecognition:f,chatbotInputRef:y}=a,{onSubmitAction:_,setIsListening:w,resetError:v,setInputText:R}=i,[T,I]=Hi(!1),b=Gi();zi(y,(()=>({focusInput:()=>{var e;null===(e=b.current)||void 0===e||e.focus()},currentElement:()=>b.current}))),$i((()=>{!u&&m&&b.current.focus(),d.current&&(d.current.scrollTop=d.current.scrollHeight)}),[m,u,d]);const S=n("mwai-input-text",{"mwai-dragging":a.draggingType,"mwai-blocked":a.isBlocked});return React.createElement("div",{ref:y,className:S},"mwai-input"===p&&React.createElement(Bi,null),React.createElement(Pi,{ref:b,disabled:E||g,placeholder:o,value:r,maxLength:s,onCompositionStart:()=>I(!0),onCompositionEnd:()=>I(!1),onKeyDown:e=>{T||"Enter"!==e.code||e.shiftKey||(e.preventDefault(),_())},onChange:e=>{return t=e.target.value,h&&w(!1),l&&v(),void R(t);var t}}),f&&React.createElement(t.tm,{active:h,disabled:!c||E,className:"mwai-microphone",onClick:()=>w(!h)}))},Ki=(0,mi.A)("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),ji=(0,mi.A)("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]),Yi=(0,mi.A)("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]),{useMemo:Vi,useCallback:qi}=wp.element,Xi=()=>{const{state:t,actions:n}=(0,e.o)(),{onClear:a,onSubmitAction:i,setIsListening:r}=n,{textClear:s,textSend:o,uploadedFile:l,inputText:c,messages:u,isListening:d,timeElapsed:m,busy:p,submitButtonConf:g,locked:h}=t,E=!(null==l||!l.uploadProgress),f=!(null!=l&&l.uploadedId)&&c.length<1&&(null==u?void 0:u.length)>1,y=Vi((()=>p?m?React.createElement("div",{className:"mwai-timer"},m):null:null!=g&&g.useLucide?f?React.createElement(Ki,{size:"20"}):React.createElement(ji,{size:"20"}):null!=g&&g.imageSend&&null!=g&&g.imageClear?React.createElement("img",{src:f?g.imageClear:g.imageSend,alt:f?s:o}):f||o?f&&!s?React.createElement(Ki,{size:"20"}):React.createElement("span",null,f?s:o):React.createElement(Yi,{size:"20"})),[p,m,f,s,o,g]),_=Vi((()=>"mwai-input-submit "+(p?"mwai-busy":"")),[p]),w=qi((()=>{d&&r(!1),f?a():i()}),[f,d,a,i,r]),v=qi((()=>{p||w()}),[p,w]);return React.createElement("button",{className:_,disabled:p||E||h,onClick:v},y)},Qi={headers:{standard:({title:e,onResize:t,onClose:n,showResize:a=!1})=>s().createElement(Vt,null,s().createElement("div",{className:"mwai-modular-header mwai-standard-header"},e&&s().createElement("div",{className:"mwai-title"},e),s().createElement("div",{className:"mwai-buttons"},a&&s().createElement("div",{className:"mwai-resize-button",onClick:t}),s().createElement("div",{className:"mwai-close-button",onClick:n})))),osx:({title:e,onClose:t,onMinimize:n,onMaximize:a,theme:i,showResize:r,children:o,onDragStart:l})=>s().createElement("div",{className:"mwai-header mwai-header-osx",role:"toolbar","aria-label":"Chat header"},s().createElement("div",{className:"mwai-osx-bar",onMouseDown:l},s().createElement("div",{className:"mwai-osx-controls"},s().createElement("button",{className:"mwai-osx-close",onClick:t,"aria-label":"Close",type:"button"},s().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"},s().createElement("path",{d:"M18 6 6 18"}),s().createElement("path",{d:"M6 6l12 12"}))),s().createElement("button",{className:"mwai-osx-minimize",onClick:n||t,"aria-label":"Minimize",type:"button"},s().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"},s().createElement("path",{d:"M5 12h14"}))),r&&s().createElement("button",{className:"mwai-osx-maximize",onClick:a,"aria-label":"Maximize",type:"button"},s().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"},s().createElement("path",{d:"M15 3h6v6"}),s().createElement("path",{d:"M9 21H3v-6"}),s().createElement("path",{d:"M21 3l-7 7"}),s().createElement("path",{d:"M3 21l7-7"})))),s().createElement("div",{className:"mwai-osx-title"},e)),o&&s().createElement("div",{className:"mwai-osx-content"},o))},messages:{standard:({messages:e,conversationRef:t,onScroll:n,shortcuts:a,blocks:i})=>{const r=e.map(((e,n)=>React.createElement(ci,{key:n,message:e,conversationRef:t})));return React.createElement(React.Fragment,null,React.createElement("div",{ref:t,className:"mwai-conversation",onScroll:n},r,a),i)},terminal:({messages:t,conversationRef:n,onScroll:a})=>{const{state:i,actions:r}=(0,e.o)(),{inputText:s,textInputMaxLength:o,busy:l,locked:c,chatbotInputRef:u}=i,{setInputText:d,onSubmitAction:m}=r,[p,g]=_i(!1),[h,E]=_i(!1),f=hi(null);fi(u,(()=>({focusInput:()=>{var e,t;null==n||null===(e=n.current)||void 0===e||null===(t=e.focus)||void 0===t||t.call(e)},currentElement:()=>null==n?void 0:n.current}))),Ei((()=>{null!=n&&n.current&&(n.current.scrollTop=n.current.scrollHeight)}),[t]),Ei((()=>()=>{f.current&&clearTimeout(f.current)}),[]);const y=t&&t.length>0?t[t.length-1]:null,_=!(!y||"assistant"!==y.role||!y.isStreaming&&!y.isQuerying),w=!l&&!c&&!_,v=yi((e=>{if(l||c||_)return;const t=e.key&&1===e.key.length&&!e.ctrlKey&&!e.metaKey&&!e.altKey;return(t||"Backspace"===e.key||"Tab"===e.key)&&(E(!0),f.current&&clearTimeout(f.current),f.current=setTimeout((()=>{E(!1)}),250)),"Enter"===e.key?(e.preventDefault(),m(),E(!1),void(f.current&&clearTimeout(f.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 n=(t||"")+e.key;return o?n.slice(0,o):n}))):void 0}),[l,c,_,d,m,o]),R=yi((e=>{var t;if(l||c)return;const n=(null===(t=e.clipboardData)||void 0===t?void 0:t.getData("text"))||"";n&&(e.preventDefault(),d((e=>{const t=(e||"")+n;return o?t.slice(0,o):t})),E(!0),f.current&&clearTimeout(f.current),f.current=setTimeout((()=>{E(!1)}),250))}),[l,c,d,o]),T=yi((()=>{g(!0)}),[]),I=yi((()=>{g(!1)}),[]),b=gi((()=>t.map(((e,t)=>"user"===e.role?React.createElement(wi,{key:t,role:"user"},React.createElement("span",{className:"mwai-terminal-prompt"},React.createElement(pi,{size:16})),React.createElement("span",{className:"mwai-terminal-text"},e.content)):"system"===e.role?React.createElement(wi,{key:t,role:"system"},React.createElement("span",{className:"mwai-terminal-text"},"# ",e.content)):React.createElement(wi,{key:t,role:"assistant"},React.createElement("span",{className:"mwai-terminal-text"},React.createElement(ni,{message:e})))))),[t]);return React.createElement(React.Fragment,null,React.createElement("div",{ref:n,className:"mwai-conversation mwai-terminal",tabIndex:0,role:"textbox","aria-label":"Terminal input",onKeyDown:v,onPaste:R,onFocus:T,onBlur:I,onClick:()=>{var e;return null==n||null===(e=n.current)||void 0===e?void 0:e.focus()},onScroll:a},b,!_&&React.createElement("div",{className:"mwai-terminal-line mwai-terminal-user-typing"},React.createElement("span",{className:"mwai-terminal-prompt"},React.createElement(pi,{size:16})),React.createElement("span",{className:"mwai-terminal-input-wrapper"},React.createElement("span",{className:"mwai-terminal-typed"},s),React.createElement("span",{className:"mwai-terminal-cursor "+(p&&w?h?"mwai-terminal-cursor-typing":"mwai-terminal-cursor-active":"mwai-terminal-cursor-inactive")})))))}},input:{standard:({inputClassNames:e,chatbotInputRef:t,handleDrop:n,handleDrag:a})=>React.createElement("div",{className:e,onClick:()=>{var e;return null===(e=t.current)||void 0===e?void 0:e.focusInput()},onDrop:n,onDragEnter:e=>a(e,!0),onDragLeave:e=>a(e,!1),onDragOver:e=>a(e,!0)},React.createElement(Wi,null),React.createElement(Xi,null))}},Ji=(e,t)=>Qi[e]&&Qi[e][t]?Qi[e][t]:(console.warn(`Component ${e}/${t} not found`),null),{useMemo:Zi}=wp.element;const er=({onDragStart:n})=>{const{state:a,actions:r}=(0,e.o)(),{theme:s,isWindow:o,fullscreen:l,aiName:c,pluginUrl:u,open:d,closing:m,iconUrl:p,aiAvatarUrl:g,windowed:h,headerSubtitle:E,popupTitle:f,headerType:y,windowAnimation:_}=a,{setOpen:w,setClosing:v,setWindowed:R}=r,T=()=>{if(m||!d)return;if(!_||"none"===_)return void w(!1);v(!0);const e={zoom:{close:180,tail:150},slide:{close:200,tail:150},fade:{close:180,tail:120}},t=e[_]&&e[_].close||180,n=e[_]&&e[_].tail||150;setTimeout((()=>{w(!1),setTimeout((()=>{v(!1)}),n)}),t)};if(!o)return null;if("none"===y)return null;const I=Zi((()=>{const e="timeless"===(null==s?void 0:s.themeId),n=e?function(e,n,a,r){if((0,i.Ve)(r||a))return s=r||a,React.createElement("div",{className:"mwai-avatar mwai-emoji",style:{fontSize:"48px",lineHeight:"48px"}},s);var s;const o=(l=r,((0,t.mv)(l)?l:l?`${n}/images/${l}`:null)||a||`${n}/images/chat-openai.svg`);var l,c;return o?(c=o,React.createElement("div",{className:"mwai-avatar"},React.createElement("img",{alt:"AI Engine",src:c}))):React.createElement("div",{className:"mwai-name-text"},e)}(c,u,p,g):null,a=null==E?"Discuss with":E,r="osx"!==y;return React.createElement(React.Fragment,null,e&&React.createElement(React.Fragment,null,n,React.createElement("div",{className:"mwai-name"},a&&React.createElement("small",{className:"mwai-subtitle"},a),React.createElement("div",null,c)),React.createElement("div",{style:{flex:"auto"}})),r&&React.createElement("div",{className:"mwai-buttons"},l&&React.createElement("div",{className:"mwai-resize-button",onClick:()=>R(!h)}),React.createElement("div",{className:"mwai-close-button",onClick:T})))}),[null==s?void 0:s.themeId,c,u,p,g,l,R,h,T,E,y]),b=y||"standard",S=Ji("headers",b);if(S&&"standard"!==b){const e={title:f||c,aiName:c,subtitle:E,pluginUrl:u,iconUrl:p,aiAvatarUrl:g,onClose:T,onResize:()=>R(!h),onMinimize:T,onMaximize:()=>R(!h),showResize:l,theme:s,isFullscreen:l&&!h,isWindowed:h,onDragStart:n},t="timeless"===(null==s?void 0:s.themeId)?I:null;return React.createElement(S,e,t)}return React.createElement("div",{className:"mwai-header",onMouseDown:n,role:"toolbar","aria-label":"Chat header"},I)},{useMemo:tr,useEffect:nr}=wp.element,ar=()=>{const{state:n,actions:a}=(0,e.o)(),{isWindow:r,iconText:s,showIconMessage:o,iconAlt:l,iconUrl:c,open:u,opening:d,windowAnimation:m}=n,{setShowIconMessage:p,setOpen:g,setOpening:h}=a,E={zoom:{open:200},slide:{open:250},fade:{open:220}};nr((()=>{u&&o&&p(!1)}),[u,p,o]);const f=tr((()=>{if(!r)return null;const e=()=>{u||d||(o&&p(!1),m&&"none"!==m?(h(!0),requestAnimationFrame((()=>{g(!0);const e=E[m]&&E[m].open||200;setTimeout((()=>{h(!1)}),e)}))):g(!0))};return React.createElement("div",{className:"mwai-trigger mwai-open-button"},React.createElement(t.bE,{className:"mwai-icon-text-container",if:s&&o,disableTransition:!0},React.createElement("div",{className:"mwai-icon-text-close",role:"button","aria-label":"Close tip",onClick:e=>{e.stopPropagation(),p(!1)},onMouseDown:e=>e.preventDefault()},"✕"),React.createElement("div",{className:"mwai-icon-text",onClick:e},s)),React.createElement("div",{className:"mwai-icon-container",onClick:e},(0,i.Ve)(c)?React.createElement("div",{className:"mwai-icon mwai-emoji",style:{fontSize:"48px",lineHeight:"64px",width:"64px",height:"64px",display:"flex",justifyContent:"center",alignItems:"center"}},c):React.createElement("img",{className:"mwai-icon",width:"64",height:"64",alt:l,src:c})))}),[r,s,o,l,c,p,g,h,u,d,m]);return React.createElement(React.Fragment,null,f)},{useMemo:ir}=wp.element,rr=()=>{const n=(0,t.gR)(),{state:a,actions:i}=(0,e.o)(),{busy:r,messages:s,theme:o}=a;if(null==o||o.themeId,!ir((()=>(s||[]).length>0),[s]))return null;const l=n("mwai-file-upload",{});return React.createElement("div",{className:l,style:{cursor:r?"default":"pointer"}},React.createElement("div",{className:"mwai-file-upload-icon mwai-lucide",role:"button","aria-label":"Clear conversation",title:"Clear",onClick:()=>{r||i.onClear()}},React.createElement(Ki,{size:16})))},sr=(0,mi.A)("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]),or=(0,mi.A)("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),lr=(0,mi.A)("Loader",[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]]),cr=(0,mi.A)("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),ur=(0,mi.A)("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]),dr=(0,mi.A)("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),mr=(0,mi.A)("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]),pr=(0,mi.A)("Captions",[["rect",{width:"18",height:"14",x:"3",y:"5",rx:"2",ry:"2",key:"12ruh7"}],["path",{d:"M7 15h4M15 15h2M7 11h2M13 11h4",key:"1ueiar"}]]),gr=(0,mi.A)("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]),{useState:hr,useRef:Er,useEffect:fr}=wp.element;function yr(e,t){e.getByteTimeDomainData(t);let n=0;for(let e=0;e<t.length;e++){const a=t[e]-128;n+=a*a}return Math.sqrt(n/t.length)}function _r({assistantStream:e=null,userStream:t=null,assistantColor:n=null,userColor:a=null,userUI:i={emoji:null,text:null,image:null,use:"text"},assistantUI:r={emoji:null,text:null,image:null,use:"text"},attackSpeed:s=.3,releaseSpeed:o=.05,circleSize:l=50,pulseMaxSize:c=30}){const[u,d]=hr(0),[m,p]=hr(0),g=Er(0),h=Er(0),E=Er(null),f=Er(null),y=Er(null),_=Er(null),w=Er(null);fr((()=>{if(!e&&!t)return;E.current||(E.current=new AudioContext);const n=E.current;let a,i,r;e&&(a=n.createMediaStreamSource(e),f.current=n.createAnalyser(),f.current.fftSize=1024,y.current=new Uint8Array(f.current.frequencyBinCount),a.connect(f.current)),t&&(i=n.createMediaStreamSource(t),_.current=n.createAnalyser(),_.current.fftSize=1024,w.current=new Uint8Array(_.current.frequencyBinCount),i.connect(_.current));const l=()=>{let e=0;f.current&&y.current&&(e=yr(f.current,y.current));let t=0;_.current&&w.current&&(t=yr(_.current,w.current)),e>g.current?g.current=g.current*(1-s)+e*s:g.current=g.current*(1-o)+e*o,t>h.current?h.current=h.current*(1-s)+t*s:h.current=h.current*(1-o)+t*o,d(g.current),p(h.current),r=requestAnimationFrame(l)};return l(),()=>{a&&a.disconnect(),f.current&&f.current.disconnect(),i&&i.disconnect(),_.current&&_.current.disconnect(),r&&cancelAnimationFrame(r)}}),[e,t,s,o]);const v=l+Math.min(u/20,1)*c,R=l+Math.min(m/20,1)*c,T=l+c,I={width:R,height:R,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",opacity:.5};a&&(I.backgroundColor=a);const b={width:v,height:v,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",opacity:.5};n&&(b.backgroundColor=n);const S={width:l,height:l,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"flex",justifyContent:"center",alignItems:"center",overflow:"hidden",color:"#fff"};a&&(S.backgroundColor=a);const A={width:l,height:l,borderRadius:"50%",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",display:"flex",justifyContent:"center",alignItems:"center",overflow:"hidden",color:"#fff"};n&&(A.backgroundColor=n);let C="mwai-visualizer";m>u?C+=" mwai-user-talking":u>m&&(C+=" mwai-assistant-talking");const N=e=>{if(!e)return null;const{emoji:t,text:n,image:a,use:i}=e;switch(i){case"emoji":return t?React.createElement("span",null,t):n?React.createElement("span",null,n.slice(0,1)):null;case"image":return a?React.createElement("img",{src:a,alt:"",style:{width:"100%",height:"100%",borderRadius:"50%"}}):t?React.createElement("span",null,t):n?React.createElement("span",null,n.slice(0,1)):null;default:return n?React.createElement("span",null,n.slice(0,1)):t?React.createElement("span",null,t):null}};return React.createElement("div",{className:C},React.createElement("div",{className:"mwai-visualizer-user",style:{position:"relative",width:T,height:T,overflow:"visible"}},React.createElement("div",{className:"mwai-animation",style:I}),React.createElement("div",{style:S},N(i))),React.createElement("hr",{className:"mwai-visualizer-line"}),React.createElement("div",{className:"mwai-visualizer-assistant",style:{position:"relative",width:T,height:T,overflow:"visible"}},React.createElement("div",{className:"mwai-animation",style:b}),React.createElement("div",{style:A},N(r))))}const wr="tool_call",vr="tool_result",Rr="status",Tr="error",Ir="transcript",br=class{constructor(e,t=!1){this.onEvent=e,this.eventLogsEnabled=t,this.sessionStartTime=null}emit(e,t,n={}){if(!this.eventLogsEnabled||!this.onEvent)return;const a={type:"event",subtype:e,data:t,timestamp:(new Date).getTime(),...n};this.onEvent("",a)}sessionStarting(){this.sessionStartTime=(new Date).getTime(),this.emit(Rr,"Starting realtime session...")}sessionConnected(){const e=this.sessionStartTime?(new Date).getTime()-this.sessionStartTime:0;this.emit(Rr,`Realtime session connected in ${e}ms.`)}sessionEnding(){this.emit(Rr,"Ending realtime session...")}sessionError(e){this.emit(Tr,`Realtime session error: ${e}`)}userStartedSpeaking(){this.emit(Rr,"User speaking...",{visibility:"collapsed"})}userStoppedSpeaking(){this.emit(Rr,"User finished speaking.",{visibility:"collapsed"})}assistantStartedSpeaking(){this.emit(Rr,"Assistant speaking...",{visibility:"collapsed"})}assistantStoppedSpeaking(){this.emit(Rr,"Assistant finished speaking.",{visibility:"collapsed"})}functionCalling(e,t){this.emit(wr,`Calling ${e}...`,{metadata:{tool_name:e,arguments:t}})}functionResult(e,t){this.emit(vr,`Got result from ${e}.`,{metadata:{tool_name:e,result:t}})}functionError(e,t){this.emit(Tr,`Function ${e} failed: ${t}`,{metadata:{tool_name:e}})}userTranscribed(e){this.emit(Rr,`User: "${e}"`,{visibility:"collapsed"})}assistantTranscribed(e){this.emit(Rr,`Assistant: "${e}"`,{visibility:"collapsed"})}usageUpdated(e){const{text_input_tokens:t,audio_input_tokens:n,text_output_tokens:a,audio_output_tokens:i}=e,r=t+n+a+i;this.emit(Rr,`Tokens used: ${r} (Text: ${t}/${a}, Audio: ${n}/${i})`,{visibility:"collapsed",metadata:{usage:e}})}},{useState:Sr,useRef:Ar,useCallback:Cr,useMemo:Nr,useEffect:kr}=wp.element,Or=e=>"undefined"!=typeof wp&&wp.i18n&&wp.i18n.__?wp.i18n.__(e,"ai-engine"):e;function xr(e,...t){1>=e&&console.log(...t)}function Mr(e,n="user"){const{pluginUrl:a,iconUrl:r,userData:s,userName:o,aiName:l,guestName:c,userAvatar:u,aiAvatar:d,guestAvatar:m,userAvatarUrl:p,aiAvatarUrl:g,guestAvatarUrl:h}=e,E=(e,n,r,s,o=!1)=>{if(n){const e=((e,n=!1)=>(0,t.mv)(e)?e:e&&!(0,i.Ve)(e)?n?e:`${a}/images/${e}`:null)(r,o)||s;if(e)return{emoji:null,text:null,image:e,use:"image"}}return(0,i.Ve)(e)?{emoji:e,text:null,image:null,use:"emoji"}:{emoji:null,text:e,image:null,use:"text"}};if("assistant"===n)return E(l,d,g,r);if(s){const e=function(e,t,n){return n&&0!==Object.keys(n).length?Object.entries(n).reduce(((e,[t,n])=>{const a=`{${t}}`;return e.includes(a)?e.replace(a,n):e}),e):t||e||"Guest"}(o,c,s);return E(e,u,p,null==s?void 0:s.AVATAR_URL,!0)}return s||"user"!==n?{emoji:null,text:"Unknown",image:null,use:"text"}:E(c||"Guest",m,h,null)}const Pr=({onMessagesUpdate:t,onStreamEvent:n})=>{const{state:a,actions:i}=(0,e.o)(),{busy:r,locked:s,open:o,popup:l,system:c,blocks:u,params:d}=a,{onStartRealtimeSession:m,onRealtimeFunctionCallback:p,onCommitStats:g,onCommitDiscussions:h}=i,E=(null==c||c.debugMode,(null==c?void 0:c.eventLogs)||!1),f=!0===(null==d?void 0:d.imageUpload)||!0===(null==c?void 0:c.imageUpload),[y,_]=Sr(!1),[w,v]=Sr(!1),[R,T]=Sr(!1),[I,b]=Sr(null),[S,A]=Sr(null),[C,N]=Sr(null),[k,O]=Sr(null),[x,M]=Sr(!1),[P,L]=Sr({text_input_tokens:0,audio_input_tokens:0,text_output_tokens:0,audio_output_tokens:0,text_cached_tokens:0,audio_cached_tokens:0}),D=Ar(null),U=Ar(null),[F,B]=Sr(!1),[G,H]=Sr(0),[$,z]=Sr(!1),[W,K]=Sr(!1),[j,Y]=Sr(!1),[V,q]=Sr([]),X=Ar(new Set),Q=Cr(((e,t)=>{t&&t.subtype&&n&&n({...t,timestamp:t.timestamp||(new Date).getTime(),messageId:"realtime-session"})}),[n]),J=Ar(null);kr((()=>{J.current=new br(Q,E)}),[Q,E]);const Z=Ar(null),ee=Ar(null),te=Ar(null),ne=Ar(null),[ae,ie]=Sr(!0),[re,se]=Sr(!0),[oe,le]=Sr(!1),[ce,ue]=Sr(!1),[de,me]=Sr(null),pe=Ar([]),ge=Nr((()=>Mr(a,"user")),[a]),he=Nr((()=>Mr(a,"assistant")),[a]);kr((()=>{!o&&w&&l&&we()}),[o,l,w]),kr((()=>{t&&t(V)}),[V,t]);const Ee=Cr((async e=>{const t=await g(e);t.overLimit&&(E&&J.current&&J.current.emit(Tr,t.limitMessage||Or("Usage limit exceeded"),{visibility:"visible",error:!0}),console.warn("Usage limit exceeded, stopping realtime connection:",t.limitMessage),ne.current&&ne.current())}),[g,E]),fe=Cr((()=>{ee.current&&"open"===ee.current.readyState?(ee.current.send(JSON.stringify({type:"session.update",session:{input_audio_transcription:{model:"whisper-1"}}})),xr(1,"Sent session.update to enable Whisper.")):console.error("Data channel is not open yet; cannot enable transcription.")}),[]),ye=Cr((async(e,t,n)=>{let a={};try{a=JSON.parse(n||"{}")}catch(e){console.error("Could not parse function arguments.",n)}const i=pe.current.find((e=>e.name===t));if(i)try{var r;const n=await p(i.id,i.type,i.name,i.target,a);if(null==n||!n.success)return void console.error("Callback failed.",null==n?void 0:n.message);const s=n.data;if(E&&J.current){const n="string"==typeof s?s:JSON.stringify(s),a=n.length>100?n.substring(0,100)+"...":n;J.current.emit(vr,`Got result from ${t}.`,{metadata:{tool_name:t,result:a,call_id:e}})}"open"===(null===(r=ee.current)||void 0===r?void 0:r.readyState)&&(xr(1,"Send callback value:",s),ee.current.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(s)}})),ee.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}'.`)}),[p,E]),_e=Cr((async(e,t)=>{_(!0),E&&J.current&&J.current.emit(Rr,"Starting realtime session...",{visibility:"visible"});const n=new RTCPeerConnection;let a;Z.current=n,n.addEventListener("connectionstatechange",(()=>{console.log("PC connection state:",n.connectionState),"failed"!==n.connectionState&&"closed"!==n.connectionState&&"disconnected"!==n.connectionState||F&&(N(Or("Connection lost. Please try again.")),B(!1),H(0))}));try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error(Or("MediaDevices API not available. Please ensure you are using HTTPS and a modern browser."));a=await navigator.mediaDevices.getUserMedia({audio:!0}),te.current=a,a.getTracks().forEach((e=>n.addTrack(e,a)))}catch(e){return console.error("Error accessing microphone.",e),E&&J.current&&J.current.emit(Rr,Or("Failed to access microphone: ")+e.message,{visibility:"visible",error:!0}),N(Or("Failed to access microphone. Please ensure microphone permissions are granted and try again.")),void _(!1)}n.ontrack=e=>{const t=document.getElementById("mwai-audio");t&&(t.srcObject=e.streams[0]),me(e.streams[0])};const i=n.createDataChannel("oai-events");ee.current=i,i.addEventListener("open",(()=>{xr(1,"Data channel open."),E&&J.current&&J.current.emit(Rr,"Realtime session connected",{visibility:"visible"}),fe()})),i.addEventListener("close",(()=>{console.log("Data channel closed"),F&&(N(Or("Connection lost while uploading image. Please try again.")),B(!1),H(0))})),i.addEventListener("error",(e=>{console.error("Data channel error:",e),F&&(N(Or("Error uploading image. Please try again.")),B(!1),H(0))})),i.addEventListener("message",(e=>{let t;try{t=JSON.parse(e.data)}catch(t){return void console.error("Could not parse Realtime message.",e.data)}var n;if(((null===(n=t.type)||void 0===n?void 0:n.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),E&&t.type&&J.current){let e="",n=Rr,a=!1;switch(t.type){case"input_audio_buffer.speech_started":e="User started talking...",a=!0;break;case"input_audio_buffer.speech_stopped":e="User stopped speaking.",a=!0;break;case"response.audio.started":e="Assistant started speaking.",a=!0;break;case"response.audio.done":e="Assistant stopped speaking.",a=!0;break;case"conversation.item.input_audio_transcription.completed":e="Got transcript from user.",n=Ir,a=!0;break;case"response.audio_transcript.done":e="Got transcript from assistant.",n=Ir,a=!0;break;case"response.function_call_arguments.done":e=`Calling ${t.name}...`,n=wr,a=!0}a&&J.current.emit(n,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;X.current.has(e)||(X.current.add(e),q((t=>[...t,{id:e,role:"user",content:"[Audio]"}]))),A("user");break}case"conversation.item.created":var a,i;console.log("Conversation item created:",t),null!==(a=t.item)&&void 0!==a&&null!==(a=a.content)&&void 0!==a&&a.some((e=>"input_image"===e.type||"input_image_url"===e.type))&&(console.log("Image item confirmed by API"),K((e=>e?(console.log("Clearing processing state - image confirmed by API"),!1):e)),B(!1),H(0),Y(!0),setTimeout((()=>{Y(!1)}),2e3)),"assistant"===(null===(i=t.item)||void 0===i?void 0:i.role)&&(console.log("Assistant response started"),W&&(console.log("Clearing processing state - assistant is responding"),K(!1)));break;case"conversation.item.input_audio_transcription.completed":{const e=t.item_id,n=(t.transcript||"[Audio]").trim();q((t=>t.map((t=>t.id===e&&"user"===t.role?{...t,content:n}:t))));break}case"response.audio_transcript.done":{const e=t.item_id,n=(t.transcript||"[Audio]").trim();A("assistant"),X.current.has(e)||(X.current.add(e),q((t=>[...t,{id:e,role:"assistant",content:n}])));break}case"response.text.done":{const e=t.item_id,n=t.text||"";n&&!X.current.has(e)&&(X.current.add(e),q((t=>[...t,{id:e,role:"assistant",content:n}])));break}case"response.output_item.done":{console.log("Output item done:",t);const e=t.item;if(W&&(console.log("Clearing processing state after response"),K(!1)),F&&(console.log("Clearing upload state after response"),B(!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&&!X.current.has(e.id)&&(X.current.add(e.id),q((n=>[...n,{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&&(X.current.has(e.id)||(X.current.add(e.id),q((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:n,arguments:a}=t;xr(1,"Function call requested.",e,n),ye(e,n,a);break}case"response.done":{const e=t.response;if(K((e=>e?(console.log("Response completed after image processing"),!1):e)),B((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:n=0,cached_tokens_details:{text_tokens:a=0,audio_tokens:i=0}={}}={},output_token_details:{text_tokens:r=0,audio_tokens:s=0}={}}=e;return{text_input_tokens:t,audio_input_tokens:n,text_output_tokens:r,audio_output_tokens:s,text_cached_tokens:a,audio_cached_tokens:i}}(e.usage);t&&L((e=>{const n={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 Ee(n),n}))}A("user");break}case"error":var r;console.error("Realtime API error:",t),null!==(r=t.error)&&void 0!==r&&r.message&&N(`API Error: ${t.error.message}`),B(!1),K(!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 n.createOffer();await n.setLocalDescription(r);const s=t||"gpt-4o-preview-2024-12-17",o=await fetch(`https://api.openai.com/v1/realtime?model=${s}`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/sdp"},body:r.sdp});if(!o.ok)return console.error("SDP exchange failed.",o),_(!1),N(Or("Failed to establish connection with OpenAI servers. Please try again.")),void(E&&J.current&&J.current.emit(Tr,Or("Failed to establish connection with OpenAI servers. Please try again."),{visibility:"visible",error:!0}));const l=await o.text();await n.setRemoteDescription({type:"answer",sdp:l}),xr(1,"Realtime connection established."),_(!1),v(!0),T(!1),A("user")}),[fe,ye,Ee,E]),we=Cr((()=>{O(null),E&&J.current&&J.current.emit(Rr,"Ending realtime session...",{visibility:"visible"});try{Z.current&&(Z.current.close(),Z.current=null),te.current&&(te.current.getTracks().forEach((e=>e.stop())),te.current=null),ee.current=null,_(!1),v(!1),T(!1),A(null),h(V),q([]),L({text_input_tokens:0,audio_input_tokens:0,text_output_tokens:0,audio_output_tokens:0,text_cached_tokens:0,audio_cached_tokens:0}),xr(1,"Stopped Realtime connection.")}catch(e){console.error("Error stopping connection.",e)}}),[V,P,h]);kr((()=>{ne.current=we}),[we]);const ve=Cr((()=>{if(!te.current)return;const e=te.current.getAudioTracks();e.length&&(R?(e.forEach((e=>{e.enabled=!0})),xr(1,"Resumed microphone."),T(!1)):(e.forEach((e=>{e.enabled=!1})),xr(1,"Paused microphone."),T(!0)))}),[R]),Re=Cr(((e,t=800,n=800,a=.6)=>new Promise((i=>{const r=new Image;r.onload=()=>{let e=r.width,s=r.height;if(e>t||s>n){const a=Math.min(t/e,n/s);e=Math.round(e*a),s=Math.round(s*a)}const o=document.createElement("canvas");o.width=e,o.height=s,o.getContext("2d").drawImage(r,0,0,e,s);const l=o.toDataURL("image/jpeg",a);i(l)},r.src=e}))),[]),Te=Cr((async e=>{if(e.type.startsWith("image/"))if(e.size>20971520)N(Or("Image file size must be less than 20MB."));else{B(!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 n=e.target.result;const a=n.length,i=204800;if(a>i){console.log(`Image too large (${(a/1024).toFixed(0)}KB), resizing...`),H(30);let e=.7,t=800,r=await Re(n,t,t,e);for(;r.length>i&&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 Re(n,t,t,e);n=r,console.log(`Image resized to ${(n.length/1024).toFixed(0)}KB`)}if("open"===(null===(t=ee.current)||void 0===t?void 0:t.readyState)){E&&J.current&&J.current.emit(Rr,"Sending image...",{visibility:"visible"}),H(50),console.log("Image details:",{totalLength:n.length,hasDataPrefix:n.includes("data:"),mimeType:n.substring(5,n.indexOf(";")),sizeKB:(n.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:n}]}},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"!==ee.current.readyState)throw new Error("Data channel is not open. State: "+ee.current.readyState);const e=ee.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)))),ee.current.send(t);const n=ee.current.bufferedAmount;console.log("Data channel buffered amount after send:",n),console.log("Image message queued for sending"),H(100),setTimeout((()=>{B(!1),K(!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),N(Or("Failed to send image. Please try again.")),B(!1),void H(0)}q((e=>[...e,{id:`img-${Date.now()}`,role:"user",content:"[Image uploaded - processing...]"}])),D.current&&(D.current.value="")}else N(Or("Please start a session before uploading images.")),B(!1),H(0)},t.onerror=()=>{N(Or("Failed to read image file.")),B(!1),H(0)},t.readAsDataURL(e)}catch(e){console.error("Error uploading image:",e),N(Or("Failed to upload image.")),B(!1),H(0)}}else N(Or("Please select an image file."))}),[ee,E,Re]),Ie=Cr((async e=>{const t=e.target.files[0];t&&Te(t)}),[Te]),be=Cr((e=>{e.preventDefault(),e.stopPropagation(),F||W||r||s||R||!w||z(!0)}),[F,W,r,s,R,w]),Se=Cr((e=>{e.preventDefault(),e.stopPropagation(),U.current&&!U.current.contains(e.relatedTarget)&&z(!1)}),[]),Ae=Cr((e=>{if(e.preventDefault(),e.stopPropagation(),z(!1),F||W||r||s||R||!w)return;const t=e.dataTransfer.files;t&&t.length>0&&Te(t[0])}),[F,W,r,s,R,w,Te]),Ce=Cr((async()=>{_(!0),N(null);try{const e=await m();if(null==e||!e.success){console.error("Could not start realtime session.",e),_(!1);const t=(null==e?void 0:e.message)||Or("Could not start realtime session.");return N(t),void(E&&J.current&&J.current.emit(Tr,t,{visibility:"visible",error:!0}))}pe.current=e.function_callbacks||[],b(e.session_id),O(e.model),console.log("Vision support from server:",e.supports_vision),M(!0===e.supports_vision),await _e(e.client_secret,e.model)}catch(e){console.error("Error in handlePlay.",e),_(!1);const t=e.message||Or("An error occurred while starting the realtime session.");N(t),E&&J.current&&J.current.emit(Tr,t,{visibility:"visible",error:!0})}}),[m,_e,E]),Ne=Cr((()=>we()),[we]),ke=Cr((()=>se((e=>!e))),[]),Oe=Cr((()=>ue((e=>!e))),[]),xe=Cr((()=>le((e=>!e))),[]),Me=Nr((()=>R?"mwai-pause mwai-active":"mwai-pause"),[R]),Pe=Nr((()=>{const e=[...V].reverse().find((e=>"assistant"===e.role));return e?e.content.length>256?`${e.content.slice(0,256)}...`:e.content:"..."}),[V]),Le=Nr((()=>re?"mwai-option mwai-option-users mwai-active":"mwai-option mwai-option-users"),[re]),De=Nr((()=>oe?"mwai-option mwai-option-captions mwai-active":"mwai-option mwai-option-captions"),[oe]),Ue=Nr((()=>ce?"mwai-option mwai-option-statistics mwai-active":"mwai-option mwai-option-statistics"),[ce]);kr((()=>{u&&u.length>0&&u.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)}}))}),[u]);const Fe=Nr((()=>u&&0!==u.length?React.createElement("div",{className:"mwai-blocks"},u.map(((e,t)=>{const{type:n,data:a}=e;if("content"!==n)return console.warn(`Block type ${n} is not supported.`),null;const{html:i,variant:r}=a,s=["mwai-block"];return"success"===r&&s.push("mwai-success"),"danger"===r&&s.push("mwai-danger"),"warning"===r&&s.push("mwai-warning"),"info"===r&&s.push("mwai-info"),React.createElement("div",{className:s.join(" "),key:e.id||t,dangerouslySetInnerHTML:{__html:i}})}))):null),[u]);return React.createElement("div",null,Fe,C&&React.createElement("div",{className:"mwai-error",style:{padding:"10px",margin:"10px 0",backgroundColor:"#fee",border:"1px solid #fcc",borderRadius:"5px",color:"#c00",textAlign:"center"}},C),React.createElement("audio",{id:"mwai-audio",autoPlay:!0}),re&&React.createElement("div",{style:{display:"flex",justifyContent:"center"}},React.createElement(_r,{assistantStream:de,userUI:ge,assistantUI:he,userStream:te.current})),React.createElement("div",{className:"mwai-controls"},!w&&!y&&React.createElement(React.Fragment,null,React.createElement("button",{onClick:Ce,className:"mwai-play",disabled:r||s,"aria-label":"Play"},React.createElement(sr,{size:16})),f&&React.createElement("button",{className:"mwai-upload",disabled:!0,"aria-label":"Upload Image (Start session first)",style:{opacity:.5,cursor:"not-allowed"},title:Or("Start session to upload images")},React.createElement(or,{size:16}))),y&&React.createElement(React.Fragment,null,React.createElement("button",{className:"mwai-play",disabled:!0},React.createElement(lr,{size:16,style:{animation:"spin 0.8s linear infinite"}})),f&&React.createElement("button",{className:"mwai-upload",disabled:!0,"aria-label":"Upload Image (Connecting...)",style:{opacity:.5,cursor:"not-allowed"}},React.createElement(or,{size:16}))),w&&!y&&React.createElement(React.Fragment,null,React.createElement("button",{onClick:Ne,className:"mwai-stop",disabled:r||s,"aria-label":"Stop"},React.createElement(cr,{size:16})),React.createElement("button",{onClick:ve,className:Me,disabled:r||s,"aria-label":"Pause"},React.createElement(ur,{size:16})),(x||f)&&React.createElement(React.Fragment,null,React.createElement("input",{ref:D,type:"file",accept:"image/*",style:{display:"none"},onChange:Ie}),React.createElement("button",{ref:U,onClick:()=>{var e;return null===(e=D.current)||void 0===e?void 0:e.click()},className:`mwai-upload ${$?"mwai-dragging":""} ${W?"mwai-processing":""} ${j?"mwai-success":""}`,disabled:r||s||F||W||j||R,"aria-label":"Upload Image",onDragOver:be,onDragLeave:Se,onDrop:Ae,style:{position:"relative",overflow:"visible",cursor:F||W?"wait":j?"default":"pointer",transition:"all 0.3s ease",...$?{transform:"scale(1.1)",backgroundColor:"rgba(34, 197, 94, 0.2)",borderColor:"rgb(34, 197, 94)"}:j?{backgroundColor:"rgba(34, 197, 94, 0.1)",borderColor:"rgb(34, 197, 94)"}:{}}},(F||W)&&React.createElement("svg",{style:{position:"absolute",top:"-2px",left:"-2px",width:"calc(100% + 4px)",height:"calc(100% + 4px)",transform:"rotate(-90deg)",pointerEvents:"none",animation:W?"spin 1s linear infinite":"none"}},W?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*G+" 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(or,{size:16,style:{position:"absolute",top:0,left:0,opacity:j?0:F||W?.5:1,transition:"opacity 0.3s ease, transform 0.3s ease",transform:j?"scale(0.8)":"scale(1)",transformOrigin:"center"}}),React.createElement(dr,{size:16,style:{position:"absolute",top:0,left:0,opacity:j?1:0,transition:"opacity 0.3s ease, transform 0.3s ease",transform:j?"scale(1)":"scale(0.8)",transformOrigin:"center",color:"rgb(34, 197, 94)"}})))))),oe&&Pe&&Pe.length>0&&React.createElement("div",{className:"mwai-last-transcript"},Pe),ce&&React.createElement("div",{className:"mwai-statistics"},React.createElement("div",null,React.createElement("label",null,"Text In"),React.createElement("span",null,P.text_input_tokens)),React.createElement("div",null,React.createElement("label",null,"Text Out"),React.createElement("span",null,P.text_output_tokens)),React.createElement("div",null,React.createElement("label",null,"Text Cached"),React.createElement("span",null,P.text_cached_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio In"),React.createElement("span",null,P.audio_input_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio Out"),React.createElement("span",null,P.audio_output_tokens)),React.createElement("div",null,React.createElement("label",null,"Audio Cached"),React.createElement("span",null,P.audio_cached_tokens))),ae&&React.createElement("div",{className:"mwai-options"},React.createElement(mr,{size:13,title:"Show Users",className:Le,onClick:ke}),React.createElement(pr,{size:18,title:"Show Captions",className:De,onClick:xe}),React.createElement(gr,{size:14,title:"Show Statistics",className:Ue,onClick:Oe})))},Lr=(0,mi.A)("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]),Dr=(0,mi.A)("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]),Ur=(0,mi.A)("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]),Fr=(0,mi.A)("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]),Br=(0,mi.A)("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),Gr=(0,mi.A)("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Hr=(0,mi.A)("Minimize2",[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]),$r=(0,mi.A)("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]),zr=(0,mi.A)("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),{useState:Wr,useMemo:Kr,useEffect:jr}=wp.element,Yr=({allStreamData:e,debugMode:t,onClear:n,hasData:a,isWindow:i})=>{const[r,s]=Wr({}),[o,l]=Wr(!1),[c,u]=Wr(!i),d=Kr((()=>{if(!e||0===e.length)return[];const t=e.map(((e,t)=>({...e,id:`${e.messageId}-${t}`,displayTime:new Date(e.timestamp).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}))).reverse();return c?t.slice(0,20):t.slice(0,1)}),[e,c]),m=(e,t)=>{switch(e){case"tool_call":case"tool_args":return"function";case"tool_result":return!0===(null==t?void 0:t.is_mcp)||null!=t&&t.tool_name&&d.some((e=>{var n;return"mcp_tool_call"===e.subtype&&(null===(n=e.metadata)||void 0===n?void 0:n.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"}},g=Kr((()=>{if(0===d.length)return null;for(const e of d){const t=m(e.subtype,e.metadata);if("debug"!==e.subtype&&"heartbeat"!==e.subtype){if(e.data.includes("Stream completed")){const t=d.findIndex((e=>e.data.includes("Request completed")));if(t>=0&&t<d.indexOf(e)){const e=d[t];return{data:e.data,category:m(e.subtype,e.metadata),color:p(m(e.subtype,e.metadata),e.data)}}}return{data:e.data,category:t,color:p(t,e.data)}}}return null}),[d]);return React.createElement("div",{className:"mwai-chunks "+(o?"":"mwai-chunks-collapsed")},React.createElement("div",{className:"mwai-chunks-header"},React.createElement(Dr,{size:12}),React.createElement("span",{className:"mwai-chunks-title"},"Events",g&&React.createElement("span",{className:"mwai-chunks-status",style:{color:g.color}},": ",g.data)),o&&React.createElement(React.Fragment,null,d.length>0&&n&&React.createElement("div",{className:"mwai-chunks-toggle",onClick:n,title:"Clear stream events"},React.createElement(Gr,{size:12})),!i&&React.createElement("div",{className:"mwai-chunks-toggle",onClick:()=>u(!c),title:c?"Show minimal (last event only)":"Show detailed (all events)"},c?React.createElement(Hr,{size:12}):React.createElement($r,{size:12}))),React.createElement("div",{className:"mwai-chunks-toggle",onClick:()=>l(!o),title:o?"Hide events":"Show events"},o?React.createElement(zr,{size:12}):React.createElement(pi,{size:12}))),o&&(0===d.length?React.createElement("div",{className:"mwai-chunk"},React.createElement("div",{className:"mwai-chunk-header"},React.createElement("span",{className:"mwai-chunk-time"},"--:--:--"),React.createElement("span",{className:"mwai-chunk-type",style:{backgroundColor:"#6b7280"}},React.createElement(Dr,{size:14}),"waiting"),React.createElement("span",{className:"mwai-chunk-data"},"No events yet."))):d.map((e=>{const t=r[e.id],n=m(e.subtype,e.metadata),a=e.metadata&&Object.keys(e.metadata).length>0||"thinking"===n;return React.createElement("div",{key:e.id,className:"mwai-chunk"},React.createElement("div",{className:"mwai-chunk-header",onClick:()=>{return a&&(t=e.id,void s((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(n,e.data)}},(e=>{switch(e){case"function":return React.createElement(Lr,{size:14});case"mcp":case"output":default:return React.createElement(Dr,{size:14});case"thinking":return React.createElement(Ur,{size:14});case"search":return React.createElement(Fr,{size:14});case"error":case"warning":return React.createElement(Br,{size:14})}})(n),n),React.createElement("span",{className:"mwai-chunk-data"},(()=>{const t="string"==typeof e.data?e.data:JSON.stringify(e.data);if("thinking"===n){const e=t.match(/^\*\*([^*]+)\*\*/);return e?e[1]:t.substring(0,50)+(t.length>50?"...":"")}return t})()),a&&React.createElement(pi,{size:12,className:"mwai-chunk-expand",style:{transform:t?"rotate(90deg)":"none"}})),t&&a&&React.createElement("div",{className:"mwai-chunk-details"},"thinking"===n?React.createElement("div",{style:{padding:"0px 10px",fontFamily:"system-ui"}},(()=>{const t="string"==typeof e.data?e.data:JSON.stringify(e.data);try{return Ja(t)}catch(e){return React.createElement("pre",null,t)}})()):React.createElement("pre",null,JSON.stringify(e.metadata,null,2))))}))))},Vr=(0,mi.A)("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]),{useMemo:qr}=wp.element,Xr=()=>{const{state:t,actions:n}=(0,e.o)(),{uploadedFiles:a,multiUpload:i}=t,{removeUploadedFile:r}=n;return i&&0!==a.length?React.createElement("div",{className:"mwai-files"},a.map(((e,t)=>((e,t)=>{var n,a,i;const s=null===(n=e.localFile)||void 0===n||null===(n=n.type)||void 0===n?void 0:n.startsWith("image/"),o=(null===(a=e.localFile)||void 0===a?void 0:a.name)||"Unknown file",l=null!==(i=e.localFile)&&void 0!==i&&i.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"},s&&e.uploadedUrl?React.createElement("img",{src:e.uploadedUrl,alt:o,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"},o),l&&React.createElement("div",{className:"mwai-file-size"},l)),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:()=>r(t),"aria-label":"Remove file"},React.createElement(Vr,{size:20}))))})(e,t)))):null},{useState:Qr,useEffect:Jr,useRef:Zr,useMemo:es}=wp.element,ts=({conversationRef:t,onScroll:n,jsxShortcuts:a,jsxBlocks:i,inputClassNames:r,handleDrop:s,handleDrag:o,needsFooter:l,needTools:c,uploadIconPosition:u})=>{const{state:d,actions:m}=(0,e.o)(),{debugMode:p,eventLogs:g,messages:h,isRealtime:E,textCompliance:f,chatbotInputRef:y,isWindow:_,fullscreen:w,windowed:v,messagesType:R,inputType:T,theme:I}=d,[b,S]=Qr([]),[A,C]=Qr(new Set),N=Zr([]),[k,O]=(Zr(0),Qr([]));return Jr((()=>{(0===h.length||1===h.length&&"assistant"===h[0].role)&&C(new Set)}),[h]),Jr((()=>{const e=[];[...h,...k].forEach((t=>{t.streamEvents&&(p||g)&&!A.has(t.id)&&t.streamEvents.forEach((n=>{e.push({...n,messageId:t.id})}))})),E||(N.current=e,S(e))}),[h,k,p,g,E,A]),React.createElement("div",{className:"mwai-body"},!E&&React.createElement(React.Fragment,null,w&&!v?React.createElement(React.Fragment,null,"none"!==R&&(()=>{const e=Ji("messages",R);if(!e){console.warn(`Messages component '${R}' not found, falling back to standard`);const e=Ji("messages","standard");return React.createElement(e,{messages:h,conversationRef:t,onScroll:n,shortcuts:a,blocks:i})}return React.createElement(e,{messages:h,conversationRef:t,onScroll:n,shortcuts:a,blocks:i})})(),React.createElement("div",{className:"mwai-fullscreen-spacer"}),React.createElement(Xr,null)):React.createElement(React.Fragment,null,"none"!==R&&(()=>{const e=Ji("messages",R);if(!e){console.warn(`Messages component '${R}' not found, falling back to standard`);const e=Ji("messages","standard");return React.createElement(e,{messages:h,conversationRef:t,onScroll:n,shortcuts:a,blocks:i})}return React.createElement(e,{messages:h,conversationRef:t,onScroll:n,shortcuts:a,blocks:i})})(),React.createElement(Xr,null)),"none"!==T&&(()=>{const e=Ji("input",T);if(!e){console.warn(`Input component '${T}' not found, falling back to standard`);const e=Ji("input","standard");return React.createElement(e,{inputClassNames:r,chatbotInputRef:y,handleDrop:s,handleDrag:o})}return React.createElement(e,{inputClassNames:r,chatbotInputRef:y,handleDrop:s,handleDrag:o})})()),E&&React.createElement("div",{className:"mwai-realtime"},React.createElement(Pr,{onMessagesUpdate:O,onStreamEvent:e=>{S((t=>[...t,e]))}})),l&&React.createElement("div",{className:"mwai-footer"},(()=>{const e=("mwai-tools"===u||"none"===T)&&c,t="none"===T||"chatgpt"!==(null==I?void 0:I.themeId)&&"timeless"!==(null==I?void 0:I.themeId)&&"messages"!==(null==I?void 0:I.themeId),n=h&&h.length>0;return e&&c||t&&n?React.createElement("div",{className:"mwai-tools"},e&&React.createElement(Bi,null),t&&React.createElement(rr,null)):null})(),f&&React.createElement("div",{className:"mwai-compliance",dangerouslySetInnerHTML:{__html:f}})),g&&React.createElement(Yr,{allStreamData:b,debugMode:p,onClear:()=>{S([]),N.current=[];const e=new Set;[...h,...k].forEach((t=>{t.streamEvents&&e.add(t.id)})),C(e)},hasData:b.length>0,isWindow:_}))},{useState:ns,useMemo:as,useLayoutEffect:is,useCallback:rs,useEffect:ss,useRef:os}=wp.element,ls=e=>e.type.startsWith("image/"),cs=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),us=n=>{const i=(0,t.gR)(),{style:r,isAdminPreview:s}=n,[o,l]=ns(!0),[c,u]=ns(!1),{state:d,actions:m}=(0,e.o)(),{theme:p,botId:g,customId:h,messages:E,textCompliance:f,isWindow:y,fullscreen:_,iconPosition:w,centerOpen:v,width:R,openDelay:T,iconBubble:I,windowAnimation:b,shortcuts:S,blocks:A,imageUpload:C,fileSearch:N,fileUpload:k,multiUpload:O,draggingType:x,isBlocked:M,windowed:P,cssVariables:L,conversationRef:D,open:U,opening:F,closing:B,busy:G,uploadIconPosition:H,containerType:$,headerType:z,messagesType:W,inputType:K,footerType:j,popupTitle:Y,aiName:V}=d,{onSubmit:q,setIsBlocked:X,setDraggingType:Q,onUploadFile:J,onMultiFileUpload:Z,setOpen:ee,setClosing:te}=m,ne=as((()=>"css"===(null==p?void 0:p.type)?(null==p?void 0:p.style)||null:null!=p&&p.customCSS?p.customCSS:null),[p]),ae=C||N||k,ie="none"!==j&&(ae||f&&f.trim()),re=os(null);ss((()=>{const e=()=>{u(window.innerWidth<=760)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)}),[]);const se=as((()=>`chatbot-${g||h||Math.random().toString(36).substr(2,9)}`),[g,h]);ss((()=>{let e=!1;return _&&!P?e=!y||U:c&&y&&U&&(e=!0),a.updateLock(se,e),()=>{a.removeLock(se)}}),[U,_,P,c,y,se]);const oe=rs(((e,t)=>{if(e.preventDefault(),!C&&!k)return;if(!t)return X(!1),void Q(!1);const n=e.dataTransfer.items;let a=!1,i=!1;if(n&&n.length>0)for(let e=0;e<n.length;e++){const t=n[e];if("file"===t.kind){const e=t.type;e?C&&e.startsWith("image/")?a=!0:k&&(e.startsWith("text/")||"application/pdf"===e||e.includes("document")||e.includes("sheet")||e.includes("presentation"))&&(i=!0):(C||k)&&(C?a=!0:i=!0)}}const r=a||i;X(!r),Q(!!r&&(a?"image":"document"))}),[C,k,Q,X]),le=rs((e=>{e.preventDefault();const t=e.dataTransfer.files;if(O){const e=Array.from(t).filter((e=>C&&ls(e)||k&&cs(e)));e.length>0&&Z(e)}else{const e=Array.from(t).find((e=>C&&ls(e)||k&&cs(e)));e&&J(e)}Q(!1),X(!1)}),[C,k,O,J,Z,Q,X]),ce=os(!1);ss((()=>{if(!ce.current&&y&&T&&T>0&&!U){ce.current=!0;const e=setTimeout((()=>{ee(!0)}),1e3*T);return re.current=e,()=>{re.current&&clearTimeout(re.current)}}}),[y,T,U,ee]),is((()=>{o&&D.current&&(D.current.scrollTop=D.current.scrollHeight)}),[E,o,D,G]);const ue=i("mwai-input",{"mwai-active":!G}),[de,me]=ns(!1),[pe,ge]=ns(null),he="undefined"==typeof window||window.matchMedia("(min-width: 761px)").matches,Ee=rs((e=>{if(!y||!U||_&&!P||!he||s)return;const t=e.target;if(t.closest&&(t.closest(".mwai-close-button")||t.closest(".mwai-resize-button")||t.closest("button")))return;const n=document.getElementById(`mwai-chatbot-${h||g}`);if(!n)return;const a=n.getBoundingClientRect(),i=e.clientX,r=e.clientY,o=a.top,l=a.left;me(!0),ge({top:o,left:l});const c=document.body.style.cursor;document.body.style.cursor="move";const u=e=>{const t=o+(e.clientY-r),n=l+(e.clientX-i);ge({top:t,left:n})},d=()=>{me(!1),document.body.style.cursor=c||"",document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",d)};document.addEventListener("mousemove",u),document.addEventListener("mouseup",d)}),[y,U,_,P,he,h,g,s]),fe=as((()=>pe?{top:`${Math.max(0,pe.top)}px`,left:`${Math.max(0,pe.left)}px`,right:"auto",bottom:"auto",transform:"none"}:{}),[pe]);ss((()=>{U||B||!pe||ge(null)}),[U,B,pe]);const ye=as((()=>({...r,...L,maxWidth:_?null:R,maxHeight:_?null:"calc(100% - 20px)",...pe?fe:{}})),[r,L,_,R,pe,fe]),_e=new Set(["zoom","slide","fade"]),we=b&&_e.has(b)?b:"none",ve=i("mwai-chat",{[`mwai-${w}`]:y,"mwai-window":y,"mwai-center-open":y&&v,"mwai-bubble":(!0===I||1===I||"1"===I||"true"===I)&&y,"mwai-open":U||!y&&_,"mwai-opening":F,"mwai-closing":B,"mwai-top-left":"top-left"===w,"mwai-top-right":"top-right"===w,"mwai-fullscreen":_&&!P,"mwai-bottom-left":"bottom-left"===w,"mwai-bottom-right":"bottom-right"===w,[`mwai-animation-${we}`]:y&&we&&"none"!==we}),Re=i(ve,{"mwai-dragging":x,"mwai-blocked":M,"mwai-window-dragging":de,[`mwai-${null==p?void 0:p.themeId}-theme`]:!0,[`mwai-container-${$}`]:$&&"standard"!==$}),Te=as((()=>{if(!S||0===S.length)return null;const e=e=>e&&(e.startsWith("http://")||e.startsWith("https://")),t=e=>!!e&&/^[\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"},S.map(((n,a)=>{const{type:r,data:s}=n,{label:o,variant:l,icon:c,className:u}=s??{};let d=i("mwai-shortcut",{"mwai-success":"success"===l,"mwai-danger":"danger"===l,"mwai-warning":"warning"===l,"mwai-info":"info"===l});switch(u&&(d+=` ${u}`),r){case"action":{const{action:n,message:i}=s??{},r=()=>{"clear"===n?m.onClear():"message"===n&&i?q(i):console.warn(`This action is not supported: ${n}.`)};return React.createElement("button",{className:d,key:a,onClick:r},(e(c)||t(c))&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},e(c)&&React.createElement("img",{src:c,alt:o||"AI Shortcut"}),t(c)&&React.createElement("span",{role:"img","aria-label":"AI Shortcut"},c)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-label"},o||"N/A"))}case"callback":{const{onClick:n}=s,i=()=>{if("function"==typeof n)n();else if("string"==typeof n){const e=n.replace(/actions\.([\w]+)/g,"actions.$1").replace(/state\.([\w]+)/g,"state.$1"),t=new Function(`return (${e});`)();s.onClick=t,t()}else console.warn("No valid callback function provided in data.onClick.")};return React.createElement("button",{className:d,key:a,onClick:i},(e(c)||t(c))&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},e(c)&&React.createElement("img",{src:c,alt:o||"AI Shortcut"}),t(c)&&React.createElement("span",{role:"img","aria-label":"AI Shortcut"},c)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-label"},o||"N/A"))}case"message":{const{message:n}=s??{},i=()=>{n?q(n):console.warn("No message provided for message shortcut.")};return React.createElement("button",{className:d,key:a,onClick:i},(e(c)||t(c))&&React.createElement(React.Fragment,null,React.createElement("div",{className:"mwai-icon"},e(c)&&React.createElement("img",{src:c,alt:o||"AI Shortcut"}),t(c)&&React.createElement("span",{role:"img","aria-label":"AI Shortcut"},c)),React.createElement("div",{style:{flex:"auto"}})),React.createElement("div",{className:"mwai-label"},o||"N/A"))}default:return console.warn(`This shortcut type is not supported: ${r}.`),null}})))}),[S,m,i,q]);ss((()=>{A&&A.length>0&&A.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)}}))}),[A]);const Ie=as((()=>A&&0!==A.length?React.createElement("div",{className:"mwai-blocks"},A.map(((e,t)=>{const{type:n,data:a}=e,{html:i}=a??{};return"content"===n?React.createElement("div",{key:t,dangerouslySetInnerHTML:{__html:i}}):(console.warn(`This block type is not supported: ${n}.`),null)}))):null),[A]);return React.createElement(t.bE,{dir:"auto",id:`mwai-chatbot-${h||g}`,className:Re,style:ye,if:!0,disableTransition:!y},ne&&React.createElement("style",null,ne),y&&we&&"none"!==we&&React.createElement("style",null,`\n @media (max-width: 760px) {\n .mwai-chat.mwai-window.mwai-animation-${we} .mwai-header {\n display: none !important;\n }\n /* Also hide during opening state */\n .mwai-chat.mwai-window.mwai-animation-${we}.mwai-opening .mwai-header {\n display: none !important;\n }\n }\n `),"osx"===$&&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"===z&&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(ar,null),React.createElement("div",{className:"mwai-window-box"},c&&y&&U&&React.createElement("div",{className:"mwai-mobile-header"},React.createElement("div",{className:"mwai-mobile-header-title"},Y||V||"AI Engine"),React.createElement("button",{className:"mwai-mobile-header-close",onClick:()=>{!B&&U&&(b&&"none"!==b?(te(!0),setTimeout((()=>{ee(!1),setTimeout((()=>{te(!1)}),150)}),180)):ee(!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"})))),!(c&&y&&U)&&React.createElement(er,{onDragStart:Ee}),React.createElement(ts,{conversationRef:D,onScroll:()=>{if(D.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=D.current;l(t-e<=n+1)}},jsxShortcuts:Te,jsxBlocks:Ie,inputClassNames:ue,handleDrop:le,handleDrag:oe,needsFooter:ie,needTools:ae,uploadIconPosition:H})))},ds=t=>React.createElement(e.G,t,React.createElement(us,t));var ms=__webpack_require__(213);const{useContext:ps,createContext:gs,useState:hs,useMemo:Es,useEffect:fs,useCallback:ys,useRef:_s}=wp.element,ws=gs(),vs=({children:e,...t})=>{const{system:n,theme:a}=t,[r,s]=hs([]),[o,l]=hs(null),[c,u]=hs(null),[d,m]=hs(!1),[p,g]=hs(0),[h,E]=hs(0),[f,y]=hs(!1),_=_s(!1),w=Es((()=>(null==a?void 0:a.settings)||{}),[a]),v=n.botId,R=n.customId,[T,I]=hs(n.restNonce||ms.A.getToken()),b=_s(n.restNonce||ms.A.getToken());fs((()=>ms.A.subscribe((e=>{I(e),b.current=e}))),[]);const S=n.pluginUrl,A=n.restUrl,C=n.debugMode,N=Es((()=>Object.keys(w).reduce(((e,t)=>(e[`--mwai-${t}`]=w[t],e)),{})),[w]),k=Es((()=>r.some((e=>0===e.messages.length))),[r]),O=ys((()=>{const e=MwaiAPI.getChatbot(v),t=null==e?void 0:e.localStorageKey;if(t)try{const e=localStorage.getItem(t);if(e)return JSON.parse(e).chatId}catch(e){console.error("[DISCUSSIONS] Error reading chatbot storage:",e)}return null}),[v]),x=ys((async(e=!1,t=p,a=!1)=>{if(_.current)return;let r;_.current=!0;try{e||(r=Date.now(),a?y(!0):m(!0));const c=(null==n?void 0:n.paging)||0,u=c>0?c:void 0,d={botId:v&&""!==v?v:R,...u&&{limit:u,offset:c>0?t*c:0}},p=e=>{I(e),b.current=e,ms.A.setToken(e)},g=await(0,i.ti)(`${A}/mwai-ui/v1/discussions/list`,d,b.current,!1,void 0,p),h=await(0,i.Pn)(g,null,C?"DISCUSSIONS":null,p,C);if(!h.success)throw new Error(`Could not retrieve the discussions: ${h.message}`);const f=h.chats.map((e=>{const t=JSON.parse(e.messages),n=JSON.parse(e.extra);return{...e,messages:t,extra:n,metadata_display:e.metadata_display}}));void 0!==h.total&&E(h.total),s((e=>{if(((null==n?void 0:n.paging)||0)>0)return f;{const t=new Map;e.forEach((e=>{t.set(e.chatId,e)})),f.forEach((e=>{t.set(e.chatId,e)}));const n=Array.from(t.values());if(o){const e=n.find((e=>e.chatId===o.chatId));e&&e!==o&&l(e)}return n}}))}catch(e){console.error(e)}finally{if(_.current=!1,!e&&r){const e=Date.now()-r,t=Math.max(0,200-e);setTimeout((()=>{a?y(!1):m(!1)}),t)}}}),[o,p,null==n?void 0:n.paging]),M=(null==n?void 0:n.refreshInterval)||5e3;fs((()=>{const e=O();if(e&&!c&&u(e),x(),M>0){const e=setInterval((()=>{x(!0)}),M);return()=>clearInterval(e)}}),[M,p]),fs((()=>{if(c&&!o){const t=r.find((e=>e.chatId===c));if(t){l(t);try{var e;const n=P(v),a=(null===(e=t.extra)||void 0===e?void 0:e.previousResponseId)||null;n.setContext({chatId:t.chatId,messages:t.messages,previousResponseId:a})}catch(e){console.debug("Chatbot not ready for auto-selected discussion",e)}}}else if(o){const e=r.find((e=>e.chatId===o.chatId));e&&e!==o&&l(e)}}),[r,c,v]);const P=e=>{const t=MwaiAPI.getChatbot(e);if(!t)throw new Error("Chatbot not found.",{botId:e,chatbots:MwaiAPI.chatbots});return t},L={onDiscussionClick:async e=>{var t;const n=r.find((t=>t.chatId===e));if(!n)return void console.error("Discussion not found.",{chatId:e,discussions:r});const a=P(v),i=(null===(t=n.extra)||void 0===t?void 0:t.previousResponseId)||null;a.setConversation({chatId:e,messages:n.messages,previousResponseId:i}),l(n),u(e)},onNewChatClick:async()=>{const e=P(v),t=(0,i.vx)();e.clear({chatId:t}),l(null),u(t)},onEditDiscussion:async e=>{const t=prompt("Enter a new title for the discussion:",e.title||"");if(null===t)return;const n=t.trim();if(""!==n)try{m(!0);const t={chatId:e.chatId,title:n},a=e=>{I(e),b.current=e,ms.A.setToken(e)},r=await(0,i.ti)(`${A}/mwai-ui/v1/discussions/edit`,t,b.current,!1,void 0,a),o=await(0,i.Pn)(r,null,C?"DISCUSSIONS":null,a,C);if(!o.success)throw new Error(`Could not update the discussion: ${o.message}`);s((t=>t.map((t=>t.chatId===e.chatId?{...t,title:n}:t))))}catch(e){console.error(e),alert("An error occurred while updating the discussion.")}finally{m(!1)}else alert("Title cannot be empty.")},onDeleteDiscussion:async e=>{if(confirm("Are you sure you want to delete this discussion?"))try{m(!0);const t={chatIds:[e.chatId]},n=e=>{I(e),b.current=e,ms.A.setToken(e)},a=await(0,i.ti)(`${A}/mwai-ui/v1/discussions/delete`,t,b.current,!1,void 0,n),c=await(0,i.Pn)(a,null,C?"DISCUSSIONS":null,n,C);if(!c.success)throw new Error(`Could not delete the discussion: ${c.message}`);if(s((t=>t.filter((t=>t.chatId!==e.chatId)))),(null==o?void 0:o.chatId)===e.chatId&&(l(null),u(null)),1===r.length&&p>0){const e=p-1;g(e),x(!1,e,!0)}else x(!1,p,!0)}catch(e){console.error(e),alert("An error occurred while deleting the discussion.")}finally{m(!1)}},refresh:x,setCurrentPage:g},D={botId:v,pluginUrl:S,busy:d,setBusy:m,cssVariables:N,discussions:r,discussion:o,theme:a,hasEmptyDiscussion:k,currentPage:p,totalCount:h,system:n,paginationBusy:f};return React.createElement(ws.Provider,{value:{state:D,actions:L}},e)},Rs=(0,mi.A)("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]),Ts=(0,mi.A)("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]),Is=(0,mi.A)("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]),bs=(0,mi.A)("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]),Ss=(0,mi.A)("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]),As=(0,mi.A)("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]),Cs=(0,mi.A)("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),Ns=(0,mi.A)("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),ks=(0,mi.A)("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),Os=ReactDOM,{useEffect:xs,useRef:Ms,useState:Ps}=wp.element,Ls=({isOpen:e,anchorEl:n,onClose:a,menuItems:i=[],className:r="",theme:s,context:o})=>{const l=(0,t.gR)(),c=Ms(null),[u,d]=Ps({top:0,left:0});if(xs((()=>{if(e&&n){const e=n.getBoundingClientRect(),t=120,a=80;let i=e.bottom+4,r=e.right-t;r<0&&(r=e.left),i+a>window.innerHeight&&(i=e.top-a-4),d({top:i,left:r})}}),[e,n]),xs((()=>{const t=e=>{c.current&&!c.current.contains(e.target)&&n&&!n.contains(e.target)&&a()},i=e=>{"Escape"===e.key&&a()};if(e)return document.addEventListener("mousedown",t),document.addEventListener("keydown",i),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("keydown",i)}}),[e,a,n]),!e)return null;const m=React.createElement("div",{ref:c,className:l("mwai-context-menu-portal",{[`mwai-${null==s?void 0:s.themeId}-theme`]:null==s?void 0:s.themeId}),style:{position:"fixed",top:`${u.top}px`,left:`${u.left}px`,zIndex:999999}},React.createElement("div",{className:l("mwai-context-menu"),style:{minWidth:"120px",overflow:"hidden"}},i.map(((e,t)=>"separator"===e.type?React.createElement("div",{key:e.id||`separator-${t}`,className:l("mwai-menu-separator"),style:{height:"1px",margin:"4px 0",background:"var(--mwai-backgroundPrimaryColor, rgba(0,0,0,0.1))"}}):"title"===e.type?React.createElement("div",{key:e.id||`title-${t}`,className:l("mwai-menu-title"),style:{padding:"8px 12px",fontSize:"11px",fontWeight:"bold",opacity:.7,textTransform:"uppercase"},dangerouslySetInnerHTML:e.html?{__html:e.html}:void 0},!e.html&&e.label):e.html?React.createElement("div",{key:e.id,className:l(e.className||"mwai-menu-item"),onClick:()=>{e.onClick&&(e.onClick(o),a())},style:e.style,dangerouslySetInnerHTML:{__html:e.html}}):React.createElement("div",{key:e.id,className:l(e.className||"mwai-menu-item"),onClick:()=>{e.onClick&&(e.onClick(o),a())},style:e.style},e.icon&&(()=>{const t=e.icon;return React.createElement(t,{size:14})})(),React.createElement("span",null,e.label))))));return(0,Os.createPortal)(m,document.body)};var Ds=__webpack_require__(137);const{useMemo:Us,useEffect:Fs,useState:Bs,useCallback:Gs,useRef:Hs}=wp.element,$s=e=>"undefined"!=typeof wp&&wp.i18n&&wp.i18n.__?wp.i18n.__(e,"ai-engine"):e,zs={NEW_CHAT:$s("New Chat"),NO_MESSAGES_YET:$s("No messages yet"),RENAME:$s("Rename"),DELETE:$s("Delete")},Ws=({discussion:e,onClick:n=(()=>{}),selected:a=!1,onEdit:i=(()=>{}),onDelete:r=(()=>{}),theme:s,system:o})=>{var l,c,u,d;const m=(0,t.gR)(),[p,g]=Bs(!1),h=Hs(null),E=e.messages,f=E[E.length-1],y=Us((()=>e.title?e.title:((null==f?void 0:f.content.length)>64?f.content.substring(0,64)+"...":f.content)||zs.NO_MESSAGES_YET),[e,f]),_=m("mwai-discussion",{"mwai-active":a}),w=Gs((e=>{e.stopPropagation(),g(!p)}),[p]),v=Gs((()=>{g(!1),i(e)}),[e,i]),R=Gs((()=>{g(!1),r(e)}),[e,r]),T=(()=>{const t=[{id:"rename",icon:Rs,label:zs.RENAME,onClick:v,className:"mwai-menu-item"},{id:"delete",icon:Ts,label:zs.DELETE,onClick:R,className:"mwai-menu-item mwai-danger"}];return(0,Ds.W5)("mwai_discussion_menu_items",t,e)})();return React.createElement(React.Fragment,null,React.createElement("li",{className:_,onClick:n},React.createElement("div",{className:m("mwai-discussion-content")},React.createElement("span",{className:m("mwai-discussion-title")},y),(null==o||null===(l=o.metadata)||void 0===l?void 0:l.enabled)&&React.createElement("div",{className:m("mwai-discussion-info")},o.metadata.startDate&&React.createElement("span",{className:m("mwai-info-item")},React.createElement(Is,{size:12}),React.createElement("span",null,(null===(c=e.metadata_display)||void 0===c?void 0:c.start_date)||e.created)),o.metadata.lastUpdate&&React.createElement("span",{className:m("mwai-info-item")},React.createElement(bs,{size:12}),React.createElement("span",null,(null===(u=e.metadata_display)||void 0===u?void 0:u.last_update)||e.updated)),o.metadata.messageCount&&React.createElement("span",{className:m("mwai-info-item")},React.createElement(Ss,{size:12}),React.createElement("span",null,(null===(d=e.metadata_display)||void 0===d?void 0:d.message_count)||E.length)))),React.createElement("div",{className:m("mwai-discussion-actions")},React.createElement("div",{ref:h,className:m("mwai-menu-icon"),onClick:w},React.createElement(As,{size:18})))),React.createElement(Ls,{isOpen:p,anchorEl:h.current,onClose:()=>g(!1),menuItems:T,theme:s,context:e}))},Ks=e=>{const{theme:n,style:a,params:i}=e,r=(0,t.gR)(),s=Us((()=>"css"===(null==n?void 0:n.type)?(null==n?void 0:n.style)||null:null!=n&&n.customCSS?n.customCSS:null),[n]),{state:o,actions:l}=(()=>{const e=ps(ws);if(!e)throw new Error("useDiscussionsContext must be used within a DiscussionsContextProvider");return e})(),{botId:c,cssVariables:u,discussions:d,discussion:m,busy:p,hasEmptyDiscussion:g,currentPage:h,totalCount:E,system:f,paginationBusy:y}=o,{onDiscussionClick:_,onNewChatClick:w,onEditDiscussion:v,onDeleteDiscussion:R,refresh:T,setCurrentPage:I}=l,{textNewChat:b}=i;Fs((()=>{}));const S=r("mwai-discussions",{[`mwai-${null==n?void 0:n.themeId}-theme`]:!0});return React.createElement(React.Fragment,null,React.createElement("div",{id:`mwai-discussions-${c}`,className:S,style:{...u,...a}},s&&React.createElement("style",null,s),React.createElement("div",{className:r("mwai-header")},React.createElement("button",{onClick:()=>w(),disabled:p||g},React.createElement("span",null,b??zs.NEW_CHAT)),-1===(null==f?void 0:f.refreshInterval)&&React.createElement("button",{className:r("mwai-refresh-btn"),onClick:()=>T(),disabled:p},React.createElement(Cs,{size:16}))),React.createElement("div",{className:r("mwai-content"),style:{position:"relative"}},y&&React.createElement("div",{className:r("mwai-loading-overlay")},React.createElement(Ns,{size:24,className:r("mwai-spinner")})),React.createElement("ul",{style:{listStyle:"none",padding:0,margin:0}},d.map((e=>React.createElement(Ws,{key:e.id,discussion:e,selected:(null==m?void 0:m.id)===e.id,onClick:()=>_(e.chatId),onEdit:v,onDelete:R,theme:n,system:f}))))),(null==f?void 0:f.paging)>0&&E>f.paging&&React.createElement("div",{className:r("mwai-pagination")},React.createElement("button",{onClick:()=>{const e=h-1;I(e),T(!1,e,!0)},disabled:0===h||p||y},React.createElement(ks,{size:16})),React.createElement("span",{className:r("mwai-page-indicator")},`Page ${h+1} of ${Math.ceil(E/f.paging)}`),React.createElement("button",{onClick:()=>{const e=h+1;I(e),T(!1,e,!0)},disabled:h>=Math.ceil(E/f.paging)-1||p||y},React.createElement(pi,{size:16})))))},js=e=>React.createElement(vs,e,React.createElement(Ks,e)),{render:Ys}=wp.element;function Vs(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}function qs(){function e(e,t){e.forEach((e=>{if(e.hasAttribute("data-mwai-initialized"))return;const n=e.getAttribute("data-params"),a=e.getAttribute("data-system"),i=e.getAttribute("data-theme");if(!n||!a||!i)return void console.warn("MWAI: Missing required attributes for initialization",e);const r=JSON.parse(Vs(n)),s=JSON.parse(Vs(a)),o=JSON.parse(Vs(i));e.setAttribute("data-mwai-initialized","true"),e.removeAttribute("data-params"),e.removeAttribute("data-system"),e.removeAttribute("data-theme"),Ys(t({system:s,params:r,theme:o}),e)}))}e(document.querySelectorAll(".mwai-chatbot-container"),ds),e(document.querySelectorAll(".mwai-discussions-container"),js)}document.addEventListener("DOMContentLoaded",qs),window.mwaiInitialize=qs})()})();