import { s as showdown } from './processCarouselData-DX152a4X.js';
import { u as updateAnchorTags, f as updateButtonEvents, h as splitContentMultiple, j as generateMessage, k as generateUUID } from './utils-DK_Yhmpx.js';

async function handleEndResponse(params) {
    var _a, _b;
    const { data, currentDomId, setMessages, setSurveyDomId, config, setButtons, inputType } = params;
    try {
        const converter = new showdown.Converter();
        let finalHtml = converter.makeHtml(data.answer);
        const linkClassName = inputType === "bot" ? "ai12z-link" : "ai12z-cta-link";
        // Update anchor tags and button events
        finalHtml = updateAnchorTags(finalHtml, ((_a = config.controlSettings) === null || _a === void 0 ? void 0 : _a.linkTarget) || '_blank', linkClassName, config.utmConfig || ((_b = config.controlSettings) === null || _b === void 0 ? void 0 : _b.utm), 'answer');
        const buttonResult = updateButtonEvents(finalHtml);
        finalHtml = buttonResult.body;
        setButtons(buttonResult.buttons);
        // Check for multiple controls
        const controlMatches = finalHtml.match(/\[control[^\]]*\]/g) || [];
        if (finalHtml.indexOf("[control") > -1) {
            await handleControlTypes(finalHtml, data, currentDomId, setMessages, controlMatches, config, setSurveyDomId, inputType);
        }
        else {
            // Handle regular content without controls
            await handleRegularContent(finalHtml, currentDomId, config, data);
        }
    }
    catch (error) {
        console.error("Error in handleEndResponse:", error);
        throw error;
    }
}
async function handleControlTypes(finalHtml, data, currentDomId, setMessages, controlMatches, config, setSurveyDomId, inputType) {
    if (controlMatches.length === 0) {
        await handleRegularContent(finalHtml, currentDomId, config, data);
    }
    else if (controlMatches.length > 0) {
        // ✅ Handle multiple controls
        await handleMultipleControls(finalHtml, data, currentDomId, setMessages, config, setSurveyDomId, inputType);
    }
}
async function handleFormControl(data, config, setSurveyDomId, inputType, setMessages, output, currentDomId, index) {
    var _a, _b, _c, _d;
    const newSurveyDomId = `surveyElement-${generateUUID()}`;
    if (setSurveyDomId) {
        setSurveyDomId(newSurveyDomId);
    }
    let newCtrlMessage;
    if (index !== 0) {
        if (inputType === "bot") {
            // Create new control message
            newCtrlMessage = generateMessage(config.conversationId);
            newCtrlMessage.surveyDomId = newSurveyDomId;
            setMessages(newCtrlMessage);
        }
        else if (inputType === "cta") {
            newCtrlMessage = config.getUpdatedChat("", data);
            newCtrlMessage.surveyDomId = newSurveyDomId;
            setMessages(newCtrlMessage);
        }
        newCtrlMessage.controlType = "form";
        newCtrlMessage.itemComponent = data;
        // Wait for DOM render
        await waitForElementRender(`#${newCtrlMessage.id}`, config.element);
    }
    data.controlType = "form";
    data.surveyDomId = newSurveyDomId;
    const formHtml = `<div id=${newSurveyDomId} style="width:${((_a = config.controlSettings) === null || _a === void 0 ? void 0 : _a.botVersion) === "v1" ? "330px" : "100%"}" class="survey-container"></div>`;
    (_b = config.updateConversations) === null || _b === void 0 ? void 0 : _b.call(config, formHtml, data);
    (_c = config.updateChatMessage) === null || _c === void 0 ? void 0 : _c.call(config, formHtml, data);
    // const formHtml = finalHtml.replace(
    //   RegExp(/\[[^>]*]/gm), 
    //   `<div id=${newSurveyDomId} style="width:${config.controlSettings?.botVersion === "v1" ? "330px" : "100%"}" class="survey-container"></div>`
    // )
    const element = config.element.shadowRoot.querySelector(`#${index === 0 ? currentDomId : newCtrlMessage.id}`);
    if (element) {
        element["style"].width = "100%";
        element.parentElement["style"].width = "100%";
        element.innerHTML = formHtml;
        // config.getUpdatedChat?.(formHtml, data)(null)
        // Filter data by agentDataId if available
        if (output.agentDataId && ((_d = data.controls) === null || _d === void 0 ? void 0 : _d.length) > 0) {
            const filteredItems = data.controls.filter(item => item.agent_data_id === output.agentDataId);
            data.controlData = filteredItems.length > 0 ? filteredItems[0] : null;
        }
    }
    // Render the survey
    setTimeout(() => {
        config.renderSurvey(data);
    }, 100);
}
async function handleMultipleControls(finalHtml, data, currentDomId, setMessages, config, setSurveyDomId, inputType) {
    var _a, _b;
    const controlOutput = splitContentMultiple(finalHtml);
    if (!controlOutput || controlOutput.parts.length === 0) {
        console.warn('No parts found in splitContentMultiple');
        return;
    }
    // Process each part sequentially
    for (let index = 0; index < controlOutput.parts.length; index++) {
        const output = controlOutput.parts[index];
        if (output.type === 'text' && output.content.trim().length > 0) {
            if (index === 0) {
                // Update first message
                (_a = config.updateConversations) === null || _a === void 0 ? void 0 : _a.call(config, output.content, data);
                (_b = config.updateChatMessage) === null || _b === void 0 ? void 0 : _b.call(config, output.content, data);
            }
            else {
                if (inputType === "bot") {
                    // Create new text message
                    const newMessage = generateMessage(config.conversationId);
                    newMessage.text = output.content;
                    newMessage.isLoading = false;
                    setMessages(newMessage);
                }
                else if (inputType === "cta") {
                    const newMessage = config.getUpdatedChat(output.content, data);
                    setMessages(newMessage);
                }
                // // Wait for DOM render then hide spinner
                // await waitForElementRender(`#${newMessage.id}`, config.element)
                // await config.hideSpinner(newMessage)
            }
        }
        if (output.type === 'control' && output.controlType) {
            switch (output.controlType) {
                case "form":
                    await handleFormControl(data, config, setSurveyDomId, inputType, setMessages, output, currentDomId, index);
                    break;
                case "carousel":
                case "list":
                case "template":
                    // Proceed to handle control below
                    await handleTemplateControl(data, config, output, setMessages, inputType);
                    break;
                default:
                    console.warn(`Unknown control type: ${output.controlType}`);
                    continue; // Skip unknown control types
            }
        }
        // Small delay between parts
        if (index < controlOutput.parts.length - 1) {
            await new Promise(resolve => setTimeout(resolve, 200));
        }
    }
}
async function handleTemplateControl(data, config, output, setMessages, inputType) {
    var _a, _b, _c;
    let newCtrlMessage;
    if (inputType === "bot") {
        // Create new control message
        newCtrlMessage = generateMessage(config.conversationId);
        newCtrlMessage.itemComponent = data;
        newCtrlMessage.controlType = output.controlType;
        // newCtrlMessage.controlType = "template"
        setMessages(newCtrlMessage);
    }
    else if (inputType === "cta") {
        newCtrlMessage = config.getUpdatedChat("", data);
        newCtrlMessage.itemComponent = data;
        newCtrlMessage.controlType = output.controlType;
        setMessages(newCtrlMessage);
    }
    // Wait for DOM render
    await waitForElementRender(`#${newCtrlMessage.id}`, config.element);
    // Filter data by agentDataId if available
    if (output.agentDataId && ((_a = data.controls) === null || _a === void 0 ? void 0 : _a.length) > 0) {
        const filteredItems = data.controls.filter(item => item.agent_data_id === output.agentDataId);
        data.controlData = filteredItems.length > 0 ? filteredItems[0].custom_data : null;
        data.messageId = newCtrlMessage.id;
        data.controlType = output.controlType;
    }
    const controlData = data.controlData ? Object.assign(Object.assign({}, data), { messageId: newCtrlMessage.id }) : data;
    // Set custom styles
    if ((_c = (_b = controlData.controlData) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.source) {
        controlData.controlData.data.source.customCss = controlData.controlData.styles || "";
        controlData.controlData.data.source.customJs = controlData.controlData.scripts || "";
    }
    requestAnimationFrame(async () => {
        setTimeout(async () => {
            // Process the control
            if (output.controlType === "template") {
                await config.processTemplateData(newCtrlMessage, controlData);
            }
            else {
                await config.processChatData(newCtrlMessage, controlData);
            }
            // Hide spinner after processing
            await config.hideSpinner(newCtrlMessage);
        }, 100);
    });
}
async function handleRegularContent(finalHtml, currentDomId, config, data) {
    var _a, _b;
    const element = config.element.shadowRoot.querySelector(`#${currentDomId}`);
    if (element) {
        element.innerHTML = finalHtml;
        config.checkHighlightcode(currentDomId);
        (_a = config.updateConversations) === null || _a === void 0 ? void 0 : _a.call(config, finalHtml, data !== null && data !== void 0 ? data : {});
        (_b = config.updateChatMessage) === null || _b === void 0 ? void 0 : _b.call(config, finalHtml, {});
        config.addEventListeners(`#${currentDomId}`);
    }
}
// Helper function to wait for element to render
function waitForElementRender(selector, element, timeoutMs = 10000) {
    return new Promise((resolve, reject) => {
        const startTime = Date.now();
        const checkElement = () => {
            var _a;
            const el = (_a = element.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector(selector);
            if (el) {
                resolve(el);
            }
            else if (Date.now() - startTime > timeoutMs) {
                reject(new Error(`AI12Z: waitForElementRender timed out after ${timeoutMs}ms waiting for "${selector}"`));
            }
            else {
                requestAnimationFrame(checkElement);
            }
        };
        checkElement();
    });
}

const DEFAULT_SHORTCUTS = [
    // General shortcuts
    {
        key: "?",
        modifiers: ["Shift", "Control"],
        description: "Show keyboard shortcuts (Windows/Linux)",
        category: "General",
    },
    {
        key: "?",
        modifiers: ["Meta", "Shift"],
        description: "Show keyboard shortcuts (Mac)",
        category: "General",
    },
    {
        key: "Escape",
        description: "Close dialog or modal",
        category: "General",
    },
    // Chat shortcuts
    {
        key: "Enter",
        description: "Send message",
        category: "Chat",
    },
    {
        key: "Enter",
        modifiers: ["Shift"],
        description: "New line in message",
        category: "Chat",
    },
    // {
    //   key: "K",
    //   modifiers: ["Meta"],
    //   description: "Open search (Mac)",
    //   category: "Chat",
    // },
    // {
    //   key: "K",
    //   modifiers: ["Control"],
    //   description: "Open search (Windows/Linux)",
    //   category: "Chat",
    // },
    {
        key: "H",
        modifiers: ["Meta"],
        description: "Show chat history (Mac)",
        category: "Chat",
    },
    {
        key: "H",
        modifiers: ["Control"],
        description: "Show chat history (Windows/Linux)",
        category: "Chat",
    },
    // Navigation shortcuts
    {
        key: "ArrowUp",
        description: "Navigate to previous message",
        category: "Navigation",
    },
    {
        key: "ArrowDown",
        description: "Navigate to next message",
        category: "Navigation",
    },
    {
        key: "/",
        description: "Focus search input",
        category: "Navigation",
    },
    // Accessibility shortcuts
    {
        key: "Tab",
        description: "Navigate between elements",
        category: "Accessibility",
    },
    {
        key: "Tab",
        modifiers: ["Shift"],
        description: "Navigate backward",
        category: "Accessibility",
    },
];

export { DEFAULT_SHORTCUTS as D, handleEndResponse as h, waitForElementRender as w };
