import { h, Env } from "@stencil/core";
import { sendFeedback, getConfig, submitForm } from "../../utils/utils";
import { adoptStyleSheet, loadScriptOnce } from "../../utils/styleSheetRegistry";
import { io } from "socket.io-client";
import showdown from "showdown";
import { getEndpoint, getBackendProtocol, generateUUID, updateButtonEvents, splitContentMultiple, getMetaInfo } from "../../utils/utils";
import { adaptCompleteToLegacy } from "../../utils/response-adapter";
import { setKnowledgeBoxElement } from "../../utils/global-store";
import { ai12zManager } from "../../utils/ai12z-manager";
import { Handlebars } from "../../utils/helpers";
import { renderSurvey } from "../../utils/surveyHelpers";
import { processChatData } from "../../utils/botHelpers/processCarouselData";
import { processTemplateData, renderTemplateData } from "../../utils/botHelpers/botHelpers";
import { trackFeedbackAnalytics } from "../../utils/analyticsService";
// import $ from "jquery"
// import { Model } from "survey-jquery"
export class Ai12zKnowledgeBox {
    constructor() {
        this.dataKey = Env.DATA_KEY || "";
        this.dataMode = Env.DATA_MODE || "prod"; // "local", "dev", or "prod"
        this.isLoading = true;
        this.questionId = null;
        this.isInitialized = false;
        this.items = [];
        this.error = null;
        this.buttons = [];
        this.currentStreamingText = "";
        this.isStreaming = false;
        this.finalResponse = false;
        this.scriptArray = [];
        this.showButton = true;
        this.welcomeReady = true;
        this.cdnPath = "https://cdn.ai12z.net/assets/kb";
        this.initializeScript = id => {
            setTimeout(() => {
                this.initializeScripts.emit({ id });
            }, 1000);
        };
        this.updateResponseContent = (htmlContent) => {
            var _a, _b;
            const newTodo = {
                id: this.domId,
                answer: htmlContent,
                title: (_a = this.kbSettings.title) !== null && _a !== void 0 ? _a : this.question,
                relevanceScore: this.searchResults["relevanceScore"],
                isRelevance: this.kbSettings.relevanceScore,
                insightId: this.searchResults["insightId"],
                thumbsUpDown: (_b = this.kbSettings.showMessageIcons) !== null && _b !== void 0 ? _b : true,
            };
            this.items = this.items.map(item => (item.id === this.domId ? newTodo : item));
            this.currentStreamingText = htmlContent; // set final answer
            this.finalResponse = true;
            // Defer until after Stencil flushes the re-render triggered by the
            // state mutations above, otherwise the buttons don't exist in the DOM yet.
            setTimeout(() => this.addEventListeners(`#${this.domId}`), 0);
        };
        this.alertResults = sender => {
            const results = JSON.stringify(sender);
            submitForm(this.dataKey, this.dataMode, sender.keyName, results)
                .then(res => {
                console.log("Form submission response:", res);
            })
                .catch(err => {
                console.error("Form submission error:", err);
            });
            const query = "Here is the data you requested:" + results;
            // sender.implementor.renderedElement.innerHTML = `<p><b>Thank you</b></p>`
            this.el.shadowRoot.querySelector(`#${this.domId}`).shadowRoot.querySelector(`#${this.surveyDomId}`).innerHTML = `<p><b>Thank you</b></p>`;
            this.question = query;
        };
        this.renderSurvey = async (chat) => {
            // console.log("Rendering survey for DOM ID:", this.surveyDomId)
            if (!this.surveyDomId) {
                console.warn("Survey DOM ID is empty");
                return;
            }
            try {
                await renderSurvey({
                    chat,
                    surveyDomId: this.surveyDomId,
                    shadowRoot: this.el.shadowRoot.querySelector(`#${this.domId}`).shadowRoot,
                    config: {
                        dataKey: this.dataKey,
                        dataMode: this.dataMode,
                        formSubmitRenderCallback: processedResults => {
                            this.alertResults(processedResults);
                        },
                        onSubmitError: errorMessage => {
                            var _a, _b;
                            if (errorMessage === "Form submission blocked by validation") {
                                const chatMsg = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector("ai12z-chat-message");
                                const container = (_b = chatMsg === null || chatMsg === void 0 ? void 0 : chatMsg.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector("#" + this.surveyDomId);
                                if (container) {
                                    container.innerHTML = "Submission blocked due to suspicious activity.";
                                }
                                else {
                                    console.error("Could not find survey container to display error");
                                }
                                return;
                            }
                        },
                    },
                });
            }
            catch (error) {
                console.error("Error rendering survey:", error);
            }
        };
        this.handleButtonClick = (label) => (_event) => {
            this.question = label;
        };
        this.handleMessage = (data, _aiMessageId) => {
            const converter = new showdown.Converter();
            // const aiMessageBubble = document.getElementById(aiMessageId);
            // const aiMessageBubble = this.element.shadowRoot?.querySelector(`#${aiMessageId}`)
            // const aiMessageBubble = this.element.querySelector('.ai12z-suggest-answer')
            // if (!aiMessageBubble) {
            //   console.error(`Message bubble with ID ${aiMessageId} not found.`)
            //   return
            // }
            // var bubbleText = aiMessageBubble.getAttribute("data-bubbleText") || ""
            // bubbleText = bubbleText + data
            // aiMessageBubble.setAttribute("data-bubbleText", bubbleText)
            // Assuming data is a string containing the message content
            // let html = converter.makeHtml(data)
            this.currentStreamingText += converter.makeHtml(data);
            // Append new content to the existing chat bubble
            // aiMessageBubble.innerHTML = html
        };
        this.removeClass = (className, elem, type) => {
            elem.classList.remove(className);
            if (type === "thumbs_up") {
                elem.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    d="M6.633 10.25c.806 0 1.533-.446 2.031-1.08a9.041 9.041 0 0 1 2.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 0 0 .322-1.672V2.75a.75.75 0 0 1 .75-.75 2.25 2.25 0 0 1 2.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282m0 0h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 0 1-2.649 7.521c-.388.482-.987.729-1.605.729H13.48c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23H5.904m10.598-9.75H14.25M5.904 18.5c.083.205.173.405.27.602.197.4-.078.898-.523.898h-.908c-.889 0-1.713-.518-1.972-1.368a12 12 0 0 1-.521-3.507c0-1.553.295-3.036.831-4.398C3.387 9.953 4.167 9.5 5 9.5h1.053c.472 0 .745.556.5.96a8.958 8.958 0 0 0-1.302 4.665c0 1.194.232 2.333.654 3.375Z"
                  />
                </svg>`;
            }
            else {
                elem.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          d="M7.498 15.25H4.372c-1.026 0-1.945-.694-2.054-1.715a12.137 12.137 0 0 1-.068-1.285c0-2.848.992-5.464 2.649-7.521C5.287 4.247 5.886 4 6.504 4h4.016a4.5 4.5 0 0 1 1.423.23l3.114 1.04a4.5 4.5 0 0 0 1.423.23h1.294M7.498 15.25c.618 0 .991.724.725 1.282A7.471 7.471 0 0 0 7.5 19.75 2.25 2.25 0 0 0 9.75 22a.75.75 0 0 0 .75-.75v-.633c0-.573.11-1.14.322-1.672.304-.76.93-1.33 1.653-1.715a9.04 9.04 0 0 0 2.86-2.4c.498-.634 1.226-1.08 2.032-1.08h.384m-10.253 1.5H9.7m8.075-9.75c.01.05.027.1.05.148.593 1.2.925 2.55.925 3.977 0 1.487-.36 2.89-.999 4.125m.023-8.25c-.076-.365.183-.75.575-.75h.908c.889 0 1.713.518 1.972 1.368.339 1.11.521 2.287.521 3.507 0 1.553-.295 3.036-.831 4.398-.306.774-1.086 1.227-1.918 1.227h-1.053c-.472 0-.745-.556-.5-.96a8.95 8.95 0 0 0 .303-.54"
                        />
                      </svg>`;
            }
        };
        this.clearThumbsHistory = () => {
            const elemup = this.el.shadowRoot.querySelector(".chat-thumbs-up");
            const elemdown = this.el.shadowRoot.querySelector(".chat-thumbs-down");
            if (elemup) {
                elemup.classList.remove("not-allowed");
                elemup.removeAttribute("disabled");
            }
            if (elemdown) {
                elemdown.classList.remove("not-allowed");
                elemdown.removeAttribute("disabled");
            }
            if (elemup && elemup.classList.contains("ai12z-suggest-thumbs-up")) {
                this.removeClass("ai12z-suggest-thumbs-up", elemup, "thumbs_up");
            }
            if (elemdown && elemdown.classList.contains("ai12z-suggest-thumbs-down")) {
                this.removeClass("ai12z-suggest-thumbs-down", elemdown, "thumbs_down");
            }
        };
        this.thumbsUp = (id, payload) => {
            const thumbsUp = this.el.shadowRoot.querySelector(`#thumbsUp_${id}`);
            thumbsUp.classList.add("ai12z-suggest-thumbs-up");
            thumbsUp.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"  fill="currentColor" class="w-6 h-6">
        <path  d="M7.493 18.5c-.425 0-.82-.236-.975-.632A7.48 7.48 0 0 1 6 15.125c0-1.75.599-3.358 1.602-4.634.151-.192.373-.309.6-.397.473-.183.89-.514 1.212-.924a9.042 9.042 0 0 1 2.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 0 0 .322-1.672V2.75A.75.75 0 0 1 15 2a2.25 2.25 0 0 1 2.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 0 1-2.649 7.521c-.388.482-.987.729-1.605.729H14.23c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23h-.777ZM2.331 10.727a11.969 11.969 0 0 0-.831 4.398 12 12 0 0 0 .52 3.507C2.28 19.482 3.105 20 3.994 20H4.9c.445 0 .72-.498.523-.898a8.963 8.963 0 0 1-.924-3.977c0-1.708.476-3.305 1.302-4.666.245-.403-.028-.959-.5-.959H4.25c-.832 0-1.612.453-1.918 1.227Z" />
      </svg>
    `;
            this.disableFeedback(id);
            sendFeedback(this.dataKey, this.dataMode, id, { value: 1 });
            trackFeedbackAnalytics("up", id, payload, this.questionId);
        };
        this.thumbsDown = (id, payload) => {
            const thumbsDown = this.el.shadowRoot.querySelector(`#thumbsDown_${id}`);
            thumbsDown.classList.add("ai12z-suggest-thumbs-down");
            thumbsDown.innerHTML = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6">
      <path d="M15.73 5.5h1.035A7.465 7.465 0 0 1 18 9.625a7.465 7.465 0 0 1-1.235 4.125h-.148c-.806 0-1.534.446-2.031 1.08a9.04 9.04 0 0 1-2.861 2.4c-.723.384-1.35.956-1.653 1.715a4.499 4.499 0 0 0-.322 1.672v.633A.75.75 0 0 1 9 22a2.25 2.25 0 0 1-2.25-2.25c0-1.152.26-2.243.723-3.218.266-.558-.107-1.282-.725-1.282H3.622c-1.026 0-1.945-.694-2.054-1.715A12.137 12.137 0 0 1 1.5 12.25c0-2.848.992-5.464 2.649-7.521C4.537 4.247 5.136 4 5.754 4H9.77a4.5 4.5 0 0 1 1.423.23l3.114 1.04a4.5 4.5 0 0 0 1.423.23ZM21.669 14.023c.536-1.362.831-2.845.831-4.398 0-1.22-.182-2.398-.52-3.507-.26-.85-1.084-1.368-1.973-1.368H19.1c-.445 0-.72.498-.523.898.591 1.2.924 2.55.924 3.977a8.958 8.958 0 0 1-1.302 4.666c-.245.403.028.959.5.959h1.053c.832 0 1.612-.453 1.918-1.227Z" />
    </svg>
  `;
            this.disableFeedback(id);
            sendFeedback(this.dataKey, this.dataMode, id, { value: -1 });
            trackFeedbackAnalytics("down", id, payload, this.questionId);
        };
        this.disableFeedback = (id) => {
            const thumbsUp = this.el.shadowRoot.querySelector(`#thumbsUp_${id}`);
            const thumbsDown = this.el.shadowRoot.querySelector(`#thumbsDown_${id}`);
            thumbsUp.classList.add("not-allowed");
            thumbsUp.setAttribute("disabled", "true");
            thumbsDown.classList.add("not-allowed");
            thumbsDown.setAttribute("disabled", "true");
        };
    }
    // private surveyCDNPath: string = "https://cdn.ai12z.net/pkg/surveyjs"
    get mainObject() {
        if (!window["ai12z"]) {
            window["ai12z"] = {};
        }
        return window["ai12z"];
    }
    async sendMessage(message, _displayText) {
        this.question = message;
    }
    async sendJSON(jsonData, _displayText) {
        this.question = JSON.stringify(jsonData);
    }
    componentDidLoad() {
        setKnowledgeBoxElement(this.el);
        // this.loadScriptsSequentially()
        ai12zManager.register("ai12z-knowledge-box", this);
        if (typeof window !== "undefined" && !window.Handlebars) {
            ;
            window.Handlebars = Handlebars;
        }
        setTimeout(() => {
            this.getResults("add");
            ai12zManager.setActive("ai12z-knowledge-box");
            this.isInitialized = true; // Enable watch handler after initial load
        }, 1000);
    }
    getConfig() {
        const payload = {
            apiKey: this.dataKey,
            configId: this.configId,
            configType: "kb",
        };
        getConfig(payload, this.dataMode)
            .then(async (data) => {
            var _a, _b, _c, _d, _e;
            if (data) {
                this.kbSettings = data;
                switch ((_a = this.kbSettings) === null || _a === void 0 ? void 0 : _a.questionType) {
                    case "static":
                        this.question = (_b = this.kbSettings) === null || _b === void 0 ? void 0 : _b.question;
                        break;
                    case "query":
                        const urlParams = new URLSearchParams(window.location.search);
                        // Extract individual query parameters
                        this.question = urlParams.get("q");
                        // console.log("Query string question:", this.question)
                        break;
                    case "staticHtml":
                        this.welcomeReady = false;
                        const tempHtml = updateButtonEvents((_c = this.kbSettings.welcome) === null || _c === void 0 ? void 0 : _c.message).body;
                        this.buttons = updateButtonEvents(tempHtml).buttons;
                        this.addEventListeners(`.ai12z-kb-wrapper`);
                        const welcomeLoads = [];
                        if ((_d = this.kbSettings.welcome) === null || _d === void 0 ? void 0 : _d.scripts) {
                            welcomeLoads.push(loadScriptOnce(this.kbSettings.welcome.scripts, this.el.shadowRoot));
                        }
                        if ((_e = this.kbSettings.welcome) === null || _e === void 0 ? void 0 : _e.styles) {
                            welcomeLoads.push(adoptStyleSheet(this.kbSettings.welcome.styles, this.el.shadowRoot));
                        }
                        if (welcomeLoads.length > 0) {
                            await Promise.all(welcomeLoads);
                        }
                        this.welcomeReady = true;
                        break;
                }
                if (this.kbSettings.theme) {
                    let themeLink = "";
                    if (this.kbSettings.theme !== "custom") {
                        themeLink = `${this.cdnPath}/v2/themes/theme-${this.kbSettings.theme}.css`;
                    }
                    else {
                        themeLink = this.kbSettings.customTheme;
                    }
                    const linkEl = document.createElement("link");
                    linkEl.setAttribute("rel", "stylesheet");
                    linkEl.setAttribute("href", themeLink);
                    document.head.appendChild(linkEl);
                }
                if (this.kbSettings.customCSS) {
                    adoptStyleSheet(this.kbSettings.customCSS, this.el.shadowRoot);
                }
                if (this.kbSettings.customJS) {
                    loadScriptOnce(this.kbSettings.customJS, this.el.shadowRoot);
                }
            }
        })
            .catch(error => {
            console.error("Error fetching config:", error);
            this.error = error;
            this.errored.emit(error);
        });
    }
    getResults(type) {
        var _a, _b;
        // console.log("Getting results for question:", this.question)
        try {
            if (this.question) {
                this.searchResults = null;
                this.error = null;
                const newTodo = {
                    id: "aimessageId-" + generateUUID(),
                    answer: " ",
                    title: "",
                    relevanceScore: "",
                    isRelevance: this.kbSettings.relevanceScore,
                    insightId: "",
                    thumbsUpDown: (_a = this.kbSettings.showMessageIcons) !== null && _a !== void 0 ? _a : true,
                };
                if (type === "add" || (this.items && this.items.length === 0)) {
                    this.socket.off("response");
                    this.socket.off("end_response");
                    this.items = [newTodo];
                }
                else {
                    this.socket.off("response");
                    this.socket.off("end_response");
                    const updatedId = this.items[0].id;
                    this.items = [...this.items, newTodo];
                    this.items = this.items.filter(item => item.id !== updatedId);
                    if ((_b = this.el.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector(`#${updatedId}`)) {
                        this.el.shadowRoot.querySelector(`#${updatedId}`).innerHTML = "";
                        this.el.shadowRoot.querySelector(`#${updatedId}`).setAttribute("data-bubbleText", "");
                    }
                }
                this.domId = this.items && this.items.length > 0 ? this.items[0].id : null;
            }
        }
        catch (error) {
            console.error(error);
            this.error = error;
            this.errored.emit(error);
        }
    }
    watchPropHandler(newValue, oldValue) {
        if (!this.isInitialized) {
            return; // Skip first-time trigger
        }
        if (newValue === oldValue) {
            return; // Skip if no actual change
        }
        // console.log("Question changed, fetching new results:", newValue, "was:", oldValue)
        this.isLoading = true;
        this.finalResponse = false;
        this.currentStreamingText = "";
        this.getResults("update");
    }
    watchStateHandler(_newValue, _oldValue) {
        const protocol = getBackendProtocol(this.dataMode);
        const responseEvent = protocol === "v2" ? "chunk" : "response";
        const endEvent = protocol === "v2" ? "complete" : "end_response";
        this.invokeSocket();
        this.socket.on(responseEvent, event => {
            this.isStreaming = true;
            this.isLoading = false;
            const messageData = protocol === "v2" ? event.content : event.data;
            this.handleMessage(messageData, `${this.domId}`); // Use the unique ID to handle messages
        });
        this.socket.on(endEvent, async (rawData) => {
            const data = protocol === "v2" ? adaptCompleteToLegacy(rawData) : rawData;
            this.isStreaming = false;
            this.messageReceived.emit({ data, domId: this.domId });
            const converter = new showdown.Converter();
            let finalHtml = converter.makeHtml(data.answer);
            finalHtml = updateButtonEvents(finalHtml).body;
            this.buttons = updateButtonEvents(finalHtml).buttons;
            this.isLoading = false;
            this.searchResults = data;
            this.error = null;
            const controlMatches = finalHtml.match(/\[control[^\]]*\]/g) || [];
            if (finalHtml.indexOf("[control") > -1 && controlMatches.length > 0) {
                this.showButton = false;
                await this.handleControlTypes(finalHtml, data);
            }
            else {
                this.showButton = true;
                this.updateResponseContent(finalHtml);
            }
        });
    }
    // invokeSurvey = chat => {
    //   const formModel = chat.controlData.form_model
    //   const survey = new window["Survey"].Model(formModel)
    //   const domELe = this.element.shadowRoot.querySelector(`#${this.domId}`).shadowRoot.querySelector(`#${this.surveyDomId}`)
    //   if (domELe) {
    //     survey.render(domELe)
    //     // window["jQuery"](domELe).Survey({ model: survey })
    //   } else {
    //     console.error("Survey Element not found")
    //   }
    //   survey.showCompletedPage = false
    //   survey.onComplete.add(this.alertResults)
    // }
    addEventListeners(msgId) {
        const container = this.el.shadowRoot.querySelector(msgId);
        if (container) {
            this.buttons.forEach(button => {
                const tmpContainer = container.shadowRoot ? container.shadowRoot : container;
                const buttonElement = tmpContainer.querySelector(`#${button.id}`);
                if (buttonElement) {
                    buttonElement.addEventListener("click", this.handleButtonClick(button.label));
                }
            });
        }
    }
    componentWillLoad() {
        adoptStyleSheet(`https://cdn.ai12z.net/assets/bot/v2/tailwind.min.css`, this.el.shadowRoot);
        this.socketConnection();
        this.getConfig();
        const w = window;
        if (!w.ai12z)
            w.ai12z = {};
        if (!w.ai12zChat)
            w.ai12zChat = w.ai12z;
    }
    disconnectedCallback() {
        if (this.socket) {
            this.socket.disconnect();
            this.socket.off("response");
            this.socket.off("end_response");
            this.socket.off("chunk");
            this.socket.off("complete");
        }
    }
    async socketConnection() {
        const protocol = getBackendProtocol(this.dataMode);
        let a12z_EndPoint = getEndpoint(this.dataMode);
        this.socket = io(a12z_EndPoint, {
            transports: protocol === "v2" ? ["websocket", "polling"] : ["websocket"],
        });
        await new Promise((resolve, reject) => {
            let settled = false;
            const timeoutId = setTimeout(() => {
                if (!settled) {
                    settled = true;
                    const errorMsg = "Unable to connect to server. Please try again later.";
                    console.error("Socket connection timed out");
                    reject(new Error(errorMsg));
                }
            }, 30000);
            this.socket.on("connect", () => {
                if (protocol === "v2") {
                    this.socket.emit("authenticate", { api_key: this.dataKey });
                    this.socket.once("authenticated", () => {
                        if (!settled) {
                            settled = true;
                            clearTimeout(timeoutId);
                        }
                        resolve();
                    });
                    this.socket.once("error", errorData => {
                        if (errorData.code === "AUTH_FAILED" || errorData.code === "AUTH_REQUIRED" || errorData.code === "AUTH_ERROR") {
                            if (!settled) {
                                settled = true;
                                clearTimeout(timeoutId);
                            }
                            reject(new Error(errorData.message));
                        }
                    });
                }
                else {
                    if (!settled) {
                        settled = true;
                        clearTimeout(timeoutId);
                    }
                    resolve();
                }
            });
        }).catch(err => {
            console.error("Socket connection failed:", err.message);
            this.isLoading = false;
            this.error = err.message;
        });
        this.socket.on("disconnect", () => {
            console.log("Disconnected from Socket.IO server");
            // Handle disconnection if needed
        });
    }
    invokeSocket() {
        var _a;
        const protocol = getBackendProtocol(this.dataMode);
        let data;
        let eventName;
        if (protocol === "v2") {
            eventName = "query";
            data = {
                query: this.question,
                conversation_id: this.questionId || "",
            };
        }
        else {
            eventName = "evaluate_query";
            data = {
                apiKey: this.dataKey,
                query: this.question,
                conversationId: (_a = this.questionId) !== null && _a !== void 0 ? _a : "",
                event: "evaluate_query",
                meta: getMetaInfo(),
            };
        }
        this.socket.emit(eventName, data);
        this.messageSent.emit({ data });
    }
    async handleControlTypes(finalHtml, data) {
        // Handle multiple controls
        const controlOutput = splitContentMultiple(finalHtml);
        if (!controlOutput || controlOutput.parts.length === 0) {
            console.warn("No parts found in splitContentMultiple");
            return;
        }
        let accumulatedHtml = "";
        const controlsToProcess = [];
        // First pass: Build HTML with placeholders
        for (let index = 0; index < controlOutput.parts.length; index++) {
            const output = controlOutput.parts[index];
            if (output.type === "text" && output.content.trim().length > 0) {
                accumulatedHtml += output.content;
            }
            if (output.type === "control" && output.controlType) {
                switch (output.controlType) {
                    case "form":
                        this.surveyDomId = "surveyElement-" + generateUUID();
                        accumulatedHtml += `<div id="${this.surveyDomId}" style="width: 100%" class="survey-container"></div>`;
                        controlsToProcess.push({ type: "form", data, output });
                        break;
                    case "carousel":
                    case "list":
                    case "template":
                        // Create placeholder for carousel/template control
                        const controlDomId = "controlElement-" + generateUUID();
                        accumulatedHtml += `<div id="${controlDomId}" class="control-container"></div>`;
                        controlsToProcess.push({ type: "template", data, output, controlDomId });
                        break;
                    default:
                        console.warn(`Unknown control type: ${output.controlType}`);
                        continue; // Skip unknown control types
                }
            }
        }
        // Update the response with all accumulated content (renders placeholders)
        this.updateResponseContent(accumulatedHtml);
        // Second pass: Wait for DOM to update, then render controls
        await new Promise(resolve => setTimeout(resolve, 100));
        // Process each control
        for (const control of controlsToProcess) {
            if (control.type === "form") {
                await this.handleFormControl(control.data, control.output);
            }
            else if (control.type === "template") {
                await this.handleTemplateControl(control.data, control.output, control.controlDomId);
            }
            // Small delay between controls
            await new Promise(resolve => setTimeout(resolve, 200));
        }
    }
    async handleFormControl(data, output) {
        var _a;
        // 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] : null;
        }
        // Render the survey
        setTimeout(() => {
            this.renderSurvey(data);
        }, 100);
    }
    async handleTemplateControl(data, output, controlDomId) {
        var _a, _b, _c;
        const newCtrlMessage = {
            id: this.domId, // Use controlDomId as the message ID
            controlDomId,
        };
        // 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 = controlDomId;
            data.controlType = output.controlType;
        }
        const controlData = data.controlData
            ? Object.assign(Object.assign({}, data), { messageId: controlDomId }) : 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 = this.kbSettings.customStyle || "";
            controlData.controlData.data.source.customJs = this.kbSettings.customJS || "";
        }
        // Process the control immediately - DOM should exist now
        if (output.controlType === "template") {
            processTemplateData(newCtrlMessage, data, this.el.shadowRoot, (_chatData) => null, chatData => renderTemplateData(chatData, this.el.shadowRoot.querySelector(`#${this.domId}`), this.scriptArray, this.mainObject, this.initializeScript, "kb"), _chatData => {
                // Control is already rendered in its placeholder
            }, Handlebars, "kb");
        }
        else {
            processChatData(newCtrlMessage, data, this.el, (_chatData) => null, _chatData => {
                // Control is already rendered in its placeholder
                // No need to update full response content here
            }, this.kbSettings.customJS, this.kbSettings.customStyle, false, "kb");
        }
    }
    render() {
        var _a, _b;
        return (h("div", { key: 'f26a34215a56acd7d3f393a4f0d23727c74ba40a', class: "ai12z-kb-wrapper" }, this.error ? h("p", { class: "ai12z-suggest-error-msg" }, "Error please try again!") : null, this.items.map(item => {
            var _a, _b, _c, _d;
            return (h("div", { class: "prose max-w-none ai12z-suggest-container" }, h("div", null, h("div", null, h("div", { class: "flex flex-row gap-1" }, h("div", { class: "flex items-center gap-2 mb-3", style: { width: "90%" } }, ((_a = this.kbSettings) === null || _a === void 0 ? void 0 : _a.showTitle) && (h("svg", { width: "28", height: "28", viewBox: "0 0 48 48", fill: "currentColor", xmlns: "http://www.w3.org/2000/svg", class: "diamond-icon" + (this.isLoading && !this.finalResponse ? " loading" : "") }, h("path", { d: "M24 2c-3 8-8 13-16 16 8 3 13 8 16 16 3-8 8-13 16-16-8-3-13-8-16-16z" }))), ((_b = this.kbSettings) === null || _b === void 0 ? void 0 : _b.showTitle) && (h("h5", { class: "text-lg font-semibold text-gray-800 m-0" }, !this.finalResponse ? "Generating..." : (_c = this.kbSettings.title) !== null && _c !== void 0 ? _c : "AI Overview"))), item.thumbsUpDown && !this.isLoading && (h("div", null, h("button", { id: `thumbsUp_${item.insightId}`, onClick: () => {
                    var _a;
                    return this.thumbsUp(item.insightId, {
                        dataKey: this.dataKey,
                        dataMode: this.dataMode,
                        conversationId: this.questionId,
                        projectId: (_a = this.kbSettings) === null || _a === void 0 ? void 0 : _a.pId,
                        questionText: this.question,
                    });
                }, class: "chat-thumbs-up", "aria-label": "Thumbs Up" }, h("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", "stroke-width": "1.5", stroke: "currentColor", class: "w-6 h-6" }, h("path", { "stroke-linecap": "round", "stroke-linejoin": "round", d: "M6.633 10.25c.806 0 1.533-.446 2.031-1.08a9.041 9.041 0 0 1 2.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 0 0 .322-1.672V2.75a.75.75 0 0 1 .75-.75 2.25 2.25 0 0 1 2.25 2.25c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282m0 0h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 0 1-2.649 7.521c-.388.482-.987.729-1.605.729H13.48c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 0 0-1.423-.23H5.904m10.598-9.75H14.25M5.904 18.5c.083.205.173.405.27.602.197.4-.078.898-.523.898h-.908c-.889 0-1.713-.518-1.972-1.368a12 12 0 0 1-.521-3.507c0-1.553.295-3.036.831-4.398C3.387 9.953 4.167 9.5 5 9.5h1.053c.472 0 .745.556.5.96a8.958 8.958 0 0 0-1.302 4.665c0 1.194.232 2.333.654 3.375Z" }))), h("button", { id: `thumbsDown_${item.insightId}`, onClick: () => {
                    var _a;
                    return this.thumbsDown(item.insightId, {
                        dataKey: this.dataKey,
                        dataMode: this.dataMode,
                        conversationId: this.questionId,
                        projectId: (_a = this.kbSettings) === null || _a === void 0 ? void 0 : _a.pId,
                        questionText: this.question,
                    });
                }, class: "chat-thumbs-down", "aria-label": "Thumbs Down" }, h("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", "stroke-width": "1.5", stroke: "currentColor", class: "w-6 h-6" }, h("path", { "stroke-linecap": "round", "stroke-linejoin": "round", d: "M7.498 15.25H4.372c-1.026 0-1.945-.694-2.054-1.715a12.137 12.137 0 0 1-.068-1.285c0-2.848.992-5.464 2.649-7.521C5.287 4.247 5.886 4 6.504 4h4.016a4.5 4.5 0 0 1 1.423.23l3.114 1.04a4.5 4.5 0 0 0 1.423.23h1.294M7.498 15.25c.618 0 .991.724.725 1.282A7.471 7.471 0 0 0 7.5 19.75 2.25 2.25 0 0 0 9.75 22a.75.75 0 0 0 .75-.75v-.633c0-.573.11-1.14.322-1.672.304-.76.93-1.33 1.653-1.715a9.04 9.04 0 0 0 2.86-2.4c.498-.634 1.226-1.08 2.032-1.08h.384m-10.253 1.5H9.7m8.075-9.75c.01.05.027.1.05.148.593 1.2.925 2.55.925 3.977 0 1.487-.36 2.89-.999 4.125m.023-8.25c-.076-.365.183-.75.575-.75h.908c.889 0 1.713.518 1.972 1.368.339 1.11.521 2.287.521 3.507 0 1.553-.295 3.036-.831 4.398-.306.774-1.086 1.227-1.918 1.227h-1.053c-.472 0-.745-.556-.5-.96a8.95 8.95 0 0 0 .303-.54" }))))))), !this.isLoading && (h("div", null, ((_d = this.searchResults) === null || _d === void 0 ? void 0 : _d.controlType) !== "form" && (h("ai12z-chat-message", { id: item.id, text: this.currentStreamingText, kbSettings: this.kbSettings, "show-button": this.showButton, streaming: this.isStreaming && item.id === this.domId })), h("div", { class: { "ai12z-suggest-relevance": true, "ai12z-suggest-hide": !item["isRelevance"] } }, h("a", { href: "" }, item["relevanceScore"])), h("div", { class: "custom-privacy" }, h("slot", { name: "custom-privacy" })))), this.isLoading && (h("div", { class: "w-full rounded-md", id: "spinner" }, h("div", { class: "flex animate-pulse space-x-4" }, h("div", { class: "flex-1 space-y-3 py-1" }, h("div", { class: "h-4 rounded bg-gray-200" }), h("div", { class: "space-y-3" }, h("div", { class: "grid grid-cols-3 gap-4" }, h("div", { class: "col-span-2 h-4 rounded bg-gray-200" }), h("div", { class: "col-span-1 h-4 rounded bg-gray-200" })), h("div", { class: "h-4 rounded bg-gray-200" })))))))));
        }), ((_a = this.kbSettings) === null || _a === void 0 ? void 0 : _a.questionType) === "staticHtml" && this.items.length === 0 && this.welcomeReady && (h("div", { key: '340c562562715563715e5a103019dd19458c994f', class: "ai12z-suggest-answer", innerHTML: (_b = this.kbSettings.welcome) === null || _b === void 0 ? void 0 : _b.message }))));
    }
    static get is() { return "ai12z-knowledge-box"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["./ai12z-knowledge-box.css", "../../global/survey-core.min.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ai12z-knowledge-box.css", "../../global/survey-core.min.css"]
        };
    }
    static get assetsDirs() { return ["assets"]; }
    static get properties() {
        return {
            "dataKey": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "data-key",
                "defaultValue": "Env.DATA_KEY || \"\""
            },
            "dataMode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "data-mode",
                "defaultValue": "Env.DATA_MODE || \"prod\""
            },
            "configId": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "config-id"
            },
            "question": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "question"
            },
            "socket": {
                "type": "any",
                "mutable": true,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "socket"
            },
            "isLoading": {
                "type": "boolean",
                "mutable": true,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-loading",
                "defaultValue": "true"
            }
        };
    }
    static get states() {
        return {
            "questionId": {},
            "isInitialized": {},
            "kbSettings": {},
            "searchResults": {},
            "items": {},
            "error": {},
            "domId": {},
            "surveyDomId": {},
            "buttons": {},
            "currentStreamingText": {},
            "isStreaming": {},
            "finalResponse": {},
            "scriptArray": {},
            "showButton": {},
            "welcomeReady": {}
        };
    }
    static get events() {
        return [{
                "method": "messageReceived",
                "name": "messageReceived",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ data: any; domId: string }",
                    "resolved": "{ data: any; domId: string; }",
                    "references": {}
                }
            }, {
                "method": "messageSent",
                "name": "messageSent",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ data: any }",
                    "resolved": "{ data: any; }",
                    "references": {}
                }
            }, {
                "method": "errored",
                "name": "errored",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "initializeScripts",
                "name": "initializeScripts",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ id: string }",
                    "resolved": "{ id: string; }",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "sendMessage": {
                "complexType": {
                    "signature": "(message: string, _displayText?: string) => Promise<void>",
                    "parameters": [{
                            "name": "message",
                            "type": "string",
                            "docs": ""
                        }, {
                            "name": "_displayText",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "sendJSON": {
                "complexType": {
                    "signature": "(jsonData: Object, _displayText?: string) => Promise<void>",
                    "parameters": [{
                            "name": "jsonData",
                            "type": "Object",
                            "docs": ""
                        }, {
                            "name": "_displayText",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "Object": {
                            "location": "global",
                            "id": "global::Object"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "question",
                "methodName": "watchPropHandler"
            }, {
                "propName": "domId",
                "methodName": "watchStateHandler"
            }];
    }
}
