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