import { h, Env } from "@stencil/core";
import showdown from "showdown";
import { ensureMessageId, parseArgsWithJson5 } from "../../../utils/parseHelper/parseHelper";
// import { io } from "socket.io-client"
import { 
/**getComponentByControlType, splitContent, splitContentMultiple, */ getAudioContent, getMetaInfo, generateUUID, updateAnchorTags, updateButtonEvents, } from "../../../utils/utils";
// import mustache from "mustache"
// import Handlebars from "handlebars"
import { saveConversation } from "../../../utils/ctaHelpers";
import { Handlebars } from "../../../utils/helpers";
import { SocketService } from "../../../utils/socket-service";
import { renderSurvey } from "../../../utils/surveyHelpers";
import { handleEndResponse, waitForElementRender } from "../../../utils/endResponseHelper";
import { processChatData as processChatDataHelper } from "../../../utils/botHelpers/processCarouselData";
import { getQuestionText, trackFeedbackAnalytics } from "../../../utils/analyticsService";
import { loadStyle, loadScript } from "../../../utils/botHelpers/botHelpers";
export class MyChat {
    constructor() {
        // private cdnPath: string = "https://cdn.ai12z.net/assets/bot"
        this.surveyCDNPath = "https://cdn.ai12z.net/pkg/surveyjs";
        this.surveyScriptsLoaded = null;
        this.chats = [];
        this.chatExcludeTags = [];
        this.chatIncludeTags = [];
        this.componentType = "search";
        this.chatPosition = "below";
        this.copied = false;
        this.isPlayed = false;
        this.buttons = [];
        this.currentPage = 0;
        this.currentSlide = 0;
        this.scriptArray = [];
        this.isProse = true;
        this.isProcessingEndResponse = false;
        this.surveyDomId = "";
        this.focusedIndex = -1;
        this.chatItemRefs = [];
        this.styles = [
            `https://cdn.ai12z.net/assets/bot/v2/tailwind.min.css`,
            // `${this.cdnPath}/v1/survey.min.css`,
            // `https://unpkg.com/survey-core/defaultV2.min.css`,
            // `${this.cdnPath}/v1/survey-core.min.css`,
            `https://unpkg.com/@highlightjs/cdn-assets@11.11.1/styles/default.min.css`,
            `https://cdn.ai12z.net/pkg/surveyjs/survey-core@2.3.4/survey-core.min.css`,
        ];
        this.getUpdatedChat = (data, message) => {
            var _a, _b, _c, _d, _e;
            const newaiMessageId = `ai-message-${this.generateUUID()}`;
            const newthumbsId = this.generateUUID();
            let chatEle = {
                message: message,
                type: "ai",
                status: "success",
                insightId: data.insightId,
                id: newaiMessageId,
                thumbsId: newthumbsId,
                controlType: (_e = (_d = (_c = (_b = (_a = data.controlData) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.source) === null || _c === void 0 ? void 0 : _c.carousel) === null || _d === void 0 ? void 0 : _d.type) !== null && _e !== void 0 ? _e : "",
                // formModel: response?.formModel,
            };
            this.survey.emit({ results: chatEle, type: "carousel" });
            return chatEle;
        };
        this.updateChatMessage = (newMessage, _data) => {
            const idx = this.chats.findIndex(item => item.id === this.aiMessageId);
            if (idx !== -1) {
                this.chats[idx].message = newMessage;
                this.chats[idx].clipboard = newMessage;
                if (_data.controlType === "form") {
                    this.chats[idx].controlType = _data.controlType;
                    this.chats[idx].itemComponent = _data;
                    this.chats[idx].surveyDomId = _data.surveyDomId;
                }
                this.chats = [...this.chats]; // Trigger reactivity
            }
        };
        this.handlePrev = () => {
            this.currentSlide = (this.currentSlide - 1 + this.itemList.length) % this.itemList.length;
            this.processTemplateData(this.currentChatData, "", "pagination");
        };
        this.handleNext = () => {
            this.currentSlide = (this.currentSlide + 1) % this.itemList.length;
            this.processTemplateData(this.currentChatData, "", "pagination");
        };
        this.handleButtonClick = (label) => (_event) => {
            // console.log(`${label} clicked! ${event}`)
            // buttonEle.classList.add("active")
            this.survey.emit({ results: label, type: "button" });
        };
        this.handleMessage = (data, aiMessageId) => {
            const converter = new showdown.Converter();
            const aiMessageBubble = this.element.shadowRoot.querySelector(`#${aiMessageId}`);
            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);
            aiMessageBubble.setAttribute("aria-label", bubbleText);
            aiMessageBubble.setAttribute("role", "log");
            aiMessageBubble.setAttribute("aria-live", "polite");
            aiMessageBubble.setAttribute("aria-atomic", "false");
            // Assuming data is a string containing the message content
            let html = converter.makeHtml(bubbleText);
            const spinner = document.getElementById("spinner");
            if (spinner) {
                spinner.style.display = "none";
            }
            // Append new content to the existing chat bubble
            aiMessageBubble.innerHTML = html;
            this.chats[this.chats.length - 1].status = "success";
        };
        this.scrollToBottom = () => {
            this.scrollBottom = this.element.shadowRoot.querySelector(".scroll-bottom");
            this.scrollBottom.scrollIntoView({ behavior: "smooth", block: "end" });
        };
        this.disableFeedback = (id) => {
            const thumbsUp = this.element.shadowRoot.querySelector(`#thumbsUp_${id}`);
            const thumbsDown = this.element.shadowRoot.querySelector(`#thumbsDown_${id}`);
            thumbsUp.classList.add("not-allowed");
            thumbsUp.setAttribute("disabled", "true");
            thumbsDown.classList.add("not-allowed");
            thumbsDown.setAttribute("disabled", "true");
        };
        this.thumbsUp = (id, insightId, payload) => {
            const thumbsUp = this.element.shadowRoot.querySelector(`#thumbsUp_${id}`);
            thumbsUp.classList.add("thumbs-up");
            thumbsUp.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"  fill="currentColor">
        <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);
            this.feedback.emit({ insightId: insightId, feedback: { value: 1 } });
            trackFeedbackAnalytics("up", insightId || id, payload);
        };
        this.thumbsDown = (id, insightId, payload) => {
            const thumbsDown = this.element.shadowRoot.querySelector(`#thumbsDown_${id}`);
            thumbsDown.classList.add("thumbs-down");
            thumbsDown.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
        <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);
            this.feedback.emit({ insightId: insightId, feedback: { value: -1 } });
            trackFeedbackAnalytics("down", insightId || id, payload);
        };
    }
    handleChatKeyNav(e, idx) {
        var _a, _b;
        if (e.key === "ArrowDown") {
            e.preventDefault();
            e.stopPropagation();
            const nextIndex = Math.min(this.chats.length - 1, idx + 1);
            this.focusedIndex = nextIndex;
            (_a = this.chatItemRefs[nextIndex]) === null || _a === void 0 ? void 0 : _a.focus();
        }
        else if (e.key === "ArrowUp") {
            e.preventDefault();
            e.stopPropagation();
            const prevIndex = Math.max(0, idx - 1);
            this.focusedIndex = prevIndex;
            (_b = this.chatItemRefs[prevIndex]) === null || _b === void 0 ? void 0 : _b.focus();
        }
    }
    componentDidLoad() {
        const ai12zHeading = document.createElement("script");
        ai12zHeading.text = `
      var ai12zChat = window["ai12z"] = {}
    `;
        document.head.appendChild(ai12zHeading);
        this.element.shadowRoot.appendChild(ai12zHeading);
        setTimeout(() => {
            var _a, _b;
            // console.log("componentDidLoad chat.tsx", this.customstyle)
            // console.log("customstyle", this.customJS)
            if (this.customstyle) {
                const linkEl = document.createElement("link");
                linkEl.setAttribute("rel", "stylesheet");
                linkEl.setAttribute("href", this.customstyle);
                (_a = this.element.shadowRoot) === null || _a === void 0 ? void 0 : _a.appendChild(linkEl);
            }
            if (this.customJS) {
                const scriptEl = document.createElement("script");
                scriptEl.setAttribute("type", "text/javascript");
                scriptEl.setAttribute("src", this.customJS);
                (_b = this.element.shadowRoot) === null || _b === void 0 ? void 0 : _b.appendChild(scriptEl);
            }
        }, 500);
        // this.loadStyles()
        this.loadScriptsSequentially();
    }
    async loadScriptsSequentially() {
        if (this.surveyScriptsLoaded) {
            return this.surveyScriptsLoaded;
        }
        this.surveyScriptsLoaded = (async () => {
            try {
                // 2. Load Survey Core
                await this.loadScript(`${this.surveyCDNPath}/survey-core@2.3.4/survey.core.min.js`);
                // 3. Load Survey i18n
                await this.loadScript(`${this.surveyCDNPath}/survey-core@2.3.4/survey.i18n.min.js`);
                // 4. Load Survey themes
                await this.loadScript(`${this.surveyCDNPath}/survey-core@2.3.4/themes/index.min.js`);
                // 6. Load Survey UI
                await this.loadScript(`${this.surveyCDNPath}/survey-js-ui@2.3.4/survey-js-ui.min.js`);
                // console.log("All Survey.js scripts loaded successfully")
                this.loadStyles();
            }
            catch (error) {
                console.error("Failed to load Survey.js scripts:", error);
                throw error;
            }
        })();
        return this.surveyScriptsLoaded;
    }
    loadScript(src) {
        return new Promise((resolve, reject) => {
            if (document.querySelector(`script[src="${src}"]`)) {
                resolve();
                return;
            }
            const script = document.createElement("script");
            script.src = src;
            script.async = false;
            script.onload = () => resolve();
            script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
            // Load in document head for global access
            // document.head.appendChild(script)
            this.element.shadowRoot.appendChild(script);
        });
    }
    loadStyles() {
        for (const style of this.styles) {
            const loadStyle = document.createElement("link");
            loadStyle.rel = "stylesheet";
            loadStyle.href = style;
            loadStyle.onerror = err => {
                console.error("Failed to load style:", err);
            };
            this.element.shadowRoot.appendChild(loadStyle);
        }
    }
    scrollToLatestBubble() {
        var _a;
        if (this.componentType === "search") {
            const scrollContainer = this.element.closest(".chat-content-wrapper");
            const chatContainer = (_a = this.element.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector(".chat-list");
            const userBubbles = chatContainer === null || chatContainer === void 0 ? void 0 : chatContainer.querySelectorAll(".non-pending-user");
            const lastBubble = userBubbles === null || userBubbles === void 0 ? void 0 : userBubbles[userBubbles.length - 1];
            if (scrollContainer && lastBubble) {
                // 🔥 calculate position relative to scroll container
                const containerRect = scrollContainer.getBoundingClientRect();
                const bubbleRect = lastBubble.getBoundingClientRect();
                // 🔥 Align TOP of bubble with TOP of container
                const targetScrollTop = bubbleRect.top - containerRect.top + scrollContainer.scrollTop;
                scrollContainer.scrollTo({
                    top: targetScrollTop,
                    behavior: "smooth",
                });
            }
            return;
        }
        const chatContainer = this.element.shadowRoot.querySelector(".chat-list");
        const userBubbles = chatContainer === null || chatContainer === void 0 ? void 0 : chatContainer.querySelectorAll(".non-pending-user");
        const lastBubble = userBubbles === null || userBubbles === void 0 ? void 0 : userBubbles[userBubbles.length - 1];
        // const lastBubble = chatContainer?.querySelector(`#${this.aiMessageId}`)
        if (lastBubble) {
            lastBubble.scrollIntoView({ behavior: "smooth", block: "start" });
        }
    }
    componentWillLoad() {
        this.loadStyles();
        if (typeof window !== "undefined" && !window.Handlebars) {
            ;
            window.Handlebars = Handlebars;
        }
    }
    async hydrateMessagesFromState() {
        var _a, _b, _c;
        if (!((_a = this.element) === null || _a === void 0 ? void 0 : _a.shadowRoot) || this.chats.length === 0) {
            return;
        }
        await this.loadScriptsSequentially();
        await new Promise(resolve => requestAnimationFrame(() => resolve()));
        for (const message of this.chats) {
            if (message.controlType === "template") {
                this.processTemplateData(message, message.itemComponent, message.controlType);
            }
            else if (message.controlType === "form") {
                if (!message.surveyDomId) {
                    continue;
                }
                this.surveyDomId = message.surveyDomId;
                const messageContainer = await waitForElementRender(`#${message.id}`, this.element);
                if (!messageContainer.querySelector(`#${message.surveyDomId}`)) {
                    await waitForElementRender(`#${message.surveyDomId}`, this.element);
                }
                messageContainer["style"].width = "100%";
                messageContainer.parentElement["style"].width = "100%";
                await this.renderSurvey(message.itemComponent);
            }
            else if (message.controlType === "carousel" && ((_b = message.itemComponent) === null || _b === void 0 ? void 0 : _b.controlType) === "carousel") {
                this.processChatData(message, message.itemComponent);
            }
            else if (!message.controlType) {
                // Update anchor tags and button events
                message.text = updateAnchorTags(message.text, this.target || "_blank", "ai12z-cta-link", (_c = this.settings) === null || _c === void 0 ? void 0 : _c.utm, "answer");
                const buttonResult = updateButtonEvents(message.text);
                message.text = buttonResult.body;
                this.buttons = buttonResult.buttons;
                this.addEventListeners(`#${message.id}`);
            }
            if (message.controlType !== "form") {
                this.hideSpinner(message).then(() => {
                    console.log("spinner is hidden");
                });
                this.checkHighlightcode(message.id);
            }
        }
    }
    disconnectedCallback() {
        window["ai12z"] = {};
        this.chats = [];
    }
    watchHandler(_newValue, _oldValue) {
        // console.log("The new value of chats is: ", _newValue)
        // this.scrollToBottom()
        // this.scrollToLatestBubble()
    }
    getProjectId() {
        var _a, _b, _c, _d;
        return (_d = (_b = (_a = this.settings) === null || _a === void 0 ? void 0 : _a.pId) !== null && _b !== void 0 ? _b : (_c = this.dataAttributes) === null || _c === void 0 ? void 0 : _c.projectId) !== null && _d !== void 0 ? _d : null;
    }
    streamResponseHandler(event) {
        // console.log("streamRenderHandler", event.detail.data, this.aiMessageId)
        const { id, idChanged } = ensureMessageId(this.aiMessageId, this.chats, "ai-message");
        this.aiMessageId = id;
        if (idChanged)
            this.chats = [...this.chats];
        requestAnimationFrame(() => this.handleMessage(event.detail.data, this.aiMessageId));
    }
    async renderSurvey(surveyData) {
        await this.loadScriptsSequentially();
        await renderSurvey({
            chat: surveyData,
            surveyDomId: this.surveyDomId,
            shadowRoot: this.element.shadowRoot,
            config: {
                dataKey: this.apiKey,
                dataMode: this.env,
                dataAttributes: this.dataAttributes,
                formSubmitRenderCallback: processedResults => {
                    this.handleSurveyCompletionRender(processedResults);
                },
                onSubmitError: errorMessage => {
                    var _a;
                    const surveyElement = (_a = this.element.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector(`#${this.surveyDomId}`);
                    if (!surveyElement) {
                        console.error(`Survey element not found for DOM ID: ${this.surveyDomId}`);
                        return;
                    }
                    if (errorMessage === "Form submission blocked by validation") {
                        surveyElement.innerHTML = "Submission blocked due to suspicious activity.";
                        return;
                    }
                    surveyElement.innerHTML = "Failed to submit form";
                },
            },
        });
    }
    handleSurveyCompletionRender(processedResults) {
        if (processedResults) {
            const surveyDom = this.element.shadowRoot.querySelector(`#${processedResults.domId}`);
            surveyDom.parentElement.innerHTML = processedResults.completedHtml; // This needs to replace the survey container instead of parent one.
            this.formSubmitted.emit(processedResults);
            this.survey.emit(processedResults);
        }
    }
    endResponseHandler(event) {
        const { id, idChanged, orphaned } = ensureMessageId(this.aiMessageId, this.chats, "ai-message");
        this.aiMessageId = id;
        if (idChanged)
            this.chats = [...this.chats]; // Trigger reactivity
        if (!orphaned) {
            this.messageReceived.emit({ data: event.detail, domId: this.aiMessageId });
        }
        // console.log("listening end_response", event.detail, this.aiMessageId)
        // ✅ Prevent concurrent processing
        if (this.isProcessingEndResponse) {
            console.log("Already processing endResponse, ignoring duplicate");
            return;
        }
        this.scrollToLatestBubble();
        this.isProcessingEndResponse = true;
        // const idx = this.chats.findIndex(item => item.id === this.aiMessageId)
        requestAnimationFrame(async () => {
            var _a, _b, _c, _d;
            try {
                // ✅ Create config object
                const config = {
                    element: this.element,
                    hideSpinner: chatData => void this.hideSpinner(chatData),
                    getUpdatedChat: (message, data) => {
                        return this.getUpdatedChat(data, message);
                    },
                    updateChatMessage: (message, data) => {
                        this.updateChatMessage(message, data);
                    },
                    // updateConversations: (html, data) => this.getUpdatedChat(html, data),
                    renderSurvey: data => this.renderSurvey(data),
                    processTemplateData: (chatData, data) => this.processTemplateData(chatData, data, "carousel"),
                    processChatData: (chatData, data) => this.processChatData(chatData, data),
                    checkHighlightcode: id => this.checkHighlightcode(id),
                    addEventListeners: selector => this.addEventListeners(selector),
                    customStyle: this.customstyle,
                    customJS: this.customJS,
                    conversationId: this.conversationId,
                    controlSettings: this.settings,
                    utmConfig: (_a = this.settings) === null || _a === void 0 ? void 0 : _a.utm,
                };
                // ✅ Use the helper function
                await handleEndResponse({
                    data: event.detail,
                    currentDomId: this.aiMessageId,
                    inputType: "cta",
                    setMessages: newMessage => {
                        this.chats = [...this.chats, newMessage];
                        this.aiMessageId = newMessage.id;
                        requestAnimationFrame(() => {
                            setTimeout(() => {
                                if (newMessage && newMessage.id) {
                                    this.hideSpinner(newMessage).then(() => {
                                        // Spinner hidden
                                        // console.log("Spinner hidden for text message")
                                    });
                                }
                            }, 100);
                        });
                    },
                    setSurveyDomId: id => {
                        this.surveyDomId = id;
                    },
                    setButtons: buttons => {
                        this.buttons = buttons;
                    },
                    config,
                });
                // ✅ Common cleanup
                this.conversationId = event.detail.conversationId;
                saveConversation(this.getProjectId(), this.chats, this.conversationId, (_d = (_c = (_b = this.settings) === null || _b === void 0 ? void 0 : _b._id) === null || _c === void 0 ? void 0 : _c.$oid) !== null && _d !== void 0 ? _d : "", "ai12z-cta-history", "search");
                this.aiMessageId = "";
            }
            catch (error) {
                console.error("Error handling end_response:", error);
            }
            finally {
                // ✅ Reset flag after processing
                setTimeout(() => {
                    this.isProcessingEndResponse = false;
                }, 500);
            }
        });
    }
    checkHighlightcode(highlightcodeId = "") {
        var _a;
        try {
            // Guard clause: Ensure highlightcodeId is provided
            if (!highlightcodeId) {
                console.warn("highlightcodeId is empty");
                this.isProse = true;
                return;
            }
            // Get the target element by ID from shadow DOM
            const container = (_a = this.element.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector(`#${highlightcodeId}`);
            if (!container) {
                console.warn(`Element with id '${highlightcodeId}' not found in shadowRoot`);
                this.isProse = true;
                return;
            }
            // Select all <pre> elements inside the target container
            const preElements = container.querySelectorAll("pre");
            if (preElements.length > 0) {
                container.classList.remove("prose");
                import("highlight.js")
                    .then(({ default: hljs }) => {
                    hljs.configure({ ignoreUnescapedHTML: true });
                    preElements.forEach(pre => {
                        if (pre.dataset.highlighted) {
                            console.warn("Element previously highlighted...");
                            return;
                        }
                        hljs.highlightElement(pre);
                    });
                })
                    .catch(err => console.error("Failed to load highlight.js:", err));
            }
            else {
                container.classList.add("prose");
                // this.isProse = true
            }
        }
        catch (error) {
            console.error("Error in highlightcode:", error);
            this.isProse = true;
        }
    }
    buttonClickHandler(event) {
        // this.query = event.detail
        this.survey.emit({ results: event.detail, type: "button" });
        // this.handleButtonClick(event.detail)
    }
    get mainObject() {
        if (!window["ai12z"]) {
            window["ai12z"] = {};
        }
        return window["ai12z"];
    }
    generateUUID() {
        return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
            var r = (Math.random() * 16) | 0, v = c == "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    }
    async processChatData(chatData, data) {
        processChatDataHelper(chatData, data, this.element, (chatData) => this.hideSpinner(chatData), chatData => {
            this.survey.emit({ results: chatData, type: "update" });
        }, this.customJS, this.customstyle, false, "ai");
        // Step 3: Append the control element if both it and the target container exist
        // await this.waitForElementRender(`#${chatData.id}`).then(async () => {
        //   // console.log("Element rendered")
        //   this.hideSpinner(chatData)
        //   const targetContainer = this.element.shadowRoot.querySelector(`#${chatData.id}`)
        //   if (targetContainer && controlElement) {
        //     targetContainer.appendChild(controlElement)
        //     // console.log("targetContainer", targetContainer.parentElement)
        //     targetContainer.parentElement["style"].width = chatData.controlType === "slider" ? "90%" : this.componentType === "inline" ? "" : "100%"
        //     if (chatData.controlType === "custom" || chatData.controlType === "list" || chatData.controlType === "slider") {
        //       targetContainer.classList.remove("p-4")
        //       targetContainer.classList.add("p-0")
        //       targetContainer.classList.add("md:p-4")
        //     }
        //     // targetContainer["style"].width = "90%"
        //     await this.waitForElementToAdd(targetContainer as HTMLElement)
        //     // Step 5: Retrieve the content and emit the updated data
        //     chatData.message = targetContainer.innerHTML
        //     this.survey.emit({ results: chatData, type: "update" })
        //   }
        // })
    }
    addEventforReadMore() {
        // Add event listeners to the "Read More" buttons
        this.element.shadowRoot.querySelectorAll(".read-more").forEach(button => {
            button.addEventListener("click", event => {
                // const index = (event.target as HTMLElement).getAttribute("data-index") // Get index from data-index attribute
                const card = event.target.closest(".card");
                const shortDescription = card.querySelector(".short-description");
                const longDescription = card.querySelector(".long-description");
                const cardImage = card.querySelector(".card-image");
                // Toggle visibility of descriptions
                shortDescription.classList.toggle("hidden");
                longDescription.classList.toggle("hidden");
                // Update button text
                if (shortDescription.classList.contains("hidden")) {
                    cardImage.classList.add("hidden");
                    card.classList.remove("md:grid-cols-2");
                    event.target.textContent = "Show Less";
                }
                else {
                    cardImage.classList.remove("hidden");
                    card.classList.add("md:grid-cols-2");
                    event.target.textContent = "Read More";
                }
                // Optionally, you can use the index to log or perform other actions
                // console.log(`Button clicked for card at index: ${index}`)
            });
        });
    }
    addEventforPanel(_template, _query) {
        this.element.shadowRoot.querySelectorAll(".panel-button").forEach(button => {
            button.addEventListener("click", event => {
                // const id = (event.target as HTMLElement).getAttribute("data-id") // Get custom data-id attribute
                // console.log(`Button clicked for item with ID: ${id}`)
                // Add your logic here
                const type = event.target.getAttribute("data-type"); // Get custom data-id attribute
                // console.log(`Button clicked for item with ID: ${type}`)
                // Add your logic here
                if (type === "panel") {
                    this.processTemplateData(this.currentChatData, "", "pagination");
                    // const panelTemplate = Handlebars.compile(template[Number(id) + 2].content)
                    // const cardList = this.element.shadowRoot.querySelectorAll(".carousel-card")
                    // const card = (event.target as HTMLElement).closest(".carousel-card")
                    // const cardIndex = card.getAttribute("data-index")
                    // cardList[cardIndex].innerHTML = panelTemplate({
                    //   title: query.items[cardIndex].title,
                    //   description: query.items[cardIndex].description,
                    //   shortDescription: query.items[cardIndex].shortDescription,
                    //   images: query.items[cardIndex].images,
                    //   subtitle: query.items[cardIndex].subtitle,
                    //   buttons: query.items[cardIndex].buttons,
                    // })
                    // this.addEventforcardButton(query, template)
                    // this.addEventforReadMore()
                }
            });
        });
    }
    handleIndicatorClick(index) {
        this.currentSlide = index;
        this.processTemplateData(this.currentChatData, "", "pagination");
    }
    updateCarousel() {
        var _a, _b;
        const prevButton = (_a = this.element.shadowRoot.querySelector(".prev")) !== null && _a !== void 0 ? _a : this.element.shadowRoot.querySelector(".prev-btn");
        const nextButton = (_b = this.element.shadowRoot.querySelector(".next")) !== null && _b !== void 0 ? _b : this.element.shadowRoot.querySelector(".next-btn");
        // Attach event listeners to indicators
        const indicators = this.element.shadowRoot.querySelectorAll(".indicator");
        indicators.forEach((indicator, index) => {
            indicator.addEventListener("click", () => this.handleIndicatorClick(index));
        });
        prevButton === null || prevButton === void 0 ? void 0 : prevButton.addEventListener("click", this.handlePrev);
        nextButton === null || nextButton === void 0 ? void 0 : nextButton.addEventListener("click", this.handleNext);
    }
    renderPagination(templateType) {
        let itemsPerPage, start, end, paginatedItems, context;
        switch (templateType) {
            case "carousel":
                itemsPerPage = 1;
                paginatedItems = this.itemList;
                const transformValue = `-${this.currentSlide * 100}%`;
                context = {
                    paginatedItems,
                    isFirstSlide: this.currentSlide === 0,
                    isLastSlide: this.currentSlide === this.itemList.length - 1,
                    transform: transformValue,
                    currentSlide: this.currentSlide,
                };
                return { context: context, end: end };
            case "list":
                itemsPerPage = 5;
                start = this.currentPage * itemsPerPage;
                end = start + itemsPerPage;
                paginatedItems = this.itemList.slice(start, end);
                context = {
                    items: paginatedItems,
                    hasPrev: this.currentPage > 0,
                    hasNext: end < this.itemList.length,
                };
                return { context: context, end: end };
        }
    }
    addEventforPagination(end) {
        var _a, _b;
        // Add event listeners for buttons
        (_a = this.element.shadowRoot.querySelector(".prev-btn")) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
            if (this.currentPage > 0) {
                this.currentPage--;
                this.processTemplateData(this.currentChatData, "", "pagination");
            }
        });
        (_b = this.element.shadowRoot.querySelector(".next-btn")) === null || _b === void 0 ? void 0 : _b.addEventListener("click", () => {
            if (end < this.itemList.length) {
                this.currentPage++;
                this.processTemplateData(this.currentChatData, "", "pagination");
            }
        });
    }
    addEventforcardButton(query, template) {
        // Attach event listeners
        this.element.shadowRoot.querySelectorAll(".card-button").forEach(button => {
            button.addEventListener("click", event => {
                var _a, _b;
                // Register a Handlebars helper to stringify objects
                Handlebars.registerHelper("json", function (context) {
                    return JSON.stringify(context);
                });
                const id = event.target.getAttribute("data-id"); // Get custom data-id attribute
                // console.log(`Button clicked for item with ID: ${id}`)
                // Add your logic here
                const type = event.target.getAttribute("data-type"); // Get custom data-id attribute
                // console.log(`Button clicked for item with ID: ${type}`)
                const url = event.target.getAttribute("data-url");
                // console.log(`Button clicked for item with ID: ${url}`)
                // Add your logic here
                if (type === "panel") {
                    const panelTemplate = Handlebars.compile(template[Number(id) + 1].content);
                    const cardList = this.element.shadowRoot.querySelectorAll(".carousel-card");
                    const card = event.target.closest(".carousel-card");
                    const cardIndex = card.getAttribute("data-index");
                    cardList[cardIndex].innerHTML = panelTemplate({
                        form: (_a = query.items[cardIndex].panels[Number(id)]) === null || _a === void 0 ? void 0 : _a.form,
                        formSettings: query.formSettings,
                        buttons: (_b = query.items[cardIndex].panels[Number(id)]) === null || _b === void 0 ? void 0 : _b.buttons,
                    });
                    this.addEventforPanel(template, query);
                }
                if (type === "url") {
                    window.open(url, "_blank");
                }
            });
        });
    }
    async processTemplateData(chatData, data, _inputType) {
        this.currentChatData = chatData;
        await this.waitForElementRender(`#${chatData.id}`).then(async () => {
            var _a, _b, _c, _d, _e;
            this.hideSpinner(chatData);
            const targetContainer = this.element.shadowRoot.querySelector(`#${chatData.id}`);
            // console.log("targetContainer", targetContainer.parentElement)
            let handletemplate;
            if (targetContainer) {
                if (_inputType === "carousel") {
                    this.currentTemplate = (_a = data.controlData) === null || _a === void 0 ? void 0 : _a.template;
                    this.currentResponse = (_b = data.controlData) === null || _b === void 0 ? void 0 : _b.data.source;
                    this.itemList = this.currentResponse.items;
                }
                targetContainer.parentElement["style"].width = "90%";
                handletemplate = Handlebars.compile((_c = this.currentTemplate[0]) === null || _c === void 0 ? void 0 : _c.content);
                // targetContainer["dangerouslySetInnerHTML"] = { __html: handletemplate(this.renderPagination().context, { currentSlide: this.currentSlide }) }
                if (this.currentResponse.process === "list") {
                    targetContainer.innerHTML = handletemplate(this.renderPagination("list").context);
                    this.addEventforPagination(this.renderPagination("list").end);
                }
                else if (this.currentResponse.process === "carousel") {
                    // Register the custom 'eq' helper for Handlebars
                    Handlebars.registerHelper("eq", function (a, b) {
                        return a === b;
                    });
                    targetContainer.innerHTML = handletemplate(this.renderPagination("carousel").context);
                    this.updateCarousel();
                }
                else {
                    // Register the helper
                    Handlebars.registerHelper("processArray", function (array) {
                        if (!Array.isArray(array)) {
                            return ""; // Return an empty string if the input is not an array
                        }
                        return new Handlebars.SafeString(JSON.stringify(array));
                    });
                    chatData.data = data.controlData.data;
                    if (data.controlData && data.controlData.data) {
                        data.controlData.data.msgId = chatData.id; //`msg-${chatData.id}`
                    }
                    const styleURL = (_d = data.controlData) === null || _d === void 0 ? void 0 : _d.styles;
                    const scriptURL = (_e = data.controlData) === null || _e === void 0 ? void 0 : _e.Scripts;
                    if (styleURL) {
                        loadStyle(styleURL, this.element.shadowRoot);
                    }
                    targetContainer.innerHTML = handletemplate({ msgId: `${chatData.id}`, source: this.currentResponse, llm: data.controlData.data.llm });
                    if (scriptURL) {
                        loadScript(scriptURL, targetContainer);
                    }
                    // targetContainer.innerHTML = handletemplate({ chartId: `chart-${chatData.id}`, source: new Handlebars.SafeString(JSON.stringify(this.currentResponse)) })
                    setTimeout(() => {
                        this.renderTemplateData(chatData);
                    }, 1000);
                }
                // targetContainer["style"].width = "100%"
                // targetContainer.innerHTML = handletemplate({ localData: new Handlebars.SafeString(JSON.stringify(query)) })
                // finalHtml = mustache.render(template, { chartData: query })
                // this.element.shadowRoot.querySelector(`#${this.aiMessageId}`).innerHTML = finalHtml
                this.addEventforReadMore();
                this.addEventforcardButton(this.currentResponse, this.currentTemplate);
                chatData.message = targetContainer.innerHTML;
                this.survey.emit({ results: chatData, type: "update" });
            }
        });
    }
    renderTemplateData(chatData) {
        // console.log(`#${chatData.id}`)
        if (!this.mainObject[`${chatData.id}`]) {
            this.mainObject[`${chatData.id}`] = {};
        }
        const scripts = this.element.shadowRoot.querySelectorAll(`#${chatData.id} script`);
        scripts.forEach(script => {
            var _a;
            const newScript = document.createElement("script");
            newScript.type = "text/javascript";
            // If it's an external script (with `src`), copy the `src` attribute
            if (script.src) {
                newScript.src = script.src;
            }
            else {
                // If it's inline, set the JavaScript code as the content of the new <script> element
                // newScript.innerHTML = `const source = ${JSON.stringify(chatData.data.source)};\n`
                // newScript.innerHTML += `const llm = ${JSON.stringify(chatData.data.llm)};\n`
                newScript.innerHTML += script.innerHTML;
            }
            // Append the new script to the document body to execute it
            if (!newScript.src) {
                this.scriptArray.push(newScript);
            }
            (_a = script.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(script);
            // Optionally, remove the old <script> tag from the DOM
            if (newScript.src && !this.element.shadowRoot.querySelector(`script[src="${newScript.src}"]`)) {
                this.element.shadowRoot.appendChild(newScript);
            }
            else {
                const scriptDom = this.element.shadowRoot.querySelector(`script[type="text/javascript"]`);
                if (scriptDom && !newScript.src) {
                    if (this.scriptArray.length > 1) {
                        this.scriptArray.forEach(script => {
                            if (!script.src && script.innerHTML !== newScript.innerHTML) {
                                this.element.shadowRoot.appendChild(newScript);
                            }
                        });
                    }
                    else {
                        this.element.shadowRoot.appendChild(newScript);
                    }
                    // this.element.shadowRoot.appendChild(newScript)
                }
            }
        });
        // Step 4: Ensure Google Charts is loaded, then call the `drawGoogleChart` function
        setTimeout(() => {
            this.initializeScript(chatData.id);
        }, 1000);
    }
    initializeScript(id) {
        if (typeof this.mainObject[`${id}`]["onLoadCallback"] === "function") {
            this.mainObject[`${id}`]["onLoadCallback"]();
        }
        // window["google"]?.charts.load("current", { packages: ["corechart"] })
        // window["google"]?.charts.setOnLoadCallback()
    }
    hideSpinner(chatData) {
        // Logic for hiding the spinner (assumed to return a Promise if async is needed)
        return new Promise(resolve => {
            const renderedBubble = this.element.shadowRoot.querySelector(`#${chatData.id}`);
            if (renderedBubble && renderedBubble.querySelector("#spinner")) {
                ;
                renderedBubble.querySelector("#spinner").style.display = "none";
            }
            // Assume some async action here, then resolve
            // console.log("Spinner hidden")
            resolve(true);
        });
    }
    waitForElementRender(selector) {
        return new Promise(resolve => {
            // Check if the target element is already in the DOM
            if (this.element.shadowRoot.querySelector(selector)) {
                resolve(); // Resolve immediately if the element is already present
                return;
            }
            const observer = new MutationObserver(() => {
                // Check for the target element in each mutation
                const targetElement = this.element.shadowRoot.querySelector(selector);
                if (targetElement) {
                    // console.log("Element found:", targetElement)
                    resolve(); // Resolve the promise once the element is found
                    observer.disconnect(); // Stop observing after the element is found
                }
            });
            // Observe childList changes within the parent element and its subtree
            observer.observe(this.element.shadowRoot, { childList: true, subtree: true });
        });
    }
    // Helper function to detect when the target element is rendered
    waitForElementToAdd(element) {
        return new Promise(resolve => {
            const observer = new MutationObserver(_mutations => {
                resolve();
                observer.disconnect();
            });
            observer.observe(element, { childList: true, subtree: true });
        });
    }
    async invokeSocket() {
        var _a, _b, _c, _d, _e, _f;
        let socketId = (_a = this.socketIn) === null || _a === void 0 ? void 0 : _a.getSocketId();
        if (!socketId) {
            console.error("Socket ID not available");
            return;
        }
        let retrievedService = SocketService.getInstanceById(socketId);
        // If no service found, try waiting for connection
        if (!retrievedService) {
            console.warn(`No socket service found for socket ID: ${socketId}, attempting to wait for connection...`);
            try {
                // Wait for the connection to complete
                await this.socketIn.waitForConnection();
                // Get the socketId again after connection
                socketId = this.socketIn.getSocketId();
                retrievedService = SocketService.getInstanceById(socketId);
            }
            catch (error) {
                console.error("Failed to wait for connection:", error);
            }
        }
        // If still no service, create a new one
        if (!retrievedService) {
            console.warn("Creating new socket service...");
            try {
                const newSocketService = SocketService.createInstance(this.env, (_b = this.apiKey) !== null && _b !== void 0 ? _b : Env.DATA_KEY);
                await newSocketService.waitForConnection();
                // Update the socketIn reference
                this.socketIn = newSocketService;
                socketId = newSocketService.getSocketId();
                retrievedService = SocketService.getInstanceById(socketId);
                if (!retrievedService) {
                    console.error("Failed to create and retrieve new socket service");
                    return;
                }
            }
            catch (error) {
                console.error("Failed to create new socket service:", error);
                return;
            }
        }
        const socket = retrievedService.getSocket();
        if (!socket) {
            console.error("Socket not available from service");
            return;
        }
        const protocol = retrievedService.getProtocol();
        let data;
        let eventName;
        if (protocol === "v2") {
            eventName = "query";
            data = {
                query: this.query,
                conversation_id: this.conversationId || "",
                base64_images: ((_c = this.imgFiles) === null || _c === void 0 ? void 0 : _c.length) > 0 ? this.imgFiles : undefined,
            };
        }
        else {
            eventName = "evaluate_query";
            data = {
                apiKey: (_d = this.apiKey) !== null && _d !== void 0 ? _d : Env.DATA_KEY,
                query: this.query,
                conversationId: (_e = this.conversationId) !== null && _e !== void 0 ? _e : "",
                base64Images: ((_f = this.imgFiles) === null || _f === void 0 ? void 0 : _f.length) > 0 ? this.imgFiles : [],
                event: "evaluate_query",
                attributes: this.dataAttributes,
                excludeTags: this.chatExcludeTags,
                includeTags: this.chatIncludeTags,
                meta: getMetaInfo(),
            };
        }
        socket.emit(eventName, data, (error, _response) => {
            if (error) {
                console.error("Error occurred while evaluating query:", error);
                this.aiMessageId = `chatbot-${generateUUID()}`;
                this.chats[this.chats.length - 1].id = this.aiMessageId;
                this.chats[this.chats.length - 1].text = "Error connecting to server. Please try again later.";
            }
        });
        // this.scrollToLatestBubble()
    }
    addEventListeners(msgId) {
        const container = this.element.shadowRoot.querySelector(msgId);
        if (container) {
            this.buttons.forEach(button => {
                const buttonElement = container.querySelector(`#${button.id}`);
                // console.log("buttonElement", buttonElement)
                // if (buttonElement) {
                //   buttonElement.addEventListener("click", this.handleButtonClick(button.label))
                // }
                if (buttonElement) {
                    const originalCall = buttonElement.getAttribute("data-original-click"); // Ensure type safety or handle undefined
                    if (!originalCall) {
                        console.warn(`originalClickHandler is not defined for button with id: ${button.id}`);
                        return;
                    }
                    // const match = originalCall.match(/^(\w+)\s*\((.*)\)$/) // extract name and arguments
                    // const match = originalCall.match(/^(\w+)\s*\(([\s\S]*)\)$/)
                    // Match both 'sendMessage' and 'ai12zCtrl.sendMessage' patterns
                    const match = originalCall.match(/^([\w.]+)\s*\(([\s\S]*)\)$/);
                    // console.log("match", match)
                    if (match) {
                        const funcName = match[1];
                        const argsStr = match[2]; // string of args, like "'param', true"
                        // const self = this
                        // const func = self[funcName]
                        //  const self = this
                        // Extract actual method name (handle both 'sendMessage' and 'ai12zCtrl.sendMessage')
                        const actualMethodName = funcName.includes(".") ? funcName.split(".").pop() : funcName;
                        // const func = self[actualMethodName]
                        buttonElement.addEventListener("click", () => {
                            // if (typeof this[funcName] === "function") {
                            try {
                                // console.log("args", argsStr)
                                // Evaluate arguments safely
                                switch (actualMethodName) {
                                    case "sendQuery":
                                        console.warn("sendQuery is deprecated, use sendMessage instead");
                                        this.survey.emit({ results: button.label, type: "button" });
                                        break;
                                    case "sendMessage":
                                    case "ai12zCtrl.sendMessage":
                                        const msgArgs = parseArgsWithJson5(argsStr);
                                        if (!msgArgs)
                                            return;
                                        this.survey.emit({ results: msgArgs, type: "sendMessage" });
                                        // func.apply(self, msgArgs)
                                        break;
                                    case "sendJSON":
                                    case "ai12zCtrl.sendJSON":
                                        const jsonArgs = parseArgsWithJson5(argsStr);
                                        if (!jsonArgs)
                                            return;
                                        // func.apply(self, jsonArgs)
                                        this.survey.emit({ results: jsonArgs, type: "sendJSON" });
                                        break;
                                }
                            }
                            catch (err) {
                                console.error(`Error invoking ${funcName}:`, err);
                            }
                        });
                        // buttonElement.addEventListener("click", this.handleButtonClick(button.label))
                    }
                }
            });
        }
    }
    stopStreamInputHandler(_state) {
        if (this.socketIn) {
            // console.log("*****stop stream***", this.socketIn)
            // this.socketIn.disconnect()
            SocketService.disconnectSocketById(_state.detail.socketId);
        }
    }
    startStreamInputHandler(_state) {
        var _a, _b, _c;
        // console.log("*****start stream***", _state.detail?.search)
        if ((_a = _state.detail) === null || _a === void 0 ? void 0 : _a.maxQuestion) {
            setTimeout(() => {
                this.hideSpinner(_state.detail.chatData);
                this.scrollToLatestBubble();
            }, 1000);
        }
        else {
            this.query = (_b = _state.detail) === null || _b === void 0 ? void 0 : _b.search;
            this.imgFiles = (_c = _state.detail) === null || _c === void 0 ? void 0 : _c.imgFiles;
            this.invokeSocket();
            if (this.chats.length > 2) {
                setTimeout(() => {
                    this.scrollToLatestBubble();
                }, 500);
            }
        }
    }
    highlightcode() {
        // Select <pre> elements within the shadow DOM
        const preElements = this.element.shadowRoot.querySelectorAll("pre");
        if (preElements.length > 0) {
            this.isProse = false;
            import("highlight.js")
                .then(({ default: hljs }) => {
                hljs.configure({ ignoreUnescapedHTML: true });
                preElements.forEach(pre => {
                    hljs.highlightElement(pre);
                });
            })
                .catch(err => console.error("Failed to load highlight.js:", err));
        }
    }
    // Function to copy the text to clipboard
    copyToClipboard(text) {
        navigator.clipboard
            .write([
            new ClipboardItem({
                "text/html": new Blob([text], { type: "text/html" }),
                "text/plain": new Blob([this.removeHtmlTags(text)], { type: "text/plain" }),
            }),
        ])
            .then(() => {
            // console.log("Text copied to clipboard", text)
            this.copied = true; // Set a flag to show copied state
            setTimeout(() => {
                this.copied = false; // Reset copied state after 2 seconds
            }, 2000);
        });
    }
    // Method to remove HTML tags from a string
    removeHtmlTags(text) {
        const div = document.createElement("div");
        div.innerHTML = text;
        return div.textContent || div.innerText || "";
    }
    // Function to trigger the text-to-speech
    async speakText(msg) {
        var _a, _b;
        if (this.voiceType === "default") {
            if ("speechSynthesis" in window) {
                const voices = window.speechSynthesis.getVoices();
                const voice = voices.find(voice => voice.name === this.voice);
                this.isPlayed = true;
                const utterance = new SpeechSynthesisUtterance(msg); // Create a speech synthesis utterance
                utterance.lang = "en-US"; // Set the language, you can change this as needed
                utterance.rate = 1;
                utterance.pitch = 1;
                utterance.voice = voice;
                // Speak the text
                window.speechSynthesis.speak(utterance);
            }
            else {
                alert("Speech Synthesis API is not supported in your browser.");
            }
        }
        if (this.voiceType === "google") {
            const base64audiocontent = await getAudioContent((_a = this.apiKey) !== null && _a !== void 0 ? _a : Env.DATA_KEY, (_b = this.env) !== null && _b !== void 0 ? _b : Env.DATA_MODE, msg, this.voice);
            const audioBlob = this.base64ToBlob(base64audiocontent.audio_content, "audio/mpeg");
            const audioUrl = URL.createObjectURL(audioBlob);
            // Create the audio element
            this.audioElement = new Audio(audioUrl);
            this.audioElement.onended = () => {
                // this.isPlaying = false
                this.isPlayed = false;
            };
            if (this.audioElement.paused) {
                this.audioElement.play();
                this.isPlayed = true;
            }
            else {
                this.audioElement.pause();
                this.audioElement.currentTime = 0;
                this.audioElement.src = ""; // Remove the audio source
                this.audioElement = null; // Dereference the object
                this.isPlayed = false;
            }
        }
    }
    base64ToBlob(base64, mimeType) {
        const byteCharacters = atob(base64);
        const byteNumbers = new Array(byteCharacters.length).fill(0).map((_, i) => byteCharacters.charCodeAt(i));
        const byteArray = new Uint8Array(byteNumbers);
        return new Blob([byteArray], { type: mimeType });
    }
    render() {
        var _a;
        const email = "";
        return (h("div", { key: '567d1598d53db83ebb453da3fcd6227ee5fe5bc0' }, h("ul", { key: '65d296e9a7503b85d6d476039123253c48a9305a', id: "main-content", tabindex: "-1", class: {
                "chat-list": true,
                "custom-list": this.componentType === "search",
                // "custom-chat-top-height": this.componentType === "search",
                "custom-chat-bottom-height": this.componentType === "inline",
                "custom-chat-above-height": this.componentType === "inline" && this.chatPosition === "above",
            }, style: {
                maxHeight: this.componentType !== "search" ? "80vh" : "none",
                overflowY: this.componentType !== "search" ? "auto" : "visible",
                height: this.componentType === "search" ? "auto" : "100%",
            } }, (_a = this.chats) === null || _a === void 0 ? void 0 :
            _a.map((chat, idx) => {
                var _a, _b, _c, _d, _e;
                const isBot = chat.type === "ai";
                const showAvatar = isBot && (idx === this.chats.length - 1 || ((_a = this.chats[idx + 1]) === null || _a === void 0 ? void 0 : _a.type) !== "ai");
                return (h("li", { class: {
                        "text-md": true,
                        "chat-list-item": true,
                        "chat-align-list": chat.type !== "user",
                        "chat-not-user-list": chat.type === "user",
                        "pointer-events-none": chat.type === "user",
                    }, tabindex: idx === this.focusedIndex ? 0 : -1, onKeyDown: e => this.handleChatKeyNav(e, idx), ref: el => (this.chatItemRefs[idx] = el), role: "article", "aria-label": `${chat.type === "user" ? "Your message" : "Bot response"} ${idx + 1}` }, chat.type !== "user" && (h("div", { class: `chat-inner-list default-avatar` }, !this.avatarUrl && (h("svg", { viewBox: "0 0 48 48", fill: "currentColor", xmlns: "http://www.w3.org/2000/svg", class: `w-8 h-8  ${showAvatar ? "md:block" : "opacity-0"}` }, 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" }))), this.avatarUrl && (h("div", { class: `avatar-container ${showAvatar ? "md:block" : "opacity-0"}` }, h("img", { src: this.avatarUrl, alt: "Avatar", class: "avatar-image w-8 h-8 rounded-full" }))))), chat.status === "pending" && (h("div", { class: "pending-chat" }, h("svg", { class: "animate-spin h-5 w-5 text-gray-400", xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24" }, h("circle", { class: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", "stroke-width": "4" }), h("path", { class: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 0 1 4 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })))), h("div", { id: "parent-element", onMouseEnter: e => {
                        let popup = e.target.querySelector(".non-user-container");
                        if (popup)
                            popup.style.display = "block";
                    }, onMouseLeave: e => {
                        let popup = e.target.querySelector(".non-user-container");
                        if (popup)
                            popup.style.display = "none";
                    } }, chat.status !== "pending" && !(chat.type === "user" && chat.isHide) && (h("div", { class: {
                        "p-4": true,
                        "max-w-full": this.componentType === "search" ? true : false,
                        "prose": true,
                        "custom-prose": true,
                        "transition-all": true,
                        "duration-300": true,
                        "opacity-100": this.isProse,
                        "opacity-90": !this.isProse,
                        "resize": (_b = chat.formModel) === null || _b === void 0 ? void 0 : _b.hasOwnProperty("answer"),
                        "non-pending-user": true,
                        // "p-0": chat.controlType === "list" ? true : false,
                    }, id: chat.id, innerHTML: chat.message }, (_c = chat === null || chat === void 0 ? void 0 : chat.images) === null || _c === void 0 ? void 0 :
                    _c.map(img => {
                        return h("img", { src: img, class: "thumbnail", alt: "thumbnail", width: "70", height: "50" });
                    }), chat.type !== "user" && (h("svg", { class: "animate-spin h-5 w-5 text-gray-400", xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", id: "spinner" }, h("circle", { class: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", "stroke-width": "4" }), h("path", { class: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 0 1 4 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" }))))), chat.type !== "user" && chat.clipboard && ((_d = this.settings.showMessageIcons) !== null && _d !== void 0 ? _d : true) && !chat.surveyDomId && (h("div", { class: "non-user-container", style: { display: "none" } }, this.isPlayed && (h("button", { class: "copy-btn", "aria-label": "Stop", tabindex: "0", onClick: () => {
                        this.isPlayed = false;
                        window.speechSynthesis.cancel();
                        if (this.audioElement) {
                            this.audioElement.pause();
                            this.audioElement.currentTime = 0;
                            this.audioElement.src = ""; // Remove the audio source
                            this.audioElement = null; // Dereference the object
                        }
                        // this.isPlayed = false
                    } }, h("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", class: "icon-md-heavy" }, h("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM9.5 8.5C8.94772 8.5 8.5 8.94772 8.5 9.5V14.5C8.5 15.0523 8.94772 15.5 9.5 15.5H14.5C15.0523 15.5 15.5 15.0523 15.5 14.5V9.5C15.5 8.94772 15.0523 8.5 14.5 8.5H9.5Z", fill: "currentColor" })))), !this.isPlayed && (h("button", { class: "copy-btn", onClick: () => this.speakText(this.removeHtmlTags(chat.clipboard)), "aria-label": "Play", tabindex: "0" }, h("svg", { class: "w-6 h-6", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, h("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M11 4.9099C11 4.47485 10.4828 4.24734 10.1621 4.54132L6.67572 7.7372C6.49129 7.90626 6.25019 8.00005 6 8.00005H4C3.44772 8.00005 3 8.44776 3 9.00005V15C3 15.5523 3.44772 16 4 16H6C6.25019 16 6.49129 16.0938 6.67572 16.2629L10.1621 19.4588C10.4828 19.7527 11 19.5252 11 19.0902V4.9099ZM8.81069 3.06701C10.4142 1.59714 13 2.73463 13 4.9099V19.0902C13 21.2655 10.4142 22.403 8.81069 20.9331L5.61102 18H4C2.34315 18 1 16.6569 1 15V9.00005C1 7.34319 2.34315 6.00005 4 6.00005H5.61102L8.81069 3.06701ZM20.3166 6.35665C20.8019 6.09313 21.409 6.27296 21.6725 6.75833C22.5191 8.3176 22.9996 10.1042 22.9996 12.0001C22.9996 13.8507 22.5418 15.5974 21.7323 17.1302C21.4744 17.6185 20.8695 17.8054 20.3811 17.5475C19.8927 17.2896 19.7059 16.6846 19.9638 16.1962C20.6249 14.9444 20.9996 13.5175 20.9996 12.0001C20.9996 10.4458 20.6064 8.98627 19.9149 7.71262C19.6514 7.22726 19.8312 6.62017 20.3166 6.35665ZM15.7994 7.90049C16.241 7.5688 16.8679 7.65789 17.1995 8.09947C18.0156 9.18593 18.4996 10.5379 18.4996 12.0001C18.4996 13.3127 18.1094 14.5372 17.4385 15.5604C17.1357 16.0222 16.5158 16.1511 16.0539 15.8483C15.5921 15.5455 15.4632 14.9255 15.766 14.4637C16.2298 13.7564 16.4996 12.9113 16.4996 12.0001C16.4996 10.9859 16.1653 10.0526 15.6004 9.30063C15.2687 8.85905 15.3578 8.23218 15.7994 7.90049Z", fill: "currentColor" })))), h("button", { class: "copy-btn", onClick: () => this.copyToClipboard(chat.clipboard), "aria-label": "Copy to Clipboard", tabindex: "0" }, !this.copied && (h("svg", { class: "w-6 h-6", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, h("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M7 5C7 3.34315 8.34315 2 10 2H19C20.6569 2 22 3.34315 22 5V14C22 15.6569 20.6569 17 19 17H17V19C17 20.6569 15.6569 22 14 22H5C3.34315 22 2 20.6569 2 19V10C2 8.34315 3.34315 7 5 7H7V5ZM9 7H14C15.6569 7 17 8.34315 17 10V15H19C19.5523 15 20 14.5523 20 14V5C20 4.44772 19.5523 4 19 4H10C9.44772 4 9 4.44772 9 5V7ZM5 9C4.44772 9 4 9.44772 4 10V19C4 19.5523 4.44772 20 5 20H14C14.5523 20 15 19.5523 15 19V10C15 9.44772 14.5523 9 14 9H5Z", fill: "currentColor" }))), this.copied && (h("svg", { viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", class: "w-6 h-6" }, h("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M19.8198 6.19526C20.0601 6.45561 20.0601 6.87772 19.8198 7.13807L9.9736 17.8047C9.73328 18.0651 9.34364 18.0651 9.10332 17.8047L4.18024 12.4714C3.93992 12.2111 3.93992 11.7889 4.18024 11.5286C4.42056 11.2682 4.8102 11.2682 5.05053 11.5286L9.53846 16.3905L18.9495 6.19526C19.1898 5.93491 19.5794 5.93491 19.8198 6.19526Z", fill: "currentColor" })))), h("button", { id: `thumbsUp_${chat.thumbsId}`, onClick: () => this.thumbsUp(chat.thumbsId, chat.insightId, {
                        dataKey: this.apiKey,
                        dataMode: this.env,
                        conversationId: this.conversationId,
                        projectId: this.getProjectId(),
                        questionText: getQuestionText(this.chats, chat.insightId) || "",
                    }), class: "chat-thumbs-up", "aria-label": "Thumbs Up", tabindex: "0" }, 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_${chat.thumbsId}`, onClick: () => this.thumbsDown(chat.thumbsId, chat.insightId, {
                        dataKey: this.apiKey,
                        dataMode: this.env,
                        conversationId: this.conversationId,
                        projectId: this.getProjectId(),
                        questionText: getQuestionText(this.chats, chat.insightId) || "",
                    }), class: "chat-thumbs-up", "aria-label": "Thumbs Down", tabindex: "0" }, 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" }))), h("button", { class: "copy-btn", tabindex: "0", "aria-label": "Send Email" }, h("a", { href: `mailto:${email}?subject=${encodeURIComponent((_e = this.chats[idx - 1]) === null || _e === void 0 ? void 0 : _e.message)}&body=${encodeURIComponent(this.removeHtmlTags(chat.clipboard))}`, target: "_blank", "aria-label": "Send Email" }, h("svg", { viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", stroke: "currentColor", "stroke-width": "0.3", class: "w-6 h-6" }, h("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M3.75 5.25L3 6V18L3.75 18.75H20.25L21 18V6L20.25 5.25H3.75ZM4.5 7.6955V17.25H19.5V7.69525L11.9999 14.5136L4.5 7.6955ZM18.3099 6.75H5.68986L11.9999 12.4864L18.3099 6.75Z", fill: "currentColor" }), " "))))))));
            }), h("div", { key: 'ead0c342309de4030cb69954fe585eb2fc06870f', class: "scroll-bottom" }))));
    }
    static get is() { return "ai12z-chat"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["ai12z-chat.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ai12z-chat.css"]
        };
    }
    static get properties() {
        return {
            "chatId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "chat-id"
            },
            "chats": {
                "type": "any",
                "mutable": true,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "chats",
                "defaultValue": "[]"
            },
            "query": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "query"
            },
            "apiKey": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "api-key"
            },
            "aiMessageId": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "ai-message-id"
            },
            "imgFiles": {
                "type": "any",
                "mutable": true,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "img-files"
            },
            "env": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "env"
            },
            "conversationId": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "conversation-id"
            },
            "dataAttributes": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "data-attributes"
            },
            "chatExcludeTags": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "Array<string>",
                    "resolved": "string[]",
                    "references": {
                        "Array": {
                            "location": "global",
                            "id": "global::Array"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "chatIncludeTags": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "Array<string>",
                    "resolved": "string[]",
                    "references": {
                        "Array": {
                            "location": "global",
                            "id": "global::Array"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "target": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "target"
            },
            "voiceType": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "voice-type"
            },
            "voice": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "voice"
            },
            "componentType": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "component-type",
                "defaultValue": "\"search\""
            },
            "chatPosition": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "chat-position",
                "defaultValue": "\"below\""
            },
            "socketIn": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "SocketService",
                    "resolved": "SocketService",
                    "references": {
                        "SocketService": {
                            "location": "import",
                            "path": "../../../utils/socket-service",
                            "id": "src/utils/socket-service.ts::SocketService",
                            "referenceLocation": "SocketService"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "customstyle": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "customstyle"
            },
            "customJS": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "custom-j-s"
            },
            "avatarUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "avatar-url"
            },
            "settings": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "settings"
            }
        };
    }
    static get states() {
        return {
            "scrollBottom": {},
            "copied": {},
            "isPlayed": {},
            "buttons": {},
            "itemList": {},
            "currentChatData": {},
            "currentTemplate": {},
            "currentPage": {},
            "currentResponse": {},
            "currentSlide": {},
            "scriptArray": {},
            "isProse": {},
            "isProcessingEndResponse": {},
            "surveyDomId": {},
            "focusedIndex": {}
        };
    }
    static get events() {
        return [{
                "method": "feedback",
                "name": "feedback",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "survey",
                "name": "survey",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "stateChanged",
                "name": "stateChanged",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "messageReceived",
                "name": "messageReceived",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ data: string; domId: string }",
                    "resolved": "{ data: string; domId: string; }",
                    "references": {}
                }
            }, {
                "method": "formSubmitted",
                "name": "formComplete",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "hydrateMessagesFromState": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "element"; }
    static get watchers() {
        return [{
                "propName": "chats",
                "methodName": "watchHandler"
            }];
    }
    static get listeners() {
        return [{
                "name": "streamResponse",
                "method": "streamResponseHandler",
                "target": "window",
                "capture": false,
                "passive": false
            }, {
                "name": "endResponse",
                "method": "endResponseHandler",
                "target": "window",
                "capture": false,
                "passive": false
            }, {
                "name": "buttonClick",
                "method": "buttonClickHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "stopStream",
                "method": "stopStreamInputHandler",
                "target": "document",
                "capture": false,
                "passive": false
            }, {
                "name": "startStream",
                "method": "startStreamInputHandler",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
